Skip to content

Optimized integrator + reflection tables - #86

Merged
PrinceWalnut merged 69 commits into
mainfrom
integrator
Sep 18, 2026
Merged

PrinceWalnut merged 69 commits into
mainfrom
integrator

Conversation

@PrinceWalnut

Copy link
Copy Markdown
Member

This is a vectorized implementation of @kmdalton's old integrator code. Some updates have also been added, like writing reflection table files in addition to MTZ files when requested by user, fixing numerical issues with intensities near 0, and trimming profile windows to the image.

@PrinceWalnut

Copy link
Copy Markdown
Member Author

@LuisA92 can you verify that this works and has all the output data you would need in the MTZ + reflection table?

return cls(x, y, counts, **kwargs)
@property
def windows(self):
return self.pixels[*self.window_idx]

@LuisA92 LuisA92 Aug 11, 2025 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I get the following syntax error for this line:

Traceback (most recent call last):
  File "/n/holylabs/hekstra_lab/Users/laldama/micromamba/envs/ld/bin/laue.integrate", line 5, in <module>
    from laue_dials.command_line.integrate import run
  File "/n/netscratch/hekstra_lab/Lab/laldama/ld_prf/laue-dials/src/laue_dials/command_line/integrate.py", line 23, in <module>
    from laue_dials.algorithms.integration import Integrator
  File "/n/netscratch/hekstra_lab/Lab/laldama/ld_prf/laue-dials/src/laue_dials/algorithms/integration.py", line 60
    return self.pixels[*self.window_idx]
                       ^
SyntaxError: invalid syntax

Steps I followed :

  1. git clone https://github.com/rs-station/laue-dials.git
  2. pip install -e .
  3. cd laue-dials
  4. gh pr checkout 86
  5. laue.integrate /n/netscratch/hekstra_lab/Lab/laldama/ld/hewl_1118/integrated/poly_refined_HEWL_anom_3049.expt n/netscratch/hekstra_lab/Lab/laldama/ld/hewl_1118/integrated/predicted_HEWL_anom_3049.ref

Using python version 3.10.18

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@LuisA92 what Python version are you using? This example is using * unpacking, since self.window_idx should be a tuple I believe. I think this may be a Python 3 feature missing in Python 2 -- I'd need to look it up

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@PrinceWalnut I'm using python version 3.10.18

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@LuisA92 I've made a commit that should fix this issue -- can you pull and verify that you no longer get syntax errors?

@PrinceWalnut

Copy link
Copy Markdown
Member Author

Let's add all of the docstrings back -- I'll take care of that

@LuisA92 LuisA92 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The reflection table columns match our discussion, and the integrator runs fine!

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey Rick, I get a complete reflection table with the output.reflections=filename.refl flag. Here are the outputs I get

from dials.array_family import flex

tbl = flex.reflection_table.from_file('filename.refl')
print(list(tbl.keys()))

#Out:
['background.sum.value',
 'background.sum.variance',
 'entering',
 'flags',
 'id',
 'imageset_id',
 'intensity.sum.value',
 'intensity.sum.variance',
 'miller_index',
 'panel',
 'phi',
 'profile.correlation',
 'rlp',
 's1',
 'strong',
 'wavelength',
 'xyzcal.mm',
 'xyzcal.px',
 'xyzobs.mm.value',
 'xyzobs.mm.variance',
 'xyzobs.px.value',
 'xyzobs.px.variance']

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I no longer get the syntax error, and I am able to use the new integrator.

Here are the steps I followed:

# installing laue-dials
micromamba create -n ld python=3.10
micromamba install -c conda-forge dials
micromamba install -c conda-forge gh
git clone https://github.com/rs-station/laue-dials.git
cd laue-dials 
pip install -e . 
gh pr checkout 86

# running laue.integrate
laue.integrate /n/netscratch/hekstra_lab/Lab/laldama/ld/hewl_1118/integrated/poly_refined_HEWL_anom_3049.expt  /n/netscratch/hekstra_lab/Lab/laldama/ld/hewl_1118/integrated/predicted_HEWL_anom_3049.refl
 

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@kmdalton @PrinceWalnut Bumping this PR.

