Skip to content

Rescale and LOT correction - #424

Open
Soorya19Pradeep wants to merge 99 commits into
mainfrom
rescale-lot-correction
Open

Soorya19Pradeep wants to merge 99 commits into
mainfrom
rescale-lot-correction

Conversation

@Soorya19Pradeep

@Soorya19Pradeep Soorya19Pradeep commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Purpose

This PR supports comparison of cell embeddings across datasets with different pixel sizes. It adds three operations.

  • TripletDataModule rescales image patches to a reference pixel size and supports maximum-intensity projection along Z.
  • Linear optimal transport (LOT) corrects batch differences between embedding datasets.
  • Maximum mean discrepancy (MMD) measures differences between embedding distributions. The PR includes example configurations.

The branch also includes DynaCLR phenotyping, classifier evaluation, and experiment-specific scripts. These additions account for much of the review scope.

Impact on DynaCell evaluation and virtual staining

Review area What to check Code at the reviewed commit
DynaCell prediction configuration CellDiff reads Phase3D as input and requests per-timepoint min–max normalization. It writes predicted membrane images to Zarr. Input and output configuration
Dataset construction HCSDataModule builds sliding windows for training and validation. Prediction enables volume caching with zero workers and no Z-plane selection. Training and validation, Prediction cache condition
Shared normalization change The helper selects statistics for timepoint t. Both the cached-volume path and the individual-window path now call it. Timepoint selection, Fixed cached call, Individual-window call
Cache behavior The dataset transforms a cached volume once when every transform is pointwise and preloading is off. Other transforms run per window. Transform selection, Cache fill and window extraction
Model input and scoring CellDiff reads the normalized source tensor. Evaluation loads stored predictions and compares them with targets at each timepoint. CellDiff prediction, Prediction store read, Pixel metric inputs
Regression coverage Two fields of view and two timepoints have different statistics. The test compares indices and exact source and target bytes. Test inputs and normalization modes, Cached and uncached assertions

Other shared components

Component What changes Why it matters
viscy-transforms BatchedZoom and BatchedZoomd accept an exact output size or a scale factor. Triplet rescaling can request an exact patch shape. Existing configurations can continue using scale factors.
viscy-utils EmbeddingWriter can store model and run metadata with exported embeddings. Evaluation tools can identify the source of an embedding dataset after someone moves it.
DynaCell and model files Direct edits cover the external-checkpoint guide and a comment in the MorphEm wrapper. The executable change relevant to virtual staining occurs in shared data loading.

Verification and remaining blockers

All 69 tests in packages/viscy-data/tests/test_hcs.py passed locally. The cache regression tests compare cached and per-window outputs byte for byte across fields of view and timepoints.

These tests verify data loading. An end-to-end comparison of virtual staining predictions and benchmark scores remains unverified.

DynaCLR test collection still fails for two experiment workflows. One imports an unpublished evaluation module. The other loads a training script from a personal filesystem path.

@edyoshikun
edyoshikun force-pushed the rescale-lot-correction branch from a93d071 to 37b81ff Compare June 29, 2026 17:59
@edyoshikun
edyoshikun changed the base branch from modular-viscy-staging to main June 29, 2026 20:22
@edyoshikun
edyoshikun force-pushed the rescale-lot-correction branch from 901d5b7 to dc39073 Compare June 29, 2026 20:35
@edyoshikun
edyoshikun requested a review from Copilot June 29, 2026 20:44

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR expands the Triplet-based data loading path to better support cross-dataset inference (pixel-size aware patch extraction + on-the-fly Z reduction + focus-centered per-FOV Z windows), and adds a LOT (Linear Optimal Transport) batch-correction pipeline with CLI entrypoints for embedding-space correction.

Changes:

  • Extend TripletDataModule/TripletDataset to support per-FOV z_range resolution via z_extraction_window + focus_slice metadata, plus optional z_reduction and pixel-size aware rescaling.
  • Add LOT correction core functions + Pydantic config models + dynaclr CLI commands for fitting/applying correction pipelines.
  • Add tests for the new Triplet Z-window/Z-reduction behavior and update docs/config examples for inference.

Reviewed changes

Copilot reviewed 14 out of 14 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
packages/viscy-data/src/viscy_data/triplet.py Adds pixel-size rescaling, per-FOV focus-centered Z windows, and optional Z-reduction in the Triplet datamodule/dataset.
packages/viscy-data/tests/test_triplet.py Adds tests for z_extraction_window XOR validation, per-FOV focus-centered windows, and Z-reduction behavior/order.
packages/viscy-data/src/viscy_data/_utils.py Extends norm-meta collation to correctly stack nested timepoint_statistics.
applications/dynaclr/src/dynaclr/evaluation/lot_correction/lot_correction.py Implements LOT correction fit/apply + pipeline save/load helpers.
applications/dynaclr/src/dynaclr/evaluation/lot_correction/config.py Adds Pydantic models for fit/apply configs and filter specs.
applications/dynaclr/src/dynaclr/evaluation/lot_correction/fit_lot_correction.py CLI wrapper for fitting and saving a LOT pipeline from YAML config.
applications/dynaclr/src/dynaclr/evaluation/lot_correction/apply_lot_correction.py CLI wrapper for applying a saved LOT pipeline to an embedding zarr.
applications/dynaclr/src/dynaclr/evaluation/lot_correction/init.py Exposes LOT correction functions at the package level.
applications/dynaclr/src/dynaclr/cli.py Registers new fit-lot-correction and apply-lot-correction CLI subcommands.
applications/dynaclr/pyproject.toml Adds joblib + pot to eval extras for LOT correction dependencies.
applications/dynaclr/scripts/dataloader_inspection/visualize_triplet_rescaling.py Adds a visualization utility for the new pixel-size rescaling behavior.
applications/dynaclr/scripts/dataloader_inspection/triplet_dataloader_zprojection.py Adds an inspection notebook/script for focus-centered Z windows + Z-reduction.
applications/dynaclr/docs/DAGs/inference_triplet.md Documents Triplet inference path and new options (needs a small wording update for z-window semantics).
applications/dynaclr/configs/prediction/predict_triplet_2d_from_3d.yml Provides a sample prediction config demonstrating reference_pixel_size + z_reduction.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@edyoshikun

Copy link
Copy Markdown
Collaborator

Before merge

The published branch conflicts with current main in five files. Lint failed. Two DynaCLR tests require experiment files that CI cannot load.

The PR description covers image rescaling, linear optical transfer correction, and maximum mean discrepancy. The diff also includes experiment-specific classifiers, analysis scripts, and configurations. It changes 238 files and adds 51,113 lines.

PRs #493 and #540 use this branch as their base. A local review branch merges cleanly with current main in a Git merge simulation. That check covers file conflicts only.

Please confirm whether the experiment-specific changes belong in this merge or in a separate PR.

Soorya19Pradeep and others added 17 commits December 2, 2026 17:19
…staging

Scale-aware patch extraction (packages/viscy-data):
- Add _read_pixel_size() helper to read X pixel size from OME-Zarr metadata
- Add reference_pixel_size parameter to TripletDataModule: when set, computes
  initial_yx_patch_size from the pixel-size ratio so the same physical area is
  covered at inference time
- Replace BatchedRescaleYXd (removed per review) with existing BatchedZoomd
  using scale_factor=(1.0, final_y/initial_y, final_x/initial_x) and
  mode="bilinear" with antialias; import is lazy to avoid a hard dep

LOT batch correction (applications/dynaclr):
- Add dynaclr.evaluation.lot_correction submodule with core logic (fit, apply,
  save, load), Pydantic configs, and Click CLI entry points
- Register fit-lot-correction and apply-lot-correction in cli.py via LazyCommand
- Add pot and joblib to optional-dependencies.eval in pyproject.toml

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Plots n cell patches side-by-side:
- Left: raw patch at initial_yx_patch_size (larger physical area)
- Right: same patch bilinearly downscaled to final_yx_patch_size (model input)

Both columns share the same percentile contrast window so differences are
spatial. Physical scale (µm × µm) is shown in each panel title.

Usage:
  python visualize_triplet_rescaling.py       --data-path /path/to/data.zarr       --tracks-path /path/to/tracks       --source-channel Phase3D       --z-range 0 5       --final-yx-patch-size 224 224       --reference-pixel-size 0.325       --output rescaling_comparison.png

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…meta

_collate_norm_meta iterated every normalization level and called
torch.stack on each stat, but timepoint_statistics is nested
{timepoint: {stat: tensor}} rather than flat {stat: tensor}. Any zarr
carrying timepoint_statistics (alongside fov/dataset stats) crashed
batch collation in TripletDataModule with "expected Tensor as element 0
... but got dict". Stack within each timepoint sub-dict instead.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…etDataModule

Lets a 3D OME-Zarr feed a 2D model without materializing a separate MIP
dataset, and centers the extracted Z window on each FOV's focus plane.

- z_reduction ("mip"/"center"): collapse the extracted z_range to one
  slice via BatchedChannelWiseZReductiond. Label-free channels (resolved
  by parse_channel_name) take the center slice; others are max-projected.
  on_after_batch_transfer expects Z=1 when reduction is on.
- z_extraction_window/z_focus_offset/focus_channel: resolve a per-FOV
  focus-centered window from each position's
  focus_slice[ch].fov_statistics.z_focus_mean (fallback z_total//2), all
  windows the same width. z_range stays as an explicit override; exactly
  one of z_range / z_extraction_window must be given. Per-FOV windows are
  resolved at setup() and looked up per patch in the dataset.

Tests cover both reduction strategies (discriminating center vs MIP),
the normalize-then-reduce order, per-FOV focus resolution, and the
z_range/z_extraction_window XOR guard.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Documents the TripletDataModule predict path (zarr + tracking, not
parquet) and adds a runnable sample config demonstrating z_reduction +
reference_pixel_size to feed a 3D dataset to a 2D model.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Notebook-style script (no CLI) that loads a 3D OME-Zarr + tracking,
extracts a per-FOV focus-centered Z window, collapses it via z_reduction,
applies a random affine so anchor/positive diverge, and visualizes a
couple of batches to a PNG.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
- Declare viscy-transforms in viscy-data's triplet extra and hoist the
  BatchedZoomd/BatchedChannelWiseZReductiond imports to module top; the
  inline imports were masking a missing runtime dependency that would
  ImportError for anyone using z_reduction or reference_pixel_size.
- Raise in _resolve_per_fov_z_ranges when a FOV's Z is smaller than
  z_extraction_window, instead of silently emitting a narrower window
  that breaks cross-FOV batch stacking.
- Remove a dead duplicate break in test_focus_centered_z_range.
- Correct the inference DAG doc: embeddings live in .X (the embedding_key
  array), mirrored to obsm["X_backbone"]/["X_projections"].

uv.lock intentionally omitted: the workspace glob currently entangles the
untracked applications/eet package, so a clean regen of the single
viscy-transforms edge is not possible until eet is committed or removed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Replace the NumPy/scipy.cdist backend with PyTorch so the pooled RBF
kernel matrix is built once on the available device (CUDA if usable,
else CPU) and reused across all permutations. Device selection probes a
trivial kernel launch and falls back to CPU, so a present-but-unusable
GPU (e.g. compute capability older than the torch build) does not crash.

Public API is unchanged: median_heuristic/compute_mmd_unbiased return the
same bandwidth-convention values, and mmd_permutation_test still returns
(mmd2, p_value, null_distribution) so dynaclr's effect-size and activity
z-score computations keep working.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Add witness_function to the MMD module: the per-point empirical witness
w(z) = mean_i k(z, x_i) - mean_j k(z, y_j), the RKHS direction along
which distributions P (X) and Q (Y) differ. Positive scores lean toward
X, negative toward Y. Reuses the GPU RBF-kernel helpers and bandwidth
(median-heuristic) convention already in the module, and chunks over
query points to bound the intermediate kernel matrices.

Tests cover distribution separation, X<->Y antisymmetry, and chunk-size
invariance.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Adds `label_source: witness` to the linear-classifier eval as a second
option to annotation-CSV labels. Per marker, cells are pooled across
experiments, control/perturbed references are built from per-experiment
wells, the MMD witness is fit and scored per cell, and scores are gated
(sign + dead-zone) into control/perturbed pseudo-labels. Everything
downstream (train_linear_classifier, publish, append-predictions, plots)
is unchanged — only the label source differs.

- evaluate_config.py: WitnessLabelSource, WitnessSettings, label_source
  switch on LinearClassifiersStepConfig (annotations stays the default).
- witness_labels.py: well->reference mask (path-component match so C/1
  != C/10), witness fit/score, dead-zone gating.
- orchestrated.py: branch label assembly into _annotation_run_specs /
  _witness_run_specs / _build_labeled_adata; training loop unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
edyoshikun and others added 22 commits December 2, 2026 17:19
…ription

2026_04_21_A549_G3BP1_DENV was re-concatenated to a flat store on VAST (odd
5-assemble layout resolved) and verified predict-ready. Note the residual
z_focus=0 frames (12/54 FOVs, mean 2.4 timepoints each).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Add audit_focus_slice() + a `qc audit-focus` CLI command that reads already-
written focus_slice.{channel}.per_timepoint metadata and reports where in-focus
detection landed at a stack edge (z == 0 or z == Z-1), the signature of a failed
search on a 3D stack. Z-depth-aware: a 2D acquisition (Z == 1) trivially focuses
at slice 0 for every timepoint, so it is reported as 2D with zero flags rather
than misclassifying every frame as failed.

Returns per-FOV suspect counts, dataset totals, and the valid (non-edge) focus
distribution — the summary previously computed ad hoc while vetting datasets for
focus-centered predict.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
embedding_store writes .../{ckpt}/embeddings/{marker}.zarr since the embeddings/
nesting landed (d89f9ed), but iter_embeddings still globbed .../{ckpt}/*.zarr —
so it returned [] and ALL cross-dataset pooling (embedding-consistency-qc, MMD,
linear classifiers) silently found zero embeddings. Add the missing EMBEDDINGS_DIR
segment; fix the test_paths fixtures that encoded the pre-nesting layout.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…ling, temporal-std

Extend the per-marker embedding-consistency QC:
- split_by: partition datasets by a per-dataset obs column (e.g. microscope) into
  within-group + cross-group blocks; degenerate blocks (single-dataset within, or
  empty cross side) are skipped with a log line.
- metrics knob: choose any of pearson/mmd/frechet (default all three). MMD pass is
  skipped when not requested.
- Fréchet (mean+covariance) matrix: 2-Wasserstein between Gaussian summaries of each
  dataset's control cells — richer than Pearson-of-means, cheaper than full MMD.
- Time-aware Pearson (pearson_hpi_bin_hours): mean per hours_post_perturbation bin
  then mean-of-means, so uneven time sampling can't masquerade as a batch effect;
  plus a per-dataset temporal-std drift diagnostic (std of the control centroid
  across HPI bins).
- Annotated, auto-scaled correlation heatmaps.

Organelle-box recipe (metrics: [pearson], split_by: microscope, 2 h HPI bins).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…tions; build-collection skill

Add per-experiment microscope (mantis_v1 for the 0.1494 um/px dataset, mantis_v2 for
the 0.1133 ones) to organelle_remodeling so obs enrichment writes it and the
consistency QC can split v1/v2. Normalize the 2024_11_07 control label mock→uninfected
in both organelle_remodeling and the source organelle-box collection so a single
uninfected filter catches every dataset's controls. Update the airtable-build-collection
skill to always populate microscope (field table, schema, derivation rule).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
plot_corr_matrix auto-scaled vmin to each matrix's own off-diagonal minimum, so
heatmaps for different markers used different colour scales and couldn't be
compared by eye. Use a shared fixed vmin (default 0.8). Fix the title
("mean-embedding" -> "control-cell summary correlation").

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Add control_normalization.py: robust z-score of embeddings against the
control (uninfected) population of the same plate and HPI bin. Stores only
per-(plate, bin) median/IQR statistics and applies (x - median) / IQR on the
fly rather than materializing a normalized array.

- control_reference_stats: per-experiment median + IQR of control cells,
  pooled across control wells, in fixed-width HPI bins anchored at 0h.
- control_reference_stats_multi: same at several bin widths (default 1h + 2h).
- ControlReference.apply: robust z-score against the matched bin, nearest
  occupied bin as fallback; zero-IQR dimensions floored to 1.0.
- Raises if a plate has cells but no controls (no silent drop).

8 unit tests cover recovery of the control center, control/perturbed
separation, nearest-bin fallback, zero-IQR flooring, multi-bin widths, and
the control-less-plate guard.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Standalone README next to control_normalization.py documenting the empirical
finding so a teammate knows when NOT to use it: it flattens control temporal
drift (−32 to −53% control-centroid std across 3 plates) but LOWERS held-out
infection/remodeling classifier AUROC on every ZIKV DynaCLR classifier tested
(−0.008 to −0.032), because flattening control-relative time removes
infection-trajectory signal. Per-dimension only (not multivariate batch
correction). Full write-up under .ed_planning/dynaclr/batch_correction/.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
…ssifiers

Add a control_normalize flag (+ control_normalize_bin_hours, default 2.0) to
LinearClassifiersStepConfig and wire it into run-linear-classifiers: when set,
embeddings are robustly z-scored per plate/HPI-bin against control cells before
training/scoring, via viscy_utils.evaluation.control_normalization.

Off by default and backward-compatible. It is off because the held-out A/B
showed it lowers infection/remodeling AUROC (see control_normalization_README);
the flag exists to reproduce that result and for cases where matched-time
cross-condition comparability is the actual goal.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@edyoshikun
edyoshikun force-pushed the rescale-lot-correction branch from ed6f6ff to 206fdfa Compare December 3, 2026 01:23
@edyoshikun

Copy link
Copy Markdown
Collaborator

The branch now includes current main and has no merge conflicts. I checked the cleanup against file contents, file names, and directory names.

CI still blocks this merge. Two data jobs fail because SlidingWindowDataset calls a missing normalization method. DynaCLR test collection also requires two missing experiment dependencies.

@edyoshikun

Copy link
Copy Markdown
Collaborator

The cached volume path now uses the shared timepoint normalization function. All six focused dataset tests passed locally.

Two comparison tools now share the same mask renderer. Both original renderers produced identical arrays to the shared implementation in local checks. All three mask comparison tests passed.

Two experiment workflows still depend on files outside the repository. That scope decision remains open.

@edyoshikun

Copy link
Copy Markdown
Collaborator

One DynaCell test still fails on both PR 424 and its main base.

test_each_leaf_composes_and_resolves raises KeyError: 'pixel_metrics.foreground' during grouped evaluation configuration validation. The validator expects that key in base_snapshot. Test · Failing lookup

All 4,240 initial test outcomes matched between PR commit 524aa0512 and main commit f46b0ffce. With GPU dependencies enabled, 55 of the 56 failures passed on rerun. Only this configuration test still failed.

This branch has not been deployed

No deployments
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