Repository navigation
Polymer ml - #325
Polymer ml#325NJMarchese wants to merge 71 commits into
Conversation
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
left a comment
There was a problem hiding this comment.
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>
…fit at the band edge to select wider band
…ing so have alternative to reading off of dataset metadata
…atch to speed up correlation calculations
… weights by saving independently
|
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
Polymer pipeline
Moving settings over from the earlier version of this PRMost settings keep their names. These changed:
Note on rotation. |
| """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 |
cedriclim1
left a comment
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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"
| 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) |
There was a problem hiding this comment.
Why are we clipping -2? Shouldn't it be -1?
| return fig, ax | ||
|
|
||
|
|
||
| def selection_box( |
There was a problem hiding this comment.
shouldn't this be in polymer visualization? has a plt.show() call
| return p | ||
|
|
||
|
|
||
| def orientation_histograms( |
There was a problem hiding this comment.
this as well should probably be in viz?
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 currentdevand ported to dev's APIs.What it does
BraggPeaksPolymertakes aDataset4dstemof a semicrystalline polymer film through these steps:polymer_models.py) predicts peak position and intensity maps. Peaks are then found by local maxima with subpixel refinement (peak_detection.py).ellipse_fitting.py, ridge or angular-variance method), and conversion to 1/Å from the dataset's calibration.polymer_polar.py, built on dev'spolar_transform).polymer_ice.py), with tuning helpers (peak widths, selection boxes, histograms) inpolymer_ice_tuning.py.polymer_orientation.py), and spatial orientation correlation with distance and slope metrics (orientation_correlation.py).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,Dataset4dstemandelectron_wavelength_angstrom.Layout
src/quantem/diffraction/. The only existing file changed there isdiffraction/__init__.py, which gains the new exports.core/ml/cnn.py:CNN2dgainsconv_kernel_size(positive odd integer, default 3, paddingk // 2, applied to every conv including the output conv). The default network is unchanged: same state-dict keys and identical outputs to dev's.MultiChannelCNN2dinpolymer_models.py) subclasses coreCNN2d, adding per-channel output activations.polymer_polar.pyand the polymer orientation code is inpolymer_orientation.py, so dev's sharedpolar_transform.pyandorientation.pyare untouched.CONTRIBUTING.md, the viewers (show_polymer_4DSTEM,ice_split_widget) and a scan-mask editor go toquantem.widgetin a separate PR. They take aBraggPeaksPolymeras input and build onscan_mask.py.Replication
The code implementation replicates results from the ML paper for the model and associated dataset.