Would we be able to merge this onto main? I'm writing a tutorial for a student to generate a PyTorch dataset from a laue-dials reflection table

PrinceWalnut and others added 7 commits June 17, 2026 09:57
Remove no-op np.zeros() calls, stray pass statement, dead-result
attribute accesses, and commented-out debug/plot code. Add comment
clarifying that background.sum.variance equals background under
Poisson noise.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
A background of exactly zero combined with non-positive intensity causes
v=0 in predict(), leading to division by zero in the optimal weight
computation. Flooring at 1e-6 reflects that real detectors always have
some dark current and guarantees v>0 without distorting pixel weights.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The previous clamp used np.max(pixels.shape) for both axes, which
allows out-of-bounds row indices on non-square detectors. Negative
indices from spots near the top or left edge were also unclamped,
causing silent wraparound to the wrong image corner. Replace with
per-axis np.clip against the correct row and column bounds.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
size was accumulated each iteration but never read. The convergence
check also referenced len(size) instead of len(obj); replace both
with obj alone.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Neither self.pixel_variance nor self.kdist were read anywhere after
being set.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Call rectify() at the end of integrate() to constrain intensity and
uncertainty to positive support via a truncated normal distribution,
rather than leaving negative intensities unconstrained.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
PrinceWalnut and others added 12 commits July 21, 2026 03:06
skimage.morphology.isotropic_dilation relies on scipy's
distance_transform_edt, which has no real background reference point
when the input mask has no True (bad) pixels at all -- the case when
no mask file is supplied. This caused a small region near pixel (0, 0)
to be spuriously marked as masked. Mark a genuine 1px border around the
detector edge as invalid in that case, and shrink the dilation radius
by 1 to compensate, so the resulting edge buffer matches the requested
integration_radius exactly.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NGvfz3AR51mt3FZJfgRmVC
Split the radius estimation and mask-dilation selection out of
filter_masked_predictions into estimate_integration_radius() and
unmasked_prediction_selection(), which operate on plain numpy arrays
instead of dxtbx objects. This makes the masking math (including the
edge-buffer fix) directly unit-testable without needing real detector
image data.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NGvfz3AR51mt3FZJfgRmVC
Cover estimate_integration_radius() and unmasked_prediction_selection(),
including a regression test for the no-mask-file edge case where an
unbuffered detector boundary previously let isotropic_dilation
spuriously mask a small region near pixel (0, 0) instead of properly
buffering the detector edges.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NGvfz3AR51mt3FZJfgRmVC
predict.py uses skimage.morphology.isotropic_dilation but scikit-image
was missing from install_requires, so a fresh install would fail at
runtime. Add it to setup.cfg and docs/requirements.txt.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NGvfz3AR51mt3FZJfgRmVC
Extends the integrator test suite from constructor-only coverage to
execution and regression testing.

Unit/execution tests (tests/algorithms/test_integration.py):
- End-to-end Integrator.fit() execution on synthetic Gaussian spots
- Window geometry, dynamic/explicit radius, and edge-clamping
- assign_knn guards for too-few strong spots
- Regression test for the profile-weight sign bug (negative numerator and
  denominator no longer yield a spurious positive weight)
- cov/mvn_log_pdf coverage for return_mean, return_zscore, invalid ddof

Regression test (tests/regression/test_integration_regression.py):
- Downloads two DHFR patterns from SBGrid (dataset 1117) via rsync,
  runs laue.integrate, and correlates against a Precognition reference
- xfail when SBGrid is unreachable; fails only on a genuine CC regression
  (Pearson CC >= 0.95; baseline ~0.978 over ~2200 matched reflections)

Fixtures (tests/data/regression/): version-controlled refined geometry,
predictions, gzipped detector mask, and Precognition reference; raw images
are not version controlled. README documents provenance. Registers a
"regression" pytest marker.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01G5EhoPs6pYqVcZgKsd79Kz
@PrinceWalnut

Copy link
Copy Markdown
Member Author

i think the integrator test only tests the constructor. i think we need to add tests at least for execution (and ideally regression) for integration.

for the regression test, download and integrate 2 of the dhfr patterns and compute the CC to precog integration results from a table. i think you should

  • not version control the images
  • okay to version control a stills expt file and maybe a refl table

as per our discussion, you can download 2 files directly from sbgrid. if sbgrid is not reachable, you want to xfail the test. if there is an actual performance regression, you want to fail. otherwise pass.

Added significant amount of testing this morning. Uses version-controlled refined experiment data with predicted reflections and does regression testing on the integrator. The remainder of the pipeline is not regression-tested yet -- will save that for a separate PR.

Also added a PHIL parameter for integration radius and a fix for the resultant corner-masking that occurs when no mask file is added for prediction by setting the pixels on the edge of the detector to a mask. This should also prevent reflections near the edge of the detector from becoming partially recorded into the integrated files as well.

@kmdalton could I get a final review on this?

@kmdalton kmdalton left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think we need
The Integrator class's constructor

Comment thread src/laue_dials/command_line/predict.py Outdated
return final_preds


def estimate_integration_radius(x, y):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this is duplicate code with the IntegratorBase constructor. it should be refactored into a single method used by both.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Eliminated from the prediction code entirely. Now only in the integrator. No longer duplicate

Comment thread src/laue_dials/command_line/predict.py Outdated
return expanded_mask_flat[x + img_row_size * y]


def filter_masked_predictions(preds, expts, integration_radius):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

there is a subtle bug with this function and how it plays with integration. this only applies when both steps (prediction & integration) automatically estimate the integration radius using the 20th percentile inter-spot distance heuristic. in this method you filter spots assuming an integration radius which is estimated from the set of predictions. then you remove some spots which are too close to a panel edge or other masked feature. this means that the integration radius estimated by the Integrator class will see a different set of spots and estimate a different radius. if the new radius is larger, it is possible that some of the integration windows will include masked pixels or pixels outside the detector. this is a serious bug that will probably cause the program to crash in some cases. i can't think of a clean mitigation that maintains the separation between filtration and integration. some options are

  • pass the integration radius down from prediction to integration somehow
  • apply the mask during integration rather than prediction (preferred)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch. Moved the mask dilation to the integrator instead. The same radius is used for dilation and for the integration windows. The predictor now only filters reflections whose centroids lie directly on masked pixels, but makes no attempt at dilation.

PrinceWalnut and others added 4 commits July 29, 2026 12:44
Previously laue.predict dilated the detector mask by a radius estimated from
the full predicted set, while laue.integrate estimated its integration-window
radius from the mask-filtered set. The two radii were derived from different
spot populations and could diverge, so an integration window could reach into
masked pixels the dilation was sized to exclude.

Consolidate the radius-dependent masking in laue.integrate, which now estimates
a single radius from the predicted set and reuses it for both the mask dilation
and the integration window. Dilation radius == window radius by construction, so
no surviving centroid's window can overlap a masked pixel.

laue.predict now performs only the radius-independent step: dropping predictions
whose centroid lands directly on a masked pixel. The shared radius/mask helpers
(estimate_integration_radius, unmasked_prediction_selection) move to
laue_dials.algorithms.integration.

Regenerate the regression fixtures on images 15/16 (both refine below half a
pixel: 0.421/0.436 px) with the new pipeline; baseline Pearson CC vs
Precognition is 0.977 over ~2290 matched reflections. Add regenerate_fixtures.sh
documenting the full generation sequence.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01G5EhoPs6pYqVcZgKsd79Kz
@PrinceWalnut

Copy link
Copy Markdown
Member Author

@kmdalton your concerns above were fixed. @LuisA92, we've made some minor changes to the predictor. It should not differ substantially from what is in the main branch now, but I'd appreciate if you could test your integrator with this just to be sure we don't break your pipeline.

PrinceWalnut and others added 10 commits July 30, 2026 12:05
The isigi_cutoff PHIL parameter was accepted by integrate_image and then
dropped at the Integrator construction site, so the class default always
won and the documented parameter had no effect.

Forward the parameter, and set the PHIL default to 3.0 to match the
Integrator default so this fix does not silently change results: the
cutoff feeds set_strong, which selects the KNN pool used for profile
estimation, so lowering it to the previous PHIL value of 2.0 shifted
1139 of 1633 intensities on a test image.

Verified against the Precognition regression fixtures: CC 0.976932 over
2293 matched reflections, unchanged from before the fix.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K65DxQwivJNYwEW4CAWHDZ
The help message still described the old SegmentedImage algorithm, which
summed counts inside a hard elliptical mask and averaged neighboring
profiles in a post-hoc pass. The current integrator instead fits an
elliptical Gaussian profile on a flat background under a Poisson noise
model and derives intensities by profile fitting.

Also document the two behaviors users are most likely to be surprised by:
profile shapes are pooled from the k nearest strong spots, and the
integration radius defaults to one estimated from centroid spacing and is
reused to dilate the detector mask.

This text is rendered into docs/cli/integrate.rst and shown by --help.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K65DxQwivJNYwEW4CAWHDZ
The number of nearest strong spots pooled for profile estimation and the
number of profile-fitting iterations were both hardcoded, reachable only
by constructing an Integrator directly. Neither is obviously correct for
every dataset: knn trades profile stability against genuine variation in
spot shape across the detector, and the fit is often still improving when
it stops.

Thread both through integrate_image, keeping the previously hardcoded
values as defaults (knn=5, maxiter=2), so results are unchanged unless a
user opts in. Verified on the Precognition regression fixtures: defaults
give CC 0.976932 over 2293 reflections, identical to before.

The help message referred to "k nearest strong spots" while no such
parameter existed in the PHIL scope; it now names knn and maxiter, both
of which users can set.

Generalize the forwarding test to cover all four tuning parameters, since
the isigi_cutoff bug it was written for could recur with any of them.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K65DxQwivJNYwEW4CAWHDZ
estimate_integration_radius built a full pairwise distance matrix and
sorted every column, to read one element per column. That is O(n^2) in
both time and memory when only each spot's nearest neighbor is needed:
21 MB at the 1633 predictions in the regression fixture, but 512 MB at
8000 spots, and that cost is paid per worker when nproc > 1.

A KDTree prunes to the nearest neighbor via the splitting-plane bound,
giving the same exact answer in O(n log n). Measured on uniform points,
it is 25x faster at n=1000 and 427x at n=8000, with the gap widening
since the two curves separate rather than differing by a constant.

The result is unchanged, not merely close: the existing formula test
re-derives the expected radius with pdist and still passes, the fixture
images still yield radii of 11 and 10, and the Precognition regression CC
is identical at 0.976932 over 2293 reflections.

assign_knn already used a KDTree for the same kind of query, so this also
makes the module internally consistent.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K65DxQwivJNYwEW4CAWHDZ
fit() evaluated self.score at the top of the loop, before that iteration's
updates were applied, so obj[-1] described the previous state. A stall was
therefore detected one iteration late and another update was applied on
top of it. The check was also a bare "did it get worse" test.

Both are artifacts of the original implementation, where obj was a buffer
for a commented-out score-vs-step plot; recording before stepping is the
right order for a trace, not for a control decision. That commit also left
an unused `tol = 0.1 #percent` and `converged = False`, scaffolding for a
relative-tolerance test that was never finished.

Evaluate the score after the updates and stop when relative improvement
falls below tol, which subsumes the increase case. Defaults are unchanged:
maxiter=2 applied two updates before and applies two now, and the
Precognition regression CC is identical at 0.976932 over 2293 reflections.
Above maxiter=2 the loop now stops at two updates rather than three, so CC
there moves from 0.978488 to 0.976932.

Note the objective is not a good proxy for accuracy on this data: it is
minimised after a single update and rises monotonically, while agreement
with Precognition keeps improving to a peak at five updates. Profile
pooling regularises each reflection toward its neighbours, which worsens
in-sample likelihood while helping weak spots, and the strong set erodes
every iteration (625 -> 485 spots) so the fit has no stable fixed point.
This commit makes the stopping rule mean what it says; it does not make
the objective worth optimising.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@PrinceWalnut
PrinceWalnut merged commit 6a91bd5 into main Sep 18, 2026
1 check failed
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.

3 participants