Skip to content

Polymer ml - #325

Open
NJMarchese wants to merge 71 commits into
electronmicroscopy:devfrom
NJMarchese:polymer-ml
Open

NJMarchese wants to merge 71 commits into
electronmicroscopy:devfrom
NJMarchese:polymer-ml

Conversation

@NJMarchese

Copy link
Copy Markdown
Collaborator

This PR adds the machine-learning analysis pipeline behind the polymer 4D-STEM ML paper (https://arxiv.org/abs/2607.16570) to quantem.diffraction. The code matches the published deposit at https://zenodo.org/records/22741835, merged onto current dev and ported to dev's APIs.

What it does

BraggPeaksPolymer takes a Dataset4dstem of a semicrystalline polymer film through these steps:

  1. Peak detection. A U-Net (polymer_models.py) predicts peak position and intensity maps. Peaks are then found by local maxima with subpixel refinement (peak_detection.py).
  2. Calibration. Per-pattern beam centers, an elliptic-distortion fit from the diffuse ring (ellipse_fitting.py, ridge or angular-variance method), and conversion to 1/Å from the dataset's calibration.
  3. Polar transform of patterns and peaks (polymer_polar.py, built on dev's polar_transform).
  4. Ice removal. Sharp, six-fold peaks from ice contamination are flagged (polymer_ice.py), with tuning helpers (peak widths, selection boxes, histograms) in polymer_ice_tuning.py.
  5. Orientation mapping and flowline images. Radial peak-family windows, in-plane orientation histograms, flowline maps (polymer_orientation.py), and spatial orientation correlation with distance and slope metrics (orientation_correlation.py).
  6. Inspection and scan-region masks. Static peak overlays and peak count and histogram maps (peak_visualization.py). Scan-region masks (scan_mask.py): circle, ellipse, square or rectangle with rotation, optionally edited pixel by pixel, saved to a versioned .npz (set_scan_mask, save_scan_mask, load_scan_mask, plot_scan_mask).

Nothing in dev covers these steps. Dev's ACOM matches orientations against a known crystal, and its disk detection uses template matching; neither handles diffuse polymer reflections. The polymer code reuses dev's polar_transform, find_origin_angular_*, Vector, Dataset4dstem and electron_wavelength_angstrom.

Layout

  • All new code is in src/quantem/diffraction/. The only existing file changed there is diffraction/__init__.py, which gains the new exports.
  • core/ml/cnn.py: CNN2d gains conv_kernel_size (positive odd integer, default 3, padding k // 2, applied to every conv including the output conv). The default network is unchanged: same state-dict keys and identical outputs to dev's.
  • The polymer detector (MultiChannelCNN2d in polymer_models.py) subclasses core CNN2d, adding per-channel output activations.
  • Polymer-only geometry is in polymer_polar.py and the polymer orientation code is in polymer_orientation.py, so dev's shared polar_transform.py and orientation.py are untouched.
  • Following CONTRIBUTING.md, the viewers (show_polymer_4DSTEM, ice_split_widget) and a scan-mask editor go to quantem.widget in a separate PR. They take a BraggPeaksPolymer as input and build on scan_mask.py.

Replication

The code implementation replicates results from the ML paper for the model and associated dataset.

Wire the existing quantem calibration tools into preprocess() (previously a
stub): image-center finding, ellipticity fitting, descan (CoM plane fit), and
detector-rotation estimation. Follows the class's lazy design -- parameters are
measured and cached (image_centers, ellipse_params, descan_origin,
detector_rotation_deg, sampling_inv_A), then consumed downstream by the polar
transforms rather than re-warping the raw 4D data.

- Ellipticity via fit_probe_ellipse on the mean DP -> metadata["ellipticity"]
- Descan + rotation via CenterOfMassOriginModel (calculate_origin,
  fit_origin_background, estimate_detector_rotation)
- image_centers via find_central_beams_4d ("descent"/"grid"/"peaks") or the
  CoM/descan field, selectable with center_source
- Register the new calibration attributes in __init__
Render a boustrophedon cursor walk over the scan to an animated GIF: each frame
pairs the real-space intensity map (cursor crosshair) with that position's
diffraction pattern and detected Bragg-peak overlay, reusing the save_peak_figures
rendering primitives. PIL-based writer.
…spacing axis

- estimate_peak_windows(mode='intensity'|'count', log_scale=False): detect peak
  windows on the peak-count radial profile as well as intensity, and optionally on
  log1p(profile) so small peaks are not dominated by large ones. peak_info now
  carries 'mode', 'log_scale', and 'profile'.
- peak_radial_intensity_plot / peak_radial_count_plot: add log_scale (log y-axis
  with a positive fill baseline) and show_d_spacing (top axis in real-space
  d-spacing (Å) = 1/q) when plotting.
- estimate_peak_windows: printed per-peak summary now reports d-spacing (Å) = 1/q
  alongside the q values (center and window).
- plot_peak_count_map: panel titles now include the d-spacing range (Å) under the
  q range (1/Å).
Reorder BraggPeaksPolymer.preprocess() so calibration runs
descan/rotation -> centering -> ellipticity (was ellipse first).
Fitting the ellipse on the raw mean DP smeared the diffraction ring
by the descan drift and biased the fit toward the central beam.

The ellipse is now fit on a centered mean DP built by the new
_centered_dp_mean() helper: when a fitted CoM model is available it
reuses shift_origin_to()'s sub-pixel grid-sampler to align every
pattern to the detector center on-device, otherwise it falls back to
translating the plain mean DP by the average center offset. Centering
(find_central_beams_4d) now runs without ellipse_params since the
ellipse is not yet known.
Replace fit_probe_ellipse (which Otsu-thresholds and fits the brightest
blob = the central beam, so it measured probe shape and latched onto a
smeared/off-center beam) with a diffraction-RING fit using Karen
Ehrhardt's angular-uniformity criterion.

New _fit_ellipse_from_ring() holds the found center fixed and searches
(b/a, theta) to minimise the azimuthal variance of a ring annulus in the
polar transform (quantem.diffraction.polar_transform). It samples out at
the ring radius and never touches the central beam, so a doubled /
off-center / drift-smeared central beam no longer biases the ellipse.

Details:
- ring band auto-detected from the circular radial profile (skip central
  beam to first trough, take strongest ring beyond), or set explicitly
  via new ellipse_radial_min / ellipse_radial_max preprocess params.
- coarse (b/a, theta) grid + local refine; output canonicalised to
  a/b >= 1.
- centered mean DP now cached on self.dp_mean_centered (was ephemeral);
  preprocess caches self.ellipse_ring_band; show=True plots the DP plus
  before/after polar so the ring flattening is visible.
- ellipse_threshold kept but unused (back-compat).

Validated against polar_transform on synthetic elliptical rings
(a/b and theta recovered to <0.5%).
_centered_dp_mean used integer torch.round rolls. The per-pattern
rounding residual (up to 0.5 px) does NOT average out when the origin
spread is narrow -- every pattern rounds to the same integer, so the
fractional part becomes a constant bias and the mean beam lands off the
detector center by a fraction of a pixel (visible as the central beam
sitting up/right of the geometric-center crosshair, and it also throws
off the fixed-center ring ellipse fit).

Replace integer rolls with bilinear splatting: each pattern's continuous
shift (center - fitted origin) is split into floor + fraction, and its
intensity is distributed over the 4 integer-shift corners with bilinear
weights, grouped by floor shift for efficiency. Same low memory (one
(Qy,Qx) accumulator + one batch), now centers to <0.01 px.

Also fix the no-CoM fallback to average image_centers over valid
(non-zero) positions only -- it is 0 outside the scan mask, which
otherwise biases the fallback center toward the origin.

Validated on synthetic beams: bilinear hits the detector center exactly
at every origin spread; integer rolls drift up to ~0.4 px at narrow spread.
The centered mean DP still showed the central beam a few px off the
detector center. Root cause: _centered_dp_mean shifted each pattern by
the descan CoM origin (origin_fitted). The CoM is the centroid of the
WHOLE pattern, so ring/background asymmetry (e.g. a bright corner) pulls
it several px off the actual beam -- centering by it puts the CoM at the
center and leaves the beam off.

Center instead by image_centers, the angular-uniformity BEAM center
(found by ring symmetry, immune to intensity asymmetry, and the center
everything downstream already uses). Only ROI (in-mask, non-zero)
patterns are averaged. Still sub-pixel bilinear, same low memory.

Validated on a synthetic pattern with an asymmetric background pulling
the CoM to (130,132): centering by CoM leaves the beam at (114.5,114.3)
(~7 px off); centering by image_centers lands it at (107.9,107.9) on the
(107.5,107.5) detector center.
The descan residual (origin_com_measured - descan_origin) showed a
uniform ~1-2 px offset inside the ROI. Cause: CenterOfMassOriginModel
fits fit_origin_background over the WHOLE scan, so out-of-ROI patterns
(vacuum/substrate, meaningless CoM) drag the global plane and leave a
constant offset inside the mask; hot/dead pixels contaminate it too.

CenterOfMassOriginModel has no mask support, so preprocess now fits the
plane itself over ROI patterns via new _fit_origin_roi (ordinary LS
z = a + b*row + c*col per component, with sigma-clip passes to reject
outlier CoM), then assigns com_model.origin_fitted and zeroes the
residual outside the ROI (measured := fitted there) so
estimate_detector_rotation's curl isn't contaminated by junk patterns
either. Falls back to the full scan when scan_mask is None.

Other centering steps already respect the ROI: find_central_beams_4d
takes scan_mask, and the ellipse fit runs on the image_centers-centered
(ROI-only) mean DP.

Validated: with out-of-ROI junk + hot-pixel outliers, the global fit
leaves a -13 px uniform ROI residual; the ROI fit brings it to -0.005 px
and recovers the true plane exactly.
save_cartesian_peaks / save_polar_peaks / save_polar_data /
save_peak_intensities did np.save(vector). A canon Vector is array-like,
so numpy flattened it into an (Ry,Rx) object array of cells, losing the
Vector's fields/units. On load, .item() only unwraps a size-1 array, so
you got back a size-(Ry*Rx) object array instead of a Vector, and
polar_transform_peaks raised "can only convert an array of size 1 to a
Python scalar".

Add _save_object() which wraps the object in a 0-d object array so
np.save pickles the whole Vector; the existing size-1/.item() unwrap in
the load_* methods then restores it. Route all four save_* through it.

Note: files saved by the old code are already flattened and can't be
reconstructed (metadata lost) -- re-run find_peaks_model and re-save.
calculate_orientation_correlation sized its angular-mode batches from
torch.cuda.mem_get_info(), which reports memory free on the *device* and
is blind to torch.cuda.set_per_process_memory_fraction. Under a cap it
budgeted headroom the process was not allowed to allocate and then died
in fft2 with the card still mostly free: a 23.74 GiB cap against 60.65
GiB device-free raised OutOfMemoryError on a 100x100 scan at
orientation_upsample=8.

Headroom is now min(device_free, cap - memory_allocated). It is measured
against *allocated*, not *reserved*: cached blocks no tensor is using are
reusable, and after a failed run they can occupy most of the cap, which
would otherwise report a zero budget and refuse to run.

Also reserve room for theta_spectrum, which is allocated after the
estimate and was previously unaccounted, and retry once after
empty_cache() before giving up, so a failed run no longer poisons the
next attempt. The MemoryError now reports the cap, live usage, spectrum
reservation and device-free rather than a bare "0.00 GiB".

Tests: tests/diffraction/test_orientation_correlation.py, 10 passed.
Numerics unchanged, max relative difference 8.96e-08. Both failure modes
reproduced on GPU and confirmed fixed: a cap saturated with stale cache
now completes at 2.74 GiB under a 7.60 GiB cap, and a 1.14 GiB cap
degrades to 182 small batches instead of failing.
Replaces the central-beam/probe-blob ellipse fit with a ridge fit on the
diffuse ring. It measures the ring radius around every azimuth, jointly
refines the residual center and the ellipse, and accepts the correction
only when held-out angular sectors improve over a plain circle. Because
it never touches the central beam, descan-drift smearing and doubling of
the beam no longer bias the ellipse.

Adds _fit_ellipse_from_ridge with polar_at / extract_ridge helpers and
ellipse and circle residual models, wires it into preprocess() via
ellipse_fit_method, and records the outcome in ellipse_fit_diagnostics
(method, accepted, selected) alongside ellipse_ring_band.

Tests: tests/diffraction/test_ellipse_ring_fit.py plus
tests/diffraction/test_origin_finding.py, 21 passed.
The correlation-equals-one boundary saturates: on real data (pg3T2
07-03-2024 scan 61) ring pair (2,2) climbs from 33.8 degrees at zero
separation to 71.6 by mid-lobe, then flattens to 78.9. Fitting an
unweighted straight line over the whole lobe let that flat tail dominate,
which displaced the intercept off the measured boundary and biased the
slope low. The fitted intercept landed up to 6.99 degrees away, visibly
inside the blue region rather than on the gray baseline.

Weight the fit exponentially towards short distances so the reported
slope is the near-origin tangent, which is the physically meaningful
quantity. Intercept error against the measured boundary at zero
separation, across all six ring pairs:

  before  +0.66  +3.14  -6.99  +4.70  -3.66  +6.89   (max 6.99)
  after   -1.11  +1.40  -1.69  -1.09  +1.31  -1.39   (max 1.69)

The 1/e decay defaults to SLOPE_WEIGHT_FRACTION (0.10) times the fitted
distance span, chosen by sweeping the fraction against this dataset.
slope_weight_scale=numpy.inf restores the previous unweighted fit
exactly. R-squared is now weighted with the same weights and is not
comparable to the old value. Adds slope_fit_intercept_degrees,
slope_fit_effective_point_count (Kish) and slope_weight_scale to the
metrics so the fit can be checked numerically. The fit line is drawn
only out to three decay lengths, past which the boundary has saturated
away from the tangent.

Note this changes reported slopes, which were biased low: pair (2,2)
0.231 -> 0.371 deg/px (+61%), (1,1) +49%, (1,2) +46%, (0,2) -20%.
Previously exported slope values need regenerating.

Tests: tests/diffraction/test_orientation_correlation.py, 10 passed.
The polymer ice flagger only tested "bright and in the q band, on one
six-fold lattice". Three additions, each off by default:

Sharpness gate. Ice reflections are small and sharp; polymer signal is a
larger dot or a broad diffuse region. Peaks carry no width, so measure it
from the polar volume: radial/annular FWHM above a local baseline, at each
candidate's (r, theta). max_width_r_invA / max_width_theta_deg gate the q
band before the lattice search, so broad peaks neither get flagged nor drag
the phi estimate. sharpness_mode picks intersection ("both", compact dots)
or union ("either", which also keeps thin streaks). sharpness_mask is public
so a tuning preview applies the same rule instead of reimplementing it, and
collect_peak_widths / measure_ice_peak_widths report the widths to tune from.

Multiple crystallites. A pattern can hold several crystallites at unrelated
orientations; one pass only ever saw the strongest. The matcher now peels:
claim the best-supported lattice, remove its peaks, look again, up to
max_crystallites. min_phi_separation_deg stops a single lattice being
re-found as a near-duplicate. IceFlaggerDebug.phi_deg lists what was found.

Folded theta. process_polar(two_fold_symmetry=True) folds theta to [0,180),
collapsing every Friedel pair onto one angle -- so a pair scored one bin and
was rejected by min_matches=2, and arms 3-5 were unreachable, making
min_matches>3 silently impossible. The matcher is now period-aware
(theta_period_deg, read off the BraggPeaksPolymer), and detect_ice raises on
an unsatisfiable min_matches rather than matching nothing. min_peaks_per_arm
recovers the distinction folding destroys: 2 demands a Friedel pair on an
arm and rejects a lone peak.

Also: plot_q_intensity_density shades the candidate region as a rectangle
instead of drawing bare window edges.

Tests: 77 pass in tests/diffraction (28 new in test_polymer_ice.py).
Folding theta to [0,180) for two-fold symmetry discarded which half of the
circle a peak came from, so a Friedel pair became indistinguishable from two
peaks that merely sit close together. Peaks are small, so keep the full angle:
polar_transform_peaks now emits a "theta_unfolded" column alongside the folded
"theta". Nothing else reads it by position -- lookups go through
fields.index() -- so the extra column is transparent.

IceFlaggerParams.require_friedel_pair uses it: an arm counts only if it holds
two peaks whose unfolded angles differ by 180 +/- dtheta_deg. That is the test
min_peaks_per_arm can only approximate, since a count of two is also satisfied
by two neighbours within dtheta_deg. The field is optional -- detect_ice raises
a clear "re-run polar_transform_peaks" error only when the strict test is
requested on a vector that predates it.

Tests: 80 pass in tests/diffraction. test_bragg_peak_polar_transform_inverts_
ellipse_mapping updated for the new column, and now pins the field order.
Follow-up to the sharpness gate, from working it against a real polymer scan.

Annular width is the discriminator; drop sharpness_mode. Ice is annularly
sharp both as compact dots and as radial streaks (narrow in theta, extended in
q), while polymer at the same q is an annularly broad arc. The radial axis does
not separate ice from polymer -- dots and arcs measure alike there -- it only
separates streaks from dots, so a radial ceiling costs the streaks and buys
nothing. That makes the "both"/"either" combining rule pointless: with one
ceiling the modes are identical, and "either" silently defeated a tight annular
ceiling for any radially sharp peak. Ceilings are now simply ANDed.

Width measurement is noise-robust. The half-maximum walk stopped at the first
sample below half, so one downward fluctuation on a weak diffuse arc ended it
early: a true 40 degree arc measured 10-30 degrees at realistic SNR, i.e. as
narrow as ice. The profile is now Gaussian-smoothed (sigma 1 bin) and the
crossing must persist for 3 samples. The kernel is removed in quadrature --
exact for a Gaussian convolved with a Gaussian, which is why it is a Gaussian
and not a boxcar; a boxcar leaves a residual bias on sharp peaks. Median over 8
seeds, true 40 degrees at SNR 2: 10.5 -> 43.6, while a true 5 degree peak stays
at 6.0. Also widened the annular window to 90 degrees and dropped the baseline
quantile to 0.05, since a window the feature fills puts the baseline partway up
it and saturates the measurement near 39 degrees.

Parameters validate on construction. Every confusion this cost came back as
"nothing was flagged" rather than an error.

Module docstring now states the four criteria and the folding constraints.

Tests: 89 pass in tests/diffraction. The synthetic polar fixture sampled q at
0.025 1/A per bin, too coarse for the default radial window; now 0.005.
…ce flagger

Choosing IceFlaggerParams against a real dataset needs plots, not just the
algorithm: a selection box over the sharpness ceilings, ice-band orientation
histograms for all/kept/removed peaks, a widget view of either side of the
split, and a per-peak FWHM probe that shows the cuts each width is measured
from. These started as notebook cells, which meant every scan directory
carried its own drifting copy; in the package any notebook can import them.

Free functions taking (bp, params) explicitly rather than methods on
BraggPeaksPolymer, which is already 79 methods. The algorithms stay in
polymer_ice; this is only the interactive layer. Nothing mutates bp --
IcePeakView delegates to it so the widget can show a peak subset without the
caller's object being altered. The quantem.widget import is deferred into the
one function that needs it, so the module imports without that package.
None of this was polymer-specific. Measured inside exact AST method boundaries,
the calibration cluster referenced `self` only to reach a Dataset4dstem, a peak
Vector, a device string, and a slot to deposit diagnostics into -- all general
core types. The two ellipse fitters take a plain 2D array and a centre, so they
apply to any diffuse or crystalline ring from any instrument; `_fit_origin_roi`
did not reference `self` at all.

New `ellipse_fitting.py` holds `fit_ellipse_from_ring` (angular variance) and
`fit_ellipse_from_ridge` (joint centre + ellipse), returning an `EllipseFit`
dataclass. Returning the fit instead of assigning `self.ellipse_fit_diagnostics`
was what actually completed the extraction: that assignment was the only thing
tying 837 lines of arithmetic to the class. `EllipseFit.diagnostics` rebuilds
the flat mapping the class has always published, so `bp.ellipse_fit_diagnostics`
keeps its exact key set -- pinned by new tests for both methods.

Origin/descan work moves to `polar_transform.py`, which already owned three
origin finders, rather than to a third location: `find_central_beams_4d`,
`find_central_beams_from_peaks_4d`, `fit_origin_roi`, `centered_dp_mean`. The
dataset, peaks and device are now parameters. `find_central_beams_4d` stays on
the class as a forwarding wrapper since it is public API; every internal caller
already used keyword arguments.

BraggPeaksPolymer: 79 -> 74 methods, 6798 -> 5691 lines. bragg_peaks.py drops
below 8k. test_ellipse_ring_fit.py no longer constructs the class via
object.__new__ to reach the fitters; the one remaining use there legitimately
exercises preprocess argument validation.

Tests: 488 passed, 10 skipped across the full suite (102 in tests/diffraction).
Verified separately that both fitters still recover a synthetic ellipse
(true ratio 1.111 -> 1.105 ring / 1.117 ridge; true theta 35 deg -> 36.0 / 35.3).
Second extraction, same pattern as the calibration one. New
`peak_visualization.py` holds the seven plotting functions whose only tie to the
class was reading one or two attributes: the radial intensity and count
profiles, the per-position count and histogram maps, the interactive pattern
browser, figure export, and the pattern grid. They take the arrays and peak
vectors they draw, so they work for any 4D-STEM dataset.

All seven are public API and three appear in 51 notebooks, so each keeps a
forwarding method on the class. The wrappers take *args/**kwargs and prepend the
data, which preserves positional calls -- verified that the notebooks'
`bp.plot_peak_count_map(peak_windows, return_values=True)` still lands
`peak_windows` on `q_ranges`.

Five shared module-level helpers moved too. The three display helpers
(`_normalized_dp`, `_resolve_intensity_map`, `_intensity_display_limits`, plus
`_mean_intensity_map`) live with the plots and are imported back for the three
peak-overlay methods that stay. The two ragged-Vector field accessors went to a
new `vector_fields.py` instead: they are needed by `estimate_peak_windows` and
`make_orientation_histogram`, which are not visualization, and importing them
from a plotting module would have been the wrong direction -- or a cycle.

Found and fixed a bug the extraction introduced: threading
`self.peak_coordinates_cartesian` in as `peaks` turned
`peaks = self.peak_coordinates_cartesian[i, j].array` into `peaks = peaks[i, j]
.array`, shadowing the parameter and failing on the second scan position. Only
two of the seven functions had any test coverage -- including none of the three
used by 51 notebooks -- so this was invisible. Added
`test_peak_visualization.py` covering the five untested ones through both entry
points, which is what caught it, and AST-scanned the rest for the same
shadowing pattern (no others).

Also repaired `test_bragg_plotting_and_save_smoke`, which monkeypatched
`interactive_output` on `bragg_peaks` only; `plot_interactive_image_map` now
resolves it from `peak_visualization`, so the patch had silently stopped
applying. It now patches both modules.

BraggPeaksPolymer: 5691 -> 4812 lines (79 -> 74 methods across both steps, since
the public plotting entry points remain as wrappers). bragg_peaks.py 7103 ->
6162, down from 8206 at the start.

Tests: 495 passed, 10 skipped.
Written before the orientation extraction so it pins current behaviour rather
than post-extraction behaviour. make_flowline_map and make_flowline_rainbow_image
appear in 51 notebooks each and had no tests; make_flowline_combined_image,
make_flowline_rainbow_legend and the two intensity helpers had none either -- 678
lines with no coverage, which is what let a shadowing bug through in the previous
extraction.

Covers the pipeline end to end on a small synthetic orientation histogram with a
coherent stripe (a uniform histogram seeds no flowlines), plus a set/get
round-trip for the interpolating intensity helpers.

Note the flowline map is asserted to be *concentrated* in the seeded band rather
than exactly zero outside it: the tracer steps along directions and set_intensity
spreads weight across neighbouring bins, so a little legitimately bleeds out.

Tests: 112 passed in tests/diffraction.
Third extraction. The cleanest cluster yet: of the 1564 lines, 678 referenced
`self` not once -- the three flowline renderers and both intensity helpers were
methods purely by accident. Nothing in it is polymer-specific; orientation
histograms and flowlines apply to any material with anisotropic scattering.

New `orientation.py` holds the pipeline -- make_orientation_histogram (threaded
polar_peaks + peak_intensities), make_flowline_map, and the rainbow/combined/
legend renderers -- plus `_get_intensity`/`_set_intensity`, now private module
helpers rather than public methods, which removes make_flowline_map's only tie to
the class. `plot_orientation_correlation` went to `orientation_correlation.py`
beside `calculate_orientation_correlation`, taking SLOPE_WEIGHT_FRACTION with it.

All eight public names keep forwarding methods.
`plot_orientation_correlation`'s wrapper preserves its self-fallback, so
`bp.plot_orientation_correlation()` with no arguments still plots the volume the
object last computed. `calculate_orientation_correlation` stays put: it writes
orient_corr/orient_corr_pairs onto the object, and already delegated its maths.

Verified per the protocol in dp_peak_detection's HANDOFF:
- Baseline tests written FIRST (e80ffa7) for the 678 previously uncovered lines.
- AST scan for rebinding of injected parameter names: none.
- refactor_diff_check.py: 23/23 bit-identical against baseline 1265551, the seven
  new orientation checks included.

One bug caught by the baseline tests: the generated wrapper prefixed `_` onto the
already-underscored `_set_intensity`, producing `__set_intensity`, which Python
name-mangles inside a class body. Fixed. Exactly the class of failure the
tests-first ordering is meant to catch, and it would have been invisible before
e80ffa7 since these had no coverage.

BraggPeaksPolymer: 4812 -> 3296 lines. bragg_peaks.py 6162 -> 4648, from 8206 at
the start of the refactor.

Tests: 500 passed, 10 skipped.
Written before extracting them. Neither resize_images nor _postprocess_single had
any tests, and between them they bracket the whole ML detection path: one prepares
every pattern for the network, the other turns its two output channels into peak
coordinates and intensities.

test_resize_images_shape_and_intensity_convention pins the existing intensity
convention rather than the one I expected. Bilinear interpolation to half the
linear size already divides the sum by 4; the code then multiplies by
scale_factor = (16*16)/(32*32) = 1/4 as well, so the total comes out 16x smaller.
Count conservation would need the reciprocal (x4). Presumably this matches the
convention the network was trained under -- pinned as-is, deliberately not
changed, and called out in the docstring so the next reader does not assume the
sum is preserved.
Fourth extraction, and a deliberately small one -- the honest finding here is how
little of this cluster should move.

Of the 617-line ML cluster, only 115 lines are cleanly extractable:
resize_images_for_model (prepares patterns for the network; read only
self._final_shape) and peaks_from_model_output (turns the two output channels into
coordinates and intensities; referenced self not at all). Both go to
peak_detection.py beside the blob detection and refinement they feed into, so the
module now covers the whole detection path rather than just its middle.

The other nine stay, and should. find_peaks_model, infer_peaks_single,
adapt_batchnorm, ensure_normalization_params, set_model_weights,
_infer_train_batch_output, _invalidate_inference_caches, prepare_inference and
resize_data read AND write instance state -- the model, the resolved
normalization parameters, the BatchNorm-adaptation flag, the live chunk cache.
That is a model lifecycle, which is what an object is for; free functions would
mean threading a mutable context through all of them, which is worse than the
class. save_peak_animation also stays: it calls infer_peaks_single and shares
seven peak-overlay drawing helpers with plot_interactive_peak_map and
save_peak_figures, so it belongs with that group's render-context decision.

Verified per protocol: baseline tests first (b199e4d), AST scan for
injected-parameter shadowing (none), refactor_diff_check.py 26/26 bit-identical.

BraggPeaksPolymer: 3296 -> 3193 lines. bragg_peaks.py 4648 -> 4550.

Tests: 504 passed, 10 skipped.
A survey of what was left in bragg_peaks.py turned up something the earlier
cluster analysis had missed entirely: ScanMaskEditor is a *separate* 885-line
class with 46 methods, sharing the file with BraggPeaksPolymer for no reason. Its
only mention of BraggPeaksPolymer is a button tooltip string, and it uses none of
the module's helpers. So this is a file split rather than a refactor -- no
signature changes, no parameter threading, no shadowing risk.

bragg_peaks.py now contains exactly one class. 3663 lines, from 8206 when the
refactor started.

All three import paths still resolve to the same object, verified:
quantem.diffraction.ScanMaskEditor (what the tests use),
quantem.diffraction.bragg_peaks.ScanMaskEditor (preserved by the import that
edit_scan_mask needs anyway), and the new
quantem.diffraction.scan_mask_editor.ScanMaskEditor.

edit_scan_mask and create_interactive_circular_mask stay on the class: the editor
is constructed as ScanMaskEditor(self), so those are factories bound to the
analysis whose mask they edit, which is a legitimate reason to be a method.

Tests: 504 passed, 10 skipped. ScanMaskEditor already had coverage
(test_scan_mask_editor.py), so no new baseline tests were needed for this step.
The 16x shrink has no effect on results, and not merely by train/inference
consistency -- the factor is annihilated. Resize precedes normalization
everywhere, and every normalization strategy here starts with a per-image
min-max, which is invariant under positive uniform scaling. Both reported
intensity fields are post-normalization, so no pre-normalization absolute
intensity reaches any output.

Replaces the speculative note with the proof, and records the one genuinely
latent concern: scale_factor depends on input detector size, so a future
normalization with a fixed absolute divisor would make it matter, differently
per dataset.
Written before extracting it. estimate_peak_windows appears in 51 notebooks and
had no tests, and it decides the q-windows that every count map, radial profile
and flowline family downstream is computed over -- a silent change would shift
every result without failing anything.

Covers recovery of three injected radial families, window bracketing and clipping
plus the min_width floor, intensity/count mode agreement under uniform
intensities, log compression, the empty-result shapes, and mode validation. Also
pins the peak_info key set including the profile/intensity_profile alias, which is
the same array under two names and easy to drop by accident when moving code.

@cedriclim1 cedriclim1 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reduce line count, check code duplication, and create a stacked PR if it's going to be a big PR please (i.e, chunk it in easily reviewable parts).

BraggPeaksPolymer is now a BraggVectors subclass: the network fills the same
(q_row, q_col, intensity) peaks, and origins, calibration, plots and saving come
from dev. The amorphous ring calibrates the ellipse through
fit_elliptical_distortion (new n_harmonics for textured rings) and
DiffractionCalibration (new ellipse_from_axes), so q and theta are in the scan
frame. Orientation, flowline, correlation and ice code is rewritten on the
calibrated (q, theta, intensity) peaks.

Fixes the default preprocess and find_peaks_model crashes, the model-to-detector
offset, flowlines near 0 degrees and the frozen forward direction, the 360 vs
60 degree ice fit, peak-window prominences, and IceDetectionResult.filter with a
scan mask. Tuning plots, scan-mask shapes and PDF/GIF export move to
quantem.widget; CONTRIBUTING.md now says what belongs there. The core CNN2d
change is reverted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@NJMarchese

Copy link
Copy Markdown
Collaborator Author

Reduced PR line count by incorporating existing functions in quantem as per @cophus PR. Re-implemented ice detection, some graphical non-widget visualizations, and adjustments to calibration. Added a multi-seed mode for elliptical ring fitting as an optional mode as there were failure cases which the default method did not fit properly. Also added a check to see if fit is at edge of bounds, indicating bounds need to be widened.

Changes

  • fit_elliptical_distortion(..., multi_seed=False) (ellipticity.py). This option is opt-in, and the default behavior is unchanged.
    • With multi_seed=True, the ring radius is seeded every 2 px across fit_radii. The fit kept is the lowest-cost one whose radius isn't pinned at the edge of the band.
    • The result now includes at_edge, which is true when the fitted radius is within 1% of the band width from either edge. A ring pinned at the edge means the fit failed.
    • multi_seed can't be combined with p0.
  • calculate_orientation_correlation (orientation_correlation.py). Some memory changes and GPU implementation.
    • With device=None, it now uses the input tensor's device, else CUDA if available, else CPU.
    • Modes are processed in batches sized to fit max_memory_fraction (default 0.6) of free GPU memory, or you can set mode_batch_size yourself. On CPU the default batch is 8.

Polymer pipeline

  • Ring calibration
    • calibrate_amorphous_ring passes multi_seed through, and raises if the ring fit ends at the edge of fit_radii, which means the band needs to be wider.
    • It also takes rotation_ccw_deg and transpose, as an alternative to the scan-rotation metadata on the dataset, as sometimes this metadata does not contain that information and defaults to 0.
  • Origins: the default is now bp.find_origins(), which wraps find_origin_angular_descent.
  • Ice peak widths
    • Widths are measured in the ellipse-corrected frame, in 1 px steps along the arc, and summed with the Friedel-opposite profile (IceFlaggerParams.sharpness_friedel_sum, default True).
    • The new bp.measure_peak_widths(params) measures them once, and bp.detect_ice(params, peaks=...) reuses them, rather than regenerating.
  • Orientation histogram: smoothing uses scipy.ndimage.gaussian_filter1d in place, instead of a float64 padded copy of the whole histogram. More memory efficient and faster.
  • polar_peaks: the intensity is labeled a.u.. It is the network's output, not detector counts, as counts is not always true.
  • Peak count maps (# of peaks): peak_maps(mode="count") shows the full range, with one color per integer count.
  • bp.save
    • The network is no longer written into the file (it was 57 MB per results file).
    • load_model records the weights file's path, SHA-256 and architecture in metadata["model"].
    • save(..., include_model=True) keeps the network if desired.
  • Static figures restored on the new peaks API:
    • polymer_ice.plot_q_intensity_density, selection_box and orientation_histograms;
    • bp.save_peak_figures: the scan map, the annotated pattern, and a polar panel from the existing polar_transform.
    • Interactive viewers stay in the widget PR. These are non-interactive figures and exports. May be phased out in a future PR.

Moving settings over from the earlier version of this PR

Most settings keep their names. These changed:

Earlier Now
make_orientation_histogram(..., orientation_offset_degrees=x) the scan rotation is part of the calibration: calibrate_amorphous_ring(..., rotation_ccw_deg=-x), or q_to_r_rotation_ccw_deg = -x in the dataset metadata
make_orientation_histogram(..., orientation_flip_sign=...) removed; theta is atan2(q_row, q_col) in the scan frame
IceFlaggerParams(max_width_r_invA=...) max_width_q_invA
IceFlaggerParams(sharpness_window_r_invA=...) sharpness_window_q_invA
IceFlaggerParams(intensity_cutoff=c, intensity_cutoff_mode="absolute") intensity_cutoff=c; leaving it None uses intensity_percentile_global
IceFlaggerParams(theta_period_deg=...) removed; the six-fold test always folds theta modulo 180 degrees (three arms)
bp.plot_q_intensity_density(intensity_field=..., cutoff=..., q_value=..., q_window=...) polymer_ice.plot_q_intensity_density(peaks, params)
polymer_ice_tuning.selection_box(bp, params, max_width_r_invA=...) polymer_ice.selection_box(bp.measure_peak_widths(params), params, max_width_q_invA=...)
polymer_ice_tuning.orientation_histograms(bp, result, params, orientation_offset_degrees=...) `polymer_ice.orientation_histograms(peaks, result

Note on rotation. orientation_offset_degrees was added to each peak angle. rotation_ccw_deg rotates the peak vectors counter-clockwise, which subtracts it from atan2(q_row, q_col). The same correction is therefore rotation_ccw_deg = -orientation_offset_degrees; passing the old value unchanged turns every orientation by twice that angle.

"""Load network weights, by default into :func:`polymer_model`.

The weights file's path, SHA-256 and the network's architecture are
recorded in ``metadata["model"]``, which :meth:`save` keeps in place of

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:meth: lmao

@cedriclim1 cedriclim1 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall LGTM - thanks for decreasing the line count.

Higher-level question for @arthurmccray or @cophus - what do you guys think about submoduling src/quantem/diffraction? There's a decent amount of files here now where it's getting hard to figure out where things live. For example, I'm thinking perhaps doing like src/quantem/diffraction/polymer, and other submodules. I'm just curious what your guys's thoughts are since so many people are working with diffraction analysis, submoduling kind of makes sense here to keep people from stepping on each other's toes and discussion for what could be globally used across the other submodules.

I think with proper submoduling, @NJMarchese could probably do some proper organization work, e.g., since there are so many visualization functions across multiple files can probably be consolidated to one file.

I'll wait on @arthurmccray to do light go over before approving.

@arthurmccray arthurmccray left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall looks pretty good to me! I left a few inline comments, but the biggest thing for sure is submoduling @cedriclim1. I think it makes sense to do so for the polymer stuff now and leave ACOM and other submodules to later. It'll only get messier and harder if we wait til after this merge happens.

Generic code can and should stay top level, and not get moved into submodules. I'm thinking something like this?

diffraction/polymer/
    __init__.py        # BraggPeaksPolymer, IceFlaggerParams, detect_ice
    peaks.py           # BraggPeaksPolymer
    ice.py
    visualization.py   # all polymer figures in one place
tests/diffraction/polymer/

There is also a little confusion between orientation for the purpose of flowlines and ACOM. The orientation correlation stuff is general and should be top level, but what it means by "orientation" is different than ACOM orientations, so that could lead to problems. I'm not entirely sure the best solution to this

"""Flag crystalline-ice reflections among peaks detected in polymer 4D-STEM diffraction.

Ice contaminating a polymer scan gives six-fold sets of sharp reflections. Its
strongest ring (d ~ 3.66 A) overlaps the pi-pi stacking peak, so q alone cannot

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this consistent with our unit conventions elsewhere? I thought we were measuring q vectors in 1/A? maybe just a typo idk. I guess just take this comment as a "let's doublecheck units"

Comment on lines +305 to +306
x = np.clip((rows + 0.5) * upsample_factor - 0.5, 0, size[0] - 2)
y = np.clip((cols + 0.5) * upsample_factor - 0.5, 0, size[1] - 2)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are we clipping -2? Shouldn't it be -1?

return fig, ax


def selection_box(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't this be in polymer visualization? has a plt.show() call

return p


def orientation_histograms(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this as well should probably be in viz?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants