diff --git a/README.md b/README.md index 90d256b..52c99b1 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ A workflow for Sub-Tomogram Averaging Membrane Proteins. Given a directory of segmented MRC volumes (i.e. as produced by [MemBrain-seg](https://github.com/teamtomo/membrain-seg)), `STAMP` runs the following workflow: \# | Stage | Description -- | -- | -- -1 | **Picking** | Finds candidate particle positions on the membrane surface, with consensus results returned across multiple pickers +1 | **Picking** | Imports candidate particle positions from external pickers, infers membrane normal orientations and returns consensus results across multiple pickers 2 | **Classification** | Group similar candidate particles by structural similarity (via unsupervised clustering) and produce class averages 3 | **Identification** | Score each class average against a panel of predicted protein structures from proteomics experiments 4 | **Refinement** | Iteratively refine particle orientations and measure resolution @@ -53,8 +53,8 @@ uv sync --group dev ### Quickstart Given a directory of membrane segmentations (`seg/`) and matching raw tomograms (`tomo/`): ```sh -# 1. Pick candidate particles using STAMP's native picker -stamp pick stamp-native -s seg/ -r tomo/ --voxel-size-a 5.38 +# 1. Import candidate particle picks +stamp pick data/picks.csv -s seg/ -r tomo/ --voxel-size-a 5.38 # 2. Group picks and generate class averages stamp classify --particles stamp/pick/particle_set.json -r tomo/ --voxel-size-a 13.48 diff --git a/docs/architecture.md b/docs/architecture.md index 2515c92..225087d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -12,7 +12,7 @@ This document contains information about STAMP's architecture and implementation - [Coordinate conventions](#coordinate-conventions) - [Picking implementation](#picking-implementation) - [Geometric primitives](#geometric-primitives) - - [`NativePickerConfig`](#nativepickerconfig) + - [Picks importer](#picks-importer) - [Vesicle labelling](#vesicle-labelling) - [Halfset assignment](#halfset-assignment) @@ -25,9 +25,9 @@ src/stamp/ cli/ CLI Typer definitions (parse args then call commands) commands/ per-stage run orchestration via a run_() function, called by cli/ and run/ schemas/ pydantic models: config, particles, picks, manifest, provenance, cluster_profile - adapters/ ToolAdapter implementations: native, relion, m_refine, mock, (base protocol) + adapters/ ToolAdapter implementations: relion, m_refine, mock, (base protocol) backends/ Runner implementations: local, cluster, mock, (base protocol) + factory - picking/ pick command scripts: geometry primitives, native picker, vesicle labelling, consensus reconciliation + picking/ pick command scripts: picks importer, geometry primitives, vesicle labelling, consensus reconciliation decoy/ decoy dataset generation and comparability checks classify/ subvolume extraction, feature engineering, clustering, class averaging identify/ candidate panel loading, shape fitting, decoy-control statistics @@ -56,8 +56,8 @@ commands/.py orchestration: selects adapter + backend, drives the stage Command | Work directory | Unit checkpointed -- | -- | -- -`pick` | `raw//` | tomogram picks (`.json`) -`decoy` | `raw//` | rejected-surface: surface scores (`scores/.npz`); shifted: surfaces (`surfaces/.npz`); synthetic-noise: volumes and picks +`pick` | `raw//` | tomogram picks with inferred orientation (`.json`) +`decoy` | `raw//` | shifted: surfaces (`surfaces/.npz`); synthetic-noise: volumes and picks `classify` | `raw/` | subvolumes, per-tomogram features, per-cluster alignment angles `identify` | `raw/{real,decoy}/` | one fit score per (class, candidate) `refine` | `//` | finished half-maps @@ -91,7 +91,6 @@ class ToolAdapter(Protocol): Available adapters: Adapter | File (`src/stamp/adapters/`) | Stage | `mac_compatible` | `requires_gpu` | `runs_in_process` -- | -- | -- | -- | -- | -- -`NativePickerAdapter` (`stamp-native`) | `native.py` | Pick | ✔ | ✘ | ✔ `RelionRefineAdapter` (`relion`) | `relion.py` | Refine | ✘ | ✔ | ✘ `MRefineAdapter` (`m`) | `m_refine.py` | Refine | ✘ | ✔ | ✘ `MockAdapter` | `mock.py` | Any (test adapter) | Configurable | Configurable | Configurable @@ -128,48 +127,26 @@ Two conventions for tomogram coordinates are used throughout STAMP: ## Picking implementation ### Geometric primitives -`src/stamp/picking/geometry.py` contains several geometric primitives, used by STAMP's native picker: +`src/stamp/picking/geometry.py` contains several geometric primitives, used by STAMP's pick importer and refine command: Function | Role -- | -- `extract_surface(segmentation, level=0.5)` | Uses marching cubes to convert a binary segmentation into `(vertices, normals)` -`downsample_points(points, normals, spacing_voxels)` | Downsamples a voxel-grid to a target spacing -`sample_along_normals(...)` | Calculates mean tomogram density in a shell offset along each point's normal; `direction` is `+1`/`-1`; out-of-volume samples clamp to the nearest edge (`map_coordinates(mode='nearest')`) -`profile_correlation_scores(...)` | Calculates Pearson correlation of a sign-corrected radial profile against a Gaussian bump at the window's own midpoint -`robust_normalise(...)` | Calculates median/MAD normalisation, global per tomogram -`local_normalise(...)` | Calculates median/MAD normalisation over a k-d tree neighbourhood (`local_radius_angstrom`) if a point has more than `min_local_neighbours` (otherwise falls back to global estimate) -`vesicle_normalise(values, vesicle_ids)` | Calculates per-vesicle median/MAD normalisation if vesicle labels are available (otherwise falls back to pooled/global estimate) -`non_maximum_suppression(...)` | Uses greedy NMS, highest score first, k-d tree exclusion radius `quaternion_from_reference_to(vector_xyz)` | Constructs a unit quaternion rotating +z onto a given outward vector `compose_roll_about_normal(...)` | Constructs a quaternion for "roll by angle, then map +z onto the normal" -`exclude_near_boundary(points, shape, margin_voxels)` | Drops points too close to a volume face to sample cleanly -`score_membrane_faces(...)` | Composes above functions to sample both faces across every offset window, scores using both modes, normalise scores, and return per-point results including which window won -`max_order_statistic_offset(n_windows)` | Applies an upward-bias correction for taking the max of `n_windows` independent scores `beam_angle_deviation_degrees(normal_xyz)` | Derives the angle between an outward normal and the beam-orthogonal (xy) plane; 0 = beam-orthogonal, 90 = beam-aligned (used to flag/drop picks whose orientation the missing wedge makes unreliable) -### `NativePickerConfig` -`picking/native.py` uses a dataclass to store the configuration options for STAMP's native picker. All distances are in Å and are converted to voxels via `config.to_voxels()`. +### Picks importer +`picking/importers.py`: -Field | Default | Meaning --- | -- | -- -`voxel_size_angstrom` | *n/a (required)* | Voxel size of input tomograms in Å -`offset_windows_angstrom` | `((20,50),(40,80),(70,110),(100,160))` | Radial windows searched outward from the surface -`n_samples` | 5 | Number of samples taken per point within each window -`surface_spacing_angstrom` | 20.0 | Target vertex spacing after downsampling -`min_particle_distance_angstrom` | 60.0 | NMS exclusion radius -`n_mad` | 3.0 | Threshold, in robust standard deviations, before the multi-window correction -`density_sign` | -1 | +1 if protein is brighter than background, -1 if darker -`boundary_margin_angstrom` | `None` | Drop points closer than this to a volume face; defaults to the widest window's outer edge -`normalisation` | `'global'` | MAD normalisation method (`'global'` or `'local'`) -`local_radius_angstrom` | 150.0 | Neighbourhood radius for local normalisation -`min_local_neighbours` | 20 | Minimum neighbours before falling back to global -`scoring_mode` | `'mean'` | Scoring mode to use (`'mean'` or `'profile'`) -`profile_width_angstrom` | `None` | Width of the expected profile bump (`None` defaults to a quarter of each window's own range) -`vesicle_labels_mrc` | `None` | Path to EValuator's `label` command output MRC, enabling per-vesicle attribution -`normalise_per_vesicle` | `False` | Normalise scores per vesicle instead of per tomogram (requires `vesicle_labels_mrc`) +Function | Role +-- | -- +`read_picks(path, *, source_picker)` | Reads a CSV, STAR, JSON or JSONL file into `RawPick` instances +`map_tomogram_ids(picks, manifests)` | Rewrites pick ids onto manifest ids (ignoring a trailing `_segmented`), raising error on unknown ids +`infer_orientations(picks, manifests, ...)` | Fills missing `orientation`, `beam_angle_deviation_degrees` and `vesicle_id` from the nearest surface vertex, with any picks beyond `max_surface_distance_angstrom` remaining unoriented ### Vesicle labelling -`picking/vesicles.py` adds per-vesicle QC and normalisation when provided with an output MRC from EValuator's `label` command. +`picking/vesicles.py` adds per-vesicle QC when provided with an output MRC from EValuator's `label` command. Function | Role -- | -- @@ -178,7 +155,7 @@ Function | Role `vesicle_surface_area_angstrom2(...)` | Per-vesicle membrane surface area, computed from marching-cubes triangle face areas assigned to their nearest labelled voxel (by face centroid) `summarise_vesicles(picks, areas_by_vesicle, tomogram_id)` | builds a `VesicleSummary` (frozen dataclass: `vesicle_id`, `tomogram_id`, `n_picks`, `surface_area_angstrom2`, `picks_per_1000_angstrom2`) per vesicle -Every kept `RawPick` will contain `vesicle_id`, which is kept through downstream stages. +Every `RawPick` oriented with `--vesicle-labels-mrc` contains `vesicle_id`, which is kept through downstream stages. ### Consensus reconciliation `picking/consensus.py` contains the function `reconcile_picks(...)` for grouping picks across pickers by proximity (complete-linkage agglomerative clustering via a `cKDTree`-backed near-linear implementation). Two modes are available: @@ -187,7 +164,7 @@ Every kept `RawPick` will contain `vesicle_id`, which is kept through downstream Each reconciled pick's position is the centroid of its group, and `source_picker` records all contributing pickers (joined with '+'). -With the current single picker (STAMP's native picker), `reconcile_picks(...)` is reduced to deduplicating near-identical picks within `distance_threshold`. +With a single picks file, `reconcile_picks(...)` is reduced to deduplicating near-identical picks within `distance_threshold`. ### Halfset assignment `utils/halfset.py` contains functions for implementing the half-set separation: diff --git a/docs/cli.md b/docs/cli.md index 0f18c95..375945e 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -51,21 +51,21 @@ If a command's inputs or parameters differ, any old partial output is discarded ## `stamp pick` ``` -stamp pick -s SEG_DIR -r RAW_DIR [options] +stamp pick -s SEG_DIR -r RAW_DIR [options] ``` Argument/Option | Default | Use -- | -- | -- -`pickers` (positional) | *n/a (required)* | Comma-separated names of pickers to use +`picks_files` | *n/a (required)* | One or more files containing picks (`.csv`, `.star`, `.json`), one file from each picker `-s, --seg-dir` | *n/a (required)* | Directory containing segmented MRC files `-r, --raw-dir` | *n/a (required)* | Directory of raw tomogram MRCs `-o, --out-dir` | `.` | Output directory (outputs will be saved to `/stamp/pick`) `--voxel-size-a` | `None` *(read from MRC file header)* | Voxel size in Å -`--picker-params` | `'{}'` | JSON of per-picker parameters, e.g. `'{"stamp-native": {"n_mad": 3.5}}'` +`--name` | `None` *(derived from file stems)* | Picker name for each file, in order (repeatable) `--consensus-rule` | `union` | Rule to use for reconciling picks (`union` or `intersection`) `--distance-threshold` | `15.0` | Voxel distance within which picks are merged +`--max-surface-distance-a` | `300.0` | Distance (Å) from a segmentation surface that a pick can be before STAMP no longer infers its orientation `--half-set-seed` | `0` | Seed for half-set assignment -`--backend` | `local` | Backend to use for picking (`local` or `mock`) `--plots/--no-plots` | `--plots` | Write consensus-pick position plots `--pick-plot-style` | `segmented` | Style of consensus-pick position plots (`segmented` or `none`) `--plot-format` | `tiff` | Consensus-pick position plot file format (`png` or `jpg` or `tiff` or `svg`) @@ -73,10 +73,22 @@ Argument/Option | Default | Use `--pick-plot-3d/--no-pick-plot-3d` | `--no-pick-plot-3d` | Write a static 3D pick visualisation per tomogram `--max-beam-angle-deviation` | `None` | Drop particles whose normal deviates from the beam-orthogonal plane by more than this many degrees `--vesicle-labels-mrc` | `None` | Path to an MRC file produced by EValuator's `label` command, or a directory to be matched by filename stem -`--normalise-per-vesicle` | `False` | Normalise `stamp-native` scores per vesicle instead of per tomogram -`-n, --n-processes` | `1` | Processes to use for the `stamp-native` picker (1 = sequential) +`-n, --n-processes` | `1` | Processes to use for reconciliation, vesicle summary and plots `--keep-raw` | `False` | Keep the raw intermediate output instead of archiving it to `raw.tar.gz` +### Picks file formats +Pick supports pick files in the following formats: +- **CSV** (`.csv`). Requires data to follow header format: `tomogram_id,x,y,z[,confidence][,qw,qx,qy,qz]` +- **RELION STAR** (`.star`). Requires columns `rlnTomoName`, `rlnCoordinateX`, `rlnCoordinateY`, `rlnCoordinateZ` in pixels, plus optional `rlnAutopickFigureOfMerit` as confidence. RELION5 centred-Angstrom columns are not yet supported. +-- **JSON / JSONL** (`.json`, `.jsonl`). Requires picks to be consistent with STAMPs internal raw pick class (`tomogram_id`, `position`, optional `orientation`, `confidence`). + +For each file, positions must be voxels in (x, y, z) order, at the same voxel size of the tomograms in `--raw-dir`. `tomogram_id` must equal the segmentation filename stem; a trailing `_segmented` on either side is ignored. Unknown ids will raise an error. + +### Orientation inference + +Where a quaternion is not provided for a pick, `stamp pick` will find the segmentation surface and normal pointing towards the pick, storing the quaternion after rotating +z onto it. It will also fill `beam_angle_deviation_degrees` and, with `--vesicle-labels-mrc`, `vesicle_id`. Quaternions supplied in the pick file are kept as is. Picks further than `--max-surface-distance-a` from any surface are left without an orientation, with a warning giving the count. + +
## `stamp decoy` @@ -89,13 +101,13 @@ Option | Default | Use -- | -- | -- `--voxel-size-a` | *n/a (required)* | Voxel size in Å `-o, --out-dir` | `.` | Output directory (outputs will be saved to `/stamp/decoy`) -`--method` | `rejected-surface` | Decoy generation method to use (`rejected-surface` or `shifted` or `synthetic-noise`) *[(see below)](#stamp-decoy-methods)* +`--method` | `shifted` | Decoy generation method to use (`shifted` or `synthetic-noise`) *[(see below)](#stamp-decoy-methods)* `--real-particle-set` | *n/a (required unless `--method synthetic-noise`)* | Path to `particle_set.json` from `stamp pick` `-s, --seg-dir` | *n/a (required unless `--method synthetic-noise`)* | Directory containing segmented MRC files `-r, --raw-dir` | *n/a (required unless `--method synthetic-noise`)* | Directory of raw tomogram MRCs -`--picker-params` | `'{}'` | JSON of native-picker parameters (must match the values used for `stamp pick` so decoys are drawn from the same candidate pool) -`--n-decoys-per-tomogram` | `None` *(adaptive: matches the real pick count per tomogram)* | Number of decoy positions to pick per tomogram (required for `--method synthetic-noise`) -`--min-distance-from-real-a` | `100.0` | Minimum distance in Å from a real pick for `--method rejected-surface`, or from the membrane surface for `--method shifted` +`--density-sign` | `-1` | `+1` if the synthetic membrane shell is brighter than background, `-1` if darker (`--method synthetic-noise` only) +`--n-decoys-per-tomogram` | `None` *(adaptive: matches the real pick count per tomogram)* | Decoy positions per noise volume (required for `--method synthetic-noise`), shifted places one decoy per real pick +`--min-distance-from-real-a` | `100.0` | Minimum distance in Å from the membrane surface for `--method shifted` `--min-pick-distance-a` | `60.0` | Minimum distance from a real pick in Å for `--method shifted` `--min-shift-a` | `200.0` | Minimum displacement in Å for `--method shifted` `--max-shift-a` | `600.0` | Maximum displacement in Å for `--method shifted` @@ -112,12 +124,11 @@ Option | Default | Use `--keep-raw` | `False` | Keep the raw intermediate output instead of archiving it to `raw.tar.gz` ### `stamp decoy` methods -`stamp decoy` provides three methods for generating decoy picks: +`stamp decoy` provides two methods for generating decoy picks: Method | What it controls for | Notes -- | -- | -- -`rejected-surface` (default) | Structure emerging from real membrane positions with no particle | Reuses pick-stage geometry -`shifted` | Structure emerging from the tomogram at large, independent of the membrane | +`shifted` (default) | Structure emerging from the tomogram at large, independent of the membrane | `synthetic-noise` | Structure emerging from pure noise |
diff --git a/docs/configuration.md b/docs/configuration.md index 7bfeb64..2742f32 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -17,7 +17,7 @@ stop_after = "refine" # pick | classify | identify | r [decoy] enabled = true -method = "rejected-surface" # rejected-surface | shifted | synthetic-noise +method = "shifted" # shifted | synthetic-noise # n_decoys_per_tomogram = 50 # omit for adaptive n min_distance_from_real_angstrom = 100.0 min_distance_from_picks_angstrom = 60.0 @@ -35,7 +35,7 @@ pick_zstack_movie = false pick_plot_3d = false [stage.pick] -pickers = ["stamp-native"] +picks_files = ["data/picks.csv"] consensus_rule = "intersection" # union | intersection distance_threshold = 15.0 half_set_seed = 0 @@ -95,7 +95,7 @@ Key | Type | Default Key | Type | Default -- | -- | -- `enabled` | bool | `True` -`method` | `rejected-surface`\|`shifted`\|`synthetic-noise` | `rejected-surface` +`method` | `shifted`\|`synthetic-noise` | `shifted` `n_decoys_per_tomogram` | int\|`None` | `None` `min_distance_from_real_angstrom` | float | `100.0` `min_distance_from_picks_angstrom` | float | `60.0` @@ -119,11 +119,11 @@ Key | Type | Default Key | Type | Default -- | -- | -- -`pickers` | `list[str]` | `['stamp-native']` +`picks_files` | `list[Path]` | *n/a (required)* `consensus_rule` | `union`\|`intersection` | `intersection` `distance_threshold` | float | `15.0` `half_set_seed` | int | `0` -`backend` | `local`\|`mock`\|`cluster`\|`None` | `None` (inherits `[run].backend`) +`backend` | `local`\|`mock`\|`cluster`\|`None` | `None` (inherits `[run].backend`), has no effect on picking `n_workers` | int | `1` ### `[stage.classify]` @@ -163,4 +163,4 @@ Key | Type | Default `class_id` | str | `'all'` `iterations` | int | `5` `mask` | Path\|`None` | `None` -`backend` | `local`\|`mock`\|`cluster`\|`None` | `None` *(inherit from `[run].backend`)* \ No newline at end of file +`backend` | `local`\|`mock`\|`cluster`\|`None` | `None` *(inherit from `[run].backend`)* diff --git a/docs/workflow.md b/docs/workflow.md index d30ce91..b2b86b5 100644 --- a/docs/workflow.md +++ b/docs/workflow.md @@ -20,7 +20,7 @@ Identify | Screen class averages against proteomics data Refine | Improve class averages and measure quality ### Pick -Picking takes raw/segmented tomograms and identify candidate particles from these. STAMP was written as a modular system to support multiple pickers, with functions for reconciling the outputs of multiple pickers into a single set of consensus particles. At present, however, STAMP only implements a native picker - for information on how this picker works, see [below](#stamps-native-picker). +Picking takes raw/segmented tomograms and candidate picks from external pickers. STAMP was written as a modular system to support multiple pickers, with functions for reconciling the outputs of multiple pickers into a single set of consensus particles. Where required, STAMP infers particle orientation from membrane segmentation before reconciliation. ### Classify Classification sorts the mixed outputs of picking into groups of similar particles. STAMP implements classification in five steps: @@ -48,30 +48,9 @@ Refinement iterates over a the class average to improve each particle's estimate STAMP implements the gold-standard split used in STA, dividing particles randomly into two halves which are processed independently. Once the pipeline has run, the two independent averages are compared to determine if they converge on the same structure and to what extent they converge. This convergence is measured using Fourier shell correlation (FSC), with the point at which agreement falls below the threshold (0.143) representing the resolution. In STAMP, each particle is assigned to half-set A or B at the end of picking and each subsequent stage processes each half-set independently. ### Decoys -As a negative control, STAMP runs a set of decoy picks (where no particles exist) through the exact same pipeline to check that the clustering and averaging steps aren't returning artefactual structures from the underlying algorithms. STAMP's main decoy method uses the rejected positions from the native picker, which provides a set of 'picks' from the same membranes/tomograms as the real picks. If the decoy set produces class averages as convincing as the real data, it's likely that STAMP is responding to membrane shape/ice thickness/missing-wedge artefacts rather than proteins themselves. If the decoy set produces weak/structureless averages (and the real set produce convincing averages), this provides evidence that STAMP is responding to the actual protein structures. +As a negative control, STAMP runs a set of decoy picks (where no particles exist) through the exact same pipeline to check that the clustering and averaging steps aren't returning artefactual structures from the underlying algorithms. STAMP's main decoy method displaces picks by a large random vector, to a position away from the membrane surface and other picks so decoys originate from the same tomograms with the same orientation prior. If the decoy set produces class averages as convincing as the real data, it's likely that STAMP is responding to membrane shape/ice thickness/missing-wedge artefacts rather than proteins themselves. If the decoy set produces weak/structureless averages (and the real set produce convincing averages), this provides evidence that STAMP is responding to the actual protein structures. ### Predicted-structure separation STAMP only introduces the candidate proteins (from proteomics experiments) after class averages have been produced, and does not use them references for alignment. This is specifically to avoid [Einstein from noise](https://doi.org/10.1073/pnas.1314449110) which could otherwise appear to be confirmation that the candidate proteins are present in the tomograms. STAMP uses the inverse approach (build averages then compare these to candidates) to control for this bias.
- -## STAMP's native picker -STAMP includes a self-contained native picking tool based on geometric principles, which depends only on a small number of Python libraries (`numpy`, `scipy`, `scikit-image`, `mrcfile`). It requires no addiitonal installs, and was designed to run on a laptop (MacBook Air M1). - -The native picker doesn't search the entire raw tomogram for particles, but instead uses the membrane segmentation as a strong prior to restrict the search space to a small window on either side of the membrane. This has computational benefits by reducing the area searched, but also provides an orientation prior for downstream classification: membrane proteins must point outward along the local surface normal, which fixes two of the three rotational degrees of freedom before any alignment begins. Only the spin about the normal (sometimes called the in-plane angle) remains unknown, but this can be resolved throughout classification and refinement. - -The specific workflow the native picker uses: - -\# | Step | Description --- | -- | -- -**1** | Extract surface from segmentation | Uses marching cubes on the binary segmentation to produce a triangle mesh with per-vertex normals -**2** | Downsample vertexes | Downsample voxel-grid to a target spacing so sampling density doesn't depend on mesh resolution -**3** | Apply bidirectional ray sampling | From each surface point, move along the membrane normal (in both directions) across one or more radial offset windows, sampling the raw tomogram by trilinear interpolation. -**4** | Score offset windows | Score each offset window[] and apply normalisation (median/MAD) using either tomogram-global, local-neighbourhood or per-vesicle background. -**5** | Apply multi-window correction and threshold | Raise the threshold for keeping the best-scoring window by an order-statistic correction to avoid upward bias, and only keep points above this -**6** | Combine local neighbours | Use non-maximum supression (greedy, highest score first) to suppress neighbours via a k-d tree to avoid detecting the same particle multiple times -**7** | Produce oriented unit quaternion | Apply a unit quaternion rotating z to the membrane normal to each pick, to give downstream classification an orientation prior - -The native picker has two methods for scoring offset windows: -- **Mean:** calculated mean density within the window -- **Profile:** Pearson correlation fo the radial profile against a Gaussian bump centred on the windows midpoint (may help to distinguish proteins from connected vesicles etc) diff --git a/pyproject.toml b/pyproject.toml index 587d188..7a9382f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,6 +9,8 @@ authors = [ requires-python = ">=3.14" dependencies = [ "fast-hdbscan>=0.3.2", + "igraph>=1.0.0", + "leidenalg>=0.12.0", "loguru>=0.7.3", "matplotlib>=3.11.1", "mrcfile>=1.5.4", diff --git a/src/stamp/adapters/mock.py b/src/stamp/adapters/mock.py index 737d830..5c2029a 100644 --- a/src/stamp/adapters/mock.py +++ b/src/stamp/adapters/mock.py @@ -41,16 +41,6 @@ def _canned_picks_for(_name: str) -> dict: # MOCK_ADAPTERS: instantiate a MockAdapter class for each external tool MOCK_ADAPTERS: dict[str, MockAdapter] = { - 'stamp-native': MockAdapter( - 'stamp-native', - stage='pick', - mac_compatible=True, - requires_gpu=False, - automatable=True, - batches_natively=True, - runs_in_process=False, - canned_parsed=_canned_picks_for('stamp-native'), - ), 'membrain-pick': MockAdapter( 'membrain-pick', stage='pick', diff --git a/src/stamp/adapters/native.py b/src/stamp/adapters/native.py deleted file mode 100644 index 410475e..0000000 --- a/src/stamp/adapters/native.py +++ /dev/null @@ -1,98 +0,0 @@ -''' -STAMP: in-process adapter for the stamp-native picker -''' - -# Import external dependencies -from dataclasses import dataclass, replace -from pathlib import Path - -# Import internal STAMP objects -from stamp.adapters.base import AdapterInputs, AdapterOutput -from stamp.backends.base import RunResult, ToolCommand -from stamp.picking.native import PICKER_NAME, NativePickerConfig, pick_tomogram -from stamp.schemas.picks import RawPick -from stamp.utils.errors import StampPipelineError, StampValidationError -from stamp.utils.io import cache_tomogram_picks, load_cached_picks -from stamp.utils.log import log -from stamp.utils.parallel import run_parallel - -# _IN_PROCESS_MESSAGE: define a message for if build_command/parse_output are called directly -_IN_PROCESS_MESSAGE = 'stamp-native runs in-process; call run_in_process() rather than build_command()/parse_output()' - -# _PickJob: one tomogram's resolved inputs -@dataclass(frozen=True) -class _PickJob: - segmentation_path: Path - tomogram_path: Path - tomogram_id: str - config: NativePickerConfig - -# _pick_one: multiprocessing worker entry point -def _pick_one(job: _PickJob) -> tuple[str, list[RawPick]]: - picks = pick_tomogram(job.segmentation_path, job.tomogram_path, job.tomogram_id, job.config) - return job.tomogram_id, picks - -# NativePickerAdapter: ToolAdapter surface for the in-process stamp-native picker -class NativePickerAdapter: - name = PICKER_NAME - stage = 'pick' - mac_compatible = True - requires_gpu = False - automatable = True - batches_natively = True - runs_in_process = True - - def build_command(self, inputs: AdapterInputs) -> ToolCommand: - raise NotImplementedError(_IN_PROCESS_MESSAGE) - - def parse_output(self, result: RunResult) -> AdapterOutput: - raise NotImplementedError(_IN_PROCESS_MESSAGE) - - def run_in_process(self, inputs: AdapterInputs) -> list[RawPick]: - if not inputs.input_paths or not inputs.raw_tomogram_paths: - raise StampPipelineError('stamp-native requires matched segmentation and raw tomogram paths; pass --raw-tomogram-dir to stamp pick') - if not (len(inputs.input_paths) == len(inputs.raw_tomogram_paths) == len(inputs.tomogram_ids)): - raise StampPipelineError('Mismatched input lengths: segmentations, raw tomograms and tomogram IDs must correspond one-to-one') - - voxel_size = inputs.parameters.get('voxel_size_angstrom') - if voxel_size is None: - raise StampPipelineError('stamp-native requires voxel_size_angstrom') - - config_fields = { - key: value - for key, value in inputs.parameters.items() - if key in NativePickerConfig.__dataclass_fields__ - } - config = NativePickerConfig(**config_fields) - vesicle_labels_mrc_by_tomogram = inputs.parameters.get('vesicle_labels_mrc_by_tomogram', {}) - inputs.output_directory.mkdir(parents=True, exist_ok=True) - - total = len(inputs.input_paths) - n_workers = int(inputs.parameters.get('n_workers', 1)) - log.progress(f'Running stamp-native over {total} tomogram(s)' + (f' ({n_workers} workers)' if n_workers > 1 else '')) - jobs: list[_PickJob] = [] - for segmentation_path, tomogram_path, tomogram_id in zip(inputs.input_paths, inputs.raw_tomogram_paths, inputs.tomogram_ids): - tomogram_config = config - labels_path = vesicle_labels_mrc_by_tomogram.get(tomogram_id) - if labels_path is not None: - tomogram_config = replace(config, vesicle_labels_mrc=Path(labels_path)) - elif config.normalise_per_vesicle: - log.warning(f'{tomogram_id}: no vesicle labels found, disabling normalise_per_vesicle for this tomogram') - tomogram_config = replace(config, normalise_per_vesicle=False, vesicle_labels_mrc=None) - jobs.append(_PickJob(segmentation_path, tomogram_path, tomogram_id, tomogram_config)) - - def _on_success(job: _PickJob, result: tuple[str, list[RawPick]]) -> None: - tomogram_id, tomogram_picks = result - log.debug(f'{tomogram_id}: {len(tomogram_picks)} raw picks') - cache_tomogram_picks(inputs.output_directory, tomogram_id, tomogram_picks) - def _on_error(job: _PickJob, exc: Exception) -> None: - if isinstance(exc, StampValidationError): - log.error(f'{job.tomogram_id}: {exc}') - else: - raise exc - # a tomogram's cache file is written atomically on completion, so its presence means it is done - pending = [job for job in jobs if not (inputs.output_directory / f'{job.tomogram_id}.json').is_file()] - if len(pending) < len(jobs): - log.info(f'Resuming stamp-native: {len(jobs) - len(pending)} tomogram(s) loaded from checkpoint') - run_parallel(pending, _pick_one, max_workers=n_workers, label='stamp-native', on_success=_on_success, on_error=_on_error) - return load_cached_picks(inputs.output_directory, inputs.tomogram_ids) diff --git a/src/stamp/adapters/relion.py b/src/stamp/adapters/relion.py index 3f92cf3..345ffbc 100644 --- a/src/stamp/adapters/relion.py +++ b/src/stamp/adapters/relion.py @@ -5,6 +5,7 @@ # Import external dependencies import numpy as np, starfile from pathlib import Path +from scipy.spatial.transform import Rotation # Import STAMP objects from stamp.adapters.base import AdapterInputs, AdapterOutput @@ -27,6 +28,21 @@ def normal_to_tilt_psi(orientation: tuple[float, float, float, float] | None) -> psi = float(np.degrees(np.arctan2(normal[1], normal[0]))) return tilt, psi +# ParticlePose: a particle's class pose as classify wrote it, class average moved by rotation then shift (box x, y, z voxels) gives the subvolume +ParticlePose = tuple[np.ndarray, np.ndarray] + +# relion_euler_angles: (rot, tilt, psi) in degrees such that RELION's matrix A(rot, tilt, psi) equals the reference-to-tomogram rotation; Euler::anglesToMatrix3 in RELION 5 gives A = (Rz(rot) Ry(tilt) Rz(psi)).T with active rotations, so decode R.T as scipy's extrinsic zyz and read the angles in reverse +def relion_euler_angles(rotation: np.ndarray) -> tuple[float, float, float]: + psi, tilt, rot = Rotation.from_matrix(np.asarray(rotation).T).as_euler('zyz', degrees=True) + return float(rot), float(tilt), float(psi) + +# pose_to_relion: Euler angles and origin (Angstrom) of a particle from its box orientation and class pose (reference-to-tomogram rotation is orientation @ rotation, and origin is minus of shift taken to tomogram frame because RELION's origin is shift that centres particle) +def pose_to_relion(orientation: tuple[float, float, float, float] | None, pose: ParticlePose, voxel_size_angstrom: float) -> dict[str, float]: + box_to_tomogram = np.eye(3) if orientation is None else quaternion_to_matrix(orientation) + rot, tilt, psi = relion_euler_angles(box_to_tomogram @ pose[0]) + origin = -(box_to_tomogram @ pose[1]) * voxel_size_angstrom + return {'rlnAngleRot': rot, 'rlnAngleTilt': tilt, 'rlnAnglePsi': psi, 'rlnOriginXAngst': float(origin[0]), 'rlnOriginYAngst': float(origin[1]), 'rlnOriginZAngst': float(origin[2])} + # RelionRefineAdapter: one half-set RELION-5 Refine3D job class RelionRefineAdapter: name = 'relion' @@ -37,16 +53,31 @@ class RelionRefineAdapter: batches_natively = True runs_in_process = False - # write_particle_star: RELION-5 particles.star with normal-derived angle priors (A5) + # write_particle_star: RELION-5 particles.star, with the full class pose as angles and origins where classify estimated one, else normal-derived angle priors def write_particle_star( self, particles: list[Particle], path: Path, - raw_tomogram_paths: dict[str, Path] + raw_tomogram_paths: dict[str, Path], + poses: dict[str, ParticlePose] | None = None, + voxel_size_angstrom: float | None = None, ) -> None: rows = [] for particle in particles: tilt_prior, psi_prior = normal_to_tilt_psi(particle.orientation) + pose = (poses or {}).get(particle.particle_id) + if pose is not None: + if voxel_size_angstrom is None: + raise StampAdapterError('voxel_size_angstrom is required to write particle poses') + rows.append({ + 'rlnTomoName': particle.tomogram_id, + 'rlnCoordinateX': particle.position[0], + 'rlnCoordinateY': particle.position[1], + 'rlnCoordinateZ': particle.position[2], + **pose_to_relion(particle.orientation, pose, voxel_size_angstrom), + 'rlnTomoParticleName': particle.particle_id, + }) + continue rows.append({ 'rlnTomoName': particle.tomogram_id, 'rlnCoordinateX': particle.position[0], diff --git a/src/stamp/classify/align.py b/src/stamp/classify/align.py index 8b31c72..fc131ff 100644 --- a/src/stamp/classify/align.py +++ b/src/stamp/classify/align.py @@ -1,22 +1,11 @@ ''' -STAMP: reference-based in-plane (azimuthal) alignment of subvolumes +STAMP: azimuthal roll of subvolumes about membrane normal ''' # Import external dependencies -import json, numpy as np -from dataclasses import dataclass -from pathlib import Path +import numpy as np from scipy.ndimage import rotate -# Import internal STAMP objects -from stamp.schemas.subvolumes import Subvolumes -from stamp.utils.checkpoint import atomic_write_json -from stamp.utils.log import log -from stamp.utils.parallel import run_parallel - -# _BATCH_SIZE: subvolumes read per chunk in a cluster worker -_BATCH_SIZE = 64 - # _ROLL_AXES: box axes spanning the plane perpendicular to the membrane normal _ROLL_AXES = (0, 1) @@ -25,108 +14,3 @@ def roll_about_normal(subvolume: np.ndarray, angle_degrees: float) -> np.ndarray if abs(angle_degrees) < 1e-6: return subvolume return rotate(subvolume, angle_degrees, axes=_ROLL_AXES, reshape=False, order=1, mode='constant') - -# _annulus_mask: True inside the largest cylinder fitting the box, minus a thin core where roll is ill-defined -def _annulus_mask(box_voxels: int, *, min_radius_fraction: float = 0.1) -> np.ndarray: - half = (box_voxels - 1) / 2.0 - axis = np.arange(box_voxels) - half - x, y, _z = np.meshgrid(axis, axis, axis, indexing='ij') - radius = np.sqrt(x * x + y * y) - return (radius >= min_radius_fraction * half) & (radius <= half) - -# _best_angle: angle_degrees maximising masked real-space CC of subvolume against reference -def _best_angle( - subvolume: np.ndarray, - reference_masked: np.ndarray, - mask: np.ndarray, - angles_degrees: np.ndarray, -) -> float: - reference_norm = np.linalg.norm(reference_masked) or 1.0 - best_angle, best_score = 0.0, -np.inf - for angle in angles_degrees: - rolled = roll_about_normal(subvolume, float(angle))[mask] - rolled = rolled - rolled.mean() - score = float(rolled @ reference_masked / ((np.linalg.norm(rolled) or 1.0) * reference_norm)) - if score > best_score: - best_angle, best_score = float(angle), score - return best_angle - -# _AlignClusterJob: one cluster's members (lazy view so no subvolume data is held or pickled) -@dataclass(frozen=True) -class _AlignClusterJob: - cluster_id: str - member_indices: list[int] - member_subvolumes: Subvolumes # local index i <-> member_indices[i] - mask: np.ndarray - angles: np.ndarray - iterations: int - -# _align_one_cluster: multiprocessing worker entry point using streamed batches -def _align_one_cluster(job: _AlignClusterJob) -> dict[int, float]: - n_members = len(job.member_indices) - current = {local: 0.0 for local in range(n_members)} - for _ in range(max(job.iterations, 1)): - total = np.zeros((job.member_subvolumes.box_voxels,) * 3, dtype=np.float64) - for locals_, batch in job.member_subvolumes.iter_batches(_BATCH_SIZE): - for local, subvolume in zip(locals_, batch): - total += roll_about_normal(subvolume, current[local]) - reference_masked = (total / n_members)[job.mask] - reference_masked = reference_masked - reference_masked.mean() - updated: dict[int, float] = {} - for locals_, batch in job.member_subvolumes.iter_batches(_BATCH_SIZE): - for local, subvolume in zip(locals_, batch): - updated[local] = _best_angle(subvolume, reference_masked, job.mask, job.angles) - current = updated - return {job.member_indices[local]: angle for local, angle in current.items()} - -# _load_cluster_checkpoint: saved angles for a cluster, or None when absent or computed for different members -def _load_cluster_checkpoint(checkpoint_dir: Path | None, cluster_id: str, members: list[int]) -> dict[int, float] | None: - if checkpoint_dir is None: - return None - try: - saved = json.loads((checkpoint_dir / f'{cluster_id}.json').read_text()) - except (OSError, json.JSONDecodeError): - return None - if saved.get('members') != members: - return None - return dict(zip(members, saved['angles'])) - -# align_inplane: per-cluster iterative azimuthal alignment, each finished cluster checkpointed in checkpoint_dir when given; returns {particle_index: angle_degrees} -def align_inplane( - subvols: Subvolumes, - cluster_ids: list[str], - *, - angular_step_degrees: float = 10.0, - iterations: int = 3, - n_workers: int = 1, - checkpoint_dir: Path | None = None, -) -> dict[int, float]: - if len(subvols) == 0: - return {} - box_voxels = subvols.box_voxels - mask = _annulus_mask(box_voxels) - angles = np.arange(0.0, 360.0, angular_step_degrees) - jobs = [] - resolved: dict[int, float] = {} - n_resumed = 0 - for cluster_id in sorted(set(cluster_ids)): - if cluster_id == 'noise': - continue - members = [index for index, cid in enumerate(cluster_ids) if cid == cluster_id] - saved = _load_cluster_checkpoint(checkpoint_dir, cluster_id, members) - if saved is not None: - resolved.update(saved) - n_resumed += 1 - continue - jobs.append(_AlignClusterJob(cluster_id, members, subvols.take(members), mask, angles, iterations)) - if n_resumed: - log.info(f'Resuming in-plane alignment: {n_resumed} cluster(s) loaded from checkpoint') - - # on_success: checkpoint each cluster as it finishes so an abort only loses in-flight clusters - def _on_success(job: _AlignClusterJob, cluster_result: dict[int, float]) -> None: - resolved.update(cluster_result) - if checkpoint_dir is not None: - atomic_write_json(checkpoint_dir / f'{job.cluster_id}.json', {'members': job.member_indices, 'angles': [cluster_result[i] for i in job.member_indices]}) - - run_parallel(jobs, _align_one_cluster, max_workers=n_workers, label='inplane-align', on_success=_on_success) - return resolved \ No newline at end of file diff --git a/src/stamp/classify/average.py b/src/stamp/classify/average.py index 4da2cb2..eb5990c 100644 --- a/src/stamp/classify/average.py +++ b/src/stamp/classify/average.py @@ -7,31 +7,10 @@ from pathlib import Path # Import internal STAMP objects -from stamp.schemas.subvolumes import Subvolumes +from stamp.classify.frames import rotate_density from stamp.utils.io import new_mrc from stamp.utils.log import log -# compute_class_averages: mean subvolume per cluster, streamed in batches -def compute_class_averages( - subvols: Subvolumes, - cluster_ids: list[str], - *, - batch_size: int = 512, -) -> dict[str, tuple[np.ndarray, int]]: - averages: dict[str, tuple[np.ndarray, int]] = {} - for cluster_id in sorted(set(cluster_ids)): - if cluster_id == 'noise': - continue - members = [index for index, cid in enumerate(cluster_ids) if cid == cluster_id] - member_subvols = subvols.take(members) - total = np.zeros((subvols.box_voxels,) * 3, dtype=np.float64) - count = 0 - for _indices, batch in member_subvols.iter_batches(batch_size): - total += batch.sum(axis=0, dtype=np.float64) - count += batch.shape[0] - averages[cluster_id] = ((total / count).astype(np.float32), count) - return averages - # write_class_averages: write each class average as an MRC with its voxel size set def write_class_averages( averages: dict[str, tuple[np.ndarray, int]], @@ -48,3 +27,29 @@ def write_class_averages( new_mrc(path, np.transpose(average, (2, 1, 0)).astype(np.float32), voxel_size=voxel_size_angstrom) written.append(path) return written + +# WeightedAverage: running Fourier-space sum of aligned particles and of their rotated wedge coverage, so averages can be built from batches +class WeightedAverage: + def __init__(self, box_voxels: int) -> None: + self.total = np.zeros((box_voxels,) * 3, dtype=np.complex128) + self.coverage = np.zeros((box_voxels,) * 3) + self.count = 0 + + # add: undo each particle's shift and rotation, then accumulate its spectrum and rotated wedge + def add(self, particles: np.ndarray, wedges: np.ndarray, rotations: np.ndarray, shifts: np.ndarray) -> None: + for particle, wedge, rotation, shift in zip(particles, wedges, rotations, shifts): + aligned = rotate_density(np.roll(particle, -np.round(shift).astype(int), axis=(0, 1, 2)), rotation.T) + self.total += np.fft.fftshift(np.fft.fftn(aligned)) + self.coverage += rotate_density(np.fft.fftshift(wedge), rotation.T) # fftshift puts the Fourier origin on the voxel the rotation turns about + self.count += len(particles) + + # result: coverage-corrected average, unobserved directions are filled by particles + def result(self, *, eps: float = 0.05) -> np.ndarray: + average = np.fft.ifftn(np.fft.ifftshift(self.total / (self.coverage + eps * max(self.count, 1)))).real + return average.astype(np.float32) + +# weighted_average: coverage-corrected average of aligned particles in one call +def weighted_average(particles: np.ndarray, wedges: np.ndarray, rotations: np.ndarray, shifts: np.ndarray, *, eps: float = 0.05) -> np.ndarray: + accumulator = WeightedAverage(particles.shape[1]) + accumulator.add(particles, wedges, rotations, shifts) + return accumulator.result(eps=eps) diff --git a/src/stamp/classify/cluster.py b/src/stamp/classify/cluster.py index 990bef3..6b75316 100644 --- a/src/stamp/classify/cluster.py +++ b/src/stamp/classify/cluster.py @@ -3,10 +3,11 @@ ''' # Import external dependencies -import numpy as np +import igraph, leidenalg, numpy as np from dataclasses import dataclass from sklearn.cluster import KMeans from sklearn.decomposition import PCA +from sklearn.neighbors import kneighbors_graph # Import internal STAMP objects from stamp.utils.log import log, log_config @@ -17,15 +18,17 @@ # ClusteringConfig: class containing parameters for dimensionality reduction and clustering run @dataclass(frozen=True) class ClusteringConfig: - method: str = 'hdbscan' # 'hdbscan' or 'kmeans' + method: str = 'leiden' # 'leiden', 'hdbscan' or 'kmeans' n_components: int = 20 # PCA components - min_cluster_size: int = 20 # HDBSCAN + min_cluster_size: int = 20 # HDBSCAN, and the smallest Leiden community kept n_clusters: int = 5 # KMeans + n_neighbors: int = 15 # Leiden kNN graph + resolution: float = 1.0 # Leiden modularity resolution random_state: int = 0 def __post_init__(self) -> None: - if self.method not in ('hdbscan', 'kmeans'): - raise ValueError("method must be 'hdbscan' or 'kmeans'.") + if self.method not in ('hdbscan', 'kmeans', 'leiden'): + raise ValueError("method must be 'hdbscan', 'kmeans' or 'leiden'.") # ClusteringResult: class containing labels, PCA embedding and centroids from a clustering @dataclass @@ -35,6 +38,18 @@ class ClusteringResult: explained_variance_ratio: np.ndarray centroids: dict[int, np.ndarray] # label -> centroid in PCA space +# _leiden_labels: Leiden modularity communities on a symmetric kNN graph of the embedding, communities below min_cluster_size are noise (-1) +def _leiden_labels(embedding: np.ndarray, config: ClusteringConfig) -> np.ndarray: + adjacency = kneighbors_graph(embedding, min(config.n_neighbors, embedding.shape[0] - 1), mode='connectivity') + symmetric = adjacency.maximum(adjacency.T).tocoo() + graph = igraph.Graph(n=embedding.shape[0], edges=list(zip(symmetric.row.tolist(), symmetric.col.tolist()))) + membership = np.array(leidenalg.find_partition(graph, leidenalg.RBConfigurationVertexPartition, resolution_parameter=config.resolution, seed=config.random_state).membership) + membership[np.bincount(membership)[membership] < config.min_cluster_size] = -1 + labels = np.full_like(membership, -1) + for new, old in enumerate(np.unique(membership[membership >= 0])): # renumber so labels run 0..K-1 + labels[membership == old] = new + return labels + # _cluster_embedding: run the configured clusterer on an embedding, return (labels, centroids) def _cluster_embedding(embedding: np.ndarray, config: ClusteringConfig) -> tuple[np.ndarray, dict[int, np.ndarray]]: if config.method == 'hdbscan': @@ -42,6 +57,8 @@ def _cluster_embedding(embedding: np.ndarray, config: ClusteringConfig) -> tuple raise ValueError(f'only {embedding.shape[0]} particles but min_cluster_size is {config.min_cluster_size}') from fast_hdbscan import HDBSCAN labels = HDBSCAN(min_cluster_size=config.min_cluster_size, min_samples=max(config.min_cluster_size - 1, 1)).fit_predict(np.asarray(embedding, dtype=np.float64)) + elif config.method == 'leiden': + labels = _leiden_labels(embedding, config) else: n_clusters = min(config.n_clusters, embedding.shape[0]) labels = KMeans(n_clusters=n_clusters, random_state=config.random_state, n_init=10).fit_predict(embedding) @@ -56,13 +73,13 @@ def reduce_features(features: np.ndarray, config: ClusteringConfig) -> tuple[np. if n_components < 2: raise ValueError(f'Too few particles ({features.shape[0]}) to run PCA (at least 2 needed)') log.progress(f'Starting PCA: {features.shape[0]} particles, {features.shape[1]} features, {n_components} components') - pca = PCA(n_components=n_components, random_state=config.random_state) + pca = PCA(n_components=n_components, whiten=config.method == 'leiden', random_state=config.random_state) # equal-variance axes keep one feature block from deciding the kNN graph embedding = pca.fit_transform(features) log.progress(f'PCA complete: {pca.explained_variance_ratio_.sum():.1%} variance explained') return embedding, pca.explained_variance_ratio_ -# reduce_and_cluster: PCA followed by HDBSCAN or KMeans +# reduce_and_cluster: PCA followed by HDBSCAN, KMeans or Leiden def reduce_and_cluster(features: np.ndarray, config: ClusteringConfig) -> ClusteringResult: embedding, explained_variance_ratio = reduce_features(features, config) log.progress(f'Starting {config.method} clustering') @@ -71,45 +88,6 @@ def reduce_and_cluster(features: np.ndarray, config: ClusteringConfig) -> Cluste log.progress(f'Clustering complete: {len(set(labels) - {-1})} cluster(s), {int((labels == -1).sum())} noise') return ClusteringResult(labels=labels, embedding=embedding, explained_variance_ratio=explained_variance_ratio, centroids=centroids) -# reduce_and_cluster_shared: one PCA basis fitted on every particle, each index group clustered in that basis -def reduce_and_cluster_shared(features: np.ndarray, groups: dict[str, np.ndarray], config: ClusteringConfig) -> dict[str, ClusteringResult]: - embedding_all, explained_variance_ratio = reduce_features(features, config) - results: dict[str, ClusteringResult] = {} - for name, indices in groups.items(): - log.progress(f'Starting {config.method} clustering for half {name}') - log_config(config.method, config) - embedding = embedding_all[indices] - labels, centroids = _cluster_embedding(embedding, config) - log.progress(f'Half {name} clustering complete: {len(set(labels) - {-1})} cluster(s), {int((labels == -1).sum())} noise') - results[name] = ClusteringResult( - labels=labels, - embedding=embedding, - explained_variance_ratio=explained_variance_ratio, - centroids=centroids, - ) - return results - # label_to_cluster_id: turn a raw cluster label into a stable string id def label_to_cluster_id(label: int) -> str: return NOISE_CLUSTER_ID if label == -1 else f'c{label:02d}' - -# match_clusters_across_halves: pair half-B clusters to half-A clusters by nearest centroid -def match_clusters_across_halves( - centroids_a: dict[int, np.ndarray], centroids_b: dict[int, np.ndarray] -) -> dict[int, tuple[int, float]]: - matches: dict[int, tuple[int, float]] = {} - available = set(centroids_a) - pairs = sorted( - ( - (float(np.linalg.norm(centroid_b - centroids_a[label_a])), label_b, label_a) - for label_b, centroid_b in centroids_b.items() - for label_a in centroids_a - ) - ) - for distance, label_b, label_a in pairs: - if label_b in matches or label_a not in available: - continue - matches[label_b] = (label_a, distance) - available.discard(label_a) - log.debug(f'Matched {len(matches)} cluster pair(s) across halves') - return matches diff --git a/src/stamp/classify/extract.py b/src/stamp/classify/extract.py index 091c25b..897b7ee 100644 --- a/src/stamp/classify/extract.py +++ b/src/stamp/classify/extract.py @@ -9,7 +9,7 @@ from scipy.ndimage import map_coordinates # Import STAMP schema -from stamp.schemas.particles import Particle +from stamp.schemas.particles import OrientationPrior, Particle from stamp.schemas.subvolumes import Subvolumes from stamp.utils.errors import StampValidationError from stamp.utils.io import new_mrc, open_mrc, read_mrc @@ -25,6 +25,7 @@ class _ExtractTomogramJob: box_voxels: int cache_dir: Path subtracted: bool = False + prior: OrientationPrior = OrientationPrior.NORMAL # _SubtractTomogramJob: one tomogram's membrane subtraction, written to disk for extraction to mmap @dataclass(frozen=True) @@ -136,10 +137,11 @@ def _extract_one_tomogram(job: _ExtractTomogramJob) -> tuple[list[Particle], lis if tomogram.dtype != np.float32: tomogram = tomogram.astype(np.float32) for particle in job.group: - if particle.orientation is None or not box_fits_inside(particle.position, tomogram.shape, job.box_voxels): + axis_aligned = job.prior is OrientationPrior.NONE # no orientation prior: the box stays in the tomogram frame whatever the picker reported + if (particle.orientation is None and not axis_aligned) or not box_fits_inside(particle.position, tomogram.shape, job.box_voxels): skipped.append(particle) continue - subvolumes.append(extract_subvolume(tomogram, particle.position, particle.orientation, job.box_voxels)) + subvolumes.append(extract_subvolume(tomogram, particle.position, None if axis_aligned else particle.orientation, job.box_voxels)) kept.append(particle) job.cache_dir.mkdir(parents=True, exist_ok=True) if subvolumes: @@ -160,6 +162,7 @@ def extract_particle_set( n_workers: int = 1, *, cache_dir: Path, + prior: OrientationPrior = OrientationPrior.NORMAL, ) -> tuple[Subvolumes, list[Particle], list[Particle]]: by_tomogram: dict[str, list[Particle]] = {} for particle in particles: @@ -194,7 +197,7 @@ def extract_particle_set( if segmentation_path is not None: subtract_jobs.append(_SubtractTomogramJob(tomogram_id, path, segmentation_path, subtracted_dir / f'{tomogram_id}.mrc')) else: - jobs.append(_ExtractTomogramJob(tomogram_id, group, path, box_voxels, cache_dir)) + jobs.append(_ExtractTomogramJob(tomogram_id, group, path, box_voxels, cache_dir, prior=prior)) if n_resumed: log.info(f'Resuming extraction: {n_resumed}/{len(by_tomogram)} tomogram(s) already extracted') @@ -211,10 +214,10 @@ def _on_subtract_error(job: _SubtractTomogramJob, exc: Exception) -> None: raise exc # fall back to the raw tomogram so the particles are still classified, just without subtraction log.warning(f'{job.tomogram_id}: {exc}; extracting from the raw tomogram without membrane subtraction') - jobs.append(_ExtractTomogramJob(job.tomogram_id, by_tomogram[job.tomogram_id], job.tomogram_path, box_voxels, cache_dir)) + jobs.append(_ExtractTomogramJob(job.tomogram_id, by_tomogram[job.tomogram_id], job.tomogram_path, box_voxels, cache_dir, prior=prior)) def _on_subtracted(job: _SubtractTomogramJob, output_path: Path) -> None: - jobs.append(_ExtractTomogramJob(job.tomogram_id, by_tomogram[job.tomogram_id], str(output_path), box_voxels, cache_dir, subtracted=True)) + jobs.append(_ExtractTomogramJob(job.tomogram_id, by_tomogram[job.tomogram_id], str(output_path), box_voxels, cache_dir, subtracted=True, prior=prior)) def _on_success(job: _ExtractTomogramJob, result: tuple[list[Particle], list[Particle]]) -> None: result_by_tomogram[job.tomogram_id] = result diff --git a/src/stamp/classify/features.py b/src/stamp/classify/features.py index 8455c2c..c4632d3 100644 --- a/src/stamp/classify/features.py +++ b/src/stamp/classify/features.py @@ -139,7 +139,7 @@ def _load_cached_magnitudes(cache_dir: Path | None, tomogram_id: str, rows: list pass return None -# build_feature_matrix: feature matrix for a Subvolumes instance, read in per-tomogram batches, per-tomogram magnitudes cached in cache_dir when given +# build_feature_matrix: feature matrix for a Subvolumes instance (axial_invariant swaps the z profile of each azimuthal mode for its magnitude spectrum, for filaments), read in per-tomogram batches, per-tomogram magnitudes cached in cache_dir when given def build_feature_matrix( subvols: Subvolumes, n_radial_bins: int = 12, @@ -151,6 +151,7 @@ def build_feature_matrix( batch_size: int = 512, cache_dir: Path | None = None, normalisation: str = 'both', + axial_invariant: bool = False, ) -> np.ndarray: log.debug(f'Building features for {len(subvols)} subvolumes, max_mode={max_azimuthal_mode}') if len(subvols) == 0: @@ -202,6 +203,8 @@ def build_feature_matrix( if n_resumed: log.info(f'Resuming feature extraction: {n_resumed}/{len(by_tomogram)} tomogram(s) loaded from checkpoint') stacked = np.stack(magnitudes) # (n_particles, n_modes, n_radial_bins, box_voxels) + if axial_invariant: + stacked = np.abs(np.fft.rfft(stacked, axis=-1)) # axis prior: a filament's position along z is arbitrary, so keep only the spectrum along z n_particles = stacked.shape[0] first_outer_bin = int(np.floor(min_radius_fraction * n_radial_bins)) diff --git a/src/stamp/classify/frames.py b/src/stamp/classify/frames.py new file mode 100644 index 0000000..1e6ad92 --- /dev/null +++ b/src/stamp/classify/frames.py @@ -0,0 +1,34 @@ +''' +STAMP: frame and rotation conventions shared by classification +''' + +# Import external dependencies +import numpy as np +from scipy.ndimage import affine_transform +from scipy.spatial.transform import Rotation + +# azimuth_matrix: right-handed rotation by angle_degrees about the box z axis (x towards y), acting on (x, y, z) box coordinates +def azimuth_matrix(angle_degrees: float) -> np.ndarray: + angle = np.radians(angle_degrees) + cos, sin = np.cos(angle), np.sin(angle) + return np.array([[cos, -sin, 0.0], [sin, cos, 0.0], [0.0, 0.0, 1.0]]) + +# azimuth_degrees: signed rotation angle about z of a matrix that is a pure z rotation, in (-180, 180] +def azimuth_degrees(rotation: np.ndarray) -> float: + return float(np.degrees(np.arctan2(rotation[1, 0], rotation[0, 0]))) + +# flip_matrix: 180 degree rotation about the box x axis, which sends +z to -z (polarity flip of axis prior) +def flip_matrix() -> np.ndarray: + return np.diag([1.0, -1.0, -1.0]) + +# rotate_density: move the density of a box by a rotation about its centre, so a feature at offset r from the centre ends at rotation @ r (array axes are the box x, y, z) +def rotate_density(volume: np.ndarray, rotation: np.ndarray) -> np.ndarray: + centre = (np.array(volume.shape) - 1) / 2.0 + matrix = np.asarray(rotation).T # affine_transform maps output to input coordinates + return affine_transform(volume, matrix, offset=centre - matrix @ centre, order=1) + +# rotation_to_quaternion: unit quaternion (w, x, y, z) of a rotation matrix, with w >= 0 so the sign is unique +def rotation_to_quaternion(rotation: np.ndarray) -> tuple[float, float, float, float]: + x, y, z, w = Rotation.from_matrix(rotation).as_quat() + sign = -1.0 if w < 0 else 1.0 + return (float(sign * w), float(sign * x), float(sign * y), float(sign * z)) diff --git a/src/stamp/classify/halves.py b/src/stamp/classify/halves.py new file mode 100644 index 0000000..7eed80b --- /dev/null +++ b/src/stamp/classify/halves.py @@ -0,0 +1,72 @@ +''' +STAMP: half-set independent polish step and reference-based matching of clusters +''' + +# Import external dependencies +import numpy as np +from dataclasses import dataclass +from pathlib import Path + +# Import internal STAMP objects +from stamp.classify.polish import PolishConfig, PolishResult, run_polish +from stamp.classify.match import align_to_reference +from stamp.classify.merge import pair_thresholds +from stamp.classify.store import ParticleStore +from stamp.utils.log import log + +# HalfMatch: a half-B cluster matched to a half-A cluster, with pose of the half-B reference against half-A one +@dataclass(frozen=True) +class HalfMatch: + label_a: int + similarity: float + rotation: np.ndarray # (3, 3) + shift: np.ndarray # (3,), working voxels + +# match_halves: pair half-B references to half-A references by best-pose similarity, greedily from most similar pair, keeping only pairs that agree at least as well as references agree with themselves +def match_halves(result_a: PolishResult, result_b: PolishResult, merge_fraction: float, *, threads: int = 1) -> dict[int, HalfMatch]: + if not result_a.references or not result_b.references: + return {} # a half with no surviving cluster has nothing to match + space = result_a.space + stack = np.stack(result_b.references) + full = np.ones_like(stack) + candidates = [] + for label_a, reference_a in enumerate(result_a.references): + aligned = align_to_reference(stack, full, reference_a, space, threads=threads) + for label_b in range(len(result_b.references)): + candidates.append((float(aligned.cc[label_b]), label_a, label_b, space.rotations[aligned.rotation_index[label_b]], aligned.shift[label_b].astype(float))) + bars = pair_thresholds(np.concatenate([result_a.ceilings, result_b.ceilings]), merge_fraction) + matches: dict[int, HalfMatch] = {} + used_a: set[int] = set() + for similarity, label_a, label_b, rotation, shift in sorted(candidates, key=lambda c: -c[0]): + if label_b in matches or label_a in used_a: + continue + if similarity >= bars[label_a, len(result_a.ceilings) + label_b]: + matches[label_b] = HalfMatch(label_a, similarity, rotation, shift) + used_a.add(label_a) + log.debug(f'Matched {len(matches)} of {len(result_b.references)} half-B cluster(s) to half A by reference similarity') + return matches + +# express_in_frame_of_a: half-B poses re-expressed against matched half-A reference, so both halves' averages sit in one frame +def express_in_frame_of_a(result_b: PolishResult, matches: dict[int, HalfMatch]) -> tuple[np.ndarray, np.ndarray]: + rotations, shifts = result_b.rotations.copy(), result_b.shifts.astype(float) + for label_b, match in matches.items(): + chosen = result_b.labels == label_b + shifts[chosen] = np.einsum('nij,j->ni', rotations[chosen], match.shift) + shifts[chosen] + rotations[chosen] = rotations[chosen] @ match.rotation + return rotations, shifts + +# run_polish_by_half: polish on each half on its own then match half-B to half-A clusters +def run_polish_by_half( + store: ParticleStore, + indices: dict[str, list[int]], + embeddings: dict[str, np.ndarray], + seed_labels: dict[str, np.ndarray], + config: PolishConfig, + *, + checkpoint_dir: Path | None = None, +) -> tuple[dict[str, PolishResult], dict[int, HalfMatch]]: + results = {} + for half in ('A', 'B'): + log.progress(f'Polish step for half {half}: {len(indices[half])} particle(s)') + results[half] = run_polish(store.take(indices[half]), embeddings[half], seed_labels[half], config, checkpoint_dir=None if checkpoint_dir is None else checkpoint_dir / half) + return results, match_halves(results['A'], results['B'], config.merge_fraction, threads=config.threads) diff --git a/src/stamp/classify/match.py b/src/stamp/classify/match.py new file mode 100644 index 0000000..463d671 --- /dev/null +++ b/src/stamp/classify/match.py @@ -0,0 +1,90 @@ +''' +STAMP: wedge-aware alignment of particles to a reference over a search space +''' + +# Import external dependencies +import numpy as np +from dataclasses import dataclass + +# Import internal STAMP objects +from stamp.classify.search import SearchSpace, rotated_bank + +# Alignment: best candidate per particle against one reference +@dataclass(frozen=True) +class Alignment: + rotation_index: np.ndarray # (n,), index into SearchSpace.rotations + shift: np.ndarray # (n, 3), integer working voxels, particle = shift(rotate(reference)) + cc: np.ndarray # (n,), normalised correlation over the particle's observed Fourier components + +# wedge_filter: particles limited to their own observed Fourier components, so correlation against an unmasked reference equals correlation against a masked one +def wedge_filter(particles: np.ndarray, wedges: np.ndarray) -> np.ndarray: + return np.fft.ifftn(np.fft.fftn(particles, axes=(1, 2, 3)) * wedges, axes=(1, 2, 3)).real.astype(np.float32) + +# EXHAUSTIVE_BELOW: search spaces up to this size get shift search for every rotation, because shift-free score cannot rank rotations when shift window is large (axis prior) +EXHAUSTIVE_BELOW = 128 + +# rank_rotations: normalised correlation and masked reference norm, both (n_particles, n_rotations), without shifts (masked norm of a rotated reference is its wedge-weighted Fourier power) +def rank_rotations(filtered: np.ndarray, wedges: np.ndarray, bank: np.ndarray, box_voxels: int, *, chunk: int = 250) -> tuple[np.ndarray, np.ndarray]: + flat = filtered.reshape(len(filtered), -1) + flat_wedges = wedges.reshape(len(wedges), -1) + particle_norms = np.linalg.norm(flat, axis=1)[:, None] + 1e-8 + scores = np.empty((len(flat), len(bank)), dtype=np.float32) + norms = np.empty_like(scores) + for start in range(0, len(bank), chunk): + part = bank[start:start + chunk] + power = np.abs(np.fft.fftn(part.reshape(-1, *(box_voxels,) * 3), axes=(1, 2, 3))) ** 2 + masked_norms = np.sqrt(flat_wedges @ power.reshape(len(part), -1).T.astype(np.float32) / flat_wedges.shape[1]) + 1e-8 + scores[:, start:start + chunk] = (flat @ part.T) / (particle_norms * masked_norms) + norms[:, start:start + chunk] = masked_norms + return scores, norms + +# _window: wrapped FFT indices of the shifts -m..m +def _window(max_shift: int, box_voxels: int) -> np.ndarray: + return np.arange(-max_shift, max_shift + 1) % box_voxels + +# refine_shift: best shift inside window for one particle against a few candidate rotations +def refine_shift( + particle_ft: np.ndarray, + filtered_norm: float, + candidates_ft: np.ndarray, + masked_norms: np.ndarray, + max_shift: tuple[int, int, int], +) -> tuple[int, np.ndarray, float]: + box_voxels = particle_ft.shape[0] + correlation = np.fft.ifftn(particle_ft[None] * np.conj(candidates_ft), axes=(1, 2, 3)).real + windows = [_window(m, box_voxels) for m in max_shift] + local = correlation[:, windows[0][:, None, None], windows[1][None, :, None], windows[2][None, None, :]] + flat = local.reshape(len(local), -1) + peaks = flat.argmax(axis=1) + scores = flat[np.arange(len(flat)), peaks] / (filtered_norm * masked_norms) + best = int(scores.argmax()) + offsets = np.unravel_index(peaks[best], local.shape[1:]) + return best, np.array([o - m for o, m in zip(offsets, max_shift)]), float(scores[best]) + +# align_to_reference: best rotation and shift of every particle against one reference (stage one ranks rotations without shifts, stage two searches shifts for the `top` best) +def align_to_reference( + particles: np.ndarray, + wedges: np.ndarray, + reference: np.ndarray, + space: SearchSpace, + *, + top: int | None = None, + threads: int = 1, + bank: np.ndarray | None = None, +) -> Alignment: + box_voxels = particles.shape[1] + bank = rotated_bank(reference, space.rotations, threads=threads) if bank is None else bank + filtered = wedge_filter(particles, wedges) + scores, norms = rank_rotations(filtered, wedges, bank, box_voxels) + top = (len(bank) if len(bank) <= EXHAUSTIVE_BELOW else 5) if top is None else min(top, len(bank)) + shortlist = np.tile(np.arange(top), (len(particles), 1)) if top == len(bank) else np.argsort(-scores, axis=1)[:, :top] # exhaustive keeps bank order so one set of spectra serves every particle + bank_ft = np.fft.fftn(bank.reshape(len(bank), *(box_voxels,) * 3), axes=(1, 2, 3)) if top == len(bank) else None + rotation_index = np.empty(len(particles), dtype=np.int64) + shift = np.zeros((len(particles), 3), dtype=np.int64) + cc = np.empty(len(particles), dtype=np.float32) + bank_cubes = bank.reshape(len(bank), *(box_voxels,) * 3) + for i in range(len(particles)): + candidates_ft = bank_ft if bank_ft is not None else np.fft.fftn(bank_cubes[shortlist[i]], axes=(1, 2, 3)) + best, shift[i], cc[i] = refine_shift(np.fft.fftn(filtered[i]), np.linalg.norm(filtered[i]) + 1e-8, candidates_ft, norms[i, shortlist[i]], space.max_shift) + rotation_index[i] = shortlist[i, best] + return Alignment(rotation_index, shift, cc) diff --git a/src/stamp/classify/merge.py b/src/stamp/classify/merge.py new file mode 100644 index 0000000..ca9a20e --- /dev/null +++ b/src/stamp/classify/merge.py @@ -0,0 +1,67 @@ +''' +STAMP: half-split ceilings and reference merging +''' + +# Import external dependencies +import numpy as np +from collections.abc import Iterable + +# Import internal STAMP objects +from stamp.classify.average import WeightedAverage +from stamp.classify.match import align_to_reference +from stamp.classify.search import SearchSpace + +# pairwise_similarity: symmetric matrix of best-pose normalised correlation between references, and pose mapping reference j onto reference i (references are coverage-corrected so no wedge) +def pairwise_similarity(references: list[np.ndarray], space: SearchSpace, *, threads: int = 1) -> tuple[np.ndarray, list[list[tuple[np.ndarray, np.ndarray]]]]: + n = len(references) + stack = np.stack(references) + full = np.ones_like(stack) + similarity = np.eye(n) + poses: list[list[tuple[np.ndarray, np.ndarray]]] = [[(np.eye(3), np.zeros(3)) for _ in range(n)] for _ in range(n)] + for i in range(n): + result = align_to_reference(stack, full, references[i], space, threads=threads) + similarity[i] = result.cc + for j in range(n): + poses[i][j] = (space.rotations[result.rotation_index[j]], result.shift[j].astype(float)) + return np.maximum(similarity, similarity.T), poses + +# merge_groups: connected components of the graph whose edges are similarities at or above threshold (scalar or per-pair matrix) +def merge_groups(similarity: np.ndarray, threshold: float | np.ndarray) -> np.ndarray: + n = len(similarity) + group = np.arange(n) + for i in range(n): + for j in range(i + 1, n): + if similarity[i, j] >= (threshold[i, j] if np.ndim(threshold) else threshold): + group[group == group[j]] = group[i] + return np.unique(group, return_inverse=True)[1] + +# pair_thresholds: merge threshold per pair (fraction of the higher of the two self-agreement ceilings) so an inconsistent reference cannot lower the bar +def pair_thresholds(ceilings: np.ndarray, fraction: float) -> np.ndarray: + return fraction * np.maximum(ceilings[:, None], ceilings[None, :]) + +# half_split_ceilings: per-label agreement between the averages of two random halves of its members, streamed from batches of (indices, volumes, wedges) +def half_split_ceilings( + batches: Iterable[tuple[list[int], np.ndarray, np.ndarray]], + labels: np.ndarray, + rotations: np.ndarray, + shifts: np.ndarray, + space: SearchSpace, + n_labels: int, + box_voxels: int, + *, + min_members: int = 8, + seed: int = 0, +) -> np.ndarray: + side = np.random.default_rng(seed).integers(0, 2, len(labels)) + sums = {(k, s): WeightedAverage(box_voxels) for k in range(n_labels) for s in (0, 1)} + for indices, volumes, wedges in batches: + indices = np.array(indices) + for (k, s), accumulator in sums.items(): + chosen = (labels[indices] == k) & (side[indices] == s) + if chosen.any(): + accumulator.add(volumes[chosen], wedges[chosen], rotations[indices[chosen]], shifts[indices[chosen]]) + out = np.full(n_labels, np.nan) + for k in range(n_labels): + if sums[k, 0].count + sums[k, 1].count >= min_members and sums[k, 0].count and sums[k, 1].count: + out[k] = pairwise_similarity([sums[k, 0].result(), sums[k, 1].result()], space)[0][0, 1] + return np.where(np.isnan(out), np.nanmedian(out) if not np.isnan(out).all() else 1.0, out) diff --git a/src/stamp/classify/null.py b/src/stamp/classify/null.py new file mode 100644 index 0000000..76b81b6 --- /dev/null +++ b/src/stamp/classify/null.py @@ -0,0 +1,35 @@ +''' +STAMP: label-free null for reference agreement and particle rejection, from phase-randomised particles +''' + +# Import external dependencies +import numpy as np + +# Import internal STAMP objects +from stamp.classify.match import align_to_reference +from stamp.classify.merge import half_split_ceilings +from stamp.classify.search import SearchSpace +from stamp.classify.store import ParticleStore +from stamp.classify.wedge import apply_wedge +from stamp.utils.phase import phase_randomise + +# null_particles: phase-randomised copies of random particles, each limited to its own wedge again so spectrum and wedge stay real +def null_particles(store: ParticleStore, count: int, rng: np.random.Generator) -> tuple[np.ndarray, np.ndarray]: + volumes, wedges = store.sample(count, rng) + return np.stack([apply_wedge(phase_randomise(v, rng), w) for v, w in zip(volumes, wedges)]), wedges + +# null_threshold: quantile of the best correlation with any reference among null particles +def null_threshold(store: ParticleStore, references: list[np.ndarray], space: SearchSpace, *, quantile: float, sample_size: int = 100, seed: int = 0, threads: int = 1) -> float: + fake, wedges = null_particles(store, sample_size, np.random.default_rng(seed)) + best = np.max([align_to_reference(fake, wedges, reference, space, threads=threads).cc for reference in references], axis=0) + return float(np.quantile(best, quantile)) + +# null_bar: acceptance bar for a reference's half-split agreement, null mean plus sigmas null standard deviations over repeats of size aligned to the reference the same way +def null_bar(store: ParticleStore, reference: np.ndarray, space: SearchSpace, size: int, *, sigmas: float, repeats: int = 8, seed: int = 0, threads: int = 1) -> float: + rng = np.random.default_rng(seed) + scores = [] + for _ in range(repeats): + fake, wedges = null_particles(store, size, rng) + alignment = align_to_reference(fake, wedges, reference, space, threads=threads) + scores.append(half_split_ceilings([(list(range(len(fake))), fake, wedges)], np.zeros(len(fake), dtype=int), space.rotations[alignment.rotation_index], alignment.shift.astype(float), space, 1, fake.shape[1], seed=int(rng.integers(1 << 30)))[0]) + return float(np.mean(scores) + sigmas * np.std(scores, ddof=1)) diff --git a/src/stamp/classify/polish.py b/src/stamp/classify/polish.py new file mode 100644 index 0000000..a4d75b0 --- /dev/null +++ b/src/stamp/classify/polish.py @@ -0,0 +1,157 @@ +''' +STAMP: polish step, seed references, reassignment, merging and null-based rejection +''' + +# Import external dependencies +import numpy as np +from dataclasses import dataclass +from pathlib import Path + +# Import internal STAMP objects +from stamp.classify.cluster import label_to_cluster_id +from stamp.classify.merge import half_split_ceilings, merge_groups, pair_thresholds, pairwise_similarity +from stamp.classify.null import null_bar, null_threshold +from stamp.classify.references import Assignment, hard_assign, rebuild_references, score_against_refs, seed_reference +from stamp.classify.search import SearchSpace, search_space +from stamp.classify.store import ParticleStore +from stamp.schemas.particles import OrientationPrior +from stamp.utils.checkpoint import atomic_save_npz +from stamp.utils.errors import StampPipelineError +from stamp.utils.log import log + +# PolishConfig: tunables of the polish step +@dataclass(frozen=True) +class PolishConfig: + prior: OrientationPrior + angular_step_degrees: float = 10.0 + n_rotations: int = 3000 # SO(3) candidates for the none prior + shift_range_voxels: int = 3 + n_polish_rounds: int = 2 + min_seed_size: int = 20 # smallest seed cluster that gets a reference + merge_fraction: float = 1.0 # fraction of the higher half-split ceiling two references must reach to merge + null_sigmas: float = 3.0 # a reference must beat the phase-randomised null agreement by this many null standard deviations + reject_quantile: float = 0.95 # null quantile of the best correlation below which a particle is rejected + seed: int = 0 + threads: int = 1 + + def __post_init__(self) -> None: + if self.n_polish_rounds < 1: + raise ValueError('n_polish_rounds must be at least 1') + if not 0.0 < self.reject_quantile < 1.0: + raise ValueError('reject_quantile must be between 0 and 1') + +# PolishResult: per-particle outcome of polish +@dataclass +class PolishResult: + labels: np.ndarray # (n,), -1 for rejected particles, else 0..K-1 + cc: np.ndarray # (n,), correlation with the assigned reference + margin: np.ndarray # (n,), best minus second-best correlation + rotations: np.ndarray # (n, 3, 3), pose against the assigned reference + shifts: np.ndarray # (n, 3), working voxels + polarity: np.ndarray # (n,), -1 where the pose contains the filament flip + references: list[np.ndarray] + ceilings: np.ndarray # (K,), half-split agreement of each final reference + space: SearchSpace + +# run_polish: refine seed clusters into references, polish them against all particles and reject what matches nothing better than noise; each stage is checkpointed in checkpoint_dir when given +def run_polish(store: ParticleStore, embedding: np.ndarray, seed_labels: np.ndarray, config: PolishConfig, *, checkpoint_dir: Path | None = None) -> PolishResult: + box_voxels = store.volumes.box_voxels + space = search_space(config.prior, box_voxels, angular_step_degrees=config.angular_step_degrees, n_rotations=config.n_rotations, shift_range_voxels=config.shift_range_voxels, seed=config.seed) + references, first_round = _resume(checkpoint_dir, seed_labels, config) + if references is None: + seeds = [k for k in np.unique(seed_labels) if k >= 0 and (seed_labels == k).sum() >= config.min_seed_size] + if not seeds: + raise StampPipelineError(f'no seed cluster has at least {config.min_seed_size} particles') + log.progress(f'Building {len(seeds)} seed reference(s)') + references = [seed_reference(store, embedding, np.where(seed_labels == k)[0], space, threads=config.threads) for k in seeds] + _save(checkpoint_dir, 'seeds', seed_labels, references) + for round_number in range(first_round, config.n_polish_rounds): + log.progress(f'Polish round {round_number + 1}/{config.n_polish_rounds}: {len(references)} reference(s)') + references = _polish_round(store, references, space, config) + if not references: + log.warning('No reference beat the phase-randomised null, every particle is rejected: the particles share no consistent structure at this resolution') + return _rejected_everything(store, space) + _save(checkpoint_dir, f'round{round_number}', seed_labels, references) + assignment = hard_assign(score_against_refs(store, references, space, threads=config.threads), space) + threshold = null_threshold(store, references, space, quantile=config.reject_quantile, seed=config.seed, threads=config.threads) + log.debug(f'Rejection threshold from the null: {threshold:.3f}') + return _finalise(store, assignment, references, threshold, space, config) + +# _polish_round: reassign every particle, rebuild references, drop those that do not beat the null and merge those that are the same structure; empty when none beats the null +def _polish_round(store: ParticleStore, references: list[np.ndarray], space: SearchSpace, config: PolishConfig) -> list[np.ndarray]: + box_voxels = store.volumes.box_voxels + assignment = hard_assign(score_against_refs(store, references, space, threads=config.threads), space) + ceilings = half_split_ceilings(store.batches(), assignment.labels, assignment.rotations, assignment.shifts, space, len(references), box_voxels, seed=config.seed) + rebuilt = rebuild_references(store, assignment.labels, assignment.rotations, assignment.shifts, len(references)) + counts = np.bincount(assignment.labels, minlength=len(references)) + bar = null_bar(store, references[int(counts.argmax())], space, max(int(np.median(counts[counts > 0])), 8), sigmas=config.null_sigmas, seed=config.seed, threads=config.threads) + keep = [k for k, reference in enumerate(rebuilt) if reference is not None and ceilings[k] >= bar] + log.debug(f'Null bar {bar:.3f}: kept {len(keep)} of {len(references)} reference(s)') + if not keep: + return [] + kept = [rebuilt[k] for k in keep] + if len(kept) == 1: + return kept + similarity, poses = pairwise_similarity(kept, space, threads=config.threads) + groups = merge_groups(similarity, pair_thresholds(ceilings[keep], config.merge_fraction)) + return _merge_references(store, assignment, keep, kept, groups, poses, space) + +# _rejected_everything: the outcome when no reference survives the null, which is the expected result for a decoy +def _rejected_everything(store: ParticleStore, space: SearchSpace) -> PolishResult: + n = len(store) + return PolishResult(np.full(n, -1), np.zeros(n, dtype=np.float32), np.zeros(n, dtype=np.float32), np.tile(np.eye(3), (n, 1, 1)), np.zeros((n, 3), dtype=np.int64), np.ones(n, dtype=np.int8), [], np.zeros(0), space) + +# _merge_references: one reference per merge group, built from every member at its pose composed with the pose of its old reference against the group's largest reference +def _merge_references(store: ParticleStore, assignment: Assignment, keep: list[int], kept: list[np.ndarray], groups: np.ndarray, poses, space: SearchSpace) -> list[np.ndarray]: + labels = np.full(len(store), -1) + rotations, shifts = assignment.rotations.copy(), assignment.shifts.astype(float) + sizes = np.array([(assignment.labels == k).sum() for k in keep]) + for group in np.unique(groups): + members = np.where(groups == group)[0] + anchor = members[np.argmax(sizes[members])] + for position in members: + chosen = assignment.labels == keep[position] + labels[chosen] = group + if position != anchor: + relative_rotation, relative_shift = poses[anchor][position] # old reference onto the anchor + shifts[chosen] = np.einsum('nij,j->ni', rotations[chosen], relative_shift) + shifts[chosen] + rotations[chosen] = rotations[chosen] @ relative_rotation + return [reference for reference in rebuild_references(store, labels, rotations, shifts, len(np.unique(groups))) if reference is not None] + +# _finalise: reject particles below the null threshold, renumber the surviving references and measure their half-split agreement +def _finalise(store: ParticleStore, assignment: Assignment, references: list[np.ndarray], threshold: float, space: SearchSpace, config: PolishConfig) -> PolishResult: + labels = np.where(assignment.cc >= threshold, assignment.labels, -1) + used = np.unique(labels[labels >= 0]) + renumbered = np.full_like(labels, -1) + for new, old in enumerate(used): + renumbered[labels == old] = new + flipped = (assignment.rotations[:, 2, 2] < 0) & (space.prior is OrientationPrior.AXIS) # a filament pose that sends +z to -z carries the polarity flip, other priors have no polarity + ceilings = half_split_ceilings(store.batches(), renumbered, assignment.rotations, assignment.shifts, space, len(used), store.volumes.box_voxels, seed=config.seed) + return PolishResult(renumbered, assignment.cc, assignment.margin, assignment.rotations, assignment.shifts, np.where(flipped, -1, 1).astype(np.int8), [references[k] for k in used], ceilings, space) + +# _save: checkpoint the references after a stage together with the seeds they derive from +def _save(checkpoint_dir: Path | None, stage: str, seed_labels: np.ndarray, references: list[np.ndarray]) -> None: + if checkpoint_dir is not None: + checkpoint_dir.mkdir(parents=True, exist_ok=True) + atomic_save_npz(checkpoint_dir / f'{stage}.npz', seed_labels=seed_labels, references=np.stack(references)) + +# _resume: references of the latest finished stage and the next round to run, or (None, 0) when nothing usable is saved +def _resume(checkpoint_dir: Path | None, seed_labels: np.ndarray, config: PolishConfig) -> tuple[list[np.ndarray] | None, int]: + if checkpoint_dir is None: + return None, 0 + for round_number in range(config.n_polish_rounds - 1, -2, -1): + path = checkpoint_dir / ('seeds.npz' if round_number < 0 else f'round{round_number}.npz') + try: + with np.load(path) as saved: + if np.array_equal(saved['seed_labels'], seed_labels): + log.info(f'Resuming polish step after {path.stem}') + return list(saved['references']), round_number + 1 + except (OSError, ValueError, KeyError): + continue + return None, 0 + +# posed_class_averages: coverage-corrected average per cluster id from particles at their polish poses +def posed_class_averages(store: ParticleStore, labels: np.ndarray, rotations: np.ndarray, shifts: np.ndarray) -> dict[str, tuple[np.ndarray, int]]: + n_labels = int(labels.max()) + 1 if (labels >= 0).any() else 0 + averages = rebuild_references(store, labels, rotations, shifts, n_labels, min_members=1) + return {label_to_cluster_id(k): (average, int((labels == k).sum())) for k, average in enumerate(averages) if average is not None} diff --git a/src/stamp/classify/prepare.py b/src/stamp/classify/prepare.py new file mode 100644 index 0000000..e2b7dfb --- /dev/null +++ b/src/stamp/classify/prepare.py @@ -0,0 +1,42 @@ +''' +STAMP: normalisation, soft masking and Fourier binning of subvolumes for alignment +''' + +# Import external dependencies +import numpy as np + +# radius_grid: distance of every voxel of a box from its centre +def radius_grid(box_voxels: int) -> np.ndarray: + axis = np.arange(box_voxels) - (box_voxels - 1) / 2.0 + x, y, z = np.meshgrid(axis, axis, axis, indexing='ij') + return np.sqrt(x * x + y * y + z * z) + +# soft_mask: sphere of 1 inside radius_voxels with a cosine fall to 0 over edge_voxels +def soft_mask(box_voxels: int, radius_voxels: float, edge_voxels: float = 3.0) -> np.ndarray: + ramp = np.clip((radius_grid(box_voxels) - radius_voxels) / edge_voxels, 0.0, 1.0) + return (0.5 * (1.0 + np.cos(np.pi * ramp))).astype(np.float32) + +# normalise: zero mean and unit variance, with statistics from the voxels where mask > 0.5 +def normalise(volume: np.ndarray, mask: np.ndarray) -> np.ndarray: + inside = volume[mask > 0.5] + return ((volume - inside.mean()) / (inside.std() + 1e-8)).astype(np.float32) + +# working_box: odd edge of a box Fourier-cropped by roughly factor, so centre stays on a voxel +def working_box(box_voxels: int, factor: int) -> int: + return box_voxels if factor <= 1 else 2 * (box_voxels // (2 * factor)) + 1 + +# fourier_bin: resample a cube to an odd smaller edge by cropping its Fourier transform, which cannot alias +def fourier_bin(volume: np.ndarray, new_box_voxels: int) -> np.ndarray: + box_voxels = volume.shape[0] + if new_box_voxels == box_voxels: + return volume + spectrum = np.fft.fftshift(np.fft.fftn(volume)) + low = box_voxels // 2 - new_box_voxels // 2 + cropped = spectrum[low:low + new_box_voxels, low:low + new_box_voxels, low:low + new_box_voxels] + binned = np.fft.ifftn(np.fft.ifftshift(cropped)).real * (new_box_voxels / box_voxels) ** 3 + return binned.astype(np.float32) + +# prepare_particle: normalise inside a soft sphere, mask, then bin to working box +def prepare_particle(volume: np.ndarray, new_box_voxels: int, *, radius_fraction: float = 0.4) -> np.ndarray: + mask = soft_mask(volume.shape[0], radius_fraction * volume.shape[0]) + return fourier_bin(normalise(volume, mask) * mask, new_box_voxels) diff --git a/src/stamp/classify/references.py b/src/stamp/classify/references.py new file mode 100644 index 0000000..ece93af --- /dev/null +++ b/src/stamp/classify/references.py @@ -0,0 +1,78 @@ +''' +STAMP: references for class polishing, scoring particles against them and rebuilding them from members +''' + +# Import external dependencies +import numpy as np +from dataclasses import dataclass + +# Import internal STAMP objects +from stamp.classify.average import WeightedAverage +from stamp.classify.match import Alignment, align_to_reference +from stamp.classify.search import SearchSpace, rotated_bank +from stamp.classify.store import ParticleStore + +# Scores: every particle aligned to every reference, first axis is the reference +@dataclass(frozen=True) +class Scores: + cc: np.ndarray # (n_refs, n) + rotation_index: np.ndarray # (n_refs, n) + shift: np.ndarray # (n_refs, n, 3) + +# Assignment: each particle's best reference and its pose against that reference +@dataclass(frozen=True) +class Assignment: + labels: np.ndarray # (n,), reference index + cc: np.ndarray # (n,), correlation with the assigned reference + margin: np.ndarray # (n,), best minus second-best correlation across references (the correlation itself with one reference) + rotations: np.ndarray # (n, 3, 3) + shifts: np.ndarray # (n, 3), working voxels + +# align_store: align every particle of a store to one reference, streaming in batches +def align_store(store: ParticleStore, reference: np.ndarray, space: SearchSpace, *, threads: int = 1, batch_size: int = 256) -> Alignment: + bank = rotated_bank(reference, space.rotations, threads=threads) + rotation_index = np.empty(len(store), dtype=np.int64) + shift = np.zeros((len(store), 3), dtype=np.int64) + cc = np.empty(len(store), dtype=np.float32) + for indices, volumes, wedges in store.batches(batch_size): + result = align_to_reference(volumes, wedges, reference, space, threads=threads, bank=bank) + rotation_index[indices], shift[indices], cc[indices] = result.rotation_index, result.shift, result.cc + return Alignment(rotation_index, shift, cc) + +# score_against_refs: alignment of every particle to every reference +def score_against_refs(store: ParticleStore, references: list[np.ndarray], space: SearchSpace, *, threads: int = 1) -> Scores: + results = [align_store(store, reference, space, threads=threads) for reference in references] + return Scores(np.stack([r.cc for r in results]), np.stack([r.rotation_index for r in results]), np.stack([r.shift for r in results])) + +# hard_assign: best reference per particle, with its pose +def hard_assign(scores: Scores, space: SearchSpace) -> Assignment: + labels = scores.cc.argmax(axis=0) + columns = np.arange(scores.cc.shape[1]) + ordered = np.sort(scores.cc, axis=0) + margin = ordered[-1] - ordered[-2] if len(ordered) > 1 else ordered[-1] + return Assignment(labels, scores.cc[labels, columns], margin, space.rotations[scores.rotation_index[labels, columns]], scores.shift[labels, columns, :]) + +# rebuild_references: coverage-corrected average of each label's members at their poses +def rebuild_references(store: ParticleStore, labels: np.ndarray, rotations: np.ndarray, shifts: np.ndarray, n_refs: int, *, min_members: int = 3, batch_size: int = 256) -> list[np.ndarray | None]: + accumulators = {k: WeightedAverage(store.volumes.box_voxels) for k in range(n_refs) if (labels == k).sum() >= min_members} + for indices, volumes, wedges in store.batches(batch_size): + indices = np.array(indices) + for k, accumulator in accumulators.items(): + chosen = labels[indices] == k + if chosen.any(): + accumulator.add(volumes[chosen], wedges[chosen], rotations[indices[chosen]], shifts[indices[chosen]]) + return [accumulators[k].result() if k in accumulators else None for k in range(n_refs)] + +# refine_reference: grow a reference from a single seed particle by iterated alignment of the members and re-averaging +def refine_reference(members: ParticleStore, seed: np.ndarray, space: SearchSpace, *, n_iter: int = 3, threads: int = 1) -> np.ndarray: + reference = seed + for _ in range(n_iter): + alignment = align_store(members, reference, space, threads=threads) + reference = rebuild_references(members, np.zeros(len(members), dtype=int), space.rotations[alignment.rotation_index], alignment.shift, 1, min_members=1)[0] + return reference + +# seed_reference: reference for a seed cluster, started from the member closest to the cluster's mean in feature space +def seed_reference(store: ParticleStore, embedding: np.ndarray, members: np.ndarray, space: SearchSpace, *, threads: int = 1) -> np.ndarray: + medoid = int(members[np.argmin(np.linalg.norm(embedding[members] - embedding[members].mean(axis=0), axis=1))]) + group = store.take(members.tolist()) + return refine_reference(group, store.load([medoid])[0][0], space, threads=threads) diff --git a/src/stamp/classify/search.py b/src/stamp/classify/search.py new file mode 100644 index 0000000..2244898 --- /dev/null +++ b/src/stamp/classify/search.py @@ -0,0 +1,58 @@ +''' +STAMP: alignment search space for each orientation prior +''' + +# Import external dependencies +import numpy as np +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass +from scipy.spatial.transform import Rotation + +# Import internal STAMP objects +from stamp.classify.frames import azimuth_matrix, flip_matrix, rotate_density +from stamp.schemas.particles import OrientationPrior + +# SearchSpace: candidate rotations (with the polarity each one carries) and the shift window searched around each +@dataclass(frozen=True) +class SearchSpace: + prior: OrientationPrior + rotations: np.ndarray # (n, 3, 3), reference moved by rotations[i] gives candidate i + polarity: np.ndarray # (n,), -1 for candidates containing the flip, +1 otherwise + max_shift: tuple[int, int, int] # largest shift searched along x, y, z in working voxels + + def __len__(self) -> int: + return len(self.rotations) + +# search_space: rotations and shift window for a prior at working box size box_voxels +def search_space( + prior: OrientationPrior, + box_voxels: int, + *, + angular_step_degrees: float = 10.0, + n_rotations: int = 3000, + shift_range_voxels: int = 3, + seed: int = 0, +) -> SearchSpace: + lateral = (shift_range_voxels,) * 2 + if prior is OrientationPrior.NORMAL: + angles = np.arange(0.0, 360.0, angular_step_degrees) + rotations = np.stack([azimuth_matrix(a) for a in angles]) + return SearchSpace(prior, rotations, np.ones(len(rotations), dtype=np.int8), (*lateral, shift_range_voxels)) + if prior is OrientationPrior.AXIS: + angles = np.arange(0.0, 360.0, angular_step_degrees) + upright = np.stack([azimuth_matrix(a) for a in angles]) + rotations = np.concatenate([upright, upright @ flip_matrix()]) + polarity = np.concatenate([np.ones(len(angles)), -np.ones(len(angles))]).astype(np.int8) + return SearchSpace(prior, rotations, polarity, (*lateral, max(shift_range_voxels, box_voxels // 4))) # a quarter box either side covers a few helical repeats + random = Rotation.random(n_rotations - 1, random_state=seed).as_matrix() + rotations = np.concatenate([np.eye(3)[None], random]) # identity first so a pre-aligned set can win + return SearchSpace(prior, rotations, np.ones(len(rotations), dtype=np.int8), (*lateral, shift_range_voxels)) + +# rotated_bank: the reference moved by every candidate rotation, flattened to (n, voxels) +def rotated_bank(reference: np.ndarray, rotations: np.ndarray, *, threads: int = 1) -> np.ndarray: + if threads <= 1: + bank = [rotate_density(reference, rotation) for rotation in rotations] + else: + with ThreadPoolExecutor(threads) as pool: # scipy.ndimage releases the GIL + bank = list(pool.map(lambda rotation: rotate_density(reference, rotation), rotations)) + return np.stack(bank).reshape(len(rotations), -1).astype(np.float32) diff --git a/src/stamp/classify/shfeatures.py b/src/stamp/classify/shfeatures.py new file mode 100644 index 0000000..ab6648c --- /dev/null +++ b/src/stamp/classify/shfeatures.py @@ -0,0 +1,58 @@ +''' +STAMP: rotation-invariant spherical-harmonic features of Fourier power spectrum, with each particle's missing wedge as missing data +''' + +# Import external dependencies +import numpy as np +from functools import partial +from scipy.ndimage import map_coordinates + +# Import internal STAMP objects +from stamp.classify.prepare import normalise, soft_mask +from stamp.classify.spherical import degree_power, fit_matrix, lm_pairs, real_sh_basis, sphere_grid +from stamp.classify.wedge import observed_directions +from stamp.schemas.subvolumes import Subvolumes +from stamp.utils.parallel import run_parallel_ordered + +# _MARGIN_DEGREES: angular safety margin inside wedge edge, where interpolation and soft mask leak +_MARGIN_DEGREES = 4.0 + +# shell_frequencies: n radial shells between low and high frequency in cycles per voxel +def shell_frequencies(n_shells: int, low: float = 0.04, high: float = 0.20) -> np.ndarray: + return np.linspace(low, high, n_shells) + +# sh_power: invariant features (n_shells * n_degrees,) of one axis-aligned box, fit weighted to directions this particle measured, one small ridge solve per particle +def sh_power( + volume: np.ndarray, + tilt_max_degrees: float | None, + tilt_axis_degrees: float, + *, + n_shells: int = 8, + lmax: int = 4, + ridge: float = 1.0, + mask_radius_fraction: float = 0.4, +) -> np.ndarray: + box_voxels = volume.shape[0] + pairs = lm_pairs(lmax, even_only=True) # |F|^2 is centrosymmetric + directions, quadrature = sphere_grid() + observed = observed_directions(directions, None, tilt_max_degrees, tilt_axis_degrees, margin_degrees=_MARGIN_DEGREES) + operator = fit_matrix(real_sh_basis(directions, pairs), quadrature * observed, ridge) + mask = soft_mask(box_voxels, mask_radius_fraction * box_voxels) + power = np.abs(np.fft.fftn(normalise(volume, mask) * mask)) ** 2 + coordinates = np.stack([shell_frequencies(n_shells)[:, None] * directions[None, :, axis] * box_voxels for axis in range(3)]) + samples = map_coordinates(power, coordinates.reshape(3, -1), order=1, mode='grid-wrap').reshape(n_shells, -1) + return degree_power(samples @ operator.T, pairs).ravel() + +# build_sh_feature_matrix: log-compressed, column-standardised invariant features for every particle of a store of axis-aligned boxes +def build_sh_feature_matrix(subvols: Subvolumes, tilt_max_degrees: float | None, tilt_axis_degrees: float, *, n_workers: int = 1, batch_size: int = 512) -> np.ndarray: + if len(subvols) == 0: + return np.empty((0, 0)) + worker = partial(sh_power, tilt_max_degrees=tilt_max_degrees, tilt_axis_degrees=tilt_axis_degrees) + rows: list[np.ndarray | None] = [None] * len(subvols) + for indices, batch in subvols.iter_batches(batch_size): + for index, row in zip(indices, run_parallel_ordered(list(batch), worker, max_workers=n_workers, label='sh-features')): + rows[index] = row + logged = np.log(np.stack(rows) + 1e-12) + spread = logged.std(axis=0, keepdims=True) + spread[spread == 0.0] = 1.0 + return (logged - logged.mean(axis=0, keepdims=True)) / spread diff --git a/src/stamp/classify/spherical.py b/src/stamp/classify/spherical.py new file mode 100644 index 0000000..46f064a --- /dev/null +++ b/src/stamp/classify/spherical.py @@ -0,0 +1,40 @@ +''' +STAMP: real spherical harmonics, sphere quadrature and masked ridge fits +''' + +# Import external dependencies +import numpy as np +from scipy.special import sph_harm_y + +# sphere_grid: Gauss-Legendre by uniform-azimuth grid on the unit sphere, unit vectors (n, 3) as (x, y, z) and quadrature weights summing to 4 pi +def sphere_grid(n_theta: int = 16, n_phi: int = 32) -> tuple[np.ndarray, np.ndarray]: + nodes, gauss_weights = np.polynomial.legendre.leggauss(n_theta) + phi = np.arange(n_phi) * 2 * np.pi / n_phi + cos_theta, azimuth = np.meshgrid(nodes, phi, indexing='ij') + sin_theta = np.sqrt(1 - cos_theta**2) + xyz = np.stack([sin_theta * np.cos(azimuth), sin_theta * np.sin(azimuth), cos_theta], axis=-1).reshape(-1, 3) + return xyz, np.repeat(gauss_weights, n_phi) * (2 * np.pi / n_phi) + +# lm_pairs: (l, m) for l up to lmax, even l only when even_only +def lm_pairs(lmax: int, *, even_only: bool) -> list[tuple[int, int]]: + return [(l, m) for l in range(0, lmax + 1, 2 if even_only else 1) for m in range(-l, l + 1)] + +# real_sh_basis: orthonormal real spherical harmonics at unit vectors, shape (n_points, n_lm) +def real_sh_basis(xyz: np.ndarray, pairs: list[tuple[int, int]]) -> np.ndarray: + theta = np.arccos(np.clip(xyz[:, 2], -1, 1)) + phi = np.arctan2(xyz[:, 1], xyz[:, 0]) + columns = [] + for l, m in pairs: + y = sph_harm_y(l, abs(m), theta, phi) + columns.append(y.real if m == 0 else np.sqrt(2) * (y.real if m > 0 else y.imag) * (-1) ** abs(m)) + return np.stack(columns, axis=1) + +# fit_matrix: ridge least-squares operator (n_lm, n_points) so coefficients = operator @ samples, with per-point weights (zero for missing data) +def fit_matrix(basis: np.ndarray, weights: np.ndarray, ridge: float) -> np.ndarray: + weighted = basis * weights[:, None] + return np.linalg.solve(basis.T @ weighted + ridge * np.eye(basis.shape[1]), weighted.T) + +# degree_power: rotation invariants P_l = sum_m c_lm^2 for each l, from coefficients (..., n_lm) +def degree_power(coefficients: np.ndarray, pairs: list[tuple[int, int]]) -> np.ndarray: + degrees = np.array([l for l, _ in pairs]) + return np.stack([(coefficients[..., degrees == l] ** 2).sum(-1) for l in np.unique(degrees)], axis=-1) diff --git a/src/stamp/classify/store.py b/src/stamp/classify/store.py new file mode 100644 index 0000000..88bb488 --- /dev/null +++ b/src/stamp/classify/store.py @@ -0,0 +1,59 @@ +''' +STAMP: working-resolution particles with their orientations, wedges served on demand +''' + +# Import external dependencies +import numpy as np +from collections.abc import Iterator, Sequence +from dataclasses import dataclass +from pathlib import Path + +# Import internal STAMP objects +from stamp.classify.prepare import prepare_particle +from stamp.classify.wedge import box_wedge +from stamp.schemas.subvolumes import Subvolumes + +# ParticleStore: prepared (normalised, masked, binned) particles on disk plus what is needed to rebuild each particle's wedge +@dataclass(frozen=True) +class ParticleStore: + volumes: Subvolumes + orientations: list[tuple[float, float, float, float] | None] + tilt_max_degrees: float | None + tilt_axis_degrees: float + + def __len__(self) -> int: + return len(self.volumes) + + # take: view over a subset of particles, no data copy + def take(self, indices: Sequence[int]) -> 'ParticleStore': + return ParticleStore(self.volumes.take(indices), [self.orientations[i] for i in indices], self.tilt_max_degrees, self.tilt_axis_degrees) + + # wedges: box-frame wedges of the given particles + def wedges(self, indices: Sequence[int]) -> np.ndarray: + box_voxels = self.volumes.box_voxels + return np.stack([box_wedge(box_voxels, self.orientations[i], self.tilt_max_degrees, self.tilt_axis_degrees) for i in indices]) + + # load: volumes and wedges of the given particles, in the order given + def load(self, indices: Sequence[int]) -> tuple[np.ndarray, np.ndarray]: + return np.stack([self.volumes[i] for i in indices]), self.wedges(indices) + + # batches: (indices, volumes, wedges) grouped by tomogram for disk-local reads + def batches(self, batch_size: int = 256) -> Iterator[tuple[list[int], np.ndarray, np.ndarray]]: + for indices, volumes in self.volumes.iter_batches(batch_size): + yield indices, volumes, self.wedges(indices) + + # sample: count distinct random particles + def sample(self, count: int, rng: np.random.Generator) -> tuple[np.ndarray, np.ndarray]: + return self.load(sorted(rng.choice(len(self), min(count, len(self)), replace=False).tolist())) + +# build_store: prepare every particle of an extracted store at working box and persist result in cache_dir +def build_store( + subvols: Subvolumes, + orientations: list[tuple[float, float, float, float] | None], + working_box_voxels: int, + tilt_max_degrees: float | None, + tilt_axis_degrees: float, + cache_dir: Path, +) -> ParticleStore: + prepared = ((index, prepare_particle(volume, working_box_voxels)) for indices, batch in subvols.iter_batches() for index, volume in zip(indices, batch)) + return ParticleStore(subvols.write_rolled(prepared, cache_dir, box_voxels=working_box_voxels), orientations, tilt_max_degrees, tilt_axis_degrees) diff --git a/src/stamp/classify/wedge.py b/src/stamp/classify/wedge.py new file mode 100644 index 0000000..1bcc1f2 --- /dev/null +++ b/src/stamp/classify/wedge.py @@ -0,0 +1,47 @@ +''' +STAMP: per-particle missing wedge in the box frame +''' + +# Import external dependencies +import numpy as np + +# Import internal STAMP objects +from stamp.classify.extract import quaternion_to_matrix + +# _tilt_normal: in-plane tomogram direction perpendicular to the tilt axis +def _tilt_normal(tilt_axis_degrees: float) -> np.ndarray: + axis = np.radians(tilt_axis_degrees) + return np.array([np.sin(axis), -np.cos(axis), 0.0]) + +# observed_directions: whether Fourier vectors (n, 3) given in the box frame survive the wedge; margin_degrees shrinks the tilt limit to stay clear of the soft edge +def observed_directions( + vectors_xyz: np.ndarray, + orientation: tuple[float, float, float, float] | None, + tilt_max_degrees: float | None, + tilt_axis_degrees: float, + *, + margin_degrees: float = 0.0, +) -> np.ndarray: + if tilt_max_degrees is None: + return np.ones(len(vectors_xyz), dtype=bool) + tomogram_frame = vectors_xyz if orientation is None else vectors_xyz @ quaternion_to_matrix(orientation).T + limit = np.tan(np.radians(max(tilt_max_degrees - margin_degrees, 1.0))) + return np.abs(tomogram_frame[:, 2]) <= np.abs(tomogram_frame @ _tilt_normal(tilt_axis_degrees)) * limit + +# box_wedge: float32 0/1 mask over the FFT grid of a box (unshifted order, axes x, y, z), 1 where the particle's Fourier components were measured +def box_wedge( + box_voxels: int, + orientation: tuple[float, float, float, float] | None, + tilt_max_degrees: float | None, + tilt_axis_degrees: float, +) -> np.ndarray: + if tilt_max_degrees is None: + return np.ones((box_voxels,) * 3, dtype=np.float32) + freq = np.fft.fftfreq(box_voxels) + grid = np.stack(np.meshgrid(freq, freq, freq, indexing='ij'), axis=-1).reshape(-1, 3) + observed = observed_directions(grid, orientation, tilt_max_degrees, tilt_axis_degrees) + return observed.reshape((box_voxels,) * 3).astype(np.float32) + +# apply_wedge: remove the unobserved Fourier components of a box +def apply_wedge(volume: np.ndarray, wedge: np.ndarray) -> np.ndarray: + return np.fft.ifftn(np.fft.fftn(volume) * wedge).real.astype(np.float32) diff --git a/src/stamp/cli/classify.py b/src/stamp/cli/classify.py index 5895079..f9763cb 100644 --- a/src/stamp/cli/classify.py +++ b/src/stamp/cli/classify.py @@ -53,12 +53,12 @@ def classify( typer.Option('--n-bins', help='Radial bins in the rotational average.', rich_help_panel = 'Subvolume extraction'), ] = 12, method: Annotated[ - Literal['hdbscan', 'kmeans'], + Literal['leiden', 'hdbscan', 'kmeans'], typer.Option('--method', help='Clustering method to use.', rich_help_panel = 'Clustering'), - ] = 'hdbscan', + ] = 'leiden', min_cluster_size: Annotated[ int, - typer.Option('--min-cluster-size', help='Minimum cluster size (used by HDBSCAN).', rich_help_panel = 'Clustering'), + typer.Option('--min-cluster-size', help='Minimum cluster size (used by HDBSCAN and Leiden, and the smallest seed the polish step refines).', rich_help_panel = 'Clustering'), ] = 20, n_clusters: Annotated[ int, @@ -70,22 +70,15 @@ def classify( ] = 20, strict_halfset_independence: Annotated[ bool, - typer.Option('--strict-halfset-independence', help='Cluster each half separately and match clusters afterwards.', rich_help_panel = 'Clustering'), + typer.Option('--strict-halfset-independence/--no-strict-halfset-independence', help='Cluster each half separately and match clusters afterwards.', rich_help_panel = 'Clustering'), ] = True, random_state: Annotated[ int, typer.Option('--seed', help='Seed for PCA and KMeans.', rich_help_panel = 'Clustering'), ] = 0, - inplane_alignment: Annotated[ - bool, - typer.Option('--inplane-alignment/--no-inplane-alignment', help='Estimate per-particle in-plane angle for averaging.', rich_help_panel = 'In-plane alignment'), - ] = True, inplane_angular_step_degrees: Annotated[ - float, typer.Option('--inplane-step-deg', help='In-plane search step in degrees.', rich_help_panel = 'In-plane alignment'), + float, typer.Option('--inplane-step-deg', help='Angular step of the azimuth search in degrees.', rich_help_panel = 'In-plane alignment'), ] = 10.0, - inplane_iterations: Annotated[ - int, typer.Option('--inplane-iterations', help='Number of reference refinement rounds to run.', rich_help_panel = 'In-plane alignment'), - ] = 3, azimuthal_modes: Annotated[ int, typer.Option(help='Highest azimuthal Fourier mode retained. 0 reproduces pure rotational averaging; 4 captures C4 symmetry. Higher modes are increasingly noisy.', rich_help_panel = 'Subvolume extraction'), @@ -102,9 +95,45 @@ def classify( Literal['none', 'particle', 'tomogram', 'both'], typer.Option('--feature-normalisation', help='Method for azimuthal mode (above 0) normalisation.', rich_help_panel = 'Subvolume extraction'), ] = 'both', + tilt_max_degrees: Annotated[ + float | None, + typer.Option('--tilt-max', help='Maximum tilt of the tilt series in degrees, sets the missing wedge. Omit for no wedge.', min=1.0, max=89.0, rich_help_panel = 'Polish'), + ] = None, + tilt_axis_degrees: Annotated[ + float, + typer.Option('--tilt-axis', help='Tilt axis angle from the tomogram x axis in the xy plane, 90 is a tilt about y.', rich_help_panel = 'Polish'), + ] = 90.0, + bin_factor: Annotated[ + int, + typer.Option('--bin-factor', help='Fourier binning factor of the polish working resolution.', min=1, rich_help_panel = 'Polish'), + ] = 2, + n_rotations: Annotated[ + int, + typer.Option('--n-rots', help='Candidate rotations of the none prior search.', min=2, rich_help_panel = 'Polish'), + ] = 3000, + shift_range_voxels: Annotated[ + int, + typer.Option('--shift-range', help='Largest shift searched (the axis prior also searches a quarter box along the axis).', min=0, rich_help_panel = 'Polish'), + ] = 3, + polish_rounds: Annotated[ + int, + typer.Option('--polish-rounds', help='Number of reassign, rebuild and merge rounds during polish.', min=1, rich_help_panel = 'Polish'), + ] = 2, + null_sigmas: Annotated[ + float, + typer.Option('--null-sigmas', help='Number of null standard deviations that a reference must beat the phase-randomised null agreement by.', min=0.0, rich_help_panel = 'Polish'), + ] = 3.0, + reject_quantile: Annotated[ + float, + typer.Option('--reject-quantile', help='Null quantile of the best correlation below which a particle is rejected as noise.', min=0.5, max=0.999, rich_help_panel = 'Polish'), + ] = 0.95, + merge_fraction: Annotated[ + float, + typer.Option('--merge-fraction', help='Fraction of the higher half-split agreement two references must reach to be merged (and two halves to be matched).', min=0.0, rich_help_panel = 'Polish'), + ] = 1.0, n_workers: Annotated[ int, - typer.Option('-n', '--n-processes', help='Number of processes to use for per-cluster in-plane alignment (1 = sequential).'), + typer.Option('-n', '--n-processes', help='Number of processes to use (1 = sequential).'), ] = 1, make_plots: Annotated[ bool, @@ -136,9 +165,7 @@ def classify( n_components=n_components, strict_halfset_independence=strict_halfset_independence, random_state=random_state, - inplane_alignment=inplane_alignment, inplane_angular_step_degrees=inplane_angular_step_degrees, - inplane_iterations=inplane_iterations, n_workers=n_workers, azimuthal_modes=azimuthal_modes, min_radius_fraction=min_radius_fraction, @@ -147,4 +174,13 @@ def classify( make_plots=make_plots, plot_format=plot_format, keep_raw=keep_raw, + tilt_max_degrees=tilt_max_degrees, + tilt_axis_degrees=tilt_axis_degrees, + bin_factor=bin_factor, + n_rotations=n_rotations, + shift_range_voxels=shift_range_voxels, + polish_rounds=polish_rounds, + null_sigmas=null_sigmas, + reject_quantile=reject_quantile, + merge_fraction=merge_fraction, ) diff --git a/src/stamp/cli/decoy.py b/src/stamp/cli/decoy.py index d493220..f68fc32 100644 --- a/src/stamp/cli/decoy.py +++ b/src/stamp/cli/decoy.py @@ -3,7 +3,7 @@ ''' # Import external dependencies -import json, typer +import typer from pathlib import Path from typing import Annotated, Literal @@ -31,9 +31,9 @@ def decoy( typer.Option('-o', '--out-dir', file_okay=False, help='Output directory.'), ] = Path('.'), method: Annotated[ - Literal['rejected-surface', 'shifted', 'synthetic-noise'], + Literal['shifted', 'synthetic-noise', 'random-volume'], typer.Option('--method', help='Decoy method to use.'), - ] = 'rejected-surface', + ] = 'shifted', real_particle_set: Annotated[ Path | None, typer.Option('--real-particle-set', help='particle_set.json from `stamp pick`. Required unless using --method synthetic-noise.', rich_help_panel = 'Inputs'), @@ -46,17 +46,17 @@ def decoy( Path | None, typer.Option('-r', '--raw-dir', help='Raw tomogram directory. Required unless using --method synthetic-noise.', rich_help_panel = 'Inputs'), ] = None, - picker_params: Annotated[ - str, - typer.Option('--picker-params', help='JSON of native-picker parameters. Must match the values used for `stamp pick`, or decoys won\'t be drawn from the same candidate pool.', rich_help_panel = 'Inputs'), - ] = '{}', + density_sign: Annotated[ + int, + typer.Option('--density-sign', help='+1 if the synthetic membrane shell is brighter than background, -1 if darker.', rich_help_panel = 'Synthetic noise decoy'), + ] = -1, n_decoys_per_tomogram: Annotated[ int | None, - typer.Option('--n-decoys-per-tomogram', help='Decoy positions per tomogram. Omit for adaptive targeting (matches real pick count per tomogram).', rich_help_panel = 'Decoy placement'), + typer.Option('--n-decoys-per-tomogram', help='Decoy positions per noise volume. Required for --method synthetic-noise; shifted places one decoy per real pick.', rich_help_panel = 'Decoy placement'), ] = None, min_distance_from_real_angstrom: Annotated[ float, - typer.Option('--min-distance-from-real-a', help='Minimum separation from any real pick.', rich_help_panel = 'Rejected surface decoy'), + typer.Option('--min-distance-from-real-a', help='Minimum distance from the membrane surface.', rich_help_panel = 'Shifted decoy'), ] = 100.0, min_distance_from_picks_angstrom: Annotated[ float, @@ -70,6 +70,10 @@ def decoy( float, typer.Option('--max-shift-a', help='Maximum displacement.', rich_help_panel = 'Shifted decoy'), ] = 600.0, + min_border_angstrom: Annotated[ + float, + typer.Option('--min-border-a', help='Minimum distance from the tomogram border.', rich_help_panel = 'Random volume decoy'), + ] = 200.0, n_synthetic_tomograms: Annotated[ int, typer.Option('--n-synthetic-tomograms', help='Noise volumes.', rich_help_panel = 'Synthetic noise decoy'), @@ -113,16 +117,16 @@ def decoy( ) -> None: '''Generate a decoy dataset to run through STAMP alongside real data.''' log_started('decoy generation') - # Validate picker parameters - try: - parameters = json.loads(picker_params) - except json.JSONDecodeError as exc: - raise typer.BadParameter(f'--picker-params is not valid JSON: {exc}') from None + if density_sign not in (1, -1): + raise typer.BadParameter('--density-sign must be 1 or -1.') # Validate method requirements - if method in ['rejected-surface', 'shifted']: + if method == 'random-volume': + if any([real_particle_set is None, raw_tomogram_dir is None]): + raise StampPipelineError('--method random-volume requires --real-particle-set and -r/--raw-dir') + elif method == 'shifted': if any([real_particle_set is None, segmentation_dir is None, raw_tomogram_dir is None]): - raise StampPipelineError(f'--method {method} requires --real-particle-set, --segmentation-dir and --raw-tomogram-dir') + raise StampPipelineError(f'--method {method} requires --real-particle-set, -s/--seg-dir and -r/--raw--dir') else: if all([voxel_size_angstrom is None, segmentation_dir is None, raw_tomogram_dir is None]): raise StampPipelineError(f'--method {method} requires one of --voxel-size-a, -s/--seg-dir or -r/--raw-dir to be set.') @@ -131,7 +135,6 @@ def decoy( decoyfuncs.run_decoy( output_dir=resolve_output_dir(output_dir, 'decoy'), method=method, - parameters=parameters, real_particle_set=real_particle_set, segmentation_dir=segmentation_dir, raw_tomogram_dir=raw_tomogram_dir, @@ -144,6 +147,7 @@ def decoy( n_synthetic_tomograms=n_synthetic_tomograms, synthetic_shape=synthetic_shape, seed=seed, + density_sign=density_sign, n_workers=n_workers, keep_raw=keep_raw, make_plots=make_plots, diff --git a/src/stamp/cli/pick.py b/src/stamp/cli/pick.py index 9cd599d..b0e3707 100644 --- a/src/stamp/cli/pick.py +++ b/src/stamp/cli/pick.py @@ -3,12 +3,13 @@ ''' # Import external dependencies -import json, typer +import typer from pathlib import Path from typing import Annotated, Literal # Import pick command functions/variables import stamp.commands.pick as pickfuncs +from stamp.schemas.particles import OrientationPrior from stamp.utils.io import resolve_output_dir from stamp.utils.log import log_started @@ -21,18 +22,18 @@ # Define pick command @pickCli.command() def pick( - pickers: Annotated[ - str, - typer.Argument(help='Comma-separated pickers to use.') - ], - segmentation_dir: Annotated[ - Path, - typer.Option('-s', '--seg-dir', exists=True, file_okay=False, help='Directory of segmented MRC files; filename stems are tomogram IDs.'), + picks_files: Annotated[ + list[Path], + typer.Argument(exists=True, dir_okay=False, readable=True, help='Picks files to import (.csv, .star, .json, .jsonl); one picker per file.'), ], raw_tomogram_dir: Annotated[ Path, typer.Option('-r', '--raw-dir', exists=True, file_okay=False, help='Directory of raw tomogram MRCs, matched to segmentations by filename stem.') ], + segmentation_dir: Annotated[ + Path | None, + typer.Option('-s', '--seg-dir', exists=True, file_okay=False, help='Directory of segmented MRC files; filename stems are tomogram IDs. Used to infer orientations. Required for the normal orientation prior.'), + ] = None, output_dir: Annotated[ Path, typer.Option('-o', '--out-dir', file_okay=False, help='Directory to write outputs to.') @@ -41,10 +42,14 @@ def pick( float | None, typer.Option('--voxel-size-a', help='Voxel size of the input tomograms, in Angstrom.') ] = None, - picker_params: Annotated[ - str, - typer.Option('--picker-params', help='JSON of per-picker parameters.', rich_help_panel = 'Consensus'), - ] = '{}', + orientation_prior: Annotated[ + OrientationPrior, + typer.Option('--orientation-prior', help='What is known about particle orientation: normal (membrane proteins, orientation inferred from --seg-dir), axis (filaments, every pick needs an orientation) or none (soluble particles, orientations are ignored).'), + ] = OrientationPrior.NORMAL, + names: Annotated[ + list[str] | None, + typer.Option('--name', help='Picker name for each picks file, in order (repeatable). Defaults to the file stem.', rich_help_panel = 'Consensus'), + ] = None, consensus_rule: Annotated[ Literal['union', 'intersection'], typer.Option('--consensus-rule', help='Rule to use for consensus reconciliation.', rich_help_panel = 'Consensus'), @@ -57,26 +62,22 @@ def pick( int, typer.Option('--half-set-seed', help='Seed for half-set assignment.', rich_help_panel = 'Consensus'), ] = 0, - backend: Annotated[ - Literal['local', 'mock'], - typer.Option('--backend', help='Backend to use for processing.', rich_help_panel = 'Backend'), - ] = 'local', n_workers: Annotated[ int, - typer.Option('-n', '--n-processes', help='Processes to use for stamp-native picker (1 = sequential).', rich_help_panel = 'Backend'), + typer.Option('-n', '--n-processes', help='Processes to use for reconciliation, the vesicle summary and plots (1 = sequential).', rich_help_panel = 'Backend'), ] = 1, max_beam_angle_deviation: Annotated[ float | None, typer.Option('--max-beam-angle-deviation', help='Normal deviation from beam-orthogonal plane to drop particles.', rich_help_panel = 'Filtering'), ] = None, + max_surface_distance_angstrom: Annotated[ + float, + typer.Option('--max-surface-distance-a', help='Picks further than this from any segmentation surface get no inferred orientation (classify skips them).', rich_help_panel = 'Filtering'), + ] = 300.0, vesicle_labels_mrc: Annotated[ Path | None, typer.Option('--vesicle-labels-mrc', help='Path to an EValuator labelled MRC, or a directory to be matched by filename stem.', exists=True, readable=True, rich_help_panel = 'Filtering'), ] = None, - normalise_per_vesicle: Annotated[ - bool, - typer.Option('--normalise-per-vesicle', help='Normalise stamp-native scores per vesicle instead of per tomogram.', rich_help_panel = 'Filtering'), - ] = False, make_plots: Annotated[ bool, typer.Option('--plots', help='Write consensus-pick position plots.', rich_help_panel = 'Plotting'), @@ -99,37 +100,21 @@ def pick( ] = False, keep_raw: Annotated[ bool, - typer.Option('--keep-raw', help='Keep the raw per-picker output directory instead of archiving it to raw.tar.gz.', rich_help_panel = 'Backend'), + typer.Option('--keep-raw', help='Keep the per-picker import cache instead of archiving it to raw.tar.gz.', rich_help_panel = 'Backend'), ] = False, ) -> None: - '''Run particle picking, reconcile across pickers, and assign half-sets.''' + '''Import external picks, infer orientations, reconcile across pickers, and assign half-sets.''' log_started('picking') - # Validate provided pickers - picker_names = [name.strip() for name in pickers.split(',') if name.strip()] - if not picker_names: - raise typer.BadParameter('At least one picker must be provided.') - for name in picker_names: - if name not in pickfuncs.REAL_ADAPTERS: - raise typer.BadParameter(f'Picker "{name}" not recognised.') - - # Validate picker parameters - try: - extra_params: dict[str, dict] = json.loads(picker_params) - except json.JSONDecodeError as exc: - raise typer.BadParameter(f'--picker-params is not valid JSON: {exc}') from None - - # Run picking pickfuncs.run_pick( - picker_names=picker_names, + picks_files=picks_files, + picker_names=names, segmentation_dir=segmentation_dir, raw_tomogram_dir=raw_tomogram_dir, output_dir=resolve_output_dir(output_dir, 'pick'), voxel_size_angstrom=voxel_size_angstrom, - extra_params=extra_params, consensus_rule=consensus_rule, distance_threshold=distance_threshold, half_set_seed=half_set_seed, - backend=backend, n_workers=n_workers, make_plots=make_plots, pick_plot_style=pick_plot_style, @@ -138,6 +123,7 @@ def pick( pick_plot_3d=pick_plot_3d, max_beam_angle_deviation=max_beam_angle_deviation, vesicle_labels_mrc=vesicle_labels_mrc, - normalise_per_vesicle=normalise_per_vesicle, + max_surface_distance_angstrom=max_surface_distance_angstrom, keep_raw=keep_raw, + orientation_prior=orientation_prior, ) diff --git a/src/stamp/commands/classify.py b/src/stamp/commands/classify.py index 31e8a90..3dff2ee 100644 --- a/src/stamp/commands/classify.py +++ b/src/stamp/commands/classify.py @@ -7,24 +7,22 @@ from pathlib import Path # Import internal STAMP objects -from stamp.classify.align import align_inplane, roll_about_normal -from stamp.classify.average import compute_class_averages, write_class_averages -from stamp.classify.cluster import ( - ClusteringConfig, - ClusteringResult, - label_to_cluster_id, - match_clusters_across_halves, - reduce_and_cluster, - reduce_and_cluster_shared, -) +from stamp.classify.average import write_class_averages +from stamp.classify.cluster import ClusteringConfig, ClusteringResult, label_to_cluster_id, reduce_and_cluster from stamp.utils.checkpoint import file_signature, signatures, sync_checkpoint +from stamp.classify.polish import PolishConfig, posed_class_averages, run_polish from stamp.classify.extract import extract_particle_set +from stamp.classify.halves import express_in_frame_of_a, run_polish_by_half +from stamp.classify.frames import azimuth_degrees, rotation_to_quaternion +from stamp.classify.prepare import working_box +from stamp.classify.shfeatures import build_sh_feature_matrix +from stamp.classify.store import ParticleStore, build_store from stamp.classify.features import build_feature_matrix from stamp.backends.base import ToolCommand from stamp.decoy.validate import is_decoy_particle_set from stamp.run.state import stage_dir from stamp.utils.halfset import split_by_half_set -from stamp.schemas.particles import ClassAssignment, HalfSet, ParticleSet +from stamp.schemas.particles import ClassAssignment, HalfSet, OrientationPrior, ParticleSet from stamp.schemas.subvolumes import Subvolumes from stamp.utils.errors import StampPipelineError from stamp.utils.io import archive_and_remove_directory, glob_mrc, match_by_stem, resolve_directory_voxel_size_angstrom, write_sidecar @@ -47,9 +45,7 @@ def run_classify( n_components, strict_halfset_independence, random_state, - inplane_alignment = True, inplane_angular_step_degrees = 10.0, - inplane_iterations = 3, azimuthal_modes = 4, min_radius_fraction = 0.25, n_azimuthal_samples = 64, @@ -58,6 +54,15 @@ def run_classify( make_plots: bool = True, plot_format: str = 'tiff', keep_raw: bool = False, + tilt_max_degrees: float | None = None, + tilt_axis_degrees: float = 90.0, + bin_factor: int = 2, + n_rotations: int = 3000, + shift_range_voxels: int = 3, + polish_rounds: int = 2, + null_sigmas: float = 3.0, + reject_quantile: float = 0.95, + merge_fraction: float = 1.0, ) -> None: if voxel_size_angstrom is None: voxel_size_angstrom = resolve_directory_voxel_size_angstrom(glob_mrc(raw_tomogram_dir)) @@ -67,6 +72,7 @@ def run_classify( log.progress('Classifying particle set') particle_set = ParticleSet.model_validate(json.loads(particles.read_text())) is_decoy = is_decoy_particle_set(particle_set) + prior = particle_set.orientation_prior log.info(f'Loaded {len(particle_set.particles)} {"decoy" if is_decoy else "real"} particles') tomogram_ids = sorted({particle.tomogram_id for particle in particle_set.particles}) matched, unmatched = match_by_stem([Path(f'{tomogram_id}.mrc') for tomogram_id in tomogram_ids], glob_mrc(raw_tomogram_dir)) @@ -99,10 +105,18 @@ def run_classify( 'n_clusters': n_clusters, 'n_components': n_components, 'strict_halfset_independence': strict_halfset_independence, - 'inplane_alignment': inplane_alignment, 'inplane_angular_step_degrees': inplane_angular_step_degrees, - 'inplane_iterations': inplane_iterations, 'random_state': random_state, + 'orientation_prior': prior.value, + 'tilt_max_degrees': tilt_max_degrees, + 'tilt_axis_degrees': tilt_axis_degrees, + 'bin_factor': bin_factor, + 'n_rotations': n_rotations, + 'shift_range_voxels': shift_range_voxels, + 'polish_rounds': polish_rounds, + 'null_sigmas': null_sigmas, + 'reject_quantile': reject_quantile, + 'merge_fraction': merge_fraction, } if sync_checkpoint(output_dir / 'raw', fingerprint): log.info('Found matching partial output, resuming') @@ -110,7 +124,7 @@ def run_classify( log.progress('Starting subvolume extraction') subvols, kept, skipped = extract_particle_set( particle_set.particles, {k: str(v) for k, v in tomogram_paths.items()}, box_voxels, - segmentation_paths=segmentation_paths, n_workers=n_workers, cache_dir=output_dir / 'raw' / 'subvolumes', + segmentation_paths=segmentation_paths, n_workers=n_workers, cache_dir=output_dir / 'raw' / 'subvolumes', prior=prior, ) if skipped: log.warning(f'Skipped {len(skipped)} particles whose {box_voxels}-voxel box fell outside the volume or had no matching tomogram or had no orientation') @@ -118,17 +132,21 @@ def run_classify( raise StampPipelineError('No particles could be extracted. Check --raw-dir and --box-length-a') log.progress('Starting feature matrix construction') - features = build_feature_matrix( - subvols, - n_radial_bins=n_radial_bins, - max_azimuthal_mode=azimuthal_modes, - n_azimuthal_samples=n_azimuthal_samples, - min_radius_fraction=min_radius_fraction, - n_workers=n_workers, - cache_dir=output_dir / 'raw' / 'features', - normalisation=feature_normalisation, - ) - log.progress(f'Feature matrix complete: {features.shape[0]} particles x {features.shape[1]} features (modes 0-{azimuthal_modes})') + if prior is OrientationPrior.NONE: + features = build_sh_feature_matrix(subvols, tilt_max_degrees, tilt_axis_degrees, n_workers=n_workers) + else: + features = build_feature_matrix( + subvols, + n_radial_bins=n_radial_bins, + max_azimuthal_mode=azimuthal_modes, + n_azimuthal_samples=n_azimuthal_samples, + min_radius_fraction=min_radius_fraction, + n_workers=n_workers, + cache_dir=output_dir / 'raw' / 'features', + normalisation=feature_normalisation, + axial_invariant=prior is OrientationPrior.AXIS, + ) + log.progress(f'Feature matrix complete: {features.shape[0]} particles x {features.shape[1]} features ({prior.value} prior)') degenerate = ~features.any(axis=1) if degenerate.any(): @@ -154,23 +172,15 @@ def run_classify( output_dir.mkdir(parents=True, exist_ok=True) - align_settings = dict( - enabled=inplane_alignment, - angular_step_degrees=inplane_angular_step_degrees, - iterations=inplane_iterations, - n_workers=n_workers, + polish_config = PolishConfig( + prior=prior, angular_step_degrees=inplane_angular_step_degrees, n_rotations=n_rotations, shift_range_voxels=shift_range_voxels, + n_polish_rounds=polish_rounds, min_seed_size=min_cluster_size, merge_fraction=merge_fraction, null_sigmas=null_sigmas, + reject_quantile=reject_quantile, seed=random_state, threads=n_workers, ) - if not inplane_alignment: - log.warning('--no-inplane-alignment: class averages are a rotational average about the membrane normal (Cinf assumed). Downstream fit scores and half-map FSC will reflect the shared radial profile, not a 3D structure.') - + classify = _classify_strict if strict_halfset_independence else _classify_combined if not strict_halfset_independence: - log.warning('--no-strict-halfset-independence used, half-A and half-B particles are clustered together; FSC built on these classes will be inflated') - if strict_halfset_independence: - log.debug('Dispatching to strict half-set-independent clustering') - assignments, result_by_half, averages_by_half = _classify_strict(kept, subvols, features, config, output_dir, voxel_size_angstrom, align_settings) - else: - log.debug('Dispatching to combined clustering (half-sets pooled)') - assignments, result_by_half, averages_by_half = _classify_combined(kept, subvols, features, config, output_dir, voxel_size_angstrom, align_settings) + log.warning('--no-strict-halfset-independence used, half-A and half-B particles are classified together; FSC built on these classes will be inflated') + assignments, result_by_half, averages_by_half = classify(kept, subvols, features, config, polish_config, working_box(box_voxels, bin_factor), (tilt_max_degrees, tilt_axis_degrees), output_dir, voxel_size_angstrom) assignments_path = output_dir / 'class_assignments.json' assignments_path.write_text(json.dumps([a.model_dump() for a in assignments], indent=2)) @@ -184,7 +194,7 @@ def run_classify( write_sidecar( output_dir, stage='classify', - tool='stamp-native-classifier', + tool='stamp-polish-classifier', tool_version=None, parameters={ 'box_angstrom': box_angstrom, @@ -195,10 +205,18 @@ def run_classify( 'n_clusters': n_clusters, 'n_components': n_components, 'strict_halfset_independence': strict_halfset_independence, - 'inplane_alignment': inplane_alignment, 'inplane_angular_step_degrees': inplane_angular_step_degrees, - 'inplane_iterations': inplane_iterations, 'random_state': random_state, + 'orientation_prior': prior.value, + 'tilt_max_degrees': tilt_max_degrees, + 'tilt_axis_degrees': tilt_axis_degrees, + 'bin_factor': bin_factor, + 'n_rotations': n_rotations, + 'shift_range_voxels': shift_range_voxels, + 'polish_rounds': polish_rounds, + 'null_sigmas': null_sigmas, + 'reject_quantile': reject_quantile, + 'merge_fraction': merge_fraction, 'azimuthal_modes': azimuthal_modes, 'n_azimuthal_samples': n_azimuthal_samples, 'min_radius_fraction': min_radius_fraction, @@ -243,7 +261,6 @@ def build_classify_commands(config, output_dir: Path, track: str = 'real') -> li 'stamp', 'classify', '--particles', str(particles), '--raw-dir', str(config.run.raw_tomogram_dir), - '--seg-dir', str(config.run.segmentation_dir), '--out-dir', str(target), '--voxel-size-a', str(config.run.voxel_size_angstrom), '--box-length-a', str(settings.box_angstrom), @@ -254,129 +271,123 @@ def build_classify_commands(config, output_dir: Path, track: str = 'real') -> li '--n-components', str(settings.n_components), '--seed', str(settings.random_state), '--inplane-step-deg', str(settings.inplane_angular_step_degrees), - '--inplane-iterations', str(settings.inplane_iterations), '-n', str(settings.n_workers), + '--tilt-axis', str(config.run.tilt_axis_degrees), + '--bin-factor', str(settings.bin_factor), + '--n-rots', str(settings.n_rotations), + '--shift-range', str(settings.shift_range_voxels), + '--polish-rounds', str(settings.polish_rounds), + '--null-sigmas', str(settings.null_sigmas), + '--reject-quantile', str(settings.reject_quantile), + '--merge-fraction', str(settings.merge_fraction), ] + if config.run.tilt_max_degrees is not None: + argv += ['--tilt-max', str(config.run.tilt_max_degrees)] + if config.run.segmentation_dir is not None: + argv += ['--seg-dir', str(config.run.segmentation_dir)] if not settings.strict_halfset_independence: argv.append('--no-strict-halfset-independence') - if not settings.inplane_alignment: - argv.append('--no-inplane-alignment') argv.append('--keep-raw' if settings.keep_raw else '--no-keep-raw') argv.append('--plots' if config.plots.enabled else '--no-plots') argv += ['--plot-format', config.plots.format] return [ToolCommand(tool='classify', argv=argv, working_directory=target, output_paths=[target / 'class_averages'])] -# _resolve_and_apply_inplane: estimate per-row azimuth, return a rolled subvols and {row: angle} -def _resolve_and_apply_inplane( - subvols: Subvolumes, - cluster_ids: list[str], - align_settings: dict, - rolled_cache_dir: Path, - checkpoint_dir: Path, -) -> tuple[Subvolumes, dict[int, float]]: - if not align_settings['enabled']: - return subvols, {} - angles = align_inplane( - subvols, - cluster_ids, - angular_step_degrees=align_settings['angular_step_degrees'], - iterations=align_settings['iterations'], - n_workers=align_settings['n_workers'], - checkpoint_dir=checkpoint_dir, +# _pose_assignment: a class assignment carrying polish's pose, the in-plane angle only where it means something (membrane normal prior) +def _pose_assignment(particle, cluster_id: str, classifier: str, prior: OrientationPrior, rotation: np.ndarray, shift_voxels: np.ndarray, cc: float, margin: float, polarity: int) -> ClassAssignment: + if cluster_id == 'noise': + return ClassAssignment(particle_id=particle.particle_id, cluster_id=cluster_id, classifier=classifier, vesicle_id=particle.vesicle_id, cc=cc, margin=margin) + return ClassAssignment( + particle_id=particle.particle_id, + cluster_id=cluster_id, + classifier=classifier, + inplane_angle_degrees=azimuth_degrees(rotation.T) if prior is OrientationPrior.NORMAL else None, + vesicle_id=particle.vesicle_id, + rotation=rotation_to_quaternion(rotation), + shift_voxels=tuple(float(v) for v in shift_voxels), + cc=cc, + margin=margin, + polarity=polarity if prior is OrientationPrior.AXIS else None, ) - rolled = ((index, roll_about_normal(subvolume, angles.get(index, 0.0))) for indices, batch in subvols.iter_batches() for index, subvolume in zip(indices, batch)) - return subvols.write_rolled(rolled, rolled_cache_dir), angles -# _classify_combined: cluster all particles together, then average each half separately +# _classify: seed clusters from the features, run polish over all particles together, then average each half at polish's poses def _classify_combined( particles, subvols: Subvolumes, features, config, + polish_config: PolishConfig, + working_voxels: int, + tilt: tuple[float | None, float], output_dir: Path, voxel_size_angstrom: float, - align_settings: dict, ) -> tuple[list[ClassAssignment], dict[str, ClusteringResult], dict[str, dict[str, tuple[np.ndarray, int]]]]: - result = reduce_and_cluster(features, config) - cluster_ids = [label_to_cluster_id(int(label)) for label in result.labels] - - _report_clusters(cluster_ids, result.explained_variance_ratio) - - aligned, angles = _resolve_and_apply_inplane(subvols, cluster_ids, align_settings, output_dir / 'raw' / 'subvolumes_rolled', output_dir / 'raw' / 'align' / 'combined') - + seeds = reduce_and_cluster(features, config) + (output_dir / 'class_averages').mkdir(parents=True, exist_ok=True) # present even when polish rejects everything, so a decoy that matched nothing is still compared + orientations = [particle.orientation for particle in particles] + store = build_store(subvols, orientations, working_voxels, *tilt, output_dir / 'raw' / 'working') + outcome = run_polish(store, seeds.embedding, seeds.labels, polish_config, checkpoint_dir=output_dir / 'raw' / 'polish') + cluster_ids = [label_to_cluster_id(int(label)) for label in outcome.labels] + _report_clusters(cluster_ids, seeds.explained_variance_ratio) + full = ParticleStore(subvols, orientations, *tilt) + scale = subvols.box_voxels / working_voxels # polish shifts are in working voxels averages_by_half: dict[str, dict[str, tuple[np.ndarray, int]]] = {} for half_set in (HalfSet.A, HalfSet.B): - half_indices = [i for i, p in enumerate(particles) if p.half_set == half_set] + half_indices = [i for i, particle in enumerate(particles) if particle.half_set == half_set] if not half_indices: continue - half_cluster_ids = [cluster_ids[i] for i in half_indices] - averages = compute_class_averages(aligned.take(half_indices), half_cluster_ids) + averages = posed_class_averages(full.take(half_indices), outcome.labels[half_indices], outcome.rotations[half_indices], outcome.shifts[half_indices] * scale) write_class_averages(averages, output_dir / 'class_averages', voxel_size_angstrom, half_set.value) averages_by_half[half_set.value] = averages - assignments = [ - ClassAssignment( - particle_id=particle.particle_id, - cluster_id=cluster_id, - classifier='stamp-native-classifier', - inplane_angle_degrees=angles.get(index), - vesicle_id=particle.vesicle_id, - ) + _pose_assignment(particle, cluster_id, 'stamp-polish-classifier', polish_config.prior, outcome.rotations[index], outcome.shifts[index] * scale, float(outcome.cc[index]), float(outcome.margin[index]), int(outcome.polarity[index])) for index, (particle, cluster_id) in enumerate(zip(particles, cluster_ids)) ] - return assignments, {'combined': result}, averages_by_half + return assignments, {'combined': seeds}, averages_by_half -# _classify_strict: cluster each half independently, then match clusters by centroid +# _classify_strict: seed and polish each half on its own, match half-B clusters to half A by reference similarity and express half-B poses in the half-A frame so the two half averages can be compared def _classify_strict( particles, subvols: Subvolumes, features, config, + polish_config: PolishConfig, + working_voxels: int, + tilt: tuple[float | None, float], output_dir: Path, voxel_size_angstrom: float, - align_settings: dict, ) -> tuple[list[ClassAssignment], dict[str, ClusteringResult], dict[str, dict[str, tuple[np.ndarray, int]]]]: half_a, half_b = split_by_half_set(list(particles)) index_of = {particle.particle_id: i for i, particle in enumerate(particles)} - indices_a = [index_of[p.particle_id] for p in half_a] - indices_b = [index_of[p.particle_id] for p in half_b] - if not indices_a or not indices_b: + members = {'A': [index_of[p.particle_id] for p in half_a], 'B': [index_of[p.particle_id] for p in half_b]} + if not members['A'] or not members['B']: raise StampPipelineError('Strict mode needs particles in both half-sets') - - results = reduce_and_cluster_shared(features, {'A': np.array(indices_a), 'B': np.array(indices_b)}, config) - result_a, result_b = results['A'], results['B'] - matches = match_clusters_across_halves(result_a.centroids, result_b.centroids) - log.debug('Cross-half cluster matching (B -> A, shared PCA space):') - for label_b, (label_a, distance) in sorted(matches.items()): - log.debug(f' c{label_b:02d} -> c{label_a:02d} d={distance:.3f}') - + seeds = {half: reduce_and_cluster(features[indices], config) for half, indices in members.items()} # one PCA per half, so nothing in half A depends on half B + (output_dir / 'class_averages').mkdir(parents=True, exist_ok=True) # present even when polish rejects everything, so a decoy that matched nothing is still compared + orientations = [particle.orientation for particle in particles] + store = build_store(subvols, orientations, working_voxels, *tilt, output_dir / 'raw' / 'working') + results, matches = run_polish_by_half(store, members, {h: seeds[h].embedding for h in members}, {h: seeds[h].labels for h in members}, polish_config, checkpoint_dir=output_dir / 'raw' / 'polish') + for label_b, match in sorted(matches.items()): + log.debug(f'Cross-half cluster matching (B -> A, by reference): c{label_b:02d} -> c{match.label_a:02d} similarity={match.similarity:.3f}') + n_a = len(results['A'].references) + renumber = {label_b: match.label_a for label_b, match in matches.items()} + unmatched = [label_b for label_b in range(len(results['B'].references)) if label_b not in matches] + renumber.update({label_b: n_a + position for position, label_b in enumerate(unmatched)}) # unmatched half-B clusters get ids that cannot collide with half A + rotations_b, shifts_b = express_in_frame_of_a(results['B'], matches) + poses = {'A': (results['A'].rotations, results['A'].shifts), 'B': (rotations_b, shifts_b)} + labels = {'A': results['A'].labels, 'B': np.array([renumber[int(l)] if l >= 0 else -1 for l in results['B'].labels])} + full = ParticleStore(subvols, orientations, *tilt) + scale = subvols.box_voxels / working_voxels assignments: list[ClassAssignment] = [] - result_by_half: dict[str, ClusteringResult] = {} averages_by_half: dict[str, dict[str, tuple[np.ndarray, int]]] = {} - for half_label, half_particles, indices, result, remap in ( - ('A', half_a, indices_a, result_a, None), - ('B', half_b, indices_b, result_b, matches), - ): - cluster_ids = [label_to_cluster_id(int(label)) for label in result.labels] - aligned, local_angles = _resolve_and_apply_inplane(subvols.take(indices), cluster_ids, align_settings, output_dir / 'raw' / f'subvolumes_rolled_{half_label}', output_dir / 'raw' / 'align' / half_label) - averages = compute_class_averages(aligned, cluster_ids) - write_class_averages(averages, output_dir / 'class_averages', voxel_size_angstrom, half_label) - result_by_half[half_label] = result - averages_by_half[half_label] = averages - for local_row, (particle, label) in enumerate(zip(half_particles, result.labels)): - cluster_id = label_to_cluster_id(int(label)) - if remap is not None and int(label) in remap: - cluster_id = label_to_cluster_id(remap[int(label)][0]) - assignments.append( - ClassAssignment( - particle_id=particle.particle_id, - cluster_id=cluster_id, - classifier='stamp-native-classifier-strict', - inplane_angle_degrees=local_angles.get(local_row), - vesicle_id=particle.vesicle_id, - ) - ) - return assignments, result_by_half, averages_by_half + for half, indices in members.items(): + averages = posed_class_averages(full.take(indices), labels[half], poses[half][0], poses[half][1] * scale) + write_class_averages(averages, output_dir / 'class_averages', voxel_size_angstrom, half) + averages_by_half[half] = averages + result = results[half] + for local, index in enumerate(indices): + cluster_id = label_to_cluster_id(int(labels[half][local])) + assignments.append(_pose_assignment(particles[index], cluster_id, 'stamp-polish-classifier-strict', polish_config.prior, poses[half][0][local], poses[half][1][local] * scale, float(result.cc[local]), float(result.margin[local]), int(result.polarity[local]))) + return assignments, {half: seeds[half] for half in seeds}, averages_by_half # _report_clusters: echo PCA variance and per-cluster sizes def _report_clusters(cluster_ids: list[str], explained_variance: np.ndarray) -> None: diff --git a/src/stamp/commands/decoy.py b/src/stamp/commands/decoy.py index 4884b7d..6515d52 100644 --- a/src/stamp/commands/decoy.py +++ b/src/stamp/commands/decoy.py @@ -4,23 +4,22 @@ # Import external dependencies import json -from dataclasses import asdict from pathlib import Path # Import internal STAMP objects from stamp.backends.base import ToolCommand from stamp.decoy.generate import ( - METHOD_REJECTED_SURFACE, + METHOD_RANDOM_VOLUME, METHOD_SHIFTED, METHOD_SYNTHETIC_NOISE, - generate_rejected_surface_decoys, + DecoyGeometry, + generate_random_volume_decoys, generate_shifted_decoys, generate_synthetic_noise_decoys, ) from stamp.decoy.validate import assert_comparable -from stamp.picking.native import NativePickerConfig from stamp.run.state import stage_dir -from stamp.schemas.particles import ParticleSet +from stamp.schemas.particles import OrientationPrior, ParticleSet from stamp.utils.checkpoint import directory_signatures, file_signature, sync_checkpoint from stamp.utils.errors import StampPipelineError, StampValidationError from stamp.utils.io import archive_and_remove_directory, glob_mrc, load_tomogram_manifests, resolve_directory_voxel_size_angstrom, write_sidecar @@ -28,13 +27,12 @@ from stamp.utils.plotting.picks import plot_positions # METHODS: decoy generation methods -METHODS = (METHOD_REJECTED_SURFACE, METHOD_SHIFTED, METHOD_SYNTHETIC_NOISE) +METHODS = (METHOD_SHIFTED, METHOD_SYNTHETIC_NOISE, METHOD_RANDOM_VOLUME) # run_decoy: generate a decoy dataset to run through STAMP alongside real data def run_decoy( output_dir, method, - parameters, real_particle_set, segmentation_dir, raw_tomogram_dir, @@ -47,6 +45,7 @@ def run_decoy( n_synthetic_tomograms, synthetic_shape, seed, + density_sign: int = -1, n_workers: int = 1, keep_raw: bool = False, make_plots: bool = False, @@ -54,32 +53,27 @@ def run_decoy( plot_format: str = 'tiff', pick_zstack_movie: bool = True, pick_plot_3d: bool = False, + min_border_angstrom: float = 200.0, ) -> None: '''Generate a decoy dataset to run through STAMP alongside real data''' if voxel_size_angstrom is None: _HEADER_DIR = raw_tomogram_dir or segmentation_dir voxel_size_angstrom = resolve_directory_voxel_size_angstrom(glob_mrc(_HEADER_DIR)) log.progress(f'Generating decoy dataset ({method})') - config_fields = { - key: value - for key, value in parameters.items() - if key in NativePickerConfig.__dataclass_fields__ - } - config = NativePickerConfig(voxel_size_angstrom=voxel_size_angstrom, **config_fields) - + config = DecoyGeometry(voxel_size_angstrom=voxel_size_angstrom, density_sign=density_sign) output_dir.mkdir(parents=True, exist_ok=True) - # everything that changes decoy positions; workers, plots and keep_raw are left out so a run can resume with different resources uses_real_data = method != METHOD_SYNTHETIC_NOISE fingerprint = { 'method': method, 'seed': seed, - 'picker_config': asdict(config), + 'density_sign': density_sign, 'n_decoys_per_tomogram': n_decoys_per_tomogram, 'min_distance_from_real_angstrom': min_distance_from_real_angstrom, 'min_shift_angstrom': min_shift_angstrom, 'max_shift_angstrom': max_shift_angstrom, 'min_distance_from_picks_angstrom': min_distance_from_picks_angstrom, + 'min_border_angstrom': min_border_angstrom, 'n_synthetic_tomograms': n_synthetic_tomograms, 'synthetic_shape': synthetic_shape, 'real_particle_set': file_signature(real_particle_set, content=True) if uses_real_data and real_particle_set else None, @@ -89,6 +83,10 @@ def run_decoy( if sync_checkpoint(output_dir / 'raw', fingerprint): log.info('Found matching partial output, resuming') + if method != METHOD_RANDOM_VOLUME and real_particle_set is not None: + prior = ParticleSet.model_validate(json.loads(real_particle_set.read_text())).orientation_prior + if prior is not OrientationPrior.NORMAL: + raise StampPipelineError(f'--method {method} is membrane-based and cannot be a control for the {prior.value!r} orientation prior, use --method {METHOD_RANDOM_VOLUME}') if method == METHOD_SYNTHETIC_NOISE: shape = tuple(int(value) for value in synthetic_shape.split(',')) if len(shape) != 3: @@ -110,21 +108,21 @@ def run_decoy( raise StampPipelineError(str(exc)) from exc else: real_set = ParticleSet.model_validate(json.loads(real_particle_set.read_text())) - manifests = load_tomogram_manifests(segmentation_dir, raw_tomogram_dir, voxel_size_angstrom) + manifests = load_tomogram_manifests(None if method == METHOD_RANDOM_VOLUME else segmentation_dir, raw_tomogram_dir, voxel_size_angstrom) if not manifests: raise StampPipelineError('No matched segmentation/tomogram pairs found') - - if method == METHOD_REJECTED_SURFACE: - decoy_set = generate_rejected_surface_decoys( - real_particle_set=real_set, - manifests=manifests, - config=config, - n_decoys_per_tomogram=n_decoys_per_tomogram, - min_distance_from_real_angstrom=min_distance_from_real_angstrom, - seed=seed, - n_workers=n_workers, - output_dir=output_dir, - ) + if method == METHOD_RANDOM_VOLUME: + try: + decoy_set = generate_random_volume_decoys( + real_particle_set=real_set, + manifests=manifests, + config=config, + min_distance_from_picks_angstrom=min_distance_from_picks_angstrom, + border_angstrom=min_border_angstrom, + seed=seed, + ) + except StampValidationError as exc: + raise StampPipelineError(str(exc)) from exc else: decoy_set = generate_shifted_decoys( real_particle_set=real_set, @@ -140,7 +138,7 @@ def run_decoy( ) if decoy_set is None or not decoy_set.particles: - raise StampPipelineError('No decoy positions generated. For rejected-surface, check that --min-distance-from-real-angstrom isn\'t excluding the whole surface; for shifted, check that the shift range fits inside the volume.') + raise StampPipelineError('No decoy positions generated. For shifted, check that the shift range fits inside the volume.') if method != METHOD_SYNTHETIC_NOISE and real_particle_set is not None: assert_comparable(real_set, decoy_set) @@ -166,10 +164,11 @@ def run_decoy( 'min_distance_from_real_angstrom': min_distance_from_real_angstrom, 'min_shift_angstrom': min_shift_angstrom, 'max_shift_angstrom': max_shift_angstrom, + 'min_border_angstrom': min_border_angstrom, 'n_synthetic_tomograms': n_synthetic_tomograms, 'synthetic_shape': synthetic_shape, 'seed': seed, - 'picker_params': parameters, + 'density_sign': density_sign, }, inputs=( [('particle_set', real_particle_set)] if real_particle_set else [] @@ -179,7 +178,7 @@ def run_decoy( ) log.info(f'Wrote {len(decoy_set.particles)} decoy particles to {decoy_path}') if make_plots: - segmentation_paths = {m.tomogram_id: m.segmentation_path for m in manifests} if method != METHOD_SYNTHETIC_NOISE else {} + segmentation_paths = {m.tomogram_id: m.segmentation_path for m in manifests if m.segmentation_path} if method != METHOD_SYNTHETIC_NOISE else {} style = pick_plot_style if segmentation_paths else 'none' plot_positions(decoy_set.particles, output_dir, style, plot_format, segmentation_paths, zstack_movie=pick_zstack_movie and bool(segmentation_paths), plot_3d_view=pick_plot_3d, max_workers=n_workers) @@ -194,11 +193,13 @@ def build_decoy_commands(config, output_dir: Path) -> list[ToolCommand]: '--voxel-size-a', str(config.run.voxel_size_angstrom), '--method', config.decoy.method, '--real-particle-set', str(real_particles), - '--seg-dir', str(config.run.segmentation_dir), '--raw-dir', str(config.run.raw_tomogram_dir), + '--min-border-a', str(config.decoy.min_border_angstrom), '--seed', str(config.stage.pick.half_set_seed), '--n-processes', str(config.decoy.n_workers), ] + if config.run.segmentation_dir is not None: + argv += ['--seg-dir', str(config.run.segmentation_dir)] if config.decoy.keep_raw: argv.append('--keep-raw') if config.plots.enabled: diff --git a/src/stamp/commands/identify.py b/src/stamp/commands/identify.py index f260904..d2f40c6 100644 --- a/src/stamp/commands/identify.py +++ b/src/stamp/commands/identify.py @@ -16,7 +16,9 @@ from stamp.backends.mock import MockRunner from stamp.identify.decoy_check import evaluate_decoy_control from stamp.run.state import stage_dir -from stamp.identify.fit import fit_candidate, rank_candidates +from stamp.schemas.particles import OrientationPrior +from stamp.identify.fit import rank_candidates +from stamp.identify.register import register_score from stamp.identify.panel import Candidate, load_candidate_panel from stamp.identify.simulate import simulate_density, to_comparable from stamp.utils.checkpoint import atomic_write_json, directory_signatures, signatures, sync_checkpoint @@ -30,18 +32,18 @@ # _CLASS_ID: leading cNN token of a class-average filename _CLASS_ID = re.compile(r'^(c\d+)') -# _classify_was_inplane_aligned: read the classify sidecar -def _classify_was_inplane_aligned(classes: Path) -> bool: +# _aligned_prior: the orientation prior the class averages were aligned under, read from the classify sidecar (normal when it is absent) +def _aligned_prior(classes: Path) -> OrientationPrior: sidecar = classes.parent / 'params.toml' if not sidecar.is_file(): - return False - return bool(tomllib.loads(sidecar.read_text()).get('parameters', {}).get('inplane_alignment')) + return OrientationPrior.NORMAL + return OrientationPrior(tomllib.loads(sidecar.read_text()).get('parameters', {}).get('orientation_prior', 'normal')) # load_class_averages: {class_id: (mean_volume, voxel_size)} merged across half-set MRCs -def load_class_averages(directory: Path) -> dict[str, tuple[np.ndarray, float]]: +def load_class_averages(directory: Path, *, allow_empty: bool = False) -> dict[str, tuple[np.ndarray, float]]: grouped: dict[str, list[np.ndarray]] = defaultdict(list) voxel_sizes: dict[str, float] = {} - for path in glob_mrc(directory): + for path in (glob_mrc(directory) if directory.is_dir() else []): match = _CLASS_ID.match(path.stem) if not match: continue @@ -49,6 +51,8 @@ def load_class_averages(directory: Path) -> dict[str, tuple[np.ndarray, float]]: grouped[match.group(1)].append(np.transpose(np.asarray(mrc.data), (2, 1, 0))) voxel_sizes[match.group(1)] = float(mrc.voxel_size.x) if not grouped: + if allow_empty: + return {} raise StampPipelineError(f'No cNN-named class averages in {directory}') return {cid: (np.mean(volumes, axis=0), voxel_sizes[cid]) for cid, volumes in grouped.items()} @@ -61,12 +65,13 @@ class _FitJob: voxel_size: float resolution: float candidate: Candidate + aligned_prior: OrientationPrior # _fit_one: multiprocessing worker entry point def _fit_one(job: _FitJob) -> tuple[str, str, float]: simulated = simulate_density(job.candidate.structure_path, job.box_voxels, job.voxel_size, job.resolution) simulated = to_comparable(simulated, job.voxel_size, job.resolution, already_bandlimited=True) - score = fit_candidate(job.comparable_average, simulated) + score = register_score(job.comparable_average, simulated, job.aligned_prior) return job.class_id, job.candidate.name, score # _score_path: checkpoint file for one (class, candidate) score; the name is sanitised for the filesystem, the payload keeps the true names @@ -86,14 +91,14 @@ def _load_score(checkpoint_dir: Path | None, class_id: str, candidate_name: str) return None # _score_panel: fit every candidate to every class average, each finished fit checkpointed in checkpoint_dir when given, returns {class_id: {candidate: score}} -def _score_panel(class_averages, panel, resolution, fitter, backend, n_workers: int = 1, checkpoint_dir: Path | None = None): +def _score_panel(class_averages, panel, resolution, fitter, backend, n_workers: int = 1, checkpoint_dir: Path | None = None, aligned_prior: OrientationPrior = OrientationPrior.NORMAL): all_scores: dict[str, dict[str, float]] = {class_id: {} for class_id in class_averages} jobs = [] for class_id, (average, voxel_size) in class_averages.items(): for candidate in panel: saved = _load_score(checkpoint_dir, class_id, candidate.name) if saved is None: - jobs.append(_FitJob(class_id, to_comparable(average, voxel_size, resolution), average.shape[-1], voxel_size, resolution, candidate)) + jobs.append(_FitJob(class_id, to_comparable(average, voxel_size, resolution), average.shape[-1], voxel_size, resolution, candidate, aligned_prior)) else: all_scores[class_id][candidate.name] = saved n_resumed = sum(len(scores) for scores in all_scores.values()) @@ -131,7 +136,7 @@ def run_identify( log.info(f'Loaded {len(panel)} candidates') class_averages = load_class_averages(classes) log.info(f'Loaded {len(class_averages)} class averages') - inplane_aligned = _classify_was_inplane_aligned(classes) + aligned_prior = _aligned_prior(classes) # everything that changes scores; n_workers, backend and plots are left out so a run can resume with different resources fingerprint = { @@ -140,13 +145,14 @@ def run_identify( 'candidates': signatures({'panel': candidates, **{f'structure:{candidate.name}': candidate.structure_path for candidate in panel}}), 'resolution': resolution, 'fitter': fitter, + 'aligned_prior': aligned_prior.value, } checkpoint_dir = output_dir / 'raw' if sync_checkpoint(checkpoint_dir, fingerprint): log.info('Found matching partial output, resuming') log.progress(f'Fitting {len(panel)} candidates against {len(class_averages)} classes') - real_scores = _score_panel(class_averages, panel, resolution, fitter, backend, n_workers, checkpoint_dir / 'real') + real_scores = _score_panel(class_averages, panel, resolution, fitter, backend, n_workers, checkpoint_dir / 'real', aligned_prior) results = [rank_candidates(class_id, scores, method=f'stamp-{fitter}') for class_id, scores in sorted(real_scores.items())] output_dir.mkdir(parents=True, exist_ok=True) @@ -156,7 +162,7 @@ def run_identify( real_best, decoy_best = None, None if decoy_classes is not None: log.progress('Fitting candidates against decoy classes for control') - decoy_scores = _score_panel(load_class_averages(decoy_classes), panel, resolution, fitter, backend, n_workers, checkpoint_dir / 'decoy') + decoy_scores = _score_panel(load_class_averages(decoy_classes, allow_empty=True), panel, resolution, fitter, backend, n_workers, checkpoint_dir / 'decoy', aligned_prior) real_best = [max(s.values()) for s in real_scores.values()] decoy_best = [max(s.values()) for s in decoy_scores.values()] decoy_control = evaluate_decoy_control(real_best, decoy_best) @@ -169,7 +175,7 @@ def run_identify( log.debug('No --decoy-classes given, skipping decoy control') log.progress('Writing identification report') - _write_report(output_dir / 'identification_report.txt', results, real_scores, decoy_control, resolution, inplane_aligned) + _write_report(output_dir / 'identification_report.txt', results, real_scores, decoy_control, resolution, aligned_prior) write_sidecar( output_dir, @@ -180,8 +186,8 @@ def run_identify( 'fitter': fitter, 'backend': backend, 'resolution_angstrom': resolution, - 'inplane_aligned_class_averages': inplane_aligned, - 'symmetry': 'C1' if inplane_aligned else 'Cinf_z', + 'symmetry': 'C1', + 'orientation_prior': aligned_prior.value, 'n_candidates': len(panel), 'n_classes': len(class_averages), 'n_workers': n_workers, 'decoy_control': decoy_control.model_dump() if decoy_control else None, @@ -203,7 +209,7 @@ def _plot_identify(real_scores, results, decoy_control, real_best, decoy_best, o fig, ax = plt.subplots(figsize=(6.5, 0.6 * len(cluster_ids) + 2)) score_heatmap(ax, cluster_ids, names, real_scores, row_labels=row_labels, title='identify: fit score per candidate') finish(fig, plot_path(output_dir, 'identify_scores', fmt)) - if decoy_control is not None: + if decoy_control is not None and decoy_best: fig, ax = plt.subplots(figsize=(5, 4)) decoy_hist(ax, real_best, decoy_best, decoy_control.passed) finish(fig, plot_path(output_dir, 'decoy_control', fmt)) @@ -233,8 +239,8 @@ def build_identify_commands(config, output_dir: Path) -> list[ToolCommand]: return [ToolCommand(tool='identify', argv=argv, working_directory=target, output_paths=[target / 'identification.json'])] # _write_report: human-readable ranked table per class, decoy verdict first if present -def _write_report(path: Path, results, all_scores, decoy_control, resolution, inplane_aligned) -> None: - space = f'low-pass {resolution:.1f} Å, in-plane angles estimated in classify (C1)' if inplane_aligned else f'low-pass {resolution:.1f} Å, azimuthal average about the membrane normal (Cinf assumed; asymmetric features discarded)' +def _write_report(path: Path, results, all_scores, decoy_control, resolution, aligned_prior: OrientationPrior) -> None: + space = f'low-pass {resolution:.1f} Å, class averages aligned in 3D by classify (C1), candidates registered over the {aligned_prior.value} orientation prior' lines: list[str] = [ f'Comparison space: {space}.', '', diff --git a/src/stamp/commands/pick.py b/src/stamp/commands/pick.py index e9d91b5..59e289f 100644 --- a/src/stamp/commands/pick.py +++ b/src/stamp/commands/pick.py @@ -9,96 +9,51 @@ from skimage import measure # Import internal STAMP objects -from stamp.adapters.base import AdapterInputs, ToolAdapter -from stamp.adapters.mock import get_mock_adapter -from stamp.adapters.native import NativePickerAdapter -from stamp.backends.base import Runner, ToolCommand -from stamp.backends.factory import check_backend_supports, select_runner +from stamp.backends.base import ToolCommand from stamp.picking.consensus import build_particle_set, reconcile_picks_for_tomograms from stamp.picking.geometry import extract_surface -from stamp.picking.native import PICKER_NAME as NATIVE_PICKER_NAME +from stamp.picking.importers import apply_prior, infer_orientations, map_tomogram_ids, read_picks from stamp.picking.vesicles import load_vesicle_labels, summarise_vesicles, vesicle_surface_area_angstrom2 from stamp.run.state import stage_dir from stamp.schemas.manifest import TomogramManifest +from stamp.schemas.particles import OrientationPrior from stamp.schemas.picks import RawPick -from stamp.utils.checkpoint import signatures, sync_checkpoint +from stamp.utils.checkpoint import file_signature, signatures, sync_checkpoint from stamp.utils.errors import StampPipelineError, StampValidationError -from stamp.utils.io import archive_and_remove_directory, glob_mrc, load_cached_picks, load_tomogram_manifests, read_mrc, write_sidecar +from stamp.utils.io import archive_and_remove_directory, cache_tomogram_picks, glob_mrc, load_cached_picks, load_tomogram_manifests, read_mrc, write_sidecar from stamp.utils.log import log from stamp.utils.parallel import run_parallel from stamp.utils.plotting.picks import plot_positions from stamp.utils.reporting import report_beam_angle_distribution -# REAL_ADAPTERS: dictionary containing all implemented pickers -REAL_ADAPTERS: dict[str, ToolAdapter] = { - NATIVE_PICKER_NAME: NativePickerAdapter(), -} - -# _execute: build a command, run it, and parse the resulting RawPicks -def _execute(adapter: ToolAdapter, inputs: AdapterInputs, runner: Runner) -> list[RawPick]: - command = adapter.build_command(inputs) - log.debug(f'{adapter.name}: dispatching {" ".join(command.argv)}') - result = runner.run(command) - if not result.succeeded: - raise StampPipelineError(f'{adapter.name} failed (exit {result.exit_code}): {result.stderr}') - output = adapter.parse_output(result) - return [RawPick(**raw) for raw in output.parsed.get('picks', [])] - -# _select_adapter: return the adapter for a picker name, guarding it against the chosen backend -def _select_adapter(picker_name: str, backend: str) -> ToolAdapter: - if backend == 'mock': - log.debug(f'{picker_name}: using mock adapter (backend=mock)') - return get_mock_adapter(picker_name) - - adapter = REAL_ADAPTERS.get(picker_name) - if adapter is None: - raise StampPipelineError(f'Unknown picker {picker_name!r}') - check_backend_supports(adapter, backend) - return adapter - -# _run_picker: dispatch to the in-process, batched, or per-tomogram path -def _run_picker( - adapter: ToolAdapter, +# _import_picker: read one picks file, infer orientations per tomogram, cache under cache_dir and return the cached picks +def _import_picker( + path: Path, + name: str, manifests: list[TomogramManifest], - picker_output_dir: Path, - parameters: dict, - runner: Runner, - backend: str, + vesicle_labels_by_tomogram: dict[str, Path], + max_surface_distance_angstrom: float, + cache_dir: Path, + prior: OrientationPrior = OrientationPrior.NORMAL, ) -> list[RawPick]: - if backend != 'mock' and getattr(adapter, 'runs_in_process', False): - log.debug(f'{adapter.name}: dispatching in-process for {len(manifests)} tomogram(s)') - inputs = AdapterInputs( - input_paths=[m.segmentation_path for m in manifests], - raw_tomogram_paths=[m.raw_tomogram_path for m in manifests], - tomogram_ids=[m.tomogram_id for m in manifests], - output_directory=picker_output_dir, - parameters=parameters, - ) - return adapter.run_in_process(inputs) # type: ignore[attr-defined] - - if backend == 'mock' or adapter.batches_natively: - log.debug(f'{adapter.name}: dispatching as a single batched command for {len(manifests)} tomogram(s)') - inputs = AdapterInputs( - input_paths=[m.segmentation_path for m in manifests], - raw_tomogram_paths=[m.raw_tomogram_path for m in manifests], - tomogram_ids=[m.tomogram_id for m in manifests], - output_directory=picker_output_dir, - parameters=parameters, - ) - return _execute(adapter, inputs, runner) - - log.debug(f'{adapter.name}: dispatching one command per tomogram for {len(manifests)} tomogram(s)') - collected: list[RawPick] = [] - for manifest in manifests: - inputs = AdapterInputs( - input_paths=[manifest.segmentation_path], - raw_tomogram_paths=[manifest.raw_tomogram_path], - tomogram_ids=[manifest.tomogram_id], - output_directory=picker_output_dir / manifest.tomogram_id, - parameters=parameters, - ) - collected.extend(_execute(adapter, inputs, runner)) - return collected + picks_by_tomogram: dict[str, list[RawPick]] = {} + for pick in map_tomogram_ids(apply_prior(read_picks(path, source_picker=name), prior), manifests): + picks_by_tomogram.setdefault(pick.tomogram_id, []).append(pick) + manifest_by_id = {manifest.tomogram_id: manifest for manifest in manifests} + + # a tomogram's cache file is written atomically on completion, so its presence means it is done + pending = [tomogram_id for tomogram_id in picks_by_tomogram if not (cache_dir / f'{tomogram_id}.json').is_file()] + if len(pending) < len(picks_by_tomogram): + log.info(f'Resuming {name}: {len(picks_by_tomogram) - len(pending)} tomogram(s) loaded from checkpoint') + for tomogram_id in pending: + oriented = infer_orientations( + picks_by_tomogram[tomogram_id], + [manifest_by_id[tomogram_id]], + vesicle_labels_by_tomogram=vesicle_labels_by_tomogram, + max_surface_distance_angstrom=max_surface_distance_angstrom, + ) if prior is OrientationPrior.NORMAL else picks_by_tomogram[tomogram_id] # only membrane picks are oriented from the segmentation + cache_tomogram_picks(cache_dir, tomogram_id, oriented) + return load_cached_picks(cache_dir, list(picks_by_tomogram)) # _resolve_vesicle_labels: match --vesicle-labels-mrc (file or directory) to manifests by tomogram_id, warning per unmatched tomogram def _resolve_vesicle_labels(vesicle_labels_mrc: Path | None, manifests: list[TomogramManifest]) -> dict[str, Path]: @@ -155,7 +110,7 @@ def _write_vesicle_summary( for manifest in manifests: labels_mrc = vesicle_labels_mrc_by_tomogram.get(manifest.tomogram_id) picks = picks_by_tomogram.get(manifest.tomogram_id, []) - if labels_mrc is None or not any(p.vesicle_id for p in picks): + if manifest.segmentation_path is None or labels_mrc is None or not any(p.vesicle_id for p in picks): continue jobs.append(_VesicleSummaryJob(manifest.tomogram_id, manifest.segmentation_path, labels_mrc, manifest.voxel_size_angstrom, picks)) @@ -183,16 +138,15 @@ def _on_error(job: _VesicleSummaryJob, exc: Exception) -> None: # run_pick: pick command orchestration def run_pick( - picker_names, - segmentation_dir, - raw_tomogram_dir, - output_dir, - voxel_size_angstrom, - extra_params, - consensus_rule, - distance_threshold, - half_set_seed, - backend, + picks_files: list[Path], + segmentation_dir: Path | None, + raw_tomogram_dir: Path, + output_dir: Path, + voxel_size_angstrom: float | None, + consensus_rule: str, + distance_threshold: float, + half_set_seed: int, + picker_names: list[str] | None = None, n_workers: int = 1, make_plots: bool = False, pick_plot_style: str = 'segmented', @@ -201,55 +155,47 @@ def run_pick( pick_plot_3d: bool = False, max_beam_angle_deviation: float | None = None, vesicle_labels_mrc: Path | None = None, - normalise_per_vesicle: bool = False, + max_surface_distance_angstrom: float = 300.0, keep_raw: bool = False, + orientation_prior: OrientationPrior = OrientationPrior.NORMAL, ) -> None: + if orientation_prior is OrientationPrior.NORMAL and segmentation_dir is None: + raise StampPipelineError('--seg-dir is required for the normal orientation prior, orientations are inferred from the membrane segmentation') + names = picker_names or [path.stem for path in picks_files] + if len(names) != len(picks_files): + raise StampPipelineError(f'{len(picks_files)} picks file(s) but {len(names)} picker name(s)') + if len(set(names)) != len(names): + raise StampPipelineError(f'picker names must be unique, got {names!r}; use --name to disambiguate files with the same stem') + # Load manifests to check for matching files manifests = load_tomogram_manifests(segmentation_dir, raw_tomogram_dir, voxel_size_angstrom) if not manifests: - raise StampPipelineError(f'No .mrc files in {segmentation_dir} with a matching stem in {raw_tomogram_dir}') + raise StampPipelineError(f'No .mrc files in {segmentation_dir or raw_tomogram_dir} with a matching stem in {raw_tomogram_dir}') log.info(f'Matched {len(manifests)} tomograms/segmentations') resolved_voxel_size_angstrom = manifests[0].voxel_size_angstrom log.debug(f'Resolved voxel size: {resolved_voxel_size_angstrom} Å') - runner = select_runner(backend) output_dir.mkdir(parents=True, exist_ok=True) - vesicle_labels_mrc_by_tomogram = _resolve_vesicle_labels(vesicle_labels_mrc, manifests) - if normalise_per_vesicle and not vesicle_labels_mrc_by_tomogram: - raise StampPipelineError('--normalise-per-vesicle requires --vesicle-labels-mrc to resolve to at least one tomogram') - # everything that changes raw picks; consensus, seed, beam filter, workers and plots are left out so they can change between runs + # everything that changes imported picks; consensus, seed, beam filter, workers and plots are left out so they can change between runs fingerprint = { - 'pickers': list(picker_names), - 'segmentation': signatures({m.tomogram_id: m.segmentation_path for m in manifests}), + 'picks': {name: file_signature(path, content=True) for name, path in zip(names, picks_files)}, + 'segmentation': signatures({m.tomogram_id: m.segmentation_path for m in manifests if m.segmentation_path}), + 'orientation_prior': orientation_prior.value, 'raw': signatures({m.tomogram_id: m.raw_tomogram_path for m in manifests}), 'vesicle_labels': signatures(vesicle_labels_mrc_by_tomogram), - 'normalise_per_vesicle': normalise_per_vesicle, 'voxel_size_angstrom': resolved_voxel_size_angstrom, - 'picker_params': extra_params, - 'backend': backend, + 'max_surface_distance_angstrom': max_surface_distance_angstrom, } if sync_checkpoint(output_dir / 'raw', fingerprint): log.info('Found matching partial output, resuming') picks_by_picker: dict[str, list[RawPick]] = {} - for picker_name in picker_names: - adapter = _select_adapter(picker_name, backend) - picker_output_dir = output_dir / 'raw' / picker_name - parameters = { - 'voxel_size_angstrom': resolved_voxel_size_angstrom, - **extra_params.get(picker_name, {}), - } - if picker_name == NATIVE_PICKER_NAME: - parameters.setdefault('n_workers', n_workers) - if vesicle_labels_mrc_by_tomogram: - parameters['vesicle_labels_mrc_by_tomogram'] = {tomogram_id: str(path) for tomogram_id, path in vesicle_labels_mrc_by_tomogram.items()} - parameters.setdefault('normalise_per_vesicle', normalise_per_vesicle) - - log.progress(f'Running {picker_name}...') - picks_by_picker[picker_name] = _run_picker(adapter, manifests, picker_output_dir, parameters, runner, backend) - log.info(f'{picker_name}: {len(picks_by_picker[picker_name])} raw picks') + for name, path in zip(names, picks_files): + log.progress(f'Importing {name} from {path.name}...') + picks_by_picker[name] = _import_picker(path, name, manifests, vesicle_labels_mrc_by_tomogram, max_surface_distance_angstrom, output_dir / 'raw' / name, orientation_prior) + log.info(f'{name}: {len(picks_by_picker[name])} raw picks') log.progress(f'Reconciling picks...') all_reconciled = reconcile_picks_for_tomograms( @@ -260,14 +206,15 @@ def run_pick( n_workers=n_workers, ) if not all_reconciled: - raise StampPipelineError('No particles survived reconciliation. If using stamp-native, try lowering n_mad or check density_sign matches your tomograms (-1 for conventional dark-protein contrast).') + raise StampPipelineError('No particles survived reconciliation. With --consensus-rule intersection, every picks file must have a pick within --distance-threshold voxels of each particle.') log.progress(f'Building particle set and determining beam angle distribution') particle_set = build_particle_set( reconciled_picks=all_reconciled, consensus_rule=consensus_rule, # type: ignore[arg-type] - contributing_pickers=picker_names, + contributing_pickers=names, half_set_seed=half_set_seed, + orientation_prior=orientation_prior, ) if max_beam_angle_deviation is not None: before = len(particle_set.particles) @@ -279,7 +226,8 @@ def run_pick( log.info(f'--max-beam-angle-deviation {max_beam_angle_deviation}: dropped {dropped} of {before} particles') if not particle_set.particles: raise StampPipelineError('No particles survived the beam angle deviation filter. Try raising --max-beam-angle-deviation.') - report_beam_angle_distribution(particle_set.particles) + if orientation_prior is OrientationPrior.NORMAL: + report_beam_angle_distribution(particle_set.particles) particle_set_path = output_dir / 'particle_set.json' particle_set_path.write_text(particle_set.model_dump_json(indent=2)) log.info(f'Wrote {len(particle_set.particles)} consensus particles to {particle_set_path}') @@ -290,24 +238,27 @@ def run_pick( write_sidecar( output_dir, stage='pick', - tool='+'.join(picker_names), + tool='+'.join(names), tool_version=None, parameters={ - 'pickers': picker_names, + 'pickers': names, + 'picks_files': [str(path) for path in picks_files], 'consensus_rule': consensus_rule, 'distance_threshold': distance_threshold, 'half_set_seed': half_set_seed, + 'orientation_prior': orientation_prior.value, 'voxel_size_angstrom': resolved_voxel_size_angstrom, - 'backend': backend, - 'picker_params': extra_params, + 'max_surface_distance_angstrom': max_surface_distance_angstrom, 'vesicle_labels_mrc': {tomogram_id: str(path) for tomogram_id, path in vesicle_labels_mrc_by_tomogram.items()}, }, - inputs=[(f'segmentation:{m.tomogram_id}', m.segmentation_path) for m in manifests] + [(f'raw_tomogram:{m.tomogram_id}', m.raw_tomogram_path) for m in manifests], + inputs=[(f'picks:{name}', path) for name, path in zip(names, picks_files)] + + [(f'segmentation:{m.tomogram_id}', m.segmentation_path) for m in manifests if m.segmentation_path] + + [(f'raw_tomogram:{m.tomogram_id}', m.raw_tomogram_path) for m in manifests], ) log.progress(f'Rendering plots...') if make_plots: - segmentation_paths = {m.tomogram_id: m.segmentation_path for m in manifests} + segmentation_paths = {m.tomogram_id: m.segmentation_path for m in manifests if m.segmentation_path} raw_tomogram_paths = {m.tomogram_id: m.raw_tomogram_path for m in manifests} plot_positions(particle_set.particles, output_dir, pick_plot_style, plot_format, segmentation_paths, raw_tomogram_paths, zstack_movie=pick_zstack_movie, plot_3d_view=pick_plot_3d, max_workers=n_workers) @@ -315,23 +266,27 @@ def run_pick( raw_dir = output_dir / 'raw' if raw_dir.is_dir(): archive_path = archive_and_remove_directory(raw_dir) - log.info(f'Archived raw picker output to {archive_path}') + log.info(f'Archived imported pick cache to {archive_path}') # build_pick_commands: the ToolCommand `stamp pick` would run for the real track, without running it def build_pick_commands(config, output_dir: Path) -> list[ToolCommand]: target = stage_dir(output_dir, 'real', 'pick') argv = [ - 'stamp', 'pick', ','.join(config.stage.pick.pickers), - '--seg-dir', str(config.run.segmentation_dir), + 'stamp', 'pick', *[str(path) for path in config.stage.pick.picks_files], + '--orientation-prior', config.run.orientation_prior.value, '--raw-dir', str(config.run.raw_tomogram_dir), '--out-dir', str(output_dir), '--voxel-size-a', str(config.run.voxel_size_angstrom), '--consensus-rule', config.stage.pick.consensus_rule, '--distance-threshold', str(config.stage.pick.distance_threshold), '--half-set-seed', str(config.stage.pick.half_set_seed), - '--backend', 'local', + '--max-surface-distance-a', str(config.stage.pick.max_surface_distance_angstrom), '--n-processes', str(config.stage.pick.n_workers), ] + if config.run.segmentation_dir is not None: + argv += ['--seg-dir', str(config.run.segmentation_dir)] + for name in config.stage.pick.picker_names or []: + argv += ['--name', name] if config.plots.enabled: argv.append('--plots') argv += ['--pick-plot-style', config.plots.pick_style, '--plot-format', config.plots.format] @@ -341,4 +296,4 @@ def build_pick_commands(config, output_dir: Path) -> list[ToolCommand]: argv.append('--pick-plot-3d') if config.stage.pick.keep_raw: argv.append('--keep-raw') - return [ToolCommand(tool='pick', argv=argv, working_directory=target, output_paths=[target / 'particle_set.json'])] \ No newline at end of file + return [ToolCommand(tool='pick', argv=argv, working_directory=target, output_paths=[target / 'particle_set.json'])] diff --git a/src/stamp/commands/refine.py b/src/stamp/commands/refine.py index 7e07ed8..12aa4fa 100644 --- a/src/stamp/commands/refine.py +++ b/src/stamp/commands/refine.py @@ -13,6 +13,7 @@ from stamp.adapters.relion import RelionRefineAdapter from stamp.backends.base import ToolCommand from stamp.backends.factory import check_backend_supports, select_runner +from stamp.classify.extract import quaternion_to_matrix from stamp.picking.geometry import compose_roll_about_normal from stamp.refine.fsc import compute_fsc, soft_sphere_mask, write_fsc_files from stamp.refine.halfset_guard import ( @@ -52,6 +53,10 @@ def _with_inplane(particle, angle_by_particle: dict[str, float]): return particle return particle.model_copy(update={'orientation': compose_roll_about_normal(particle.orientation, angle)}) +# _full_poses: {particle_id: (rotation matrix, shift)} for assignments the polish step posed, which replace the in-plane angle +def _full_poses(assignments: list[ClassAssignment]) -> dict[str, tuple[np.ndarray, np.ndarray]]: + return {row.particle_id: (quaternion_to_matrix(row.rotation), np.array(row.shift_voxels if row.shift_voxels is not None else (0.0, 0.0, 0.0))) for row in assignments if row.rotation is not None} + # _run_half: one independent half-set refinement, returns the final map path def _run_half(adapter, runner, particles, reference, workdir, parameters, backend) -> Path: inputs = AdapterInputs( @@ -60,7 +65,7 @@ def _run_half(adapter, runner, particles, reference, workdir, parameters, backen parameters=parameters, ) if backend != 'mock': - adapter.write_particle_star(particles, workdir / 'particles.star', {}) + adapter.write_particle_star(particles, workdir / 'particles.star', {}, poses=parameters.get('poses'), voxel_size_angstrom=parameters['voxel_size_angstrom']) command = adapter.build_command(inputs) log.debug(f'{workdir.name}: dispatching {adapter.name} refinement') result = runner.run(command) @@ -102,7 +107,8 @@ def run_refine( log.debug(f'Resolved voxel size from MRC headers: {voxel_size_angstrom} Å') particle_set = ParticleSet.model_validate(json.loads(particles.read_text())) assignments = [ClassAssignment.model_validate(row) for row in json.loads(class_assignments.read_text())] - angle_by_particle = {row.particle_id: row.inplane_angle_degrees for row in assignments if row.inplane_angle_degrees is not None} + poses = _full_poses(assignments) + angle_by_particle = {row.particle_id: row.inplane_angle_degrees for row in assignments if row.inplane_angle_degrees is not None and row.particle_id not in poses} # a full pose already contains the in-plane angle class_averages_dir = class_assignments.parent / 'class_averages' identified = {row['cluster_id'] for row in json.loads(identification.read_text())} @@ -111,7 +117,7 @@ def run_refine( adapter = get_mock_adapter('relion' if tool == 'relion' else 'm-refine') if backend == 'mock' else _ADAPTERS[tool]() check_backend_supports(adapter, backend) runner = select_runner(backend, requires_gpu=getattr(adapter, 'requires_gpu', False)) - parameters = {'voxel_size_angstrom': voxel_size_angstrom, 'iterations': iterations} + parameters = {'voxel_size_angstrom': voxel_size_angstrom, 'iterations': iterations, 'poses': poses} # poses ride along to the adapter that writes the particle file failed_targets: list[str] = [] for target in targets: diff --git a/src/stamp/config/template.py b/src/stamp/config/template.py index 690e018..327d666 100644 --- a/src/stamp/config/template.py +++ b/src/stamp/config/template.py @@ -9,21 +9,25 @@ # stamp run --config stamp_run.toml [run] -segmentation_dir = "data/seg" # --seg-dir +segmentation_dir = "data/seg" # --seg-dir (required for orientation_prior = "normal") raw_tomogram_dir = "data/tomo" # --raw-dir output_dir = "." # output directory for each stage voxel_size_angstrom = "" # --voxel-size-a (blank = auto-detect from tomogram headers) backend = "local" # --backend (local|mock|cluster; per-stage backends below override) stop_after = "" # optional; blank|pick|classify|identify|refine +orientation_prior = "normal" # normal (membrane proteins)|axis (filaments)|none (soluble particles) +tilt_max_degrees = "" # --tilt-max (maximum tilt of the tilt series; blank = no missing wedge modelled) +tilt_axis_degrees = 90.0 # --tilt-axis (tilt axis angle from the tomogram x axis, 90 = tilt about y) [decoy] enabled = true # --no-decoy -method = "rejected-surface" # --method (rejected-surface|shifted|synthetic-noise) -n_decoys_per_tomogram = 50 +method = "shifted" # --method (shifted|synthetic-noise|random-volume; random-volume for the axis and none priors) +n_decoys_per_tomogram = 50 # synthetic-noise only min_distance_from_real_angstrom = 100.0 min_distance_from_picks_angstrom = 60.0 min_shift_angstrom = 200.0 max_shift_angstrom = 600.0 +min_border_angstrom = 200.0 # random-volume only n_synthetic_tomograms = 3 n_workers = 1 synthetic_shape_voxels = "" # blank = match first real tomogram, or e.g. [128, 128, 128] @@ -36,25 +40,32 @@ pick_plot_3d = false [stage.pick] -pickers = ["stamp-native"] +picks_files = ["data/picks.csv"] # positional picks files (.csv|.star|.json|.jsonl), one picker per file +# picker_names = ["picker-a"] # --name (one per file, unique; default = file stems) consensus_rule = "intersection" # --consensus-rule (union|intersection) distance_threshold = 15.0 # --distance-threshold half_set_seed = 0 # --half-set-seed +max_surface_distance_angstrom = 300.0 # --max-surface-distance-a n_workers = 1 keep_raw = false -backend = "" # blank = defaults to [run].backend +backend = "" # inert for pick; blank = defaults to [run].backend [stage.classify] -method = "hdbscan" # --method (hdbscan|kmeans) -min_cluster_size = 20 +method = "leiden" # --method (leiden|hdbscan|kmeans) +min_cluster_size = 20 # smallest cluster, and the smallest seed polish refines n_clusters = 5 n_components = 20 box_angstrom = 300.0 # --box-length-a n_radial_bins = 12 # --n-bins strict_halfset_independence = true -inplane_alignment = true inplane_angular_step_degrees = 10.0 -inplane_iterations = 3 +bin_factor = 2 # --bin-factor (working resolution) +n_rotations = 3000 # --n-rots (none prior) +shift_range_voxels = 3 # --shift-range (working voxels) +polish_rounds = 2 # --polish-rounds +null_sigmas = 3.0 # --null-sigmas +reject_quantile = 0.95 # --reject-quantile +merge_fraction = 1.0 # --merge-fraction random_state = 0 # --seed n_workers = 1 diff --git a/src/stamp/decoy/generate.py b/src/stamp/decoy/generate.py index bfb1702..b72c9d7 100644 --- a/src/stamp/decoy/generate.py +++ b/src/stamp/decoy/generate.py @@ -10,179 +10,38 @@ # Import internal STAMP objects from stamp.utils.halfset import assign_half_sets -from stamp.picking.geometry import ( - downsample_points, - exclude_near_boundary, - extract_surface, - quaternion_from_reference_to, - robust_normalise, - sample_along_normals, - score_membrane_faces -) -from stamp.picking.native import NativePickerConfig +from stamp.picking.geometry import extract_surface, quaternion_from_reference_to from stamp.schemas.manifest import TomogramManifest -from stamp.schemas.particles import Particle, ParticleSet +from stamp.schemas.particles import OrientationPrior, Particle, ParticleSet from stamp.schemas.picks import RawPick from stamp.utils.checkpoint import atomic_save_npz from stamp.utils.errors import StampValidationError -from stamp.utils.io import cache_tomogram_picks, load_cached_picks, new_mrc, read_mrc +from stamp.utils.io import cache_tomogram_picks, load_cached_picks, new_mrc, open_mrc, read_mrc from stamp.utils.log import log from stamp.utils.parallel import run_parallel, run_parallel_ordered # Define constants -METHOD_REJECTED_SURFACE = 'rejected-surface' METHOD_SHIFTED = 'shifted' METHOD_SYNTHETIC_NOISE = 'synthetic-noise' +METHOD_RANDOM_VOLUME = 'random-volume' DECOY_SOURCE_PREFIX = 'decoy-' -# _RejectedSurfaceJob: one manifest's scoring inputs +# DecoyGeometry: voxel size and density sign shared by the decoy generators @dataclass(frozen=True) -class _RejectedSurfaceJob: - manifest: TomogramManifest - config: NativePickerConfig +class DecoyGeometry: + voxel_size_angstrom: float + # +1 if the synthetic membrane shell is brighter than background, -1 if darker + density_sign: int = -1 -# _ScoreSurfaceResult: type alias for _score_surface's return shape -_ScoreSurfaceResult = tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray] + def __post_init__(self) -> None: + if self.voxel_size_angstrom <= 0: + raise StampValidationError('voxel_size_angstrom must be positive.') + if self.density_sign not in (1, -1): + raise StampValidationError('density_sign must be +1 or -1.') -# _adaptive_decoy_count: target decoy count derived from a tomogram's real pick count -def _adaptive_decoy_count(n_real_picks: int, *, target_ratio: float = 1.0) -> int: - return max(1, round(n_real_picks * target_ratio)) - -# _score_one_tomogram: worker entry point, isolates StampValidationError per tomogram for on_error -def _score_one_tomogram(job: _RejectedSurfaceJob) -> _ScoreSurfaceResult: - return _score_surface(job.manifest, job.config) - -# _SCORE_FIELDS: names under which _score_surface's six arrays are stored -_SCORE_FIELDS = ('points', 'normals', 'scores', 'winning_window', 'mean_scores', 'profile_scores') - -# _save_cached_scores: checkpoint one tomogram's surface scores -def _save_cached_scores(scores_dir: Path, tomogram_id: str, result: _ScoreSurfaceResult) -> None: - atomic_save_npz(scores_dir / f'{tomogram_id}.npz', **dict(zip(_SCORE_FIELDS, result))) - -# _load_cached_scores: one tomogram's checkpointed surface scores, or None when absent or unreadable -def _load_cached_scores(scores_dir: Path | None, tomogram_id: str) -> _ScoreSurfaceResult | None: - if scores_dir is None: - return None - try: - with np.load(scores_dir / f'{tomogram_id}.npz') as cached: - return tuple(cached[name] for name in _SCORE_FIELDS) # type: ignore[return-value] - except (OSError, ValueError, KeyError): - return None - -# generate_rejected_surface_decoys: sample decoys from surface points the native picker scored and rejected -def generate_rejected_surface_decoys( - real_particle_set: ParticleSet, - manifests: list[TomogramManifest], - config: NativePickerConfig, - n_decoys_per_tomogram: int | None, - min_distance_from_real_angstrom: float, - seed: int, - *, - n_workers: int = 1, - output_dir: Path | None = None, -) -> ParticleSet | None: - log.progress(f'Generating rejected-surface decoys ({n_decoys_per_tomogram or "adaptive n"}/tomogram)') - rng = np.random.default_rng(seed) - real_by_tomogram: dict[str, list[tuple[float, float, float]]] = {} - for particle in real_particle_set.particles: - real_by_tomogram.setdefault(particle.tomogram_id, []).append(particle.position) - - min_distance_voxels = config.to_voxels(min_distance_from_real_angstrom) - raw_picks: list[RawPick] = [] - cache_dir = output_dir / 'raw' / METHOD_REJECTED_SURFACE if output_dir is not None else None - tomogram_ids = [] - - scores_dir = cache_dir / 'scores' if cache_dir is not None else None - - # run surface scoring in a pool but keep rng-driven sampling sequential and in manifest order so results stay reproducible for a given seed - result_by_tomogram: dict[str, _ScoreSurfaceResult] = {} - - def _on_success(job: _RejectedSurfaceJob, result: _ScoreSurfaceResult) -> None: - result_by_tomogram[job.manifest.tomogram_id] = result - if scores_dir is not None: - _save_cached_scores(scores_dir, job.manifest.tomogram_id, result) - - def _on_error(job: _RejectedSurfaceJob, exc: Exception) -> None: - if isinstance(exc, StampValidationError): - log.warning(f'{job.manifest.tomogram_id}: skipped ({exc})') - else: - raise exc - - jobs: list[_RejectedSurfaceJob] = [] - for manifest in manifests: - cached = _load_cached_scores(scores_dir, manifest.tomogram_id) - if cached is None: - jobs.append(_RejectedSurfaceJob(manifest, config)) - else: - result_by_tomogram[manifest.tomogram_id] = cached - if len(jobs) < len(manifests): - log.info(f'Resuming rejected-surface decoys: {len(manifests) - len(jobs)} tomogram(s) loaded from checkpoint') - run_parallel(jobs, _score_one_tomogram, max_workers=n_workers, label='decoy-surface-score', on_success=_on_success, on_error=_on_error) - - for manifest in manifests: - result = result_by_tomogram.get(manifest.tomogram_id) - if result is None: - continue - points_zyx, normals_zyx, scores, winning_window, mean_scores, profile_scores = result - if points_zyx.shape[0] == 0: - continue - - # only use points the picker rejected - rejected = scores < config.effective_n_mad - points_zyx, normals_zyx, scores, winning_window, mean_scores, profile_scores = ( - points_zyx[rejected], normals_zyx[rejected], scores[rejected], winning_window[rejected], - mean_scores[rejected], profile_scores[rejected], - ) - if points_zyx.shape[0] == 0: - continue - - # convert positions (z, y, x) to position (x, y, z) - points_xyz = points_zyx[:, ::-1] - real_positions = real_by_tomogram.get(manifest.tomogram_id, []) - if real_positions: - tree = cKDTree(np.array(real_positions)) - far_enough = ( - tree.query(points_xyz, k=1)[0] >= min_distance_voxels - ) - points_xyz, points_zyx, normals_zyx, scores, winning_window, mean_scores, profile_scores = ( - points_xyz[far_enough], points_zyx[far_enough], - normals_zyx[far_enough], scores[far_enough], winning_window[far_enough], - mean_scores[far_enough], profile_scores[far_enough], - ) - if points_xyz.shape[0] == 0: - continue - - # prefer the most confidently empty positions, but jitter the choice so decoys aren't all clustered in one flat region - target = n_decoys_per_tomogram if n_decoys_per_tomogram is not None else _adaptive_decoy_count(len(real_positions)) - n_to_take = min(target, points_xyz.shape[0]) - candidate_pool = min(points_xyz.shape[0], n_to_take * 5) - lowest_first = np.argsort(scores)[:candidate_pool] - chosen = rng.choice(lowest_first, size=n_to_take, replace=False) - - tomogram_picks = [ - RawPick( - tomogram_id=manifest.tomogram_id, - position=tuple(float(c) for c in points_xyz[index]), - orientation=quaternion_from_reference_to(np.asarray(normals_zyx[index][::-1])), - confidence=float(scores[index]), - source_picker=f'{DECOY_SOURCE_PREFIX}{METHOD_REJECTED_SURFACE}', - offset_window_angstrom=config.offset_windows_angstrom[int(winning_window[index])], - mean_score=float(mean_scores[index]), - profile_score=float(profile_scores[index]), - ) - for index in chosen - ] - if cache_dir is not None: - cache_tomogram_picks(cache_dir, manifest.tomogram_id, tomogram_picks) - tomogram_ids.append(manifest.tomogram_id) - else: - raw_picks.extend(tomogram_picks) - - if cache_dir is not None: - raw_picks = load_cached_picks(cache_dir, tomogram_ids) - decoys = _finalise(raw_picks, seed, METHOD_REJECTED_SURFACE) - log.info(f'Generated {len(raw_picks)} decoy particles') - return decoys + # to_voxels: convert a distance in Angstrom to voxels + def to_voxels(self, angstrom: float) -> float: + return angstrom / self.voxel_size_angstrom # _extract_surface_for_manifest: worker entry point, loads segmentation and extracts its surface def _extract_surface_for_manifest(manifest: TomogramManifest) -> tuple[tuple[int, ...], np.ndarray, np.ndarray]: @@ -209,7 +68,7 @@ def _load_cached_surface(surfaces_dir: Path | None, tomogram_id: str) -> tuple[t def generate_shifted_decoys( real_particle_set: ParticleSet, manifests: list[TomogramManifest], - config: NativePickerConfig, + config: DecoyGeometry, min_shift_angstrom: float, max_shift_angstrom: float, min_distance_from_surface_angstrom: float, @@ -318,6 +177,56 @@ def _on_error(manifest: TomogramManifest, exc: Exception) -> None: log.info(f'Generated {len(raw_picks)} decoy particles') return decoys +# generate_random_volume_decoys: one decoy per real pick at a uniformly random position in the tomogram, clear of every real pick and of the border, with a random orientation where the prior has one; needs no segmentation so it serves every prior except the membrane normal +def generate_random_volume_decoys( + real_particle_set: ParticleSet, + manifests: list[TomogramManifest], + config: DecoyGeometry, + min_distance_from_picks_angstrom: float, + border_angstrom: float, + seed: int, + max_attempts_per_particle: int = 200, +) -> ParticleSet | None: + prior = real_particle_set.orientation_prior + if prior is OrientationPrior.NORMAL: + raise StampValidationError('random-volume decoys have no membrane normal to orient by, use the shifted method for the normal orientation prior') + log.progress('Generating random-volume decoys') + rng = np.random.default_rng(seed) + raw_path_by_tomogram = {manifest.tomogram_id: manifest.raw_tomogram_path for manifest in manifests} + positions_by_tomogram: dict[str, list[tuple[float, float, float]]] = {} + for particle in real_particle_set.particles: + positions_by_tomogram.setdefault(particle.tomogram_id, []).append(particle.position) + min_distance = config.to_voxels(min_distance_from_picks_angstrom) + border = config.to_voxels(border_angstrom) + raw_picks: list[RawPick] = [] + for tomogram_id, positions in positions_by_tomogram.items(): + if tomogram_id not in raw_path_by_tomogram: + continue + with open_mrc(raw_path_by_tomogram[tomogram_id], header_only=True) as mrc: + extent_xyz = np.array([int(mrc.header.nx), int(mrc.header.ny), int(mrc.header.nz)]) - 1 + low, high = np.full(3, border), extent_xyz - border + if np.any(high <= low): + log.warning(f'{tomogram_id}: smaller than twice the {border_angstrom} Å border, no random-volume decoys placed') + continue + pick_tree = cKDTree(np.array(positions)) + for _ in positions: + for _attempt in range(max_attempts_per_particle): + candidate = rng.uniform(low, high) + if pick_tree.query(candidate, k=1)[0] < min_distance: + continue + axis = rng.normal(size=3) + raw_picks.append(RawPick( + tomogram_id=tomogram_id, + position=tuple(float(c) for c in candidate), + orientation=quaternion_from_reference_to(axis / np.linalg.norm(axis)) if prior is OrientationPrior.AXIS else None, + source_picker=f'{DECOY_SOURCE_PREFIX}{METHOD_RANDOM_VOLUME}', + )) + break + else: + log.debug(f'{tomogram_id}: exhausted {max_attempts_per_particle} attempts placing a random-volume decoy, skipping one particle') + log.info(f'Generated {len(raw_picks)} decoy particles') + return _finalise(raw_picks, seed, METHOD_RANDOM_VOLUME, prior) + # _SyntheticNoiseJob: one noise volume's inputs @dataclass(frozen=True) class _SyntheticNoiseJob: @@ -327,7 +236,7 @@ class _SyntheticNoiseJob: centre: np.ndarray segmentation_dir: Path tomogram_dir: Path - config: NativePickerConfig + config: DecoyGeometry seed: int n_decoys_per_tomogram: int cache_dir: Path | None = None @@ -386,7 +295,7 @@ def generate_synthetic_noise_decoys( n_tomograms: int, n_decoys_per_tomogram: int | None, output_dir: Path, - config: NativePickerConfig, + config: DecoyGeometry, seed: int, *, n_workers: int = 1, @@ -417,48 +326,8 @@ def generate_synthetic_noise_decoys( log.info(f'Generated {len(raw_picks)} decoy particles') return decoys, manifests -# _score_surface: re-run the native picker's surface scoring for one tomogram -def _score_surface( - manifest: TomogramManifest, config: NativePickerConfig -) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - segmentation = read_mrc(manifest.segmentation_path) - tomogram = read_mrc(manifest.raw_tomogram_path) - - if segmentation.shape != tomogram.shape: - raise StampValidationError(f'Segmentation and tomogram shapes disagree for {manifest.tomogram_id}') - - try: - vertices, normals = extract_surface(segmentation) - except ValueError as exc: - log.warning(f'{manifest.tomogram_id}: skipped ({exc})') - empty = np.empty((0, 3)) - return empty, empty, np.empty(0), np.empty(0, dtype=np.int64), np.empty(0), np.empty(0) - - vertices, normals = downsample_points( - vertices, normals, config.to_voxels(config.surface_spacing_angstrom) - ) - margin = ( - config.boundary_margin_angstrom - if config.boundary_margin_angstrom is not None - else config.max_offset_angstrom - ) - inside = exclude_near_boundary(vertices, segmentation.shape, config.to_voxels(margin)) - vertices, normals = vertices[inside], normals[inside] - if vertices.shape[0] == 0: - empty = np.empty((0, 3)) - return empty, empty, np.empty(0), np.empty(0, dtype=np.int64), np.empty(0), np.empty(0) - - offset_windows_voxels = [(config.to_voxels(offset_min), config.to_voxels(offset_max)) for offset_min, offset_max in config.offset_windows_angstrom] - profile_width_voxels = (config.to_voxels(config.profile_width_angstrom) if config.profile_width_angstrom is not None else None) - - points, normals_out, scores, winning_window, _used_fallback, mean_scores, profile_scores = score_membrane_faces( - tomogram, vertices, normals, offset_windows_voxels, config.n_samples, config.density_sign, - scoring_mode=config.scoring_mode, profile_width_voxels=profile_width_voxels, - ) - return points, normals_out, scores, winning_window, mean_scores, profile_scores - # _finalise: assign decoy particle IDs and half-sets, returning a decoy ParticleSet or None if no decoys were generated -def _finalise(raw_picks: list[RawPick], seed: int, method: str) -> ParticleSet | None: +def _finalise(raw_picks: list[RawPick], seed: int, method: str, orientation_prior: OrientationPrior = OrientationPrior.NORMAL) -> ParticleSet | None: particle_ids = [f'decoy-{index:06d}' for index in range(len(raw_picks))] if not particle_ids: return None @@ -480,4 +349,5 @@ def _finalise(raw_picks: list[RawPick], seed: int, method: str) -> ParticleSet | particles=particles, consensus_rule='union', contributing_pickers=[f'{DECOY_SOURCE_PREFIX}{method}'], + orientation_prior=orientation_prior, ) diff --git a/src/stamp/decoy/validate.py b/src/stamp/decoy/validate.py index 4eab411..384208e 100644 --- a/src/stamp/decoy/validate.py +++ b/src/stamp/decoy/validate.py @@ -37,6 +37,8 @@ def assert_comparable(real: ParticleSet, decoy: ParticleSet) -> None: if is_decoy_particle_set(real): raise StampPipelineError('The real ParticleSet contains decoy particles') + if real.orientation_prior != decoy.orientation_prior: + raise StampPipelineError(f'Decoy orientation prior {decoy.orientation_prior.value!r} differs from the real set\'s {real.orientation_prior.value!r}, the control would classify with a different search space') real_count = len(real.particles) decoy_count = len(decoy.particles) if decoy_count < 0.5 * real_count: diff --git a/src/stamp/identify/decoy_check.py b/src/stamp/identify/decoy_check.py index b7a7d97..0d6af19 100644 --- a/src/stamp/identify/decoy_check.py +++ b/src/stamp/identify/decoy_check.py @@ -30,8 +30,17 @@ def evaluate_decoy_control( decoy_scores: list[float], min_separation_sigma: float = 2.0, ) -> DecoyControlResult: - if not real_scores or not decoy_scores: - raise ValueError('need at least one real and one decoy score') + if not real_scores: + raise ValueError('need at least one real score') + if not decoy_scores: # the polish step rejects every decoy particle when nothing beats its null, which is the best outcome for a control + return DecoyControlResult( + passed=True, + reason=f'the decoy produced no classes, so there is nothing for the fit to match (best real fit {max(real_scores):.3f})', + real_best=max(real_scores), + decoy_best=0.0, + separation_sigma=float('inf'), + mann_whitney_p=float('nan'), + ) real_best = max(real_scores) decoy_best = max(decoy_scores) decoy_spread = stdev(decoy_scores) if len(decoy_scores) > 1 else 0.0 diff --git a/src/stamp/identify/fit.py b/src/stamp/identify/fit.py index acc83b2..0682031 100644 --- a/src/stamp/identify/fit.py +++ b/src/stamp/identify/fit.py @@ -1,60 +1,11 @@ ''' -STAMP: rigid real-space fit of a simulated map to a class average +STAMP: ranking of candidate scores for a class ''' -# Import external dependencies -import numpy as np -from itertools import product -from scipy.ndimage import rotate, shift - # Import STAMP schema from stamp.schemas.particles import IdentificationResult from stamp.utils.log import log -# _standardise: zero-mean, unit-variance flatten of the masked voxels -def _standardise(values: np.ndarray) -> np.ndarray: - centred = values - values.mean() - spread = centred.std() - return centred / spread if spread > 0 else centred - -# _discrete_orients: the 8 axis-aligned orientations left ambiguous after principal-axis alignment -def _discrete_orients(volume: np.ndarray) -> list[np.ndarray]: - in_plane = [np.rot90(volume, k, axes=(0, 1)) for k in range(4)] - return in_plane + [np.flip(v, axis=2) for v in in_plane] # z-flip: which leaflet faces which - -# fit_candidate: best masked real-space CC over a bounded rigid search -def fit_candidate( - class_average: np.ndarray, - simulated: np.ndarray, - translation_voxels: int = 3, - tilt_degrees: float = 12.0, - tilt_step: float = 6.0, - *, - match_contrast: bool = True, -) -> float: - deviation = np.abs(class_average - class_average.mean()) - mask = deviation > class_average.std() - if not mask.any(): - mask = np.ones_like(class_average, dtype=bool) - reference = _standardise(class_average[mask]) - - tilts = np.arange(-tilt_degrees, tilt_degrees + 1e-6, tilt_step) - shifts = range(-translation_voxels, translation_voxels + 1) - best = -1.0 - for oriented in _discrete_orients(simulated): - for tilt_yz, tilt_xz in product(tilts, tilts): - tilted = oriented - if abs(tilt_yz) > 1e-6: - tilted = rotate(tilted, float(tilt_yz), axes=(1, 2), reshape=False, order=1, mode='constant') - if abs(tilt_xz) > 1e-6: - tilted = rotate(tilted, float(tilt_xz), axes=(0, 2), reshape=False, order=1, mode='constant') - for dx, dy, dz in product(shifts, shifts, shifts): - moved = shift(tilted, (dx, dy, dz), order=1, mode='constant', cval=0.0) - candidate = _standardise(moved[mask]) - score = float(np.dot(reference, candidate) / reference.size) - best = max(best, abs(score) if match_contrast else score) - return best - # rank_candidates: ranked IdentificationResult for one class def rank_candidates(class_id: str, scores: dict[str, float], method: str) -> IdentificationResult: if not scores: diff --git a/src/stamp/identify/register.py b/src/stamp/identify/register.py new file mode 100644 index 0000000..22ea85c --- /dev/null +++ b/src/stamp/identify/register.py @@ -0,0 +1,60 @@ +''' +STAMP: rigid registration of a simulated map to an aligned class average over an orientation prior's search space +''' + +# Import external dependencies +import numpy as np +from scipy.spatial.transform import Rotation + +# Import internal STAMP objects +from stamp.classify.match import Alignment, align_to_reference +from stamp.classify.prepare import soft_mask +from stamp.classify.search import SearchSpace, search_space +from stamp.schemas.particles import OrientationPrior + +# _prepare: soft-masked, mean-removed copy of a map so correlation is not driven by background or edges +def _prepare(volume: np.ndarray, mask: np.ndarray) -> np.ndarray: + inside = volume[mask > 0.5] + return ((volume - inside.mean()) * mask).astype(np.float32) + +# _local_rotations: n small random rotations up to max_degrees composed onto base +def _local_rotations(base: np.ndarray, n: int, max_degrees: float, rng: np.random.Generator) -> np.ndarray: + vectors = rng.normal(size=(n, 3)) + vectors *= (np.radians(max_degrees) * rng.random((n, 1)) ** (1 / 3)) / np.linalg.norm(vectors, axis=1, keepdims=True) + return np.einsum('nij,jk->nik', Rotation.from_rotvec(vectors).as_matrix(), base) + +# _best_pose: best alignment of average against reference over one search space +def _best_pose(average: np.ndarray, reference: np.ndarray, space: SearchSpace) -> tuple[Alignment, np.ndarray]: + result = align_to_reference(average[None], np.ones_like(average)[None], reference, space) + return result, space.rotations[result.rotation_index[0]] + +# register_score: best normalised correlation of simulated map with class average over every orientation, a coarse bank then two rounds of local refinement +def register_score( + average: np.ndarray, + simulated: np.ndarray, + prior: OrientationPrior, + *, + max_shift_voxels: int = 3, + n_rotations: int = 1500, + n_local: int = 200, + seed: int = 0, + match_contrast: bool = True, +) -> float: + box_voxels = average.shape[0] + mask = soft_mask(box_voxels, 0.45 * box_voxels) + target = _prepare(average, mask) + coarse = search_space(OrientationPrior.AXIS if prior is OrientationPrior.NORMAL else OrientationPrior.NONE, box_voxels, n_rotations=n_rotations, shift_range_voxels=max_shift_voxels, seed=seed) # membrane candidates are slab-oriented, so only the azimuth and the leaflet flip are open + rng = np.random.default_rng(seed) + best = -np.inf + for sign in ((1.0, -1.0) if match_contrast else (1.0,)): + reference = sign * _prepare(simulated, mask) + result, rotation = _best_pose(target, reference, coarse) + score, max_degrees = float(result.cc[0]), 12.0 + for _ in range(2): + local = _local_rotations(rotation, n_local, max_degrees, rng) + result, rotation_local = _best_pose(target, reference, SearchSpace(prior, local, np.ones(len(local), dtype=np.int8), coarse.max_shift)) + if result.cc[0] > score: + score, rotation = float(result.cc[0]), rotation_local + max_degrees /= 2 + best = max(best, score) + return best diff --git a/src/stamp/identify/simulate.py b/src/stamp/identify/simulate.py index 59a7d35..78a3a1b 100644 --- a/src/stamp/identify/simulate.py +++ b/src/stamp/identify/simulate.py @@ -6,7 +6,7 @@ import numpy as np from itertools import product from pathlib import Path -from scipy.ndimage import gaussian_filter, rotate +from scipy.ndimage import gaussian_filter # Import internal STAMP objects from stamp.utils.log import log @@ -63,16 +63,7 @@ def simulate_density( peak = blurred.max() return (blurred / peak).astype(np.float32) if peak > 0 else blurred.astype(np.float32) -# azimuthal_smear: rotational average about z, to match class average -def azimuthal_smear(volume: np.ndarray, n_angles: int = 72) -> np.ndarray: - accumulator = np.zeros_like(volume, dtype=np.float64) - for angle in np.linspace(0.0, 360.0, n_angles, endpoint=False): - accumulator += rotate( - volume, angle, axes=(0, 1), reshape=False, order=1, mode='constant' - ) - return (accumulator / n_angles).astype(volume.dtype) - -# to_comparable: reduce density maps for comparability by band-limiting to common resolution and azimuthally averaging about z +# to_comparable: reduce density maps for comparability by band-limiting to common resolution def to_comparable( volume: np.ndarray, voxel_size_angstrom: float, @@ -84,7 +75,7 @@ def to_comparable( if not already_bandlimited: sigma_voxels = resolution_angstrom * _FWHM_TO_SIGMA / voxel_size_angstrom prepared = gaussian_filter(prepared, sigma=max(sigma_voxels, 0.5)) - return azimuthal_smear(prepared).astype(np.float32) + return prepared.astype(np.float32) # orient_to_membrane_slab: rotate mass-weighted coordinates so the slab normal (largest inertial moment) is +z def orient_to_membrane_slab(coordinates: np.ndarray, weights: np.ndarray) -> np.ndarray: diff --git a/src/stamp/picking/consensus.py b/src/stamp/picking/consensus.py index 739b518..a943cfe 100644 --- a/src/stamp/picking/consensus.py +++ b/src/stamp/picking/consensus.py @@ -10,7 +10,7 @@ # Import internal STAMP objects from stamp.utils.halfset import assign_half_sets -from stamp.schemas.particles import Particle, ParticleSet +from stamp.schemas.particles import OrientationPrior, Particle, ParticleSet from stamp.schemas.picks import RawPick from stamp.utils.log import log from stamp.utils.parallel import run_parallel_ordered @@ -125,6 +125,7 @@ def build_particle_set( consensus_rule: Literal['intersection', 'union'], contributing_pickers: list[str], half_set_seed: int, + orientation_prior: OrientationPrior = OrientationPrior.NORMAL, ) -> ParticleSet: particle_ids = [f'p{index:06d}' for index in range(len(reconciled_picks))] group_of = {particle_id: pick.tomogram_id for particle_id, pick in zip(particle_ids, reconciled_picks)} @@ -148,4 +149,5 @@ def build_particle_set( particles=particles, consensus_rule=consensus_rule, contributing_pickers=contributing_pickers, + orientation_prior=orientation_prior, ) diff --git a/src/stamp/picking/geometry.py b/src/stamp/picking/geometry.py index 733f56c..7de95ec 100644 --- a/src/stamp/picking/geometry.py +++ b/src/stamp/picking/geometry.py @@ -4,11 +4,7 @@ # Import external dependencies import numpy as np -from collections.abc import Sequence -from scipy.ndimage import map_coordinates -from scipy.spatial import cKDTree from skimage import measure -from typing import Literal # Import internal STAMP objects from stamp.utils.errors import StampValidationError @@ -32,169 +28,6 @@ def extract_surface(segmentation: np.ndarray, level: float = 0.5) -> tuple[np.nd log.debug(f'Extracted surface: {len(vertices)} vertices, {len(faces)} faces') return vertices, normals / lengths -# downsample_points: voxel-grid downsample keeping one point per cell of side spacing_voxels (so sampling density is set by the requested spacing rather than mesh resolution) -def downsample_points(points: np.ndarray, normals: np.ndarray, spacing_voxels: float) -> tuple[np.ndarray, np.ndarray]: - if spacing_voxels <= 0: - raise ValueError('spacing_voxels must be positive.') - if points.shape[0] == 0: - return points, normals - cells = np.floor(points / spacing_voxels).astype(np.int64) - # np.unique with return_index gives the lowest original index per unique cell - _unique_cells, first_indices = np.unique(cells, axis=0, return_index=True) - keep = np.sort(first_indices) - return points[keep], normals[keep] - -# sample_along_normals: mean tomogram density in a shell offset along each point's normal -def sample_along_normals( - tomogram: np.ndarray, - points: np.ndarray, - normals: np.ndarray, - offset_min_voxels: float, - offset_max_voxels: float, - n_samples: int, - direction: int, - *, - return_samples: bool = False, -) -> np.ndarray | tuple[np.ndarray, np.ndarray]: - if direction not in (1, -1): - raise ValueError('direction must be +1 or -1.') - if n_samples < 1: - raise ValueError('n_samples must be at least 1.') - if offset_max_voxels < offset_min_voxels: - raise ValueError('offset_max_voxels must be >= offset_min_voxels.') - offsets = np.linspace(offset_min_voxels, offset_max_voxels, n_samples) - # (n_samples, N, 3): each surface point stepped out to each offset - sample_points = points[None, :, :] + direction * offsets[:, None, None] * normals[None, :, :] - flat = sample_points.reshape(-1, 3).T # (3, n_samples*N) in (z, y, x) - densities = map_coordinates( - tomogram.astype(np.float32), flat, order=1, mode='nearest' - ) - reshaped = densities.reshape(n_samples, points.shape[0]) # (n_samples, N) - mean = reshaped.mean(axis=0) - if return_samples: - return mean, reshaped.T # profile: (N, n_samples), sample order matches offsets - return mean - -# profile_correlation_scores: Pearson correlation of each point's sign-corrected radial profile against a Gaussian bump centred at peak_offset_voxels with the given width -def profile_correlation_scores( - profiles: np.ndarray, - offsets_voxels: np.ndarray, - peak_offset_voxels: float, - width_voxels: float, - density_sign: int, -) -> np.ndarray: - if width_voxels <= 0: - raise ValueError('width_voxels must be positive.') - if profiles.shape[1] < 3: - raise ValueError('Profile scoring needs at least 3 samples per point to be meaningful.') - expected = np.exp(-0.5 * ((offsets_voxels - peak_offset_voxels) / width_voxels) ** 2) - expected_centred = expected - expected.mean() - expected_norm = np.sqrt(np.sum(expected_centred**2)) - if expected_norm == 0.0: - raise ValueError('Expected profile has zero variance; widen width_voxels or move the peak inside the offset window.') - signed = density_sign * profiles - signed_centred = signed - signed.mean(axis=1, keepdims=True) - numerator = signed_centred @ expected_centred - signed_norm = np.sqrt(np.sum(signed_centred**2, axis=1)) - # points with a flat profile (zero variance) correlate with nothing; score them 0 rather than NaN - return np.divide( - numerator, signed_norm * expected_norm, - out=np.zeros_like(numerator), where=signed_norm > 0, - ) - -# robust_normalise: median/MAD normalisation so score thresholds are comparable across tomograms -def robust_normalise( - values: np.ndarray, - *, - mode: Literal['global', 'local', 'vesicle'] = 'global', - points: np.ndarray | None = None, - local_radius_voxels: float | None = None, - min_local_neighbours: int = 20, - vesicle_ids: list[str] | None = None, -) -> tuple[np.ndarray, np.ndarray]: - if mode == 'local': - if points is None or local_radius_voxels is None: - raise ValueError('local mode requires points and local_radius_voxels') - return local_normalise(values, points, local_radius_voxels, min_local_neighbours) - if mode == 'vesicle': - if vesicle_ids is None: - raise ValueError('vesicle mode requires vesicle_ids') - return vesicle_normalise(values, vesicle_ids) - - median = np.median(values) - mad = np.median(np.abs(values - median)) - if mad > 0.0: - # 1.4826 makes MAD a consistent estimator of sigma for normal data - scaled = (values - median) / (1.4826 * mad) - else: - std = values.std() - scaled = np.zeros_like(values) if std == 0.0 else (values - median) / std - return scaled, np.zeros_like(values, dtype=bool) - -# local_normalise: per-point median/MAD normalisation over a k-d tree neighbourhood -def local_normalise( - values: np.ndarray, - points: np.ndarray, - radius_voxels: float, - min_neighbours: int, -) -> tuple[np.ndarray, np.ndarray]: - n_points = points.shape[0] - normalised = np.empty(n_points, dtype=np.float64) - used_fallback = np.zeros(n_points, dtype=bool) - - global_median = np.median(values) - global_mad = np.median(np.abs(values - global_median)) - global_scale = 1.4826 * global_mad if global_mad > 0.0 else (values.std() or 1.0) - - tree = cKDTree(points) - neighbour_lists = tree.query_ball_point(points, r=radius_voxels) - - for index, neighbours in enumerate(neighbour_lists): - if len(neighbours) < min_neighbours: - used_fallback[index] = True - normalised[index] = (values[index] - global_median) / global_scale - continue - local_values = values[neighbours] - local_median = np.median(local_values) - local_mad = np.median(np.abs(local_values - local_median)) - local_scale = 1.4826 * local_mad if local_mad > 0.0 else global_scale - normalised[index] = (values[index] - local_median) / local_scale - - return normalised, used_fallback - -# vesicle_normalise: per-vesicle median/MAD normalisation; points with no vesicle_id ('') fall back to the pooled/global estimate -def vesicle_normalise(values: np.ndarray, vesicle_ids: list[str]) -> tuple[np.ndarray, np.ndarray]: - groups = np.asarray(vesicle_ids) - normalised, _fallback = robust_normalise(values) - used_fallback = np.zeros(values.shape[0], dtype=bool) - for group in set(groups): - if not group: - continue - mask = groups == group - normalised[mask], _ = robust_normalise(values[mask]) - used_fallback[groups == ''] = True - return normalised, used_fallback - -# non_maximum_suppression: greedy non-maximum suppression, highest score first, returning indices of kept points -def non_maximum_suppression( - points: np.ndarray, scores: np.ndarray, min_distance_voxels: float -) -> np.ndarray: - if points.shape[0] == 0: - return np.array([], dtype=np.int64) - if min_distance_voxels <= 0: - return np.arange(points.shape[0]) - tree = cKDTree(points) - order = np.argsort(-scores) - suppressed = np.zeros(points.shape[0], dtype=bool) - kept: list[int] = [] - for index in order: - if suppressed[index]: - continue - kept.append(int(index)) - for neighbour in tree.query_ball_point(points[index], r=min_distance_voxels): - suppressed[neighbour] = True - return np.array(sorted(kept), dtype=np.int64) - # quaternion_from_reference_to: unit quaternion rotating REFERENCE_AXIS_XYZ (+z) onto the given vector def quaternion_from_reference_to(vector_xyz: np.ndarray) -> tuple[float, float, float, float]: norm = np.linalg.norm(vector_xyz) @@ -228,72 +61,6 @@ def compose_roll_about_normal( product /= np.linalg.norm(product) or 1.0 return tuple(float(component) for component in product) -# exclude_near_boundary: boolean mask of points at least margin_voxels from every face of the volume -def exclude_near_boundary(points: np.ndarray, shape: tuple[int, ...], margin_voxels: float) -> np.ndarray: - lower = np.all(points >= margin_voxels, axis=1) - upper = np.all(points <= (np.array(shape) - 1 - margin_voxels), axis=1) - return lower & upper - -# score_membrane_faces: sample both faces of every surface point across multiple offset windows, scoring each window by mean density and by radial-profile shape -def score_membrane_faces( - tomogram: np.ndarray, - vertices: np.ndarray, - normals: np.ndarray, - offset_windows_voxels: Sequence[tuple[float, float]], - n_samples: int, - density_sign: int, - *, - scoring_mode: Literal['mean', 'profile'] = 'mean', - profile_width_voxels: float | None = None, - mode: Literal['global', 'local', 'vesicle'] = 'global', - local_radius_voxels: float | None = None, - min_local_neighbours: int = 20, - vesicle_ids: list[str] | None = None, -) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - if len(offset_windows_voxels) == 0: - raise ValueError('offset_windows_voxels must contain at least one window.') - - points = np.concatenate([vertices, vertices]) - face_normals = np.concatenate([normals, -normals]) - - n_windows = len(offset_windows_voxels) - window_scores = np.empty((n_windows, points.shape[0])) - window_mean_scores = np.empty((n_windows, points.shape[0])) - window_profile_scores = np.empty((n_windows, points.shape[0])) - window_fallback = np.empty((n_windows, points.shape[0]), dtype=bool) - for window_index, (offset_min_voxels, offset_max_voxels) in enumerate(offset_windows_voxels): - means, profiles = zip(*[sample_along_normals(tomogram, vertices, normals, offset_min_voxels, offset_max_voxels, n_samples, direction, return_samples=True) for direction in (1, -1)]) - raw_means = density_sign * np.concatenate(means) - pooled_profiles = np.concatenate(profiles, axis=0) - - offsets_voxels = np.linspace(offset_min_voxels, offset_max_voxels, n_samples) - peak_voxels = (offset_min_voxels + offset_max_voxels) / 2.0 # window's own midpoint - width_voxels = profile_width_voxels if profile_width_voxels is not None else (offset_max_voxels - offset_min_voxels) / 4.0 - raw_profile = profile_correlation_scores(pooled_profiles, offsets_voxels, peak_voxels, width_voxels, density_sign) - - window_mean_scores[window_index], mean_fallback = robust_normalise(raw_means, mode=mode, points=points, local_radius_voxels=local_radius_voxels, min_local_neighbours=min_local_neighbours, vesicle_ids=vesicle_ids) - window_profile_scores[window_index], profile_fallback = robust_normalise(raw_profile, mode=mode, points=points, local_radius_voxels=local_radius_voxels, min_local_neighbours=min_local_neighbours, vesicle_ids=vesicle_ids) - if scoring_mode == 'profile': - window_scores[window_index], window_fallback[window_index] = window_profile_scores[window_index], profile_fallback - else: - window_scores[window_index], window_fallback[window_index] = window_mean_scores[window_index], mean_fallback - - winning_window = np.argmax(window_scores, axis=0) - point_index = np.arange(points.shape[0]) - scores = window_scores[winning_window, point_index] - mean_scores = window_mean_scores[winning_window, point_index] - profile_scores = window_profile_scores[winning_window, point_index] - used_fallback = window_fallback[winning_window, point_index] - return points, face_normals, scores, winning_window, used_fallback, mean_scores, profile_scores - -# max_order_statistic_offset: approximate upward bias, in normalised score units, of the maximum of n_windows independent standard-normal scores -def max_order_statistic_offset(n_windows: int) -> float: - if n_windows < 1: - raise ValueError('n_windows must be at least 1.') - if n_windows == 1: - return 0.0 - return float(np.sqrt(2.0 * np.log(n_windows))) - # beam_angle_deviation_degrees: angle between an outward normal and the beam-orthogonal plane (0 = beam-orthogonal, 90 = beam-aligned) def beam_angle_deviation_degrees(normal_xyz: np.ndarray) -> float: norm = np.linalg.norm(normal_xyz) diff --git a/src/stamp/picking/importers.py b/src/stamp/picking/importers.py new file mode 100644 index 0000000..e175f29 --- /dev/null +++ b/src/stamp/picking/importers.py @@ -0,0 +1,205 @@ +''' +STAMP: import externally generated picks (CSV, RELION STAR, JSON) and infer missing orientations +''' + +# Import external dependencies +import csv, json, numpy as np, starfile +from pathlib import Path +from scipy.spatial import cKDTree + +# Import internal STAMP objects +from stamp.picking.geometry import beam_angle_deviation_degrees, extract_surface, quaternion_from_reference_to +from stamp.picking.vesicles import load_vesicle_labels, vesicle_ids_at +from stamp.schemas.manifest import TomogramManifest +from stamp.schemas.particles import OrientationPrior +from stamp.schemas.picks import RawPick +from stamp.utils.errors import StampError, StampValidationError +from stamp.utils.io import read_mrc +from stamp.utils.log import log + +# CSV_REQUIRED: columns every CSV picks file must carry +CSV_REQUIRED = ('tomogram_id', 'x', 'y', 'z') + +# CSV_QUATERNION: optional orientation columns, all or none +CSV_QUATERNION = ('qw', 'qx', 'qy', 'qz') + +# STAR_COLUMNS: RELION columns read from a STAR file, positions in pixels +STAR_COLUMNS = ('rlnTomoName', 'rlnCoordinateX', 'rlnCoordinateY', 'rlnCoordinateZ') + +# STAR_CONFIDENCE: optional RELION column mapped onto RawPick.confidence +STAR_CONFIDENCE = 'rlnAutopickFigureOfMerit' + +# TOMOGRAM_ID_SUFFIX: segmentation filename suffix ignored when matching pick ids to manifests +TOMOGRAM_ID_SUFFIX = '_segmented' + +# read_picks: RawPicks from a CSV, STAR, JSON or JSONL picks file, tagged with source_picker +def read_picks(path: Path, *, source_picker: str) -> list[RawPick]: + reader = _READERS.get(path.suffix.lower()) + if reader is None: + raise StampValidationError(f'unsupported picks file {str(path)!r}, expected one of {sorted(_READERS)}') + picks = reader(path, source_picker) + if not picks: + raise StampValidationError(f'{str(path)!r} contains no picks') + return picks + +# map_tomogram_ids: rewrite pick ids onto manifest ids (ignoring trailings suffix on either side), raising on ids with no manifest +def map_tomogram_ids(picks: list[RawPick], manifests: list[TomogramManifest]) -> list[RawPick]: + by_key = {_id_key(manifest.tomogram_id): manifest.tomogram_id for manifest in manifests} + unknown = sorted({pick.tomogram_id for pick in picks if _id_key(pick.tomogram_id) not in by_key}) + if unknown: + raise StampValidationError(f'picks reference tomogram id(s) with no matching segmentation/tomogram pair: {unknown}; known ids: {sorted(by_key.values())}') + return [pick.model_copy(update={'tomogram_id': by_key[_id_key(pick.tomogram_id)]}) for pick in picks] + +# apply_prior: picks checked or reduced for the orientation prior; normal picks pass through (orientations are inferred from the segmentation next), axis picks must all carry an orientation, none picks lose theirs and the membrane fields so nothing downstream can use them +def apply_prior(picks: list[RawPick], prior: OrientationPrior) -> list[RawPick]: + if prior is OrientationPrior.NORMAL: + return picks + if prior is OrientationPrior.AXIS: + missing = [pick for pick in picks if pick.orientation is None] + if missing: + raise StampValidationError(f'orientation prior axis needs an orientation (filament axis as a quaternion) for every pick, {len(missing)} of {len(picks)} from {missing[0].source_picker!r} have none; supply qw,qx,qy,qz columns in CSV or an orientation in JSON') + return picks + return [pick.model_copy(update={'orientation': None, 'beam_angle_deviation_degrees': None, 'vesicle_id': None}) for pick in picks] + +# infer_orientations: fill missing orientation, beam angle and vesicle id from the nearest segmentation surface +def infer_orientations( + picks: list[RawPick], + manifests: list[TomogramManifest], + *, + vesicle_labels_by_tomogram: dict[str, Path] | None = None, + max_surface_distance_angstrom: float = 300.0, +) -> list[RawPick]: + labels_by_tomogram = vesicle_labels_by_tomogram or {} + manifest_by_id = {manifest.tomogram_id: manifest for manifest in manifests} + indices_by_tomogram: dict[str, list[int]] = {} + for index, pick in enumerate(picks): + indices_by_tomogram.setdefault(pick.tomogram_id, []).append(index) + result = list(picks) + # TODO: parallelise? + for tomogram_id, indices in indices_by_tomogram.items(): + manifest = manifest_by_id[tomogram_id] + labels_path = labels_by_tomogram.get(tomogram_id) + todo = [index for index in indices if _needs_inference(picks[index], labels_path is not None)] + if not todo: + continue + if manifest.segmentation_path is None: + log.warning(f'{tomogram_id}: no segmentation, cannot infer orientations') + continue + segmentation = read_mrc(manifest.segmentation_path) + try: + vertices_zyx, normals_zyx = extract_surface(segmentation) + except StampValidationError as exc: + log.warning(f'{tomogram_id}: cannot infer orientations ({exc})') + continue + positions_xyz = np.array([picks[index].position for index in todo]) + distances, nearest = cKDTree(vertices_zyx).query(positions_xyz[:, ::-1]) # surface is (z, y, x), picks are (x, y, z) + within = distances * manifest.voxel_size_angstrom <= max_surface_distance_angstrom + nearest_xyz = vertices_zyx[nearest][:, ::-1] + normals_xyz = normals_zyx[nearest][:, ::-1] + # the particle sits on the side it was picked from, so point the normal at the pick + flip = np.einsum('ij,ij->i', normals_xyz, positions_xyz - nearest_xyz) < 0 + normals_xyz = np.where(flip[:, None], -normals_xyz, normals_xyz) + vesicle_ids = vesicle_ids_at(load_vesicle_labels(labels_path, segmentation.shape), vertices_zyx[nearest], tomogram_id) if labels_path is not None else None + for position, index in enumerate(todo): + pick = picks[index] + updates: dict = {} + normal = None if pick.orientation is None else _normal_from_quaternion(pick.orientation) # a supplied quaternion always wins + if pick.orientation is None and within[position]: + normal = normals_xyz[position] + updates['orientation'] = quaternion_from_reference_to(normal) + if pick.beam_angle_deviation_degrees is None and normal is not None: + updates['beam_angle_deviation_degrees'] = beam_angle_deviation_degrees(normal) + if vesicle_ids is not None and pick.vesicle_id is None and within[position] and vesicle_ids[position]: + updates['vesicle_id'] = vesicle_ids[position] + result[index] = pick.model_copy(update=updates) + n_missing = sum(pick.orientation is None for pick in result) + if n_missing: + log.warning(f'{n_missing} of {len(result)} picks have no orientation (further than {max_surface_distance_angstrom} Å from any surface, or no usable segmentation); classify will skip them') + return result + +# _needs_inference: True when a pick lacks something infer_orientations can fill +def _needs_inference(pick: RawPick, want_vesicle_id: bool) -> bool: + return pick.orientation is None or pick.beam_angle_deviation_degrees is None or (want_vesicle_id and pick.vesicle_id is None) + +# _normal_from_quaternion: the image of +z under a (w, x, y, z) unit quaternion +def _normal_from_quaternion(quaternion: tuple[float, float, float, float]) -> np.ndarray: + w, x, y, z = quaternion + return np.array([2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x * x + y * y)]) + +# _id_key: comparison key for a tomogram id +def _id_key(tomogram_id: str) -> str: + return tomogram_id.removesuffix(TOMOGRAM_ID_SUFFIX) + +# _cell: stripped string value of a CSV cell, '' when absent +def _cell(row: dict, key: str) -> str: + return (row.get(key) or '').strip() + +# _read_csv: picks from a CSV with tomogram_id,x,y,z[,confidence][,qw,qx,qy,qz] +def _read_csv(path: Path, source_picker: str) -> list[RawPick]: + with path.open(newline='') as handle: + reader = csv.DictReader(handle) + header = reader.fieldnames or [] + rows = list(reader) + missing = [column for column in CSV_REQUIRED if column not in header] + if missing: + raise StampValidationError(f'{str(path)!r} is missing required column(s) {missing}') + has_quaternion = [column for column in CSV_QUATERNION if column in header] + if has_quaternion and len(has_quaternion) != len(CSV_QUATERNION): + raise StampValidationError(f'{str(path)!r} must carry all of {list(CSV_QUATERNION)} or none of them') + + picks: list[RawPick] = [] + for line, row in enumerate(rows, start=2): # line 1 is the header + quaternion = [_cell(row, column) for column in CSV_QUATERNION] if has_quaternion else [] + try: + picks.append(RawPick( + tomogram_id=_cell(row, 'tomogram_id'), + position=(float(row['x']), float(row['y']), float(row['z'])), + orientation=tuple(float(value) for value in quaternion) if quaternion and all(quaternion) else None, + confidence=float(_cell(row, 'confidence')) if _cell(row, 'confidence') else None, + source_picker=source_picker, + )) + except (ValueError, TypeError, StampError) as exc: # pydantic's ValidationError is a ValueError; the quaternion validator raises StampPipelineError + raise StampValidationError(f'{str(path)!r} line {line}: {exc}') from exc + return picks + +# _read_star: picks from a RELION STAR file (pixel coordinates not RELION 5 centred-Angstrom columns) +def _read_star(path: Path, source_picker: str) -> list[RawPick]: + data = starfile.read(path) + blocks = data if isinstance(data, dict) else {'': data} + table = next((block for block in blocks.values() if hasattr(block, 'columns') and 'rlnCoordinateX' in block.columns), None) + if table is None: + raise StampValidationError(f'{str(path)!r} has no STAR block with rlnCoordinateX (RELION 5 centred-Angstrom columns are not yet supported)') + missing = [column for column in STAR_COLUMNS if column not in table.columns] + if missing: + raise StampValidationError(f'{str(path)!r} is missing required column(s) {missing}') + + confidence = table[STAR_CONFIDENCE].tolist() if STAR_CONFIDENCE in table.columns else [None] * len(table) + try: + return [ + RawPick( + tomogram_id=str(name), + position=(float(x), float(y), float(z)), + confidence=None if score is None else float(score), + source_picker=source_picker, + ) + for name, x, y, z, score in zip(table['rlnTomoName'], table['rlnCoordinateX'], table['rlnCoordinateY'], table['rlnCoordinateZ'], confidence) + ] + except (ValueError, TypeError, StampError) as exc: + raise StampValidationError(f'{str(path)!r}: {exc}') from exc + +# _read_json: picks from a JSON list or JSONL file of RawPick records; source_picker is overwritten +def _read_json(path: Path, source_picker: str) -> list[RawPick]: + text = path.read_text() + try: + records = [json.loads(line) for line in text.splitlines() if line.strip()] if path.suffix.lower() == '.jsonl' else json.loads(text) + return [RawPick.model_validate({**record, 'source_picker': source_picker}) for record in records] + except (ValueError, TypeError, StampError) as exc: + raise StampValidationError(f'{str(path)!r}: {exc}') from exc + +# _READERS: picks file reader per lowercase suffix +_READERS = { + '.csv': _read_csv, + '.star': _read_star, + '.json': _read_json, + '.jsonl': _read_json, +} diff --git a/src/stamp/picking/native.py b/src/stamp/picking/native.py deleted file mode 100644 index ab01e17..0000000 --- a/src/stamp/picking/native.py +++ /dev/null @@ -1,204 +0,0 @@ -''' -STAMP: native membrane-guided, template-free picker -''' - -# Import external dependencies -import numpy as np -from dataclasses import dataclass -from pathlib import Path -from typing import Literal - -# Import internal STAMP objects -from stamp.picking.geometry import ( - beam_angle_deviation_degrees, - downsample_points, - exclude_near_boundary, - extract_surface, - max_order_statistic_offset, - non_maximum_suppression, - quaternion_from_reference_to, - robust_normalise, - sample_along_normals, - score_membrane_faces -) -from stamp.picking.vesicles import load_vesicle_labels, vesicle_ids_at -from stamp.schemas.picks import RawPick -from stamp.utils.errors import StampPipelineError, StampValidationError -from stamp.utils.io import read_mrc -from stamp.utils.log import log - -# PICKER_NAME: name for picker tool -PICKER_NAME = 'stamp-native' - -# DEFAULT_OFFSET_WINDOWS_ANGSTROM: (min, max) radial windows -DEFAULT_OFFSET_WINDOWS_ANGSTROM: tuple[tuple[float, float], ...] = ( - (20.0, 50.0), - (40.0, 80.0), - (70.0, 110.0), - (100.0, 160.0), -) - -# NativePickerConfig: parameters for one stamp-native run (all distances in Angstrom) -@dataclass(frozen=True) -class NativePickerConfig: - voxel_size_angstrom: float - # radial windows from membrane surface to search - offset_windows_angstrom: tuple[tuple[float, float], ...] = DEFAULT_OFFSET_WINDOWS_ANGSTROM - # sample per surface point within each radial window - n_samples: int = 5 - # sampling point spacing - surface_spacing_angstrom: float = 20.0 - # minimum particle separation - min_particle_distance_angstrom: float = 60.0 - # score threshold before multi-window order-statistic correction - n_mad: float = 3.0 - # protein/background density - density_sign: int = -1 - # boundary for dropping surface points; defaults to the largest window's outer edge - boundary_margin_angstrom: float | None = None - # score normalisation to use - normalisation: Literal['global', 'local'] = 'global' - # neighbourhood radius for local normalisation - local_radius_angstrom: float = 150.0 - # minimum neighbours within local_radius_angstrom before falling back to global - min_local_neighbours: int = 20 - # scoring mode to use for particle radial density - scoring_mode: Literal['mean', 'profile'] = 'mean' - # width (Angstrom) of the expected profile bump - profile_width_angstrom: float | None = None - # path to EValuator labelled MRC - vesicle_labels_mrc: Path | None = None - # normalise scores per vesicle instead of per tomogram/local neighbourhood - normalise_per_vesicle: bool = False - - def __post_init__(self) -> None: - if self.voxel_size_angstrom <= 0: - raise StampPipelineError('voxel_size_angstrom must be positive.') - if self.density_sign not in (1, -1): - raise StampPipelineError('density_sign must be +1 or -1.') - if len(self.offset_windows_angstrom) == 0: - raise StampPipelineError('offset_windows_angstrom must contain at least one window.') - for offset_min, offset_max in self.offset_windows_angstrom: - if offset_max < offset_min: - raise StampPipelineError('each offset window must have offset_max >= offset_min.') - if self.local_radius_angstrom <= 0: - raise StampPipelineError('local_radius_angstrom must be positive.') - if self.min_local_neighbours < 1: - raise StampPipelineError('min_local_neighbours must be at least 1.') - if self.scoring_mode not in ('mean', 'profile'): - raise StampPipelineError('scoring_mode must be "mean" or "profile".') - if self.profile_width_angstrom is not None and self.profile_width_angstrom <= 0: - raise StampPipelineError('profile_width_angstrom must be positive.') - if self.normalise_per_vesicle and self.vesicle_labels_mrc is None: - raise StampPipelineError('normalise_per_vesicle requires vesicle_labels_mrc.') - - def to_voxels(self, angstrom: float) -> float: - return angstrom / self.voxel_size_angstrom - - # effective_n_mad: n_mad corrected for taking the best of len(offset_windows_angstrom) scores - @property - def effective_n_mad(self) -> float: - return self.n_mad + max_order_statistic_offset(len(self.offset_windows_angstrom)) - - # max_offset_angstrom: outer edge of the widest window, used as the default boundary margin - @property - def max_offset_angstrom(self) -> float: - return max(offset_max for _offset_min, offset_max in self.offset_windows_angstrom) - -# pick_tomogram: run the native picker over one tomogram, returning RawPicks -def pick_tomogram( - segmentation_path, - tomogram_path, - tomogram_id: str, - config: NativePickerConfig, -) -> list[RawPick]: - segmentation = read_mrc(segmentation_path) - tomogram = read_mrc(tomogram_path) - - if segmentation.shape != tomogram.shape: - raise StampValidationError(f'Segmentation shape {segmentation.shape} does not match tomogram shape {tomogram.shape} for {tomogram_id}; they must be the same volume at the same binning') - - # Blank membrane signal so offset shell only scores densities off membrane surface - tomogram = tomogram.astype(np.float32).copy() - tomogram[segmentation > 0] = np.median(tomogram[segmentation <= 0]) - - vertices, normals = extract_surface(segmentation) - vertices, normals = downsample_points(vertices, normals, config.to_voxels(config.surface_spacing_angstrom)) - - margin_angstrom = config.boundary_margin_angstrom if config.boundary_margin_angstrom is not None else config.max_offset_angstrom - inside = exclude_near_boundary(vertices, segmentation.shape, config.to_voxels(margin_angstrom)) - vertices, normals = vertices[inside], normals[inside] - if vertices.shape[0] == 0: - log.warning(f'{tomogram_id}: no surface points survived boundary exclusion, skipping') - return [] - - if config.vesicle_labels_mrc is not None: - label_volume = load_vesicle_labels(config.vesicle_labels_mrc, segmentation.shape) - vesicle_of_vertex = vesicle_ids_at(label_volume, vertices, tomogram_id) - else: - vesicle_of_vertex = [''] * vertices.shape[0] - # score_membrane_faces doubles each vertex's row (both faces); double vesicle_of_vertex to match - vesicle_of_point = vesicle_of_vertex + vesicle_of_vertex - - offset_windows_voxels = [(config.to_voxels(offset_min), config.to_voxels(offset_max)) for offset_min, offset_max in config.offset_windows_angstrom] - - normalisation_mode = 'vesicle' if config.normalise_per_vesicle else config.normalisation - profile_width_voxels = (config.to_voxels(config.profile_width_angstrom) if config.profile_width_angstrom is not None else None) - points, outward_normals, scores, winning_window, used_fallback, mean_scores, profile_scores = score_membrane_faces( - tomogram, vertices, normals, - offset_windows_voxels, - config.n_samples, config.density_sign, - scoring_mode=config.scoring_mode, - profile_width_voxels=profile_width_voxels, - mode=normalisation_mode, - local_radius_voxels=config.to_voxels(config.local_radius_angstrom), - min_local_neighbours=config.min_local_neighbours, - vesicle_ids=vesicle_of_point if config.normalise_per_vesicle else None, - ) - above_threshold = scores >= config.effective_n_mad - n_candidates = points.shape[0] - points, outward_normals, scores, winning_window, used_fallback, mean_scores, profile_scores, vesicle_of_point = ( - points[above_threshold], - outward_normals[above_threshold], - scores[above_threshold], - winning_window[above_threshold], - used_fallback[above_threshold], - mean_scores[above_threshold], - profile_scores[above_threshold], - [v for v, keep in zip(vesicle_of_point, above_threshold) if keep], - ) - log.debug(f'{tomogram_id}: {n_candidates} candidates before filtering, {points.shape[0]} kept') - if points.shape[0] == 0: - log.warning(f'{tomogram_id}: no candidates survived score threshold {config.effective_n_mad:.2f}, skipping') - return [] - if config.normalisation == 'local' and used_fallback.any(): - log.debug(f'{tomogram_id}: {int(used_fallback.sum())}/{points.shape[0]} kept points used global fallback (too few neighbours within local_radius_angstrom)') - - kept = non_maximum_suppression(points, scores, config.to_voxels(config.min_particle_distance_angstrom)) - - picks: list[RawPick] = [] - for index in kept: - # convert internal (z, y, x) -> output (x, y, z) - position_zyx = points[index] - normal_zyx = outward_normals[index] - position_xyz = ( - float(position_zyx[2]), float(position_zyx[1]), float(position_zyx[0]) - ) - normal_xyz = np.array([normal_zyx[2], normal_zyx[1], normal_zyx[0]]) - - picks.append( - RawPick( - tomogram_id=tomogram_id, - position=position_xyz, - orientation=quaternion_from_reference_to(normal_xyz), - confidence=float(scores[index]), - source_picker=PICKER_NAME, - metadata={'used_global_fallback': bool(used_fallback[index])} if config.normalisation == 'local' else {}, - beam_angle_deviation_degrees=beam_angle_deviation_degrees(normal_xyz), - offset_window_angstrom=config.offset_windows_angstrom[int(winning_window[index])], - mean_score=float(mean_scores[index]), - profile_score=float(profile_scores[index]), - vesicle_id=vesicle_of_point[index] or None, - ) - ) - return picks diff --git a/src/stamp/refine/fsc.py b/src/stamp/refine/fsc.py index 782d6bd..9879845 100644 --- a/src/stamp/refine/fsc.py +++ b/src/stamp/refine/fsc.py @@ -10,6 +10,7 @@ # Import internal STAMP objects from stamp.utils.errors import StampValidationError from stamp.utils.log import log +from stamp.utils.phase import phase_randomise # FSCResult: both curves plus the resolution read at the threshold @dataclass @@ -55,16 +56,6 @@ def _shell_fsc(map_a: np.ndarray, map_b: np.ndarray, shell: np.ndarray, n_shells correlation[index] = np.real(cross / power) if power > 0 else 0.0 return correlation -# _phase_randomise: keep shell amplitudes, randomise phases at or beyond from_shell -def _phase_randomise( - map_array: np.ndarray, shell: np.ndarray, from_shell: int, rng: np.random.Generator -) -> np.ndarray: - transform = np.fft.fftn(map_array) - beyond = shell >= from_shell - phases = rng.uniform(0.0, 2.0 * np.pi, size=transform.shape) - transform[beyond] = np.abs(transform[beyond]) * np.exp(1j * phases[beyond]) - return np.real(np.fft.ifftn(transform)) - # _first_below: index of the first shell whose value drops under level, or None def _first_below(curve: np.ndarray, level: float) -> int | None: hits = np.argwhere(curve < level).ravel() @@ -100,8 +91,8 @@ def compute_fsc( randomise_from = _first_below(unmasked, 0.8) if randomise_from is not None and randomise_from + 1 < n_shells: rng = np.random.default_rng(seed) - rand_a = _phase_randomise(half_map_a, shell, randomise_from, rng) * mask - rand_b = _phase_randomise(half_map_b, shell, randomise_from, rng) * mask + rand_a = phase_randomise(half_map_a, rng, keep=shell < randomise_from) * mask + rand_b = phase_randomise(half_map_b, rng, keep=shell < randomise_from) * mask fsc_rand = _shell_fsc(rand_a, rand_b, shell, n_shells) high = np.arange(n_shells) > randomise_from denom = np.clip(1.0 - fsc_rand, 1e-3, None) diff --git a/src/stamp/run/cluster_orchestrate.py b/src/stamp/run/cluster_orchestrate.py index f379b34..3e485ea 100644 --- a/src/stamp/run/cluster_orchestrate.py +++ b/src/stamp/run/cluster_orchestrate.py @@ -27,16 +27,11 @@ class ClusterJob: depends_on: list[str] = field(default_factory=list) requires_gpu: bool = False -# _pick_needs_gpu: True if any configured picker adapter wants a GPU -def _pick_needs_gpu(config) -> bool: - from stamp.commands.pick import REAL_ADAPTERS - return any(getattr(REAL_ADAPTERS.get(name), 'requires_gpu', False) for name in config.stage.pick.pickers) - # plan_pipeline_jobs: planned pipeline, skipping stages stages_to_run() excludes def plan_pipeline_jobs(config, output_dir: Path, planned_stages: list[str]) -> list[ClusterJob]: jobs = [] if 'pick' in planned_stages: - jobs.append(ClusterJob('real.pick', 'real', 'pick', build_pick_commands(config, output_dir), requires_gpu=_pick_needs_gpu(config))) + jobs.append(ClusterJob('real.pick', 'real', 'pick', build_pick_commands(config, output_dir))) if config.decoy.enabled: jobs.append(ClusterJob('decoy.pick', 'decoy', 'pick', build_decoy_commands(config, output_dir))) if 'classify' in planned_stages: diff --git a/src/stamp/run/orchestrate.py b/src/stamp/run/orchestrate.py index 8bf3451..7e40c41 100644 --- a/src/stamp/run/orchestrate.py +++ b/src/stamp/run/orchestrate.py @@ -12,7 +12,7 @@ from stamp.commands.classify import run_classify from stamp.commands.decoy import run_decoy from stamp.commands.identify import run_identify -from stamp.commands.pick import REAL_ADAPTERS, run_pick +from stamp.commands.pick import run_pick from stamp.commands.refine import _ADAPTERS as REFINE_ADAPTERS, run_refine from stamp.run.state import STAGE_ORDER, is_complete, mark_complete, stage_dir, stages_to_run from stamp.schemas.config import RunConfig @@ -34,17 +34,19 @@ class RunOutcome: def _real_pick(config: RunConfig, output_dir: Path) -> Path: target = stage_dir(output_dir, 'real', 'pick') run_pick( - picker_names=config.stage.pick.pickers, + picks_files=config.stage.pick.picks_files, + picker_names=config.stage.pick.picker_names, segmentation_dir=config.run.segmentation_dir, raw_tomogram_dir=config.run.raw_tomogram_dir, output_dir=target, voxel_size_angstrom=config.run.voxel_size_angstrom, - extra_params={}, consensus_rule=config.stage.pick.consensus_rule, distance_threshold=config.stage.pick.distance_threshold, half_set_seed=config.stage.pick.half_set_seed, - backend=config.stage.pick.backend, + max_surface_distance_angstrom=config.stage.pick.max_surface_distance_angstrom, n_workers=config.stage.pick.n_workers, + keep_raw=config.stage.pick.keep_raw, + orientation_prior=config.run.orientation_prior, ) return target / 'particle_set.json' @@ -68,7 +70,6 @@ def _decoy_pick(config: RunConfig, output_dir: Path, real_particle_set: Path) -> run_decoy( output_dir=target, method=config.decoy.method, - parameters={}, real_particle_set=real_particle_set, segmentation_dir=config.run.segmentation_dir, raw_tomogram_dir=config.run.raw_tomogram_dir, @@ -78,6 +79,7 @@ def _decoy_pick(config: RunConfig, output_dir: Path, real_particle_set: Path) -> min_distance_from_picks_angstrom=config.decoy.min_distance_from_picks_angstrom, min_shift_angstrom=config.decoy.min_shift_angstrom, max_shift_angstrom=config.decoy.max_shift_angstrom, + min_border_angstrom=config.decoy.min_border_angstrom, n_synthetic_tomograms=config.decoy.n_synthetic_tomograms, synthetic_shape=','.join(str(dimension) for dimension in shape), seed=config.stage.pick.half_set_seed, @@ -103,20 +105,22 @@ def _classify_track(config: RunConfig, output_dir: Path, track: str, particles: n_components=settings.n_components, strict_halfset_independence=settings.strict_halfset_independence, random_state=settings.random_state, - inplane_alignment=settings.inplane_alignment, inplane_angular_step_degrees=settings.inplane_angular_step_degrees, - inplane_iterations=settings.inplane_iterations, n_workers=settings.n_workers, + tilt_max_degrees=config.run.tilt_max_degrees, + tilt_axis_degrees=config.run.tilt_axis_degrees, + bin_factor=settings.bin_factor, + n_rotations=settings.n_rotations, + shift_range_voxels=settings.shift_range_voxels, + polish_rounds=settings.polish_rounds, + null_sigmas=settings.null_sigmas, + reject_quantile=settings.reject_quantile, + merge_fraction=settings.merge_fraction, ) return target # _guard_backends: raise before any stage runs if a stage's backend can't run its adapter def _guard_backends(config: RunConfig) -> None: - for picker in config.stage.pick.pickers: - adapter = REAL_ADAPTERS.get(picker) - if adapter is not None: - log.debug(f'Checking backend {config.stage.pick.backend or config.run.backend!r} supports pick adapter {picker!r}') - check_backend_supports(adapter, config.stage.pick.backend or config.run.backend) refine_adapter = REFINE_ADAPTERS.get(config.stage.refine.tool) if refine_adapter is not None: log.debug(f'Checking backend {config.stage.refine.backend or config.run.backend!r} supports refine adapter {config.stage.refine.tool!r}') @@ -175,6 +179,10 @@ def run_pipeline( elif config.decoy.enabled: log.debug('Stage classify (decoy) already complete, skipping') + if stop_after == 'classify': + log.info(f'Stopping after stage {stop_after!r} as configured') + return _finalise(outcome, output_dir) + # --- identify --- identify_dir = stage_dir(output_dir, 'real', 'identify') real_classes = stage_dir(output_dir, 'real', 'classify') / 'class_averages' diff --git a/src/stamp/schemas/config.py b/src/stamp/schemas/config.py index bb7b597..b961e64 100644 --- a/src/stamp/schemas/config.py +++ b/src/stamp/schemas/config.py @@ -5,10 +5,11 @@ # Import external dependencies import tomllib from pathlib import Path -from pydantic import BaseModel, ConfigDict, model_validator +from pydantic import BaseModel, ConfigDict, Field, model_validator from typing import Literal # Import internal STAMP objects +from stamp.schemas.particles import OrientationPrior from stamp.utils.errors import StampPipelineError from stamp.utils.log import log, log_config @@ -25,12 +26,15 @@ def _blank_to_none(cls, data: object) -> object: # RunSettings: the [run] table class RunSettings(_Strict): - segmentation_dir: Path + segmentation_dir: Path | None = None # required for the normal orientation prior only raw_tomogram_dir: Path output_dir: Path voxel_size_angstrom: float | None = None backend: Literal['local', 'mock', 'cluster'] = 'local' stop_after: Literal['pick', 'classify', 'identify', 'refine'] | None = None + orientation_prior: OrientationPrior = OrientationPrior.NORMAL + tilt_max_degrees: float | None = Field(default=None, gt=0, lt=90) # None means no missing wedge is modelled + tilt_axis_degrees: float = 90.0 # angle of the tilt axis from the tomogram x axis in the xy plane, 90 is a tilt about y # PlotSettings: the [plots] table class PlotSettings(_Strict): @@ -43,12 +47,13 @@ class PlotSettings(_Strict): # DecoySettings: the [decoy] table class DecoySettings(_Strict): enabled: bool = True - method: Literal['rejected-surface', 'shifted', 'synthetic-noise'] = 'rejected-surface' - n_decoys_per_tomogram: int | None = None # None = adaptive (target same N as real picks) + method: Literal['shifted', 'synthetic-noise', 'random-volume'] = 'shifted' + n_decoys_per_tomogram: int | None = None # synthetic-noise only min_distance_from_real_angstrom: float = 100.0 min_distance_from_picks_angstrom: float = 60.0 min_shift_angstrom: float = 200.0 max_shift_angstrom: float = 600.0 + min_border_angstrom: float = 200.0 n_synthetic_tomograms: int = 3 synthetic_shape_voxels: tuple[int, int, int] | None = None # None = match the first real tomogram n_workers: int = 1 @@ -56,25 +61,32 @@ class DecoySettings(_Strict): # Per-stage tables mirror each command's options class PickStage(_Strict): - pickers: list[str] = ['stamp-native'] + picks_files: list[Path] + picker_names: list[str] | None = None # defaults to file stems consensus_rule: Literal['union', 'intersection'] = 'intersection' distance_threshold: float = 15.0 half_set_seed: int = 0 - backend: Literal['local', 'mock', 'cluster'] | None = None + max_surface_distance_angstrom: float = 300.0 + backend: Literal['local', 'mock', 'cluster'] | None = None # inert for pick, kept so run.backend inheritance is uniform n_workers: int = 1 keep_raw: bool = False class ClassifyStage(_Strict): - method: Literal['hdbscan', 'kmeans'] = 'hdbscan' + method: Literal['leiden', 'hdbscan', 'kmeans'] = 'leiden' min_cluster_size: int = 20 n_clusters: int = 5 n_components: int = 20 box_angstrom: float = 300.0 n_radial_bins: int = 12 strict_halfset_independence: bool = True - inplane_alignment: bool = True inplane_angular_step_degrees: float = 10.0 - inplane_iterations: int = 3 + bin_factor: int = Field(default=2, ge=1) + n_rotations: int = Field(default=3000, ge=2) + shift_range_voxels: int = Field(default=3, ge=0) + polish_rounds: int = Field(default=2, ge=1) + null_sigmas: float = Field(default=3.0, ge=0) + reject_quantile: float = Field(default=0.95, gt=0.5, lt=1.0) + merge_fraction: float = Field(default=1.0, ge=0) random_state: int = 0 n_workers: int = 1 keep_raw: bool = False @@ -97,7 +109,7 @@ class RefineStage(_Strict): # StageConfigs: the [stage.*] tables class StageConfigs(_Strict): - pick: PickStage = PickStage() + pick: PickStage classify: ClassifyStage = ClassifyStage() identify: IdentifyStage refine: RefineStage = RefineStage() @@ -111,6 +123,10 @@ class RunConfig(_Strict): @model_validator(mode='after') def _cross_field(self) -> 'RunConfig': + if self.run.orientation_prior is OrientationPrior.NORMAL and self.run.segmentation_dir is None: + raise StampPipelineError('[run].segmentation_dir is required for orientation_prior "normal", orientations are inferred from the membrane segmentation') + if self.run.orientation_prior is not OrientationPrior.NORMAL and self.decoy.enabled and self.decoy.method != 'random-volume': + raise StampPipelineError(f'[decoy].method "{self.decoy.method}" is membrane-based, use "random-volume" (or disable the decoy) for orientation_prior "{self.run.orientation_prior.value}"') stop = self.run.stop_after needs_identify = stop in (None, 'identify', 'refine') if needs_identify and not self.stage.identify.candidates: @@ -124,12 +140,14 @@ def load_run_config(path: Path) -> RunConfig: raw = tomllib.loads(path.read_text()) config = RunConfig.model_validate(raw) base = path.parent - config.run.segmentation_dir = (base / config.run.segmentation_dir).resolve() + if config.run.segmentation_dir is not None: + config.run.segmentation_dir = (base / config.run.segmentation_dir).resolve() config.run.raw_tomogram_dir = (base / config.run.raw_tomogram_dir).resolve() config.run.output_dir = (base / config.run.output_dir).resolve() config.stage.identify.candidates = (base / config.stage.identify.candidates).resolve() if config.stage.refine.mask is not None: config.stage.refine.mask = (base / config.stage.refine.mask).resolve() + config.stage.pick.picks_files = [(base / path).resolve() for path in config.stage.pick.picks_files] if config.stage.pick.backend is None: log.debug(f'stage.pick.backend not set, inheriting run.backend={config.run.backend!r}') config.stage.pick.backend = config.run.backend diff --git a/src/stamp/schemas/manifest.py b/src/stamp/schemas/manifest.py index a3c5d1c..3570ab9 100644 --- a/src/stamp/schemas/manifest.py +++ b/src/stamp/schemas/manifest.py @@ -6,10 +6,10 @@ from pathlib import Path from pydantic import BaseModel -# TomogramManifest: class defining a single segmented tomogram used by STAMP +# TomogramManifest: class defining a single tomogram class TomogramManifest(BaseModel): tomogram_id: str - segmentation_path: Path + segmentation_path: Path | None = None # absent for priors that need no membrane segmentation raw_tomogram_path: Path voxel_size_angstrom: float is_decoy: bool = False diff --git a/src/stamp/schemas/particles.py b/src/stamp/schemas/particles.py index 9284b7c..248b138 100644 --- a/src/stamp/schemas/particles.py +++ b/src/stamp/schemas/particles.py @@ -16,6 +16,12 @@ class HalfSet(str, Enum): A = 'A' B = 'B' +# OrientationPrior: what the picker knows about particle orientation, which fixes the alignment search space +class OrientationPrior(str, Enum): + NORMAL = 'normal' # +z is the membrane normal, only the azimuth about z is unknown + AXIS = 'axis' # +z is the filament axis, azimuth, polarity and the shift along z are unknown + NONE = 'none' # no orientation known, full rotation and shift are unknown + # Particle: class for a single consensus particle, located within one tomogram class Particle(BaseModel): particle_id: str @@ -41,6 +47,7 @@ class ParticleSet(BaseModel): particles: list[Particle] consensus_rule: Literal['intersection', 'union'] contributing_pickers: list[str] + orientation_prior: OrientationPrior = OrientationPrior.NORMAL # files written before priors existed are membrane sets @field_validator('particles') @classmethod @@ -56,6 +63,18 @@ class ClassAssignment(BaseModel): classifier: str inplane_angle_degrees: float | None = None vesicle_id: str | None = None # denormalised from Particle so class_assignments.json doesn't need to rejoin particle_set.json + rotation: tuple[float, float, float, float] | None = Field(default=None, description='Unit quaternion (w, x, y, z) of the full pose against the class average: the average moved by it, then shifted, gives the particle') + shift_voxels: tuple[float, float, float] | None = Field(default=None, description='Shift (x, y, z) in subvolume voxels applied after the rotation') + cc: float | None = Field(default=None, description='Normalised correlation with the assigned class average over the particle\'s observed Fourier components') + margin: float | None = Field(default=None, description='Best minus second-best class correlation, a confidence in the assignment') + polarity: Literal[1, -1] | None = Field(default=None, description='-1 when the filament was flipped end to end to match the class average, axis prior only') + + @field_validator('rotation') + @classmethod + def _rotation_is_unit_length(cls, value: tuple[float, float, float, float] | None) -> tuple[float, float, float, float] | None: + if value is not None: + assert_unit_quaternion(value) + return value # IdentificationResult: candidate protein assignment for a cluster class IdentificationResult(BaseModel): diff --git a/src/stamp/schemas/subvolumes.py b/src/stamp/schemas/subvolumes.py index ddfd68a..9f750d0 100644 --- a/src/stamp/schemas/subvolumes.py +++ b/src/stamp/schemas/subvolumes.py @@ -56,14 +56,15 @@ def iter_batches(self, batch_size: int = 512) -> Iterator[tuple[list[int], np.nd yield chunk, np.asarray(mmap[rows]) # write_rolled: persist (global_index, subvolume) pairs to a new per-tomogram cache via preallocated memmaps, return the resulting store - def write_rolled(self, rolled: Iterator[tuple[int, np.ndarray]], new_cache_dir: Path) -> 'Subvolumes': + def write_rolled(self, rolled: Iterator[tuple[int, np.ndarray]], new_cache_dir: Path, *, box_voxels: int | None = None) -> 'Subvolumes': new_cache_dir.mkdir(parents=True, exist_ok=True) row_counts: dict[str, int] = {} new_index: list[tuple[str, int]] = [] for tomogram_id, _row in self.index: new_index.append((tomogram_id, row_counts.get(tomogram_id, 0))) row_counts[tomogram_id] = row_counts.get(tomogram_id, 0) + 1 - shape = (self.box_voxels,) * 3 + new_box_voxels = box_voxels or self.box_voxels + shape = (new_box_voxels,) * 3 outputs: dict[str, np.ndarray] = {} written = 0 for global_index, subvolume in rolled: @@ -77,4 +78,4 @@ def write_rolled(self, rolled: Iterator[tuple[int, np.ndarray]], new_cache_dir: for output in outputs.values(): output.flush() assert written == len(self.index) # every particle must be rolled exactly once - return Subvolumes(new_cache_dir, new_index, self.box_voxels) + return Subvolumes(new_cache_dir, new_index, new_box_voxels) diff --git a/src/stamp/tools/diagram/diagram.py b/src/stamp/tools/diagram/diagram.py index e9b03c1..53a694a 100644 --- a/src/stamp/tools/diagram/diagram.py +++ b/src/stamp/tools/diagram/diagram.py @@ -10,7 +10,6 @@ # Import diagram stage renderers from stamp.tools.diagram import classify as classify_diagram from stamp.tools.diagram import identify as identify_diagram -from stamp.tools.diagram import native as native_diagram from stamp.tools.diagram import overview as overview_diagram from stamp.tools.diagram import pick as pick_diagram from stamp.tools.diagram.utils.config import DiagramConfig @@ -156,70 +155,6 @@ def pick_subcommand( seed=seed, ) -# Define native diagram command -@diagramCli.command('native', rich_help_panel='Command Diagrams') -def native_subcommand( - target: TargetArg, - distractor: DistractorArg, - output_dir: OutDirOpt = Path('out/diagrams/native'), - also: AlsoOpt = None, - n_synthetic_unknowns: UnknownsOpt = 2, - box_size: BoxOpt = 64, - pixel_size: PixelOpt = 3.0, - field_px: FieldPxOpt = 760, - n_vesicles: NVesiclesOpt = 10, - offset_min_a: Annotated[ - float, - typer.Option('--offset-min-a', help='Shell inner offset from the membrane, in Å.'), - ] = 20.0, - offset_max_a: Annotated[ - float, - typer.Option('--offset-max-a', help='Shell outer offset from the membrane, in Å.'), - ] = 80.0, - n_samples: Annotated[ - int, - typer.Option('--n-samples', help='Samples along each normal.'), - ] = 5, - surface_spacing_a: Annotated[ - float, - typer.Option('--surface-spacing-a', help='Surface point spacing, in Å.'), - ] = 20.0, - min_particle_distance_a: Annotated[ - float, - typer.Option('--min-particle-distance-a', help='NMS minimum separation, in Å.'), - ] = 60.0, - n_mad: Annotated[ - float, - typer.Option('--n-mad', help='Robust-score threshold, in MAD units.'), - ] = 3.0, - density_sign: Annotated[ - int, - typer.Option('--density-sign', help='+1: protein brighter than background (this mock); -1: protein darker (real cryo-ET).'), - ] = 1, - seed: SeedOpt = 0, -) -> None: - '''Generate a diagram of the template-free native picker workflow.''' - _run( - native_diagram.render, - target, - distractor, - also, - output_dir, - n_synthetic_unknowns=n_synthetic_unknowns, - box_size=box_size, - pixel_size=pixel_size, - field_px=field_px, - n_vesicles=n_vesicles, - offset_min_a=offset_min_a, - offset_max_a=offset_max_a, - n_samples=n_samples, - surface_spacing_a=surface_spacing_a, - min_particle_distance_a=min_particle_distance_a, - n_mad=n_mad, - density_sign=density_sign, - seed=seed, - ) - # Define classify diagram command @diagramCli.command('classify', rich_help_panel='Command Diagrams') def classify_subcommand( diff --git a/src/stamp/tools/diagram/native.py b/src/stamp/tools/diagram/native.py deleted file mode 100644 index c373e95..0000000 --- a/src/stamp/tools/diagram/native.py +++ /dev/null @@ -1,189 +0,0 @@ -''' -STAMP: detailed native picker workflow diagram -''' - -# Import external dependencies -import numpy as np, matplotlib.pyplot as plt -from pathlib import Path - -# Import internal STAMP objects -from stamp.tools.diagram.utils.config import DiagramConfig, NativePickerConfig -from stamp.tools.diagram.utils.render import DiagramRun, render_diagram -from stamp.tools.diagram.utils.native import run_native_picker -from stamp.tools.diagram.utils.plotting import draw_vesicles -from stamp.utils.plotting.core import BLUE, GREEN, GREY, ORANGE, RED, bare, finish, frame, show_segmentation - -# NativeRun: run the native picker on the mock scene and score its picks against the ground truth -class NativeRun(DiagramRun): - def build(self): - self.w.build_scene() - self.diagram_config = self.config - self.config = NativePickerConfig.from_diagram_config(self.diagram_config) - self.r = run_native_picker(self.w.raw_tomogram, self.w.segmentation, self.w.vesicles, self.config) - self.field_px = self.w.field_px - self.true_xy = self.w.true_xy - # precision / recall of the native picks against the ground truth - capture = 0.5 * self.w.box - picks = self.r['picks'] - if len(picks) and len(self.true_xy): - dist = np.linalg.norm(picks[:, None, :] - self.true_xy[None, :, :], axis=2) - self.tp = int((dist.min(axis=1) < capture).sum()) - self.recall = (dist.min(axis=0) < capture).sum() / len(self.true_xy) - else: - self.tp, self.recall = 0, 0.0 - self.precision = self.tp / max(len(picks), 1) - - -# --- panels --- -# plot_inputs: raw tomogram next to the membrane segmentation -def plot_inputs(run, axes): - ax_raw, ax_seg = axes - ax_raw.imshow(run.w.raw_tomogram, cmap=GREY) - frame(ax_raw, run.field_px, 'input: raw tomogram') - show_segmentation(ax_seg, run.w.segmentation, run.field_px) - frame(ax_seg, run.field_px, 'input: membrane segmentation') - -# plot_blank: tomogram with the membrane blanked to the background median -def plot_blank(run, ax): - ax.imshow(run.r['blanked'], cmap=GREY) - frame(ax, run.field_px, 'membrane blanked to background median\n(shell then scores only off-membrane density)') - -# plot_surface: the extracted + downsampled surface points with outward normals -def plot_surface(run, ax): - ax.imshow(run.r['blanked'], cmap=GREY, alpha=0.5) - v = run.r['vertices'] - n = run.r['normals'] - ax.scatter(v[:, 0], v[:, 1], s=6, c=BLUE) - step = max(1, len(v) // 220) - ax.quiver(v[::step, 0], v[::step, 1], n[::step, 0], -n[::step, 1], color=ORANGE, scale=30, width=0.003, headwidth=4) - frame(ax, run.field_px, f'surface extracted + downsampled ({len(v)} points, {run.config.surface_spacing_angstrom:g} Å spacing)') - -# plot_sampling: zoom on one vesicle, showing the density shell sampled along each normal -def plot_sampling(run, ax): - v = run.w.vesicles[0] - pad = v['r'] + run.r['off_max_px'] + 12 - ax.imshow(run.r['blanked'], cmap=GREY) - ax.add_patch(plt.Circle((v['cx'], v['cy']), v['r'], fill=False, edgecolor=GREEN, lw=1.2)) - for scale, style in ((run.r['off_min_px'], ':'), (run.r['off_max_px'], '--')): - for sign in (1, -1): - ax.add_patch(plt.Circle((v['cx'], v['cy']), v['r'] + sign * scale, fill=False, edgecolor=ORANGE, lw=0.8, ls=style)) - offsets = np.linspace(run.r['off_min_px'], run.r['off_max_px'], run.config.n_samples) - for theta in np.linspace(0, 2 * np.pi, 14, endpoint=False): - d = np.array([np.cos(theta), np.sin(theta)]) - base = np.array([v['cx'], v['cy']]) + v['r'] * d - for sign in (1, -1): - pts = base[None, :] + sign * offsets[:, None] * d[None, :] - ax.scatter(pts[:, 0], pts[:, 1], s=10, c=BLUE if sign == 1 else RED) - ax.set_xlim(v['cx'] - pad, v['cx'] + pad) - ax.set_ylim(v['cy'] + pad, v['cy'] - pad) - ax.set_aspect('equal') - ax.set_title(f'sample density shell along the normal, both faces\n' - f'offsets {run.config.offset_min_angstrom:g}-' - f'{run.config.offset_max_angstrom:g} A, ' - f'{run.config.n_samples} samples', fontsize=9) - bare(ax) - - -# plot_score_faces: robust score per surface point for the inner and outer faces -def plot_score_faces(run, fig, cell): - inner = cell.subgridspec(1, 2, wspace=0.15) - limit = max(3.0, np.abs(run.r['all_scores']).max()) - for i, face in enumerate(run.r['faces']): - ax = fig.add_subplot(inner[i]) - sc = ax.scatter(face['points'][:, 0], face['points'][:, 1], c=face['scores'], cmap='coolwarm', s=10, vmin=-limit, vmax=limit) - draw_vesicles(ax, run.w.vesicles, colour='k', lw=0.5) - frame(ax, run.field_px, f'{"outer" if face["direction"] == 1 else "inner"} face score') - if i == 1: - cbar = sc.figure.colorbar(sc, ax=ax, fraction=0.046, pad=0.06) - cbar.ax.tick_params(labelsize=6) - cbar.set_label('robust score (MAD)', fontsize=6) - -# plot_histogram: robust score distribution over both faces with the n_mad threshold -def plot_histogram(run, ax): - ax.hist(run.r['all_scores'], bins=40, color='#b0b0b0') - ax.axvline(run.config.n_mad, color=RED, ls='--', lw=1.0, label=f'threshold n_mad = {run.config.n_mad:g}') - ax.set_title('robust score distribution (both faces)', fontsize=9) - ax.set_xlabel('score (MAD units)', fontsize=8) - ax.set_ylabel('surface points', fontsize=8) - ax.legend(fontsize=6) - ax.tick_params(labelsize=6) - -# plot_threshold_nms: points above threshold and the subset kept after NMS -def plot_threshold_nms(run, ax): - above = run.r['all_points'][run.r['above_mask']] - ax.imshow(run.w.raw_tomogram, cmap=GREY, alpha=0.55) - if len(above): - ax.scatter(above[:, 0], above[:, 1], s=22, facecolors='none', edgecolors=ORANGE, linewidths=0.9, label=f'above threshold (n={len(above)})') - picks = run.r['picks'] - if len(picks): - ax.scatter(picks[:, 0], picks[:, 1], s=26, c=GREEN, label=f'kept after NMS (n={len(picks)})') - frame(ax, run.field_px, f'threshold then NMS (min separation {run.config.min_particle_distance_angstrom:g} Å)') - if len(above) or len(picks): - ax.legend(fontsize=6, loc='upper right', framealpha=0.4) - -# plot_final: final picks with orientation from the surface normal, plus precision / recall -def plot_final(run, ax): - ax.imshow(run.w.raw_tomogram, cmap=GREY) - picks = run.r['picks'] - n = run.r['pick_normals'] - if len(picks): - ax.quiver(picks[:, 0], picks[:, 1], n[:, 0], -n[:, 1], color=ORANGE, scale=22, width=0.004, headwidth=4) - ax.scatter(picks[:, 0], picks[:, 1], s=18, c=GREEN) - frame(ax, run.field_px, f'picks + orientation from normal (prec {run.precision:.2f}, recall {run.recall:.2f})') - -# --- drivers --- -# save_panels: write each stage panel as a numbered PNG -def save_panels(run, outdir): - fig, axes = plt.subplots(1, 2, figsize=(11, 5.5)) - plot_inputs(run, axes) - finish(fig, outdir / '01_inputs.png') - - fig, ax = plt.subplots(figsize=(5.5, 5.5)) - plot_blank(run, ax) - finish(fig, outdir / '02_blank_membrane.png') - - fig, ax = plt.subplots(figsize=(5.5, 5.5)) - plot_surface(run, ax) - finish(fig, outdir / '03_surface_normals.png') - - fig, ax = plt.subplots(figsize=(5.5, 5.5)) - plot_sampling(run, ax) - finish(fig, outdir / '04_normal_sampling.png') - - fig = plt.figure(figsize=(11, 5)) - plot_score_faces(run, fig, fig.add_gridspec(1, 1)[0, 0]) - finish(fig, outdir / '05_score_faces.png') - - fig, ax = plt.subplots(figsize=(6, 4)) - plot_histogram(run, ax) - finish(fig, outdir / '06_score_histogram.png') - - fig, ax = plt.subplots(figsize=(5.5, 5.5)) - plot_threshold_nms(run, ax) - finish(fig, outdir / '07_threshold_nms.png') - - fig, ax = plt.subplots(figsize=(5.5, 5.5)) - plot_final(run, ax) - finish(fig, outdir / '08_picks_orientation.png') - -# save_storyboard: lay every native-picker panel out on one storyboard figure -def save_storyboard(run, outdir): - fig = plt.figure(figsize=(23, 11)) - grid = fig.add_gridspec(2, 4, hspace=0.25, wspace=0.3) - - inner = grid[0, 0].subgridspec(2, 1, hspace=0.3) - plot_inputs(run, [fig.add_subplot(inner[0]), fig.add_subplot(inner[1])]) - plot_blank(run, fig.add_subplot(grid[0, 1])) - plot_surface(run, fig.add_subplot(grid[0, 2])) - plot_sampling(run, fig.add_subplot(grid[0, 3])) - - plot_score_faces(run, fig, grid[1, 0]) - plot_histogram(run, fig.add_subplot(grid[1, 1])) - plot_threshold_nms(run, fig.add_subplot(grid[1, 2])) - plot_final(run, fig.add_subplot(grid[1, 3])) - - finish(fig, outdir / '00_native_picker_storyboard.png') - -# render: run the mocked native picker and write its figures, returning the output directory -def render(config: DiagramConfig) -> Path: - return render_diagram(config, NativeRun, save_panels, save_storyboard) diff --git a/src/stamp/tools/diagram/pick.py b/src/stamp/tools/diagram/pick.py index 0bbc6db..339dc86 100644 --- a/src/stamp/tools/diagram/pick.py +++ b/src/stamp/tools/diagram/pick.py @@ -57,7 +57,7 @@ def plot_consensus(run, ax): frame(ax, w.field_px, 'reconcile: keep points both pickers agree on') ax.legend(fontsize=6, loc='upper right', framealpha=0.4) -# plot_halfsets: half-set split (whole vesicle to one half) with rejected-surface decoys +# plot_halfsets: half-set split (whole vesicle to one half) with decoys def plot_halfsets(run, ax): w = run.w draw_vesicles(ax, w.vesicles, colour='0.7', lw=0.6) @@ -66,7 +66,7 @@ def plot_halfsets(run, ax): if sel.any(): ax.scatter(w.consensus[sel, 0], w.consensus[sel, 1], s=24, c=colour, label=f'half {half + 1} (n={int(sel.sum())})') if len(w.decoy_points): - ax.scatter(w.decoy_points[:, 0], w.decoy_points[:, 1], s=30, c='0.5', marker='x', label=f'rejected-surface decoys (n={len(w.decoy_points)})') + ax.scatter(w.decoy_points[:, 0], w.decoy_points[:, 1], s=30, c='0.5', marker='x', label=f'decoys (n={len(w.decoy_points)})') frame(ax, w.field_px, 'half-set split (whole vesicle -> one half) + decoys') ax.legend(fontsize=6, loc='upper right', framealpha=0.4) diff --git a/src/stamp/tools/diagram/utils/config.py b/src/stamp/tools/diagram/utils/config.py index b1efc17..beed56f 100644 --- a/src/stamp/tools/diagram/utils/config.py +++ b/src/stamp/tools/diagram/utils/config.py @@ -35,42 +35,4 @@ class DiagramConfig: identify_min_gap: float = 0.06 decoy_margin: float = 0.05 n_decoy_trials: int = 40 - # native picker - offset_min_a: float = 20.0 - offset_max_a: float = 80.0 - n_samples: int = 5 - surface_spacing_a: float = 20.0 - min_particle_distance_a: float = 60.0 - n_mad: float = 3.0 - density_sign: int = 1 seed: int = 0 - -# NativePickerConfig: native-picker parameters for the mock, mirroring stamp.picking.native.NativePickerConfig -@dataclass(frozen=True) -class NativePickerConfig: - pixel_size_angstrom: float - offset_min_angstrom: float = 20.0 - offset_max_angstrom: float = 80.0 - n_samples: int = 5 - surface_spacing_angstrom: float = 20.0 - min_particle_distance_angstrom: float = 60.0 - n_mad: float = 3.0 - density_sign: int = 1 - - # to_voxels: convert a distance in Angstrom to voxels - def to_voxels(self, angstrom: float) -> float: - return angstrom / self.pixel_size_angstrom - - # from_diagram_config: pull the native-picker knobs out of a DiagramConfig - @classmethod - def from_diagram_config(cls, config: DiagramConfig) -> 'NativePickerConfig': - return cls( - pixel_size_angstrom=config.pixel_size, - offset_min_angstrom=config.offset_min_a, - offset_max_angstrom=config.offset_max_a, - n_samples=config.n_samples, - surface_spacing_angstrom=config.surface_spacing_a, - min_particle_distance_angstrom=config.min_particle_distance_a, - n_mad=config.n_mad, - density_sign=config.density_sign, - ) diff --git a/src/stamp/tools/diagram/utils/geometry.py b/src/stamp/tools/diagram/utils/geometry.py index 1e098a8..45f37bf 100644 --- a/src/stamp/tools/diagram/utils/geometry.py +++ b/src/stamp/tools/diagram/utils/geometry.py @@ -1,5 +1,5 @@ ''' -STAMP: small geometry helpers shared by the scene, pick and native stages +STAMP: small geometry helpers shared by the scene and pick stages ''' # Import external dependencies diff --git a/src/stamp/tools/diagram/utils/native.py b/src/stamp/tools/diagram/utils/native.py deleted file mode 100644 index 1857b3d..0000000 --- a/src/stamp/tools/diagram/utils/native.py +++ /dev/null @@ -1,108 +0,0 @@ -''' -STAMP: 2D mock of the stamp-native picker -''' - -# Import external dependencies -import numpy as np -from scipy.ndimage import map_coordinates - -# Import internal STAMP objects -from stamp.tools.diagram.utils.config import NativePickerConfig -from stamp.tools.diagram.utils.geometry import non_max_suppression - -# robust_normalise: median / MAD z-score, as stamp.picking.geometry.robust_normalise -def robust_normalise(values: np.ndarray) -> np.ndarray: - median = np.median(values) - mad = np.median(np.abs(values - median)) - if mad > 0.0: - return (values - median) / (1.4826 * mad) - std = values.std() - return np.zeros_like(values) if std == 0.0 else (values - median) / std - -# blank_membrane: set membrane voxels to the background median so the offset shell only scores density off the membrane surface -def blank_membrane(image: np.ndarray, segmentation: np.ndarray) -> np.ndarray: - out = image.astype(np.float32).copy() - background = image[segmentation == 0] - fill = float(np.median(background)) if background.size else 0.0 - out[segmentation == 1] = fill - return out - -# extract_surface_2d: points around each vesicle at ~spacing_px arc spacing with the outward unit normal; 2D analogue of marching_cubes + downsample -def extract_surface_2d(vesicles, spacing_px: float): - points, normals, owner = [], [], [] - for index, v in enumerate(vesicles): - step = max(spacing_px / v['r'], 1e-3) - for theta in np.arange(0.0, 2 * np.pi, step): - direction = np.array([np.cos(theta), np.sin(theta)]) - points.append([v['cx'] + v['r'] * direction[0], v['cy'] + v['r'] * direction[1]]) - normals.append(direction) - owner.append(index) - return np.array(points), np.array(normals), np.array(owner) - -# exclude_near_boundary_2d: mask of points at least margin_px from every edge of a shape -def exclude_near_boundary_2d(points, shape, margin_px): - lower = np.all(points >= margin_px, axis=1) - upper = np.all(points <= (np.array(shape)[::-1] - 1 - margin_px), axis=1) - return lower & upper - -# sample_along_normals_2d: mean bilinear-interpolated density in a shell stepped out from each point along direction * normal -def sample_along_normals_2d(image, points, normals, off_min, off_max, n_samples, direction): - offsets = np.linspace(off_min, off_max, n_samples) - sample_xy = (points[None, :, :] + direction * offsets[:, None, None] * normals[None, :, :]) - rows = sample_xy[..., 1].ravel() - cols = sample_xy[..., 0].ravel() - values = map_coordinates(image, np.vstack([rows, cols]), order=1, mode='nearest') - return values.reshape(n_samples, points.shape[0]).mean(axis=0) - -# run_native_picker: the whole native-picker pipeline, returning every intermediate so a diagram can show each step -def run_native_picker(image, segmentation, vesicles, config: NativePickerConfig): - blanked = blank_membrane(image, segmentation) - spacing = config.to_voxels(config.surface_spacing_angstrom) - vertices, normals, owner = extract_surface_2d(vesicles, spacing) - - margin = config.to_voxels(config.offset_max_angstrom) - inside = exclude_near_boundary_2d(vertices, image.shape, margin) - vertices, normals, owner = vertices[inside], normals[inside], owner[inside] - - off_min = config.to_voxels(config.offset_min_angstrom) - off_max = config.to_voxels(config.offset_max_angstrom) - - faces = [] - for direction in (1, -1): - densities = sample_along_normals_2d(blanked, vertices, normals, off_min, off_max, config.n_samples, direction) - scores = robust_normalise(config.density_sign * densities) - faces.append({ - 'direction': direction, - 'points': vertices, - 'normals': direction * normals, - 'densities': densities, - 'scores': scores, - }) - - all_points = np.concatenate([f['points'] for f in faces]) - all_normals = np.concatenate([f['normals'] for f in faces]) - all_scores = np.concatenate([f['scores'] for f in faces]) - - above = all_scores >= config.n_mad - kept_local = non_max_suppression( - all_points[above], all_scores[above], - config.to_voxels(config.min_particle_distance_angstrom), - ) if above.any() else np.array([], dtype=int) - kept_index = np.where(above)[0][kept_local] if len(kept_local) else kept_local - - return { - 'blanked': blanked, - 'off_min_px': off_min, - 'off_max_px': off_max, - 'vertices': vertices, - 'normals': normals, - 'faces': faces, - 'all_points': all_points, - 'all_normals': all_normals, - 'all_scores': all_scores, - 'above_mask': above, - 'picks': all_points[kept_index] if len(kept_index) else np.empty((0, 2)), - 'pick_normals': all_normals[kept_index] if len(kept_index) else np.empty((0, 2)), - 'pick_scores': all_scores[kept_index] if len(kept_index) else np.empty(0), - 'config': config, - } diff --git a/src/stamp/tools/diagram/utils/pick.py b/src/stamp/tools/diagram/utils/pick.py index 11f94ae..bf56df8 100644 --- a/src/stamp/tools/diagram/utils/pick.py +++ b/src/stamp/tools/diagram/utils/pick.py @@ -8,7 +8,7 @@ # Import internal STAMP objects from stamp.tools.diagram.utils.geometry import UnionFind -# sample_membrane_surface: points walked around each vesicle membrane, as a native picker would score surface positions +# sample_membrane_surface: points walked around each vesicle membrane, as a picker would score surface positions def sample_membrane_surface(vesicles, rng, spacing_deg=5.0, jitter_px=1.5): points, owner = [], [] for index, v in enumerate(vesicles): diff --git a/src/stamp/tools/diagram/utils/walkthrough.py b/src/stamp/tools/diagram/utils/walkthrough.py index 14ffad7..7ae64f8 100644 --- a/src/stamp/tools/diagram/utils/walkthrough.py +++ b/src/stamp/tools/diagram/utils/walkthrough.py @@ -123,7 +123,7 @@ def build_scene(self): self.consensus_class = np.array([], dtype=int) self.consensus_nearest = np.array([], dtype=int) - # rejected-surface decoys: low-scoring points picked by neither + # decoys: surface points picked by neither picker idle = ~(self.picker_a_mask | self.picker_b_mask) & \ (self.surface_nearest > capture_px) idle_points = self.surface_points[idle] diff --git a/src/stamp/utils/io.py b/src/stamp/utils/io.py index eac1394..8562448 100644 --- a/src/stamp/utils/io.py +++ b/src/stamp/utils/io.py @@ -233,16 +233,22 @@ def match_by_stem( matched[segmentation_path] = raw_path return matched, unmatched -# load_tomogram_manifests: match segmentations to raw tomograms by filename stem, unmatched segmentations skipped with a warning +# load_tomogram_manifests: match segmentations to raw tomograms by filename stem, unmatched segmentations skipped with a warning; without a segmentation directory every raw tomogram gets a manifest with no segmentation def load_tomogram_manifests( - segmentation_dir: Path, + segmentation_dir: Path | None, raw_tomogram_dir: Path, voxel_size_angstrom: float | None, ) -> list[TomogramManifest]: from stamp.utils.errors import StampPipelineError from stamp.utils.log import log - segmentation_paths = glob_mrc(segmentation_dir) raw_paths = glob_mrc(raw_tomogram_dir) + if segmentation_dir is None: + if voxel_size_angstrom is None: + voxel_size_angstrom = resolve_directory_voxel_size_angstrom(raw_paths) + if voxel_size_angstrom is None: + raise StampPipelineError(f'No voxel size in any raw tomogram header under {raw_tomogram_dir} and --voxel-size-a not given') + return [TomogramManifest(tomogram_id=path.stem, raw_tomogram_path=path, voxel_size_angstrom=voxel_size_angstrom) for path in raw_paths] + segmentation_paths = glob_mrc(segmentation_dir) matched, unmatched = match_by_stem(segmentation_paths, raw_paths) for segmentation_path in unmatched: log.warning(f'No raw tomogram matching {segmentation_path.stem}, skipping') diff --git a/src/stamp/utils/phase.py b/src/stamp/utils/phase.py new file mode 100644 index 0000000..d45689c --- /dev/null +++ b/src/stamp/utils/phase.py @@ -0,0 +1,15 @@ +''' +STAMP: phase randomisation +''' + +# Import external dependencies +import numpy as np + +# phase_randomise: keep Fourier amplitudes and replace phases by those of white noise, outside the voxels flagged in keep (Hermitian noise spectrum) +def phase_randomise(volume: np.ndarray, rng: np.random.Generator, *, keep: np.ndarray | None = None) -> np.ndarray: + transform = np.fft.fftn(volume) + noise_phase = np.exp(1j * np.angle(np.fft.fftn(rng.normal(size=volume.shape)))) + randomised = np.abs(transform) * noise_phase + if keep is not None: + randomised[keep] = transform[keep] + return np.fft.ifftn(randomised).real.astype(np.float32) diff --git a/tests/TESTS.md b/tests/TESTS.md index 40ceb53..a09239b 100644 --- a/tests/TESTS.md +++ b/tests/TESTS.md @@ -61,10 +61,11 @@ File | Covers `test_classify.py` | Extraction, coordinate-convention correctness, rotational/azimuthal features, clustering, class averages `test_cli.py` | Typer app wiring `test_config.py` | Configuration management functions (`init_config`, `edit_config`, `show_config`), `_resolve_config_path` -`test_decoy.py` | Decoy generation methods (`rejected-surface`, `shifted`, `synthetic-noise`), `assert_comparable` +`test_decoy.py` | Decoy generation methods (`shifted`, `synthetic-noise`), `assert_comparable` `test_filter.py` | Particle set filter state functions `test_identify.py` | Candidate panel loading, fitting, ranking, decoy-control evaluation -`test_picking.py` | Native picker geometry: surface extraction, ray sampling, scoring, normalisation, NMS, quaternion orientation, coordinate-order correctness +`test_importers.py` | Pick file readers (CSV, STAR, JSON), tomogram id mapping, orientation inference +`test_picking.py` | Surface extraction, quaternion orientation, beam angle, consensus reconciliation, vesicle labelling `test_refine.py` | Half-set splitting/guards, FSC computation, refine output tree `test_run.py` | Overall orchestration: stage sequencing, resume/`--force`/`--from`, decoy track wiring `test_schemas.py` | Pydantic model validation (`Particle`, `RawPick`, `RunConfig`, etc.), including rejection of bad input diff --git a/tests/conftest.py b/tests/conftest.py index 13e8e5a..469306f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -31,6 +31,7 @@ def _make_dataset(root: Path) -> Path: seg.mkdir(parents=True) tomo.mkdir(parents=True) rng = np.random.default_rng(0) + picks = ['tomogram_id,x,y,z'] for index in range(12): shape = (60, 60, 60) segmentation = np.zeros(shape, dtype=np.float32) @@ -38,17 +39,19 @@ def _make_dataset(root: Path) -> Path: volume = rng.normal(0, 1, shape).astype(np.float32) # several large and small blobs, spread out, so each picker/cluster has enough # particles to survive the half-A/half-B split during refine - # keep blobs clear of the membrane plane itself (index 30), within the picker's - # 20-80 Angstrom (~1.5-6 voxel) offset window on one side of the surface - # picker default is density_sign=-1 (dark-protein contrast), so blobs are dips + # blobs sit clear of the membrane plane (x=30); picks.csv points at their centres for x, y in ((13, 13), (13, 35), (35, 13), (35, 35)): volume[x:x + 5, y:y + 5, 33:38] -= 6.0 # large blob for x, y in ((18, 28), (28, 18), (28, 38), (38, 28)): volume[x:x + 3, y:y + 3, 33:35] -= 4.0 # small blob + # picks at the planted blob centres, (x, y, z); blobs index as volume[z, y, x] + picks += [f't{index:02d},35,{y + 2},{x + 2}' for x, y in ((13, 13), (13, 35), (35, 13), (35, 35))] + picks += [f't{index:02d},33.5,{y + 1},{x + 1}' for x, y in ((18, 28), (28, 18), (28, 38), (38, 28))] for directory, data in ((seg, segmentation), (tomo, volume)): with mrcfile.new(directory / f't{index:02d}.mrc', overwrite=True) as mrc: mrc.set_data(data) mrc.voxel_size = 13.48 + (root / 'picks.csv').write_text('\n'.join(picks) + '\n') (root / 'small.pdb').write_text('ATOM 1 CA ALA A 1 0.000 0.000 0.000 1.00 0.00 C\n') (root / 'large.pdb').write_text( '\n'.join( @@ -76,16 +79,18 @@ def _write_config(root: Path, **overrides) -> Path: [decoy] enabled = {str(overrides.get('decoy_enabled', True)).lower()} -method = "rejected-surface" +method = "shifted" [stage.pick] +picks_files = ["picks.csv"] backend = "local" [stage.classify] method = "kmeans" n_clusters = 2 n_components = 3 -box_angstrom = 300 +min_cluster_size = 5 +box_angstrom = 120 [stage.identify] candidates = "candidates.yaml" diff --git a/tests/integration/test_classify_command.py b/tests/integration/test_classify_command.py index 221847d..3767f15 100644 --- a/tests/integration/test_classify_command.py +++ b/tests/integration/test_classify_command.py @@ -10,11 +10,28 @@ # Import main CLI from stamp.classify.extract import extract_particle_set from stamp.classify.features import build_feature_matrix -from stamp.classify.align import align_inplane -from stamp.classify.average import compute_class_averages from stamp.cli.cli import stamp_app +from stamp.commands.classify import build_classify_commands +from stamp.schemas.config import RunConfig from stamp.schemas.particles import HalfSet, Particle +# _CONFIG_DICT: minimal valid [run]/[decoy]/[stage] config for building classify commands +_CONFIG_DICT = { + 'run': { + 'segmentation_dir': 'seg', + 'raw_tomogram_dir': 'tomo', + 'output_dir': 'out', + 'voxel_size_angstrom': 13.48, + 'backend': 'local', + }, + 'decoy': {'enabled': True}, + 'stage': { + 'pick': {'picks_files': ['picks.csv']}, + 'identify': {'candidates': 'candidates.yaml', 'resolution': 25.0}, + 'refine': {'tool': 'relion', 'backend': 'local'}, + }, +} + # Initialise runner runner = CliRunner() @@ -64,61 +81,6 @@ def _build_dataset(tmp_path: Path) -> tuple[Path, Path]: ) return particle_set_path, raw_dir -# TestClassifyCommand: class containing unit tests for test_classify_command.py -class TestClassifyCommand: - def test_classify_end_to_end(self, tmp_path: Path) -> None: - '''Classify runs end to end and writes assignments, averages and params.''' - particle_set_path, raw_dir = _build_dataset(tmp_path) - result = runner.invoke( - stamp_app, - [ - '-d', str(tmp_path), - 'classify', - '--particles', str(particle_set_path), - '--raw-dir', str(raw_dir), - '--out-dir', tmp_path, - '--voxel-size-a', '10.0', - '--box-length-a', '200.0', - '--method', 'kmeans', - '--n-clusters', '2', - '--n-components', '10', - ], - ) - output_dir = tmp_path / 'stamp' / 'classify' - assert result.exit_code == 0, result.output - assignments = json.loads((output_dir / 'class_assignments.json').read_text()) - assert len(assignments) > 0 - assert {a['cluster_id'] for a in assignments} == {'c00', 'c01'} - averages = list((output_dir / 'class_averages').glob('*.mrc')) - assert averages, 'no class averages written' - # Averages are written per half-set. - assert any('halfA' in path.name for path in averages) - assert any('halfB' in path.name for path in averages) - assert (output_dir / 'params.toml').exists() - - def test_classify_strict_halfset_mode(self, tmp_path: Path) -> None: - '''Strict mode reports cross-half cluster matching.''' - particle_set_path, raw_dir = _build_dataset(tmp_path) - result = runner.invoke( - stamp_app, - [ - '-vv', - '-d', str(tmp_path), - 'classify', - '--particles', str(particle_set_path), - '--raw-dir', str(raw_dir), - '--out-dir', tmp_path, - '--voxel-size-a', '10.0', - '--box-length-a', '200.0', - '--method', 'kmeans', - '--n-clusters', '2', - '--n-components', '10', - '--strict-halfset-independence', - ], - ) - assert result.exit_code == 0, result.output - assert 'Cross-half cluster matching' in result.output - class TestClassifyChunking: def _guard_no_full_concatenate(self, monkeypatch, max_rows: int) -> None: '''Fail the test if anything tries to stack more than max_rows at once.''' @@ -136,7 +98,7 @@ def test_classify_resumes_from_matching_partial_output(self, tmp_path: Path) -> '-vv', '-d', str(tmp_path), 'classify', '--particles', str(particle_set_path), '--raw-dir', str(raw_dir), '--out-dir', str(tmp_path), '--voxel-size-a', '10.0', '--box-length-a', '200.0', '--method', 'kmeans', - '--n-clusters', '2', '--n-components', '10', '--keep-raw', + '--n-clusters', '2', '--n-components', '10', '--keep-raw', '--no-strict-halfset-independence', ] assert runner.invoke(stamp_app, argv).exit_code == 0 output_dir = tmp_path / 'stamp' / 'classify' @@ -146,7 +108,7 @@ def test_classify_resumes_from_matching_partial_output(self, tmp_path: Path) -> assert result.exit_code == 0, result.output assert 'Resuming extraction' in result.output assert 'features loaded from checkpoint' in result.output - assert 'Resuming in-plane alignment' in result.output + assert 'Resuming polish step' in result.output assert (output_dir / 'class_assignments.json').read_text() == first changed = argv[:argv.index('--n-clusters')] + ['--n-clusters', '3'] + argv[argv.index('--n-clusters') + 2:] @@ -194,8 +156,87 @@ def test_classify_pipeline_never_stacks_the_whole_dataset(self, tmp_path, monkey monkeypatch.undo() features = build_feature_matrix(subvols, n_workers=1, batch_size=n_particles_per_tomogram) assert features.shape[0] == len(subvols) - cluster_ids = ['c00'] * len(subvols) - angles = align_inplane(subvols, cluster_ids, n_workers=1) - assert len(angles) == len(subvols) - averages = compute_class_averages(subvols, cluster_ids) - assert averages['c00'][1] == len(subvols) \ No newline at end of file + +class TestClassifyCommand: + def _invoke(self, tmp_path: Path, *extra: str, edit=None): + particle_set_path, raw_dir = _build_dataset(tmp_path) + if edit is not None: + payload = json.loads(particle_set_path.read_text()) + edit(payload) + particle_set_path.write_text(json.dumps(payload)) + return runner.invoke(stamp_app, [ + '-vv', '-d', str(tmp_path), 'classify', '--particles', str(particle_set_path), '--raw-dir', str(raw_dir), '--out-dir', str(tmp_path), + '--voxel-size-a', '10.0', '--box-length-a', '200.0', '--method', 'kmeans', '--n-clusters', '2', '--n-components', '10', + '--min-cluster-size', '10', '--tilt-max', '60', *extra, + ]) + + def test_classify_end_to_end(self, tmp_path: Path) -> None: + '''Classify writes assignments with in-plane angles, per-half averages, params and its classifier name.''' + result = self._invoke(tmp_path, '--no-strict-halfset-independence') + assert result.exit_code == 0, result.output + output_dir = tmp_path / 'stamp' / 'classify' + assignments = json.loads((output_dir / 'class_assignments.json').read_text()) + assert {a['classifier'] for a in assignments} == {'stamp-polish-classifier'} + assert any(a['inplane_angle_degrees'] is not None for a in assignments) + posed = [a for a in assignments if a['cluster_id'] != 'noise'] + assert posed and all(a['rotation'] is not None and len(a['shift_voxels']) == 3 and a['cc'] is not None and a['polarity'] is None for a in posed) + averages = [path.name for path in (output_dir / 'class_averages').glob('*.mrc')] + assert any('halfA' in name for name in averages) and any('halfB' in name for name in averages) + assert (output_dir / 'params.toml').exists() + + def test_class_assignment_carries_vesicle_id(self, tmp_path: Path) -> None: + '''vesicle_id on a Particle survives unchanged into its ClassAssignment, and stays None when unset.''' + expected: dict[str, str | None] = {} + def add_vesicles(payload: dict) -> None: + for index, particle in enumerate(payload['particles']): + particle['vesicle_id'] = f'tomo000:v{index % 2 + 1:04d}' if index % 3 else None + expected[particle['particle_id']] = particle['vesicle_id'] + result = self._invoke(tmp_path, '--no-strict-halfset-independence', edit=add_vesicles) + assert result.exit_code == 0, result.output + assignments = json.loads((tmp_path / 'stamp' / 'classify' / 'class_assignments.json').read_text()) + assert assignments and all(a['vesicle_id'] == expected[a['particle_id']] for a in assignments) # particles near the edge are skipped, so only those classified are compared + + def test_polish_strict_halfsets(self, tmp_path: Path) -> None: + '''Strict mode runs polish per half, matches clusters by reference and writes pose fields for both halves.''' + result = self._invoke(tmp_path, '--strict-halfset-independence', '--bin-factor', '1', '--null-sigmas', '0.5') + assert result.exit_code == 0, result.output + assert 'Cross-half cluster matching' in result.output + output_dir = tmp_path / 'stamp' / 'classify' + assignments = json.loads((output_dir / 'class_assignments.json').read_text()) + assert {a['classifier'] for a in assignments} == {'stamp-polish-classifier-strict'} + assert {a['cluster_id'] for a in assignments if a['cluster_id'] != 'noise'} + halves = {path.name.split('_half')[1][0] for path in (output_dir / 'class_averages').glob('*.mrc')} + assert halves == {'A', 'B'} + + def test_polish_runs_for_every_prior(self, tmp_path: Path) -> None: + '''The axis and none priors run end to end from the same particle set, `none` without any orientation.''' + for prior in ('axis', 'none'): + root = tmp_path / prior + root.mkdir() + particle_set_path, raw_dir = _build_dataset(root) + payload = json.loads(particle_set_path.read_text()) + payload['orientation_prior'] = prior + if prior == 'none': + for particle in payload['particles']: + del particle['orientation'] + particle_set_path.write_text(json.dumps(payload)) + result = runner.invoke(stamp_app, [ + '-d', str(root), 'classify', '--particles', str(particle_set_path), '--raw-dir', str(raw_dir), '--out-dir', str(root), + '--voxel-size-a', '10.0', '--box-length-a', '200.0', '--method', 'leiden', '--min-cluster-size', '10', '--n-components', '10', + '--tilt-max', '60', '--bin-factor', '1', '--null-sigmas', '0.5', '--n-rots', '150', '--no-strict-halfset-independence', + ]) + assert result.exit_code == 0, result.output + assignments = json.loads((root / 'stamp' / 'classify' / 'class_assignments.json').read_text()) + posed = [a for a in assignments if a['cluster_id'] != 'noise'] + assert posed and all((a['polarity'] in (1, -1)) == (prior == 'axis') for a in posed) + +# TestBuildClassifyCommands: class containing tests for the classify argv built from the run config +class TestBuildClassifyCommands: + # test_build_classify_commands_passes_polish_settings: the wedge and alignment settings reach the classify argv + def test_build_classify_commands_passes_polish_settings(self, tmp_path) -> None: + config = RunConfig.model_validate({**_CONFIG_DICT, 'run': {**_CONFIG_DICT['run'], 'tilt_max_degrees': 60.0, 'tilt_axis_degrees': 85.0}, 'stage': {**_CONFIG_DICT['stage'], 'classify': {'method': 'kmeans', 'n_rotations': 500}}}) + argv = build_classify_commands(config, tmp_path)[0].argv + for flag, value in (('--method', 'kmeans'), ('--n-rots', '500'), ('--tilt-max', '60.0'), ('--tilt-axis', '85.0')): + assert argv[argv.index(flag) + 1] == value + default = build_classify_commands(RunConfig.model_validate(_CONFIG_DICT), tmp_path)[0].argv + assert '--tilt-max' not in default and default[default.index('--method') + 1] == 'leiden' diff --git a/tests/integration/test_decoy_command.py b/tests/integration/test_decoy_command.py index ccb4bf1..c7c0a96 100644 --- a/tests/integration/test_decoy_command.py +++ b/tests/integration/test_decoy_command.py @@ -10,7 +10,6 @@ # Import internal STAMP objects from stamp.cli.cli import stamp_app from stamp.schemas.particles import ParticleSet -from stamp.utils.errors import StampPipelineError # Initialise runner runner = CliRunner() @@ -38,6 +37,9 @@ def _run_pick(tmp_path: Path, n_tomograms: int = 1) -> tuple[Path, Path, Path]: seg_dir, raw_dir, pick_out = tmp_path / 'seg', tmp_path / 'raw', tmp_path / 'stamp' / 'pick' for index in range(n_tomograms): _write_pair(seg_dir, raw_dir, f'tomo{index:03d}') + # one pick per tomogram at the planted blob centre, (x, y, z); the blob indexes as tomogram[z, y, x] + picks_file = tmp_path / 'picks.csv' + picks_file.write_text('tomogram_id,x,y,z\n' + ''.join(f'tomo{index:03d},30,30,44\n' for index in range(n_tomograms))) result = runner.invoke( stamp_app, [ @@ -47,9 +49,7 @@ def _run_pick(tmp_path: Path, n_tomograms: int = 1) -> tuple[Path, Path, Path]: '--raw-dir', str(raw_dir), '--out-dir', tmp_path, '--voxel-size-a', '10.0', - '--picker-params', json.dumps({'stamp-native': {'n_mad': 2.5, 'offset_windows_angstrom': [[20.0, 80.0]]}}), - '--backend', 'local', - 'stamp-native' + str(picks_file), ], ) assert result.exit_code == 0, result.output @@ -59,23 +59,6 @@ def _run_pick(tmp_path: Path, n_tomograms: int = 1) -> tuple[Path, Path, Path]: def _positions(path: Path) -> list[tuple[float, float, float]]: return [p.position for p in ParticleSet.model_validate(json.loads(path.read_text())).particles] -# _rejected_surface_args: CLI arguments for a rejected-surface decoy run writing under out_dir -def _rejected_surface_args(tmp_path: Path, out_dir: Path, seg_dir: Path, raw_dir: Path, particle_set_path: Path) -> list[str]: - return [ - '-d', str(tmp_path), - 'decoy', - '--method', 'rejected-surface', - '--real-particle-set', str(particle_set_path), - '--seg-dir', str(seg_dir), - '--raw-dir', str(raw_dir), - '--out-dir', str(out_dir), - '--voxel-size-a', '10.0', - '--picker-params', json.dumps({'n_mad': 2.5, 'offset_windows_angstrom': [[20.0, 80.0]]}), - '--n-decoys-per-tomogram', '20', - '--seed', '1', - '--n-processes', '1', - ] - # _shifted_args: CLI arguments for a shifted decoy run writing under out_dir def _shifted_args(tmp_path: Path, out_dir: Path, seg_dir: Path, raw_dir: Path, particle_set_path: Path) -> list[str]: return [ @@ -95,35 +78,6 @@ def _shifted_args(tmp_path: Path, out_dir: Path, seg_dir: Path, raw_dir: Path, p # TestDecoyCommand: class containing unit tests for test_decoy_command.py class TestDecoyCommand: - def test_decoy_rejected_surface_end_to_end(self, tmp_path: Path) -> None: - '''Rejected-surface runs end to end and writes a decoy set.''' - seg_dir, raw_dir, particle_set_path = _run_pick(tmp_path) - output_dir = tmp_path / 'decoy' - - result = runner.invoke( - stamp_app, - [ - '-d', str(tmp_path), - 'decoy', - '--method', 'rejected-surface', - '--real-particle-set', str(particle_set_path), - '--seg-dir', str(seg_dir), - '--raw-dir', str(raw_dir), - '--out-dir', tmp_path, - '--voxel-size-a', '10.0', - '--picker-params', json.dumps({'n_mad': 2.5, 'offset_windows_angstrom': [[20.0, 80.0]]}), - '--n-decoys-per-tomogram', '20', - '--seed', '1', - ], - ) - assert result.exit_code == 0, result.output - - decoy_set = ParticleSet.model_validate( - json.loads((tmp_path / 'stamp' / 'decoy' / 'decoy_particle_set.json').read_text()) - ) - assert decoy_set.particles - assert all(p.source_picker.startswith('decoy-') for p in decoy_set.particles) - def test_decoy_shifted_end_to_end(self, tmp_path: Path) -> None: '''Shifted runs end to end without error.''' seg_dir, raw_dir, particle_set_path = _run_pick(tmp_path) @@ -169,71 +123,6 @@ def test_decoy_synthetic_noise_end_to_end(self, tmp_path: Path) -> None: assert (output_dir / 'segmentations').is_dir() assert (output_dir / 'tomograms').is_dir() - def test_decoy_rejects_undersized_set(self, tmp_path: Path) -> None: - '''Too few decoys per tomogram fails comparability check.''' - seg_dir, raw_dir = tmp_path / 'seg', tmp_path / 'raw' - shape = (60, 60, 60) - centre = np.array(shape) / 2.0 - grid = np.stack(np.meshgrid(*[np.arange(s) for s in shape], indexing='ij'), axis=-1) - distance = np.linalg.norm(grid - centre, axis=-1) - segmentation = ((distance > 16.0) & (distance < 20.0)).astype(np.float32) - tomogram = np.zeros(shape, dtype=np.float32) - tomogram[segmentation > 0] = -1.0 - - rng = np.random.default_rng(3) - for _ in range(8): - z, y, x = rng.integers(10, 50, 3) - tomogram[z - 2:z + 3, y - 2:y + 3, x - 2:x + 3] = -8.0 - - seg_dir.mkdir(parents=True, exist_ok=True) - raw_dir.mkdir(parents=True, exist_ok=True) - with mrcfile.new(seg_dir / 'tomo000.mrc', overwrite=True) as mrc: - mrc.set_data(segmentation) - with mrcfile.new(raw_dir / 'tomo000.mrc', overwrite=True) as mrc: - mrc.set_data(tomogram) - - pick_result = runner.invoke( - stamp_app, - [ - '-d', str(tmp_path), - 'pick', - '--seg-dir', str(seg_dir), - '--raw-dir', str(raw_dir), - '--out-dir', tmp_path, - '--voxel-size-a', '10.0', - '--picker-params', json.dumps({'n_mad': 2.0, 'offset_windows_angstrom': [[20.0, 80.0]]}), - '--backend', 'local', - 'stamp-native' - ], - ) - assert pick_result.exit_code == 0, pick_result.output - particle_set_path = tmp_path / 'stamp' / 'pick' / 'particle_set.json' - real_set = ParticleSet.model_validate(json.loads(particle_set_path.read_text())) - assert len(real_set.particles) >= 3 - - output_dir = tmp_path / 'decoy_undersized' - result = runner.invoke( - stamp_app, - [ - '-d', str(tmp_path), - 'decoy', - '--method', 'rejected-surface', - '--real-particle-set', str(particle_set_path), - '--seg-dir', str(seg_dir), - '--raw-dir', str(raw_dir), - '--out-dir', tmp_path, - '--voxel-size-a', '10.0', - '--picker-params', json.dumps({'n_mad': 2.0, 'offset_windows_angstrom': [[20.0, 80.0]]}), - '--n-decoys-per-tomogram', '1', - '--seed', '1', - ], - ) - - assert result.exit_code != 0 - assert isinstance(result.exception, StampPipelineError) - assert 'less than half the size of the real set' in str(result.exception) - assert not (tmp_path / 'stamp' / 'decoy' / 'decoy_particle_set.json').exists() - def test_decoy_synthetic_noise_reuses_finished_volumes(self, tmp_path: Path) -> None: '''A rerun over a kept raw dir reuses finished volumes and gives identical decoys.''' args = [ @@ -259,36 +148,6 @@ def test_decoy_synthetic_noise_reuses_finished_volumes(self, tmp_path: Path) -> assert volume.stat().st_mtime_ns == modified assert _positions(output_dir / 'decoy_particle_set.json') == first - def test_decoy_rejected_surface_resumes_after_interruption(self, tmp_path: Path, monkeypatch) -> None: - '''Scoring resumes from finished tomograms and the decoys match an uninterrupted run.''' - from stamp.decoy import generate - seg_dir, raw_dir, particle_set_path = _run_pick(tmp_path, n_tomograms=3) - real = generate._score_surface - scored: list[str] = [] - state = {'fail': True} - - # flaky: fail on the second tomogram until told otherwise, else score normally - def flaky(manifest, config): - if state['fail'] and len(scored) == 1: - raise RuntimeError('boom') - scored.append(manifest.tomogram_id) - return real(manifest, config) - - monkeypatch.setattr(generate, '_score_surface', flaky) - args = _rejected_surface_args(tmp_path, tmp_path, seg_dir, raw_dir, particle_set_path) - assert runner.invoke(stamp_app, args).exit_code != 0 - finished = list(scored) - assert len(finished) == 1 - - state['fail'] = False - scored.clear() - assert runner.invoke(stamp_app, args).exit_code == 0 - assert len(scored) == 2 and not set(scored) & set(finished) - - clean = _rejected_surface_args(tmp_path, tmp_path / 'clean', seg_dir, raw_dir, particle_set_path) - assert runner.invoke(stamp_app, clean).exit_code == 0 - assert _positions(tmp_path / 'stamp' / 'decoy' / 'decoy_particle_set.json') == _positions(tmp_path / 'clean' / 'stamp' / 'decoy' / 'decoy_particle_set.json') - def test_decoy_shifted_resumes_after_interruption(self, tmp_path: Path, monkeypatch) -> None: '''Surface extraction resumes from finished tomograms and the decoys match an uninterrupted run.''' from stamp.decoy import generate diff --git a/tests/integration/test_pick_command.py b/tests/integration/test_pick_command.py index f7ec01e..e67bd83 100644 --- a/tests/integration/test_pick_command.py +++ b/tests/integration/test_pick_command.py @@ -14,76 +14,86 @@ # Initialise runner runner = CliRunner() -# _write_pair: write a vesicle with one dark particle as a matched segmentation/tomogram pair -# in _write_pair, add a keyword-only voxel_size param: -def _write_pair(seg_dir: Path, raw_dir: Path, tomogram_id: str, *, voxel_size: float | None = None) -> None: +# PARTICLES_XYZ: six particle positions (x, y, z) inside the 60^3 vesicle, 14 voxels from its centre +PARTICLES_XYZ = ((30, 30, 44), (30, 30, 16), (30, 44, 30), (30, 16, 30), (44, 30, 30), (16, 30, 30)) + +# _write_pair: write a vesicle as a matched segmentation/tomogram pair +def _write_pair(seg_dir: Path, raw_dir: Path, tomogram_id: str, *, voxel_size: float | None = None, seg_id: str | None = None) -> None: shape = (60, 60, 60) centre = np.array(shape) / 2.0 grid = np.stack(np.meshgrid(*[np.arange(s) for s in shape], indexing='ij'), axis=-1) distance = np.linalg.norm(grid - centre, axis=-1) - segmentation = ((distance > 16.0) & (distance < 20.0)).astype(np.float32) tomogram = np.zeros(shape, dtype=np.float32) tomogram[segmentation > 0] = -1.0 - tomogram[42:47, 28:33, 28:33] = -8.0 seg_dir.mkdir(parents=True, exist_ok=True) raw_dir.mkdir(parents=True, exist_ok=True) - with mrcfile.new(seg_dir / f'{tomogram_id}.mrc', overwrite=True) as mrc: + with mrcfile.new(seg_dir / f'{seg_id or tomogram_id}.mrc', overwrite=True) as mrc: mrc.set_data(segmentation) with mrcfile.new(raw_dir / f'{tomogram_id}.mrc', overwrite=True) as mrc: mrc.set_data(tomogram) if voxel_size is not None: mrc.voxel_size = voxel_size -# _pick_args: CLI arguments for a native pick run over the given directories -def _pick_args(tmp_path: Path, seg_dir: Path, raw_dir: Path, n_mad: float) -> list[str]: +# _write_picks: write a CSV picks file with PARTICLES_XYZ in each given tomogram +def _write_picks(path: Path, tomogram_ids: list[str], *, shift: float = 0.0) -> Path: + rows = ['tomogram_id,x,y,z'] + [f'{tomogram_id},{x + shift},{y},{z}' for tomogram_id in tomogram_ids for x, y, z in PARTICLES_XYZ] + path.write_text('\n'.join(rows) + '\n') + return path + +# _pick_args: CLI arguments for a pick run over the given files and directories +def _pick_args(tmp_path: Path, seg_dir: Path, raw_dir: Path, *picks_files: Path, extra: list[str] | None = None, voxel_size: str | None = '10.0') -> list[str]: return [ '-d', str(tmp_path), 'pick', + *[str(path) for path in picks_files], '--seg-dir', str(seg_dir), '--raw-dir', str(raw_dir), '--out-dir', str(tmp_path), - '--voxel-size-a', '10.0', - '--picker-params', json.dumps({'stamp-native': {'n_mad': n_mad, 'offset_windows_angstrom': [[20.0, 80.0]]}}), - '--backend', 'local', - '--n-processes', '1', - 'stamp-native', + *(['--voxel-size-a', voxel_size] if voxel_size else []), + *(extra or []), ] # TestPickCommand: class containing tests for pick command class TestPickCommand: - # check `stamp pick` runs the native picker and writes outputs - def test_pick_runs_native_picker_end_to_end(self, tmp_path: Path) -> None: + # check `stamp pick` imports picks, infers orientations and writes outputs + def test_pick_imports_picks_end_to_end(self, tmp_path: Path) -> None: seg_dir, raw_dir = tmp_path / 'seg', tmp_path / 'raw' _write_pair(seg_dir, raw_dir, 'tomo000') - result = runner.invoke( - stamp_app, - [ - '-d', str(tmp_path), - 'pick', - '--seg-dir', str(seg_dir), - '--raw-dir', str(raw_dir), - '--out-dir', tmp_path, - '--voxel-size-a', '10.0', - '--consensus-rule', 'union', - '--picker-params', json.dumps({'stamp-native': {'n_mad': 2.5, 'offset_windows_angstrom': [[20.0, 80.0]]}}), - '--backend', 'local', - 'stamp-native', - ], - ) - + picks = _write_picks(tmp_path / 'picks.csv', ['tomo000']) + result = runner.invoke(stamp_app, _pick_args(tmp_path, seg_dir, raw_dir, picks)) assert result.exit_code == 0, result.output - output_dir = tmp_path / 'stamp' / 'pick' - particle_set_path = output_dir / 'particle_set.json' - assert particle_set_path.exists() - particle_set = ParticleSet.model_validate(json.loads(particle_set_path.read_text())) - assert particle_set.particles + output_dir = tmp_path / 'stamp' / 'pick' + particle_set = ParticleSet.model_validate(json.loads((output_dir / 'particle_set.json').read_text())) + assert len(particle_set.particles) == len(PARTICLES_XYZ) assert all(p.half_set is not None for p in particle_set.particles) assert all(p.orientation is not None for p in particle_set.particles) + assert all(p.beam_angle_deviation_degrees is not None for p in particle_set.particles) + assert {p.source_picker for p in particle_set.particles} == {'picks'} assert (output_dir / 'params.toml').exists() + # check picks beyond --max-surface-distance-a are kept but get no orientation + def test_pick_leaves_far_picks_unoriented(self, tmp_path: Path) -> None: + seg_dir, raw_dir = tmp_path / 'seg', tmp_path / 'raw' + _write_pair(seg_dir, raw_dir, 'tomo000') + picks = _write_picks(tmp_path / 'picks.csv', ['tomo000']) + result = runner.invoke(stamp_app, _pick_args(tmp_path, seg_dir, raw_dir, picks, extra=['--max-surface-distance-a', '1'])) + assert result.exit_code == 0, result.output + assert 'have no orientation' in result.output + particle_set = ParticleSet.model_validate(json.loads((tmp_path / 'stamp' / 'pick' / 'particle_set.json').read_text())) + assert all(p.orientation is None for p in particle_set.particles) + + # check pick ids absent from the segmentation directory are an error that names them + def test_pick_rejects_unknown_tomogram_ids(self, tmp_path: Path) -> None: + seg_dir, raw_dir = tmp_path / 'seg', tmp_path / 'raw' + _write_pair(seg_dir, raw_dir, 'tomo000') + picks = _write_picks(tmp_path / 'picks.csv', ['tomo000', 'ghost']) + result = runner.invoke(stamp_app, _pick_args(tmp_path, seg_dir, raw_dir, picks)) + assert result.exit_code != 0 + assert "'ghost'" in str(result.exception) + # check a segmentation with no raw match is skipped def test_pick_skips_segmentations_without_raw_match(self, tmp_path: Path) -> None: seg_dir, raw_dir = tmp_path / 'seg', tmp_path / 'raw' @@ -91,55 +101,18 @@ def test_pick_skips_segmentations_without_raw_match(self, tmp_path: Path) -> Non # an extra segmentation with no matching raw tomogram. with mrcfile.new(seg_dir / 'orphan.mrc', overwrite=True) as mrc: mrc.set_data(np.zeros((60, 60, 60), dtype=np.float32)) - - result = runner.invoke( - stamp_app, - [ - '-d', str(tmp_path), - 'pick', - '--seg-dir', str(seg_dir), - '--raw-dir', str(raw_dir), - '--out-dir', tmp_path, - '--voxel-size-a', '10.0', - '--picker-params', json.dumps({'stamp-native': {'n_mad': 2.5, 'offset_windows_angstrom': [[20.0, 80.0]]}}), - '--backend', 'local', - 'stamp-native', - ], - ) + picks = _write_picks(tmp_path / 'picks.csv', ['tomo000']) + result = runner.invoke(stamp_app, _pick_args(tmp_path, seg_dir, raw_dir, picks)) assert 'No raw tomogram matching orphan, skipping' in result.output assert result.exit_code == 0, result.output # check a segmentation whose stem is the raw stem plus a suffix still matches def test_pick_matches_segmentation_by_stem_prefix(self, tmp_path: Path) -> None: seg_dir, raw_dir = tmp_path / 'seg', tmp_path / 'raw' - seg_dir.mkdir(parents=True, exist_ok=True) - raw_dir.mkdir(parents=True, exist_ok=True) - shape = (60, 60, 60) - centre = np.array(shape) / 2.0 - grid = np.stack(np.meshgrid(*[np.arange(s) for s in shape], indexing='ij'), axis=-1) - distance = np.linalg.norm(grid - centre, axis=-1) - segmentation = ((distance > 16.0) & (distance < 20.0)).astype(np.float32) - tomogram = np.zeros(shape, dtype=np.float32) - tomogram[segmentation > 0] = -1.0 - tomogram[42:47, 28:33, 28:33] = -8.0 - with mrcfile.new(raw_dir / 'Position_1_stack_Vol.mrc', overwrite=True) as mrc: - mrc.set_data(tomogram) - with mrcfile.new(seg_dir / 'Position_1_stack_Vol.denoised_segmented.mrc', overwrite=True) as mrc: - mrc.set_data(segmentation) - result = runner.invoke( - stamp_app, - [ - '-d', str(tmp_path), - 'pick', - '--seg-dir', str(seg_dir), - '--raw-dir', str(raw_dir), - '--out-dir', tmp_path, - '--voxel-size-a', '10.0', - '--picker-params', json.dumps({'stamp-native': {'n_mad': 2.5, 'offset_windows_angstrom': [[20.0, 80.0]]}}), - '--backend', 'local', - 'stamp-native', - ], - ) + _write_pair(seg_dir, raw_dir, 'Position_1_stack_Vol', seg_id='Position_1_stack_Vol.denoised_segmented') + # the picks file uses the raw-style id; the manifest id is the segmentation stem + picks = _write_picks(tmp_path / 'picks.csv', ['Position_1_stack_Vol.denoised']) + result = runner.invoke(stamp_app, _pick_args(tmp_path, seg_dir, raw_dir, picks)) assert result.exit_code == 0, result.output assert 'No raw tomogram matching' not in result.output @@ -147,90 +120,143 @@ def test_pick_matches_segmentation_by_stem_prefix(self, tmp_path: Path) -> None: def test_pick_reads_voxel_size_from_header_when_omitted(self, tmp_path: Path) -> None: seg_dir, raw_dir = tmp_path / 'seg', tmp_path / 'raw' _write_pair(seg_dir, raw_dir, 'tomo000', voxel_size=10.0) - result = runner.invoke( - stamp_app, - [ - '-d', str(tmp_path), - 'pick', - '--seg-dir', str(seg_dir), - '--raw-dir', str(raw_dir), - '--out-dir', tmp_path, - '--picker-params', json.dumps({'stamp-native': {'n_mad': 2.5, 'offset_windows_angstrom': [[20.0, 80.0]]}}), - '--backend', 'local', - 'stamp-native', - ], - ) + picks = _write_picks(tmp_path / 'picks.csv', ['tomo000']) + result = runner.invoke(stamp_app, _pick_args(tmp_path, seg_dir, raw_dir, picks, voxel_size=None)) assert result.exit_code == 0, result.output # check mixed voxel sizes across tomograms warn and fall back to the most common def test_pick_warns_and_uses_most_common_voxel_size(self, tmp_path: Path) -> None: seg_dir, raw_dir = tmp_path / 'seg', tmp_path / 'raw' - _write_pair(seg_dir, raw_dir, 'tomo000', voxel_size=10.0) - _write_pair(seg_dir, raw_dir, 'tomo001', voxel_size=10.0) - _write_pair(seg_dir, raw_dir, 'tomo002', voxel_size=14.0) - result = runner.invoke( - stamp_app, - [ - '-d', str(tmp_path), - 'pick', - '--seg-dir', str(seg_dir), - '--raw-dir', str(raw_dir), - '--out-dir', tmp_path, - '--picker-params', json.dumps({'stamp-native': {'n_mad': 2.5, 'offset_windows_angstrom': [[20.0, 80.0]]}}), - '--backend', 'local', - 'stamp-native', - ], - ) + ids = ['tomo000', 'tomo001', 'tomo002'] + for tomogram_id, voxel_size in zip(ids, (10.0, 10.0, 14.0)): + _write_pair(seg_dir, raw_dir, tomogram_id, voxel_size=voxel_size) + picks = _write_picks(tmp_path / 'picks.csv', ids) + result = runner.invoke(stamp_app, _pick_args(tmp_path, seg_dir, raw_dir, picks, voxel_size=None)) assert result.exit_code == 0, result.output assert 'Multiple voxel sizes were found' in result.output - # check an interrupted pick resumes, picking only the tomograms that had not finished + + # check two picks files with the intersection rule yield picks attributed to both pickers + def test_pick_intersection_joins_source_pickers(self, tmp_path: Path) -> None: + seg_dir, raw_dir = tmp_path / 'seg', tmp_path / 'raw' + _write_pair(seg_dir, raw_dir, 'tomo000') + first = _write_picks(tmp_path / 'first.csv', ['tomo000']) + second = _write_picks(tmp_path / 'second.csv', ['tomo000'], shift=2.0) # within the 15 voxel default threshold + result = runner.invoke(stamp_app, _pick_args(tmp_path, seg_dir, raw_dir, first, second, extra=['--consensus-rule', 'intersection'])) + assert result.exit_code == 0, result.output + particle_set = ParticleSet.model_validate(json.loads((tmp_path / 'stamp' / 'pick' / 'particle_set.json').read_text())) + assert len(particle_set.particles) == len(PARTICLES_XYZ) + assert {p.source_picker for p in particle_set.particles} == {'first+second'} + + # check --name overrides the file stem and duplicate names are rejected + def test_pick_names(self, tmp_path: Path) -> None: + seg_dir, raw_dir = tmp_path / 'seg', tmp_path / 'raw' + _write_pair(seg_dir, raw_dir, 'tomo000') + picks = _write_picks(tmp_path / 'picks.csv', ['tomo000']) + result = runner.invoke(stamp_app, _pick_args(tmp_path, seg_dir, raw_dir, picks, extra=['--name', 'mine'])) + assert result.exit_code == 0, result.output + particle_set = ParticleSet.model_validate(json.loads((tmp_path / 'stamp' / 'pick' / 'particle_set.json').read_text())) + assert {p.source_picker for p in particle_set.particles} == {'mine'} + + other = tmp_path / 'other' + other.mkdir() + twin = _write_picks(other / 'picks.csv', ['tomo000']) + result = runner.invoke(stamp_app, _pick_args(tmp_path, seg_dir, raw_dir, picks, twin)) + assert result.exit_code != 0 + assert 'must be unique' in str(result.exception) + + # check an interrupted pick resumes, orienting only the tomograms that had not finished def test_pick_resumes_after_interruption(self, tmp_path: Path, monkeypatch) -> None: - from stamp.adapters import native + import stamp.commands.pick as pickfuncs seg_dir, raw_dir = tmp_path / 'seg', tmp_path / 'raw' - for tomogram_id in ('tomo000', 'tomo001', 'tomo002'): + ids = ['tomo000', 'tomo001', 'tomo002'] + for tomogram_id in ids: _write_pair(seg_dir, raw_dir, tomogram_id) - real = native.pick_tomogram - picked: list[str] = [] + picks = _write_picks(tmp_path / 'picks.csv', ids) + real = pickfuncs.infer_orientations + oriented: list[str] = [] state = {'fail': True} - # flaky: fail on tomo001 until told otherwise, else pick normally - def flaky(segmentation_path, tomogram_path, tomogram_id, config): + # flaky: fail on tomo001 until told otherwise, else infer normally + def flaky(tomogram_picks, manifests, **kwargs): + tomogram_id = tomogram_picks[0].tomogram_id if state['fail'] and tomogram_id == 'tomo001': raise RuntimeError('boom') - picked.append(tomogram_id) - return real(segmentation_path, tomogram_path, tomogram_id, config) + oriented.append(tomogram_id) + return real(tomogram_picks, manifests, **kwargs) - monkeypatch.setattr(native, 'pick_tomogram', flaky) - args = _pick_args(tmp_path, seg_dir, raw_dir, 2.5) + monkeypatch.setattr(pickfuncs, 'infer_orientations', flaky) + args = _pick_args(tmp_path, seg_dir, raw_dir, picks) assert runner.invoke(stamp_app, args).exit_code != 0 - assert picked == ['tomo000'] # manifests are processed in sorted order + assert oriented == ['tomo000'] # picks are grouped in file order state['fail'] = False - picked.clear() + oriented.clear() result = runner.invoke(stamp_app, args) assert result.exit_code == 0, result.output - assert picked == ['tomo001', 'tomo002'] + assert oriented == ['tomo001', 'tomo002'] - # check changed picker parameters discard the checkpoint - def test_pick_restarts_when_picker_params_change(self, tmp_path: Path, monkeypatch) -> None: - from stamp.adapters import native + # check a changed picks file discards the checkpoint + def test_pick_restarts_when_picks_change(self, tmp_path: Path, monkeypatch) -> None: + import stamp.commands.pick as pickfuncs seg_dir, raw_dir = tmp_path / 'seg', tmp_path / 'raw' - for tomogram_id in ('tomo000', 'tomo001'): + ids = ['tomo000', 'tomo001'] + for tomogram_id in ids: _write_pair(seg_dir, raw_dir, tomogram_id) - real = native.pick_tomogram - picked: list[str] = [] + picks = _write_picks(tmp_path / 'picks.csv', ids) + real = pickfuncs.infer_orientations + oriented: list[str] = [] state = {'fail': True} - # flaky: fail on tomo001 until told otherwise, else pick normally - def flaky(segmentation_path, tomogram_path, tomogram_id, config): + # flaky: fail on tomo001 until told otherwise, else infer normally + def flaky(tomogram_picks, manifests, **kwargs): + tomogram_id = tomogram_picks[0].tomogram_id if state['fail'] and tomogram_id == 'tomo001': raise RuntimeError('boom') - picked.append(tomogram_id) - return real(segmentation_path, tomogram_path, tomogram_id, config) + oriented.append(tomogram_id) + return real(tomogram_picks, manifests, **kwargs) - monkeypatch.setattr(native, 'pick_tomogram', flaky) - runner.invoke(stamp_app, _pick_args(tmp_path, seg_dir, raw_dir, 2.5)) + monkeypatch.setattr(pickfuncs, 'infer_orientations', flaky) + runner.invoke(stamp_app, _pick_args(tmp_path, seg_dir, raw_dir, picks)) state['fail'] = False - picked.clear() - runner.invoke(stamp_app, _pick_args(tmp_path, seg_dir, raw_dir, 2.0)) # exit code irrelevant, only what ran matters - assert picked == ['tomo000', 'tomo001'] + oriented.clear() + _write_picks(picks, ids, shift=1.0) # same path, new content + runner.invoke(stamp_app, _pick_args(tmp_path, seg_dir, raw_dir, picks)) + assert oriented == ['tomo000', 'tomo001'] + + +# TestPickOrientationPrior: class containing tests for --orientation-prior +class TestPickOrientationPrior: + # check the none prior needs no segmentation, drops reported orientations and tags the particle set + def test_none_prior_without_segmentation(self, tmp_path: Path) -> None: + raw_dir = tmp_path / 'raw' + _write_pair(tmp_path / 'unused', raw_dir, 'tomo000') + picks = tmp_path / 'picks.csv' + picks.write_text('tomogram_id,x,y,z,qw,qx,qy,qz\n' + '\n'.join(f'tomo000,{x},{y},{z},1,0,0,0' for x, y, z in PARTICLES_XYZ) + '\n') + result = runner.invoke(stamp_app, ['-d', str(tmp_path), 'pick', str(picks), '--raw-dir', str(raw_dir), '--out-dir', str(tmp_path), '--voxel-size-a', '10.0', '--orientation-prior', 'none']) + assert result.exit_code == 0, result.output + particle_set = ParticleSet.model_validate(json.loads((tmp_path / 'stamp' / 'pick' / 'particle_set.json').read_text())) + assert particle_set.orientation_prior.value == 'none' + assert len(particle_set.particles) == len(PARTICLES_XYZ) and all(p.orientation is None for p in particle_set.particles) + + # check the axis prior keeps the supplied axis and refuses picks without one + def test_axis_prior_requires_orientations(self, tmp_path: Path) -> None: + raw_dir = tmp_path / 'raw' + _write_pair(tmp_path / 'unused', raw_dir, 'tomo000') + with_axis = tmp_path / 'with_axis.csv' + with_axis.write_text('tomogram_id,x,y,z,qw,qx,qy,qz\n' + '\n'.join(f'tomo000,{x},{y},{z},0.7071068,0,0.7071068,0' for x, y, z in PARTICLES_XYZ) + '\n') + base = ['-d', str(tmp_path), 'pick', '--raw-dir', str(raw_dir), '--out-dir', str(tmp_path), '--voxel-size-a', '10.0', '--orientation-prior', 'axis'] + ok = runner.invoke(stamp_app, [*base[:2], base[2], str(with_axis), *base[3:]]) + assert ok.exit_code == 0, ok.output + particle_set = ParticleSet.model_validate(json.loads((tmp_path / 'stamp' / 'pick' / 'particle_set.json').read_text())) + assert particle_set.orientation_prior.value == 'axis' and all(p.orientation is not None for p in particle_set.particles) + without = _write_picks(tmp_path / 'without.csv', ['tomo000']) + bad = runner.invoke(stamp_app, [*base[:2], base[2], str(without), *base[3:]]) + assert bad.exit_code != 0 and 'axis needs an orientation' in bad.output + + # check the normal prior still demands a segmentation directory + def test_normal_prior_requires_segmentation(self, tmp_path: Path) -> None: + raw_dir = tmp_path / 'raw' + _write_pair(tmp_path / 'seg', raw_dir, 'tomo000') + picks = _write_picks(tmp_path / 'picks.csv', ['tomo000']) + result = runner.invoke(stamp_app, ['-d', str(tmp_path), 'pick', str(picks), '--raw-dir', str(raw_dir), '--out-dir', str(tmp_path), '--voxel-size-a', '10.0']) + assert result.exit_code != 0 and '--seg-dir is required' in result.output diff --git a/tests/integration/test_run_command.py b/tests/integration/test_run_command.py index 8441ce6..33acc5f 100644 --- a/tests/integration/test_run_command.py +++ b/tests/integration/test_run_command.py @@ -3,7 +3,7 @@ ''' # Import external dependencies -import json, tomllib +import json, pytest, tomllib from typer.testing import CliRunner from stamp.cli.cli import stamp_app @@ -44,3 +44,50 @@ def test_no_decoy_runs_real_only(self, tmp_path, run_mock_pipeline): out = run_mock_pipeline(tmp_path, args=['--no-decoy']) assert not (out / 'decoy').exists() assert 'NOT RUN' in (out / 'report.md').read_text() + + # test_run_pipeline_for_non_membrane_priors: pick, random-volume decoy and the polish step run end to end with no segmentation, for soluble particles (none) and filaments (axis, picks carry an axis quaternion) + @pytest.mark.parametrize('prior', ['none', 'axis']) + def test_run_pipeline_for_non_membrane_priors(self, tmp_path: Path, make_dataset, prior: str) -> None: + make_dataset(tmp_path) + if prior == 'axis': + rows = (tmp_path / 'picks.csv').read_text().splitlines() + (tmp_path / 'picks.csv').write_text('\n'.join([rows[0] + ',qw,qx,qy,qz'] + [row + ',1,0,0,0' for row in rows[1:]]) + '\n') + (tmp_path / 'stamp_run.toml').write_text(f""" + [run] + raw_tomogram_dir = "tomo" + output_dir = "." + voxel_size_angstrom = 13.48 + backend = "mock" + stop_after = "classify" + orientation_prior = "{prior}" + tilt_max_degrees = 60.0 + + [decoy] + enabled = true + method = "random-volume" + min_distance_from_picks_angstrom = 40.0 + min_border_angstrom = 120.0 + + [stage.pick] + picks_files = ["picks.csv"] + + [stage.classify] + method = "leiden" + min_cluster_size = 10 + box_angstrom = 120 + bin_factor = 1 + n_rotations = 100 + null_sigmas = 0.5 + strict_halfset_independence = false + + [stage.identify] + candidates = "candidates.yaml" + resolution = 25.0 + """) + result = CliRunner().invoke(stamp_app, ['-d', str(tmp_path), 'run', '--config', str(tmp_path / 'stamp_run.toml')]) + assert result.exit_code == 0, result.output + for classify_dir in (tmp_path / 'stamp' / 'classify_real', tmp_path / 'stamp' / 'classify_decoy'): + assert (classify_dir / 'class_assignments.json').is_file() + assert json.loads((tmp_path / 'stamp' / 'pick' / 'particle_set.json').read_text())['orientation_prior'] == prior + decoy_assignments = json.loads((tmp_path / 'stamp' / 'classify_decoy' / 'class_assignments.json').read_text()) + assert {a['cluster_id'] for a in decoy_assignments} == {'noise'} # random positions share no structure, polish rejects them all diff --git a/tests/synthetic.py b/tests/synthetic.py new file mode 100644 index 0000000..8c44e1b --- /dev/null +++ b/tests/synthetic.py @@ -0,0 +1,100 @@ +''' +STAMP: synthetic particles with known orientations, shifts and wedges +''' + +# Import external dependencies +import numpy as np +from dataclasses import dataclass +from pathlib import Path +from scipy.ndimage import gaussian_filter, shift as shift_volume +from scipy.spatial.transform import Rotation + +# Import internal STAMP objects +from stamp.classify.frames import azimuth_matrix, flip_matrix, rotate_density +from stamp.classify.store import ParticleStore +from stamp.classify.wedge import apply_wedge, box_wedge +from stamp.picking.geometry import quaternion_from_reference_to +from stamp.schemas.particles import OrientationPrior +from stamp.schemas.subvolumes import Subvolumes + +# asymmetric_object: smooth volume of random gaussian blobs, no symmetry, so every rotation and flip is distinguishable +def asymmetric_object(box: int, seed: int, *, n_blobs: int = 7, spread: float = 0.22) -> np.ndarray: + rng = np.random.default_rng(seed) + volume = np.zeros((box,) * 3, dtype=np.float32) + centre = (box - 1) / 2.0 + for _ in range(n_blobs): + index = np.round(centre + rng.normal(0.0, spread * box, 3)).astype(int).clip(2, box - 3) + volume[tuple(index)] += rng.uniform(0.5, 1.5) + smooth = gaussian_filter(volume, box / 14.0) + return smooth / smooth.max() + +# rod_object: filament along z with a repeating asymmetric pattern, polarity and axial position are both observable +def rod_object(box: int, seed: int, *, repeat: float = 6.0) -> np.ndarray: + rng = np.random.default_rng(seed) + centre = (box - 1) / 2.0 + axis = np.arange(box) - centre + x, y, z = np.meshgrid(axis, axis, axis, indexing='ij') + body = np.exp(-(x**2 + y**2) / (2 * (box / 10.0) ** 2)) + phase = rng.uniform(0, 2 * np.pi) + lump = np.exp(-((x - box / 7.0 * np.cos(2 * np.pi * z / repeat + phase)) ** 2 + (y - box / 7.0 * np.sin(2 * np.pi * z / repeat + phase)) ** 2) / (2 * (box / 16.0) ** 2)) + cap = 2.0 * np.exp(-((x - box / 5.0) ** 2 + y**2 + (z - box / 4.0) ** 2) / (2 * (box / 12.0) ** 2)) # off-axis cap at one end breaks the up-down symmetry so polarity is observable + return (body + lump + cap).astype(np.float32) + +# make_particle: the object moved by rotation then shift, limited to the box-frame wedge, plus white noise +def make_particle( + obj: np.ndarray, + rotation: np.ndarray, + shift: tuple[float, float, float], + wedge: np.ndarray | None, + noise_sigma: float, + rng: np.random.Generator, +) -> np.ndarray: + moved = shift_volume(rotate_density(obj, rotation), shift, order=1) + if wedge is not None: + moved = apply_wedge(moved, wedge) + return (moved + rng.normal(0.0, noise_sigma, obj.shape)).astype(np.float32) + +# SyntheticSet: particles with known class, pose and shift, as a prepared store +@dataclass(frozen=True) +class SyntheticSet: + store: ParticleStore + labels: np.ndarray + rotations: np.ndarray + shifts: np.ndarray + +# synthetic_set: n_per_class particles of each object, poses drawn for the prior, one cache per fake tomogram, wedges from random orientations +def synthetic_set( + directory: Path, + objects: list[np.ndarray], + prior: OrientationPrior, + n_per_class: int, + *, + noise_sigma: float = 0.1, + tilt_max: float | None = 60.0, + seed: int = 0, + max_shift: int = 2, +) -> SyntheticSet: + rng = np.random.default_rng(seed) + box = objects[0].shape[0] + labels = np.repeat(np.arange(len(objects)), n_per_class) + rng.shuffle(labels) + n = len(labels) + if prior is OrientationPrior.NONE: + rotations = Rotation.random(n, random_state=seed).as_matrix() + orientations = [None] * n + else: + flips = [flip_matrix() if prior is OrientationPrior.AXIS and rng.random() < 0.5 else np.eye(3) for _ in range(n)] + rotations = np.stack([azimuth_matrix(a) @ f for a, f in zip(rng.uniform(0, 360, n), flips)]) + orientations = [quaternion_from_reference_to(rng.normal(size=3)) for _ in range(n)] + shifts = rng.integers(-max_shift, max_shift + 1, (n, 3)) * (np.array([0, 0, 2]) if prior is OrientationPrior.AXIS else 1) + wedges = [box_wedge(box, o, tilt_max, 90.0) for o in orientations] + volumes = np.stack([make_particle(objects[label], rotation, tuple(shift), wedge, noise_sigma, rng) for label, rotation, shift, wedge in zip(labels, rotations, shifts, wedges)]) + directory.mkdir(parents=True, exist_ok=True) + index = [] + for tomogram in range(3): + rows = np.arange(tomogram, n, 3) + np.save(directory / f't{tomogram}.npy', volumes[rows]) + index += [(f't{tomogram}', row) for row in range(len(rows))] + order = np.concatenate([np.arange(t, n, 3) for t in range(3)]) # store index i holds particle order[i] + store = ParticleStore(Subvolumes(directory, index, box), [orientations[i] for i in order], tilt_max, 90.0) + return SyntheticSet(store, labels[order], rotations[order], shifts[order]) diff --git a/tests/unit/test_adapters.py b/tests/unit/test_adapters.py index 471d4f3..7be53d4 100644 --- a/tests/unit/test_adapters.py +++ b/tests/unit/test_adapters.py @@ -37,11 +37,9 @@ def test_capability_metadata(self) -> None: assert MOCK_ADAPTERS['domainfit'].mac_compatible is True assert MOCK_ADAPTERS['relion'].mac_compatible is False assert MOCK_ADAPTERS['relion'].requires_gpu is True - assert MOCK_ADAPTERS['stamp-native'].mac_compatible is True def test_all_nine_tools_present(self) -> None: expected = { - 'stamp-native', 'membrain-pick', 'pytom-match-pick', 'tomotwin', @@ -50,4 +48,45 @@ def test_all_nine_tools_present(self) -> None: 'm-refine', 'domainfit', } - assert set(MOCK_ADAPTERS) == expected \ No newline at end of file + assert set(MOCK_ADAPTERS) == expected + +# _relion_matrix: RELION 5 Euler::anglesToMatrix3 (jaz/math/Euler_angles_relion.h), the matrix mapping particle space to tomogram space +def _relion_matrix(rot: float, tilt: float, psi: float): + import numpy as np + p, t, c = np.radians([rot, tilt, psi]) + sp, cp, st, ct, sc, cc = np.sin(p), np.cos(p), np.sin(t), np.cos(t), np.sin(c), np.cos(c) + return np.array([[cc * ct * cp - sc * sp, cc * ct * sp + sc * cp, -cc * st], [-sc * ct * cp - cc * sp, -sc * ct * sp + cc * cp, sc * st], [st * cp, st * sp, ct]]) + +# TestRelionPoses: class containing tests for writing class poses into RELION particle files +class TestRelionPoses: + def test_euler_angles_round_trip(self) -> None: + import numpy as np + from scipy.spatial.transform import Rotation + from stamp.adapters.relion import relion_euler_angles + for seed in range(5): + rotation = Rotation.random(random_state=seed).as_matrix() + rot, tilt, psi = relion_euler_angles(rotation) + assert np.allclose(_relion_matrix(rot, tilt, psi), rotation) + assert 0.0 <= tilt <= 180.0 + + def test_pose_is_composed_with_the_box_orientation_and_origin_is_in_angstrom(self) -> None: + import numpy as np + from scipy.spatial.transform import Rotation + from stamp.adapters.relion import pose_to_relion + from stamp.classify.frames import azimuth_matrix, rotation_to_quaternion + orientation = rotation_to_quaternion(Rotation.from_euler('y', 90, degrees=True).as_matrix()) + row = pose_to_relion(orientation, (azimuth_matrix(30.0), np.array([2.0, 0.0, 0.0])), 5.0) + composed = Rotation.from_euler('y', 90, degrees=True).as_matrix() @ azimuth_matrix(30.0) + assert np.allclose(_relion_matrix(row['rlnAngleRot'], row['rlnAngleTilt'], row['rlnAnglePsi']), composed) + # a 2 voxel box x shift is -z in the tomogram under this orientation, the origin is the negative of it, 5 A per voxel + assert np.allclose([row['rlnOriginXAngst'], row['rlnOriginYAngst'], row['rlnOriginZAngst']], [0.0, 0.0, 10.0], atol=1e-6) + + def test_star_carries_poses_when_given_and_priors_otherwise(self, tmp_path: Path) -> None: + import numpy as np, starfile + from stamp.adapters.relion import RelionRefineAdapter + from stamp.schemas.particles import HalfSet, Particle + make = lambda i: Particle(particle_id=f'p{i}', tomogram_id='t', position=(1.0, 2.0, 3.0), orientation=(1.0, 0.0, 0.0, 0.0), source_picker='x', half_set=HalfSet.A) + RelionRefineAdapter().write_particle_star([make(0), make(1)], tmp_path / 'p.star', {}, poses={'p0': (np.eye(3), np.zeros(3))}, voxel_size_angstrom=4.0) + table = starfile.read(tmp_path / 'p.star').set_index('rlnTomoParticleName') + assert 'rlnOriginXAngst' in table.columns and table.loc['p0', 'rlnOriginXAngst'] == 0.0 + assert table.loc['p1', 'rlnAngleTiltPrior'] == 0.0 # no pose for p1, so the old normal-derived prior path diff --git a/tests/unit/test_classify.py b/tests/unit/test_classify.py index 4ee17e9..b7640a0 100644 --- a/tests/unit/test_classify.py +++ b/tests/unit/test_classify.py @@ -6,45 +6,74 @@ import mrcfile, numpy as np, pytest from pathlib import Path from scipy.ndimage import gaussian_filter, rotate +from scipy.spatial.transform import Rotation # Import internal STAMP objects -from stamp.classify.align import align_inplane, roll_about_normal -from stamp.classify.cluster import ( - ClusteringConfig, - label_to_cluster_id, - match_clusters_across_halves, - reduce_and_cluster, - reduce_features, - reduce_and_cluster_shared, -) -from stamp.classify.extract import ( - box_fits_inside, - canonical_grid, - extract_particle_set, - extract_subvolume, - quaternion_to_matrix, -) +from stamp.classify.align import roll_about_normal +from stamp.classify.average import weighted_average +from stamp.classify.cluster import ClusteringConfig, label_to_cluster_id, reduce_and_cluster, reduce_features +from stamp.classify.extract import box_fits_inside, canonical_grid, extract_particle_set, extract_subvolume, quaternion_to_matrix from stamp.classify.features import azimuthal_magnitudes, build_feature_matrix, cylindrical_bins, rotational_average -from stamp.commands.classify import _classify_combined +from stamp.classify.frames import azimuth_degrees, azimuth_matrix, flip_matrix, rotate_density, rotation_to_quaternion +from stamp.classify.halves import express_in_frame_of_a, run_polish_by_half +from stamp.classify.match import align_to_reference, rank_rotations, wedge_filter +from stamp.classify.merge import half_split_ceilings, merge_groups, pair_thresholds, pairwise_similarity +from stamp.classify.null import null_bar, null_threshold +from stamp.classify.polish import PolishConfig, run_polish +from stamp.classify.prepare import fourier_bin, normalise, prepare_particle, soft_mask, working_box +from stamp.classify.references import hard_assign, rebuild_references, score_against_refs +from stamp.classify.search import rotated_bank, search_space +from stamp.classify.shfeatures import build_sh_feature_matrix, sh_power +from stamp.classify.spherical import fit_matrix, lm_pairs, real_sh_basis, sphere_grid +from stamp.classify.store import ParticleStore, build_store +from stamp.classify.wedge import apply_wedge, box_wedge, observed_directions from stamp.picking.geometry import quaternion_from_reference_to -from stamp.schemas.particles import HalfSet, Particle +from stamp.schemas.particles import HalfSet, OrientationPrior, Particle from stamp.schemas.subvolumes import Subvolumes +from synthetic import asymmetric_object, make_particle, rod_object, synthetic_set -# _subvols_from_array: write a dense subvolume stack to a single-tomogram cache and wrap it as a Subvolumes subvols -def _subvols_from_array(tmp_path: Path, array: np.ndarray) -> Subvolumes: - tmp_path.mkdir(parents=True, exist_ok=True) - box_voxels = array.shape[-1] - np.save(tmp_path / 'tomo000.npy', np.asarray(array, dtype=np.float32)) - index = [('tomo000', i) for i in range(array.shape[0])] - return Subvolumes(tmp_path, index, box_voxels) +# _BOX: working box edge for alignment tests +_BOX = 25 + +# _BOX: working box edge for reference scoring tests +_REF_BOX = 21 -# _three_blobs: three well-separated Gaussian blobs in 2D -def _three_blobs(n_per_group: int = 40, seed: int = 0) -> np.ndarray: - rng = np.random.default_rng(seed) - centres = np.array([[0.0, 0.0], [20.0, 0.0], [0.0, 20.0]]) - return np.vstack( - [rng.normal(centre, 1.0, size=(n_per_group, 2)) for centre in centres] - ) + +# _aligned_cc: normalised correlation of two volumes +def _aligned_cc(a: np.ndarray, b: np.ndarray) -> float: + return float((a * b).sum() / (np.linalg.norm(a) * np.linalg.norm(b))) + +# _angle_error: absolute difference of two angles in degrees, wrapped to [0, 180] +def _angle_error(a: np.ndarray, b: np.ndarray) -> np.ndarray: + return np.abs((a - b + 180.0) % 360.0 - 180.0) + +# _asymmetric_blob: a subvolume with a clear azimuthal feature (an off-axis lobe) +def _asymmetric_blob(box: int) -> np.ndarray: + volume = np.zeros((box, box, box)) + volume[box // 2 + 4, box // 2, box // 2] = 1.0 + volume[box // 2, box // 2, box // 2] = 1.0 + return gaussian_filter(volume, 1.5) + +# _blob: volume with one gaussian blob at the given integer index +def _blob(shape: tuple[int, int, int], index: tuple[int, int, int]) -> np.ndarray: + volume = np.zeros(shape, dtype=np.float32) + volume[index] = 1.0 + return gaussian_filter(volume, 1.0) + +# _brute_wedge: explicit triple loop, tomogram-frame vectors from the rotation matrix, tilt about the axis at tilt_axis_degrees +def _brute_wedge(box: int, orientation, tilt_max: float, tilt_axis: float) -> np.ndarray: + rotation = np.eye(3) if orientation is None else quaternion_to_matrix(orientation) + axis = np.radians(tilt_axis) + direction = np.array([np.cos(axis), np.sin(axis), 0.0]) # tilt axis itself + freq = np.fft.fftfreq(box) + out = np.zeros((box,) * 3, dtype=np.float32) + for i in range(box): + for j in range(box): + for k in range(box): + tomo = rotation @ np.array([freq[i], freq[j], freq[k]]) + across = np.sqrt(max(tomo[0] ** 2 + tomo[1] ** 2 - (tomo @ direction) ** 2, 0.0)) # in-plane component perpendicular to the tilt axis + out[i, j, k] = abs(tomo[2]) <= across * np.tan(np.radians(tilt_max)) + 1e-12 + return out # _c_n_particle: a ring of n_fold blobs above the canonical mid-plane (idealised C-n oligomer on a membrane) def _c_n_particle(box: int = 25, n_fold: int = 4, radius: float = 6.0) -> np.ndarray: @@ -59,16 +88,178 @@ def _c_n_particle(box: int = 25, n_fold: int = 4, radius: float = 6.0) -> np.nda volume[x - 1 : x + 2, y - 1 : y + 2, z_plane - 1 : z_plane + 2] = 1.0 return volume +# _concatenate: one store from the volumes of two synthetic sets +def _concatenate(directory: Path, first, second): + from stamp.classify.store import ParticleStore + from stamp.schemas.subvolumes import Subvolumes + directory.mkdir(parents=True) + volumes = [np.stack([s.store.volumes[i] for i in range(len(s.store))]) for s in (first, second)] + np.save(directory / 'all.npy', np.concatenate(volumes)) + total = sum(len(v) for v in volumes) + return ParticleStore(Subvolumes(directory, [('all', i) for i in range(total)], _BOX), first.store.orientations + second.store.orientations, first.store.tilt_max_degrees, first.store.tilt_axis_degrees) + +# _config: small polish settings for fast tests +def _config(prior: OrientationPrior, **overrides) -> PolishConfig: + return PolishConfig(prior=prior, angular_step_degrees=15.0, n_rotations=250, shift_range_voxels=2, min_seed_size=10, **overrides) + +# _corrupted_seeds: true labels with a fraction replaced by a random class, plus an embedding in which seeds sit near their class +def _corrupted_seeds(truth: np.ndarray, fraction: float, seed: int) -> tuple[np.ndarray, np.ndarray]: + rng = np.random.default_rng(seed) + seeds = truth.copy() + wrong = rng.random(len(truth)) < fraction + seeds[wrong] = rng.integers(0, truth.max() + 1, wrong.sum()) + embedding = np.eye(truth.max() + 1)[seeds] + rng.normal(0, 0.1, (len(truth), truth.max() + 1)) + return seeds, embedding + +# _peak: index of the maximum of a volume +def _peak(volume: np.ndarray) -> tuple[int, ...]: + return tuple(int(i) for i in np.unravel_index(volume.argmax(), volume.shape)) + +# _purity: fraction of accepted particles whose cluster's majority class is their own class +def _purity(labels: np.ndarray, truth: np.ndarray) -> float: + accepted = labels >= 0 + hits = sum(np.bincount(truth[labels == k]).max() for k in np.unique(labels[accepted])) + return float(hits / accepted.sum()) + +# _random_orientation: unit quaternion mapping +z onto a random direction within 60 degrees of the beam-orthogonal plane +def _random_orientation(rng: np.random.Generator) -> tuple[float, float, float, float]: + vector = rng.normal(size=3) + vector[2] *= 0.5 + return quaternion_from_reference_to(vector / np.linalg.norm(vector)) + # _rotate_in_plane: rotate a canonical (x, y, z) volume in-plane about axes (0, 1) def _rotate_in_plane(volume: np.ndarray, degrees: float) -> np.ndarray: return rotate(volume, angle=degrees, axes=(0, 1), reshape=False, order=1) -# _asymmetric_blob: a subvolume with a clear azimuthal feature (an off-axis lobe) -def _asymmetric_blob(box: int) -> np.ndarray: - volume = np.zeros((box, box, box)) - volume[box // 2 + 4, box // 2, box // 2] = 1.0 - volume[box // 2, box // 2, box // 2] = 1.0 - return gaussian_filter(volume, 1.5) +# _subvols_from_array: write a dense subvolume stack to a single-tomogram cache and wrap it as a Subvolumes subvols +def _subvols_from_array(tmp_path: Path, array: np.ndarray) -> Subvolumes: + tmp_path.mkdir(parents=True, exist_ok=True) + box_voxels = array.shape[-1] + np.save(tmp_path / 'tomo000.npy', np.asarray(array, dtype=np.float32)) + index = [('tomo000', i) for i in range(array.shape[0])] + return Subvolumes(tmp_path, index, box_voxels) + +# _three_blobs: three well-separated Gaussian blobs in 2D +def _three_blobs(n_per_group: int = 40, seed: int = 0) -> np.ndarray: + rng = np.random.default_rng(seed) + centres = np.array([[0.0, 0.0], [20.0, 0.0], [0.0, 20.0]]) + return np.vstack( + [rng.normal(centre, 1.0, size=(n_per_group, 2)) for centre in centres] + ) + +# _nearest_neighbour_accuracy: fraction of rows whose nearest other row has the same label +def _nearest_neighbour_accuracy(features: np.ndarray, labels: np.ndarray) -> float: + distances = np.linalg.norm(features[:, None] - features[None], axis=2) + np.fill_diagonal(distances, np.inf) + return float((labels[distances.argmin(axis=1)] == labels).mean()) + +# _split: interleaved halves of a synthetic set with seeds from the true labels, and the store +def _split(data): + n = len(data.labels) + indices = {'A': list(range(0, n, 2)), 'B': list(range(1, n, 2))} + seeds = {h: data.labels[i] for h, i in indices.items()} + embeddings = {h: np.eye(2)[seeds[h]] + np.random.default_rng(0).normal(0, 0.05, (len(seeds[h]), 2)) for h in indices} + return indices, embeddings, seeds + +# TestAverage: class containing tests for subvolume averages +class TestAverage: + # test_weighted_average_beats_plain_mean: on wedged particles of known pose the coverage-corrected average is closer to the truth than the plain mean of the aligned particles, for every prior + @pytest.mark.parametrize('prior', ['normal', 'axis', 'none']) + def test_weighted_average_beats_plain_mean(self, prior: str) -> None: + from stamp.classify.average import weighted_average + from stamp.classify.frames import azimuth_matrix, flip_matrix, rotate_density + from stamp.classify.wedge import box_wedge + from scipy.spatial.transform import Rotation + from synthetic import asymmetric_object, make_particle, rod_object + box, n = 25, 60 + rng = np.random.default_rng(8) + obj = rod_object(box, 1, repeat=box) if prior == 'axis' else asymmetric_object(box, 1) + if prior == 'none': + rotations = Rotation.random(n, random_state=1).as_matrix() + wedges = np.stack([box_wedge(box, None, 35.0, 90.0)] * n) + else: + flips = [flip_matrix() if prior == 'axis' and rng.random() < 0.5 else np.eye(3) for _ in range(n)] + rotations = np.stack([azimuth_matrix(a) @ f for a, f in zip(rng.uniform(0, 360, n), flips)]) + wedges = np.stack([box_wedge(box, quaternion_from_reference_to(rng.normal(size=3)), 35.0, 90.0) for _ in range(n)]) + shifts = rng.integers(-2, 3, (n, 3)) * (np.array([0, 0, 1]) if prior == 'axis' else 1) + particles = np.stack([make_particle(obj, r, tuple(s), w, 0.02, rng) for r, s, w in zip(rotations, shifts, wedges)]) + weighted = weighted_average(particles, wedges, rotations, shifts) + plain = np.mean([rotate_density(np.roll(p, -s, axis=(0, 1, 2)), r.T) for p, r, s in zip(particles, rotations, shifts)], axis=0) + assert _aligned_cc(weighted, obj) > _aligned_cc(plain, obj) + +# TestCluster: class containing unit tests for src/stamp/classify/cluster.py +class TestCluster: + def test_hdbscan_recovers_three_groups(self) -> None: + '''HDBSCAN finds three groups in three-blob data.''' + result = reduce_and_cluster( + _three_blobs(), + ClusteringConfig(method='hdbscan', n_components=2, min_cluster_size=10), + ) + real_labels = {label for label in result.labels if label != -1} + assert len(real_labels) == 3 + + def test_kmeans_respects_requested_cluster_count(self) -> None: + '''KMeans returns exactly n_clusters groups.''' + result = reduce_and_cluster( + _three_blobs(), ClusteringConfig(method='kmeans', n_components=2, n_clusters=3) + ) + assert len(set(result.labels)) == 3 + + def test_pca_components_capped_by_sample_count(self) -> None: + '''N_components is capped at what the data supports.''' + features = np.random.default_rng(0).normal(size=(5, 100)) + embedding, explained = reduce_features(features, ClusteringConfig(n_components=50)) + assert embedding.shape[1] <= 4 + assert explained.shape == (embedding.shape[1],) + + def test_too_few_particles_raises(self) -> None: + '''A single particle raises a clear error.''' + with pytest.raises(ValueError, match='Too few particles'): + reduce_features(np.zeros((1, 10)), ClusteringConfig()) + + def test_hdbscan_below_min_cluster_size_raises_clearly(self) -> None: + '''Too few particles for min_cluster_size raises.''' + with pytest.raises(ValueError, match='min_cluster_size'): + reduce_and_cluster( + np.random.default_rng(0).normal(size=(5, 10)), + ClusteringConfig(method='hdbscan', min_cluster_size=20), + ) + + def test_noise_label_becomes_named_id(self) -> None: + '''Label -1 becomes 'noise', other labels become 'cNN'.''' + assert label_to_cluster_id(-1) == 'noise' + assert label_to_cluster_id(3) == 'c03' + + # test_leiden_finds_blobs_and_applies_min_size: three well separated blobs give three clusters, and communities under min_cluster_size are noise + def test_leiden_finds_blobs_and_applies_min_size(self) -> None: + rng = np.random.default_rng(0) + centres = np.array([[0.0] * 5, [8.0] * 5, [-8.0, 8.0, -8.0, 8.0, -8.0]]) + features = np.vstack([rng.normal(c, 1.0, (40, 5)) for c in centres]) + result = reduce_and_cluster(features, ClusteringConfig(method='leiden', n_components=5, min_cluster_size=10)) + assert result.labels.max() == 2 and all(len(set(result.labels[i * 40:(i + 1) * 40])) == 1 for i in range(3)) + assert set(result.centroids) == {0, 1, 2} + assert (reduce_and_cluster(features, ClusteringConfig(method='leiden', n_components=5, min_cluster_size=50)).labels == -1).all() + + # test_leiden_is_reproducible: same seed, same partition + def test_leiden_is_reproducible(self) -> None: + features = np.random.default_rng(1).normal(size=(120, 6)) + config = ClusteringConfig(method='leiden', n_components=4, min_cluster_size=5, random_state=3) + assert np.array_equal(reduce_and_cluster(features, config).labels, reduce_and_cluster(features, config).labels) + + # test_seed_purity_per_prior: Leiden on the prior's features separates two distinct structures into pure seeds, wedge and random pose included + @pytest.mark.parametrize('prior', [OrientationPrior.NORMAL, OrientationPrior.AXIS, OrientationPrior.NONE]) + def test_seed_purity_per_prior(self, tmp_path: Path, prior: OrientationPrior) -> None: + box = 25 + objects = [rod_object(box, s, repeat=box) if prior is OrientationPrior.AXIS else asymmetric_object(box, s) for s in (1, 2)] + data = synthetic_set(tmp_path, objects, prior, 40, noise_sigma=0.1, seed=11, max_shift=1) + if prior is OrientationPrior.NONE: + features = build_sh_feature_matrix(data.store.volumes, 60.0, 90.0) + else: + features = build_feature_matrix(data.store.volumes, n_radial_bins=6, max_azimuthal_mode=3, n_azimuthal_samples=32, axial_invariant=prior is OrientationPrior.AXIS) + labels = reduce_and_cluster(features, ClusteringConfig(n_components=8, min_cluster_size=10)).labels + seeded = labels >= 0 + purity = sum(np.bincount(data.labels[labels == k]).max() for k in np.unique(labels[seeded])) / seeded.sum() + assert seeded.mean() > 0.8 and purity >= 0.9 # TestExtract: class containing unit tests for src/stamp/classify/extract.py class TestExtract: @@ -195,6 +386,20 @@ def test_aborted_extraction_resumes_without_recomputing(self, tmp_path, monkeypa extract_particle_set(particles, paths, 13, cache_dir=cache) assert sorted(calls) == ['a', 'b'] + # test_none_prior_extracts_axis_aligned_boxes_without_orientation: particles without an orientation are kept and the box ignores any reported orientation + def test_none_prior_extracts_axis_aligned_boxes_without_orientation(self, tmp_path: Path) -> None: + volume = np.zeros((40, 40, 40), dtype=np.float32) + volume[20, 20, 26] = 1.0 # zyx: 6 voxels along +x of the particle at (20, 20, 20) + with mrcfile.new(tmp_path / 't0.mrc', overwrite=True) as mrc: + mrc.set_data(volume) + plain = Particle(particle_id='a', tomogram_id='t0', position=(20.0, 20.0, 20.0), source_picker='x', half_set=HalfSet.A) + tilted = plain.model_copy(update={'particle_id': 'b', 'orientation': quaternion_from_reference_to(np.array([1.0, 0.0, 1.0]))}) + subvols, kept, skipped = extract_particle_set([plain, tilted], {'t0': str(tmp_path / 't0.mrc')}, 17, cache_dir=tmp_path / 'cache', prior=OrientationPrior.NONE) + assert len(kept) == 2 and not skipped + assert all(tuple(np.unravel_index(subvols[i].argmax(), subvols[i].shape)) == (14, 8, 8) for i in range(2)) + _, kept_normal, skipped_normal = extract_particle_set([plain], {'t0': str(tmp_path / 't0.mrc')}, 17, cache_dir=tmp_path / 'cache2') + assert not kept_normal and len(skipped_normal) == 1 + # TestFeatures: class containing unit tests for src/stamp/classify/features.py class TestFeatures: def test_rotational_average_shape(self) -> None: @@ -380,182 +585,425 @@ def test_unknown_normalisation_is_rejected(self, tmp_path: Path) -> None: with pytest.raises(ValueError, match='normalisation'): build_feature_matrix(subvols, n_radial_bins=4, normalisation='bogus') -# TestCluster: class containing unit tests for src/stamp/classify/cluster.py -class TestCluster: - def test_hdbscan_recovers_three_groups(self) -> None: - '''HDBSCAN finds three groups in three-blob data.''' - result = reduce_and_cluster( - _three_blobs(), - ClusteringConfig(method='hdbscan', n_components=2, min_cluster_size=10), - ) - real_labels = {label for label in result.labels if label != -1} - assert len(real_labels) == 3 - - def test_kmeans_respects_requested_cluster_count(self) -> None: - '''KMeans returns exactly n_clusters groups.''' - result = reduce_and_cluster( - _three_blobs(), ClusteringConfig(method='kmeans', n_components=2, n_clusters=3) - ) - assert len(set(result.labels)) == 3 - - def test_pca_components_capped_by_sample_count(self) -> None: - '''N_components is capped at what the data supports.''' - features = np.random.default_rng(0).normal(size=(5, 100)) - embedding, explained = reduce_features(features, ClusteringConfig(n_components=50)) - assert embedding.shape[1] <= 4 - assert explained.shape == (embedding.shape[1],) - - def test_too_few_particles_raises(self) -> None: - '''A single particle raises a clear error.''' - with pytest.raises(ValueError, match='Too few particles'): - reduce_features(np.zeros((1, 10)), ClusteringConfig()) - - def test_hdbscan_below_min_cluster_size_raises_clearly(self) -> None: - '''Too few particles for min_cluster_size raises.''' - with pytest.raises(ValueError, match='min_cluster_size'): - reduce_and_cluster( - np.random.default_rng(0).normal(size=(5, 10)), - ClusteringConfig(method='hdbscan', min_cluster_size=20), - ) - - def test_noise_label_becomes_named_id(self) -> None: - '''Label -1 becomes 'noise', other labels become 'cNN'.''' - assert label_to_cluster_id(-1) == 'noise' - assert label_to_cluster_id(3) == 'c03' - - def test_cluster_matching_pairs_nearest_centroids(self) -> None: - '''Cross-half matching pairs the nearest centroids.''' - centroids_a = {0: np.array([0.0, 0.0]), 1: np.array([10.0, 0.0])} - centroids_b = {0: np.array([10.2, 0.1]), 1: np.array([0.1, 0.2])} - matches = match_clusters_across_halves(centroids_a, centroids_b) - assert matches[0][0] == 1 - assert matches[1][0] == 0 - - def test_cluster_matching_uses_each_a_cluster_once(self) -> None: - '''A half-A cluster is matched at most once.''' - centroids_a = {0: np.array([0.0, 0.0])} - centroids_b = {0: np.array([0.1, 0.0]), 1: np.array([0.2, 0.0])} - matches = match_clusters_across_halves(centroids_a, centroids_b) - assert len([m for m in matches.values() if m[0] == 0]) == 1 - - def test_shared_basis_matches_recover_planted_split(self): - '''Two motifs, each split A/B, match A<->B correctly.''' + # test_axial_features_ignore_azimuth_and_axial_shift: rods of two kinds at random azimuth and axial position group by kind with axial_invariant, and by position without it + def test_axial_features_ignore_azimuth_and_axial_shift(self, tmp_path: Path) -> None: + box, rng = 25, np.random.default_rng(0) + rods = [rod_object(box, seed, repeat=box) for seed in (3, 4)] + labels = np.repeat([0, 1], 15) + volumes = [roll_about_normal(np.roll(rods[k], int(rng.integers(0, box)), axis=2), float(rng.uniform(0, 360))) for k in labels] + subvols = _subvols_from_array(tmp_path, np.stack(volumes)) + kwargs = dict(n_radial_bins=6, max_azimuthal_mode=3, n_azimuthal_samples=32, normalisation='both') + assert _nearest_neighbour_accuracy(build_feature_matrix(subvols, axial_invariant=True, **kwargs), labels) >= 0.95 + assert _nearest_neighbour_accuracy(build_feature_matrix(subvols, **kwargs), labels) < 0.9 + +# TestFrames: class containing tests for frame and rotation conventions +class TestFrames: + # test_rotate_density_moves_features_by_the_matrix: a feature at +x moves to +y under a +90 degree azimuth and to -z under the flip + def test_rotate_density_moves_features_by_the_matrix(self) -> None: + volume = _blob((15, 15, 15), (10, 7, 9)) # offset (+3, 0, +2) from the centre + assert _peak(rotate_density(volume, azimuth_matrix(90.0))) == (7, 10, 9) + assert _peak(rotate_density(volume, flip_matrix())) == (10, 7, 5) + + # test_roll_about_normal_is_azimuth_matrix: the existing scipy roll equals rotate_density with azimuth_matrix for random angles + def test_roll_about_normal_is_azimuth_matrix(self) -> None: rng = np.random.default_rng(0) - motif_a = rng.normal(0.0, 1.0, 40) - motif_b = rng.normal(5.0, 1.0, 40) - rows, group_a, group_b = [], [], [] - for i in range(40): - rows.append(motif_a + rng.normal(0, 0.1, 40)); (group_a if i % 2 else group_b).append(len(rows) - 1) - for i in range(40): - rows.append(motif_b + rng.normal(0, 0.1, 40)); (group_a if i % 2 else group_b).append(len(rows) - 1) - features = np.array(rows) - config = ClusteringConfig(method='kmeans', n_clusters=2, n_components=5) - results = reduce_and_cluster_shared(features, {'A': np.array(group_a), 'B': np.array(group_b)}, config) - matches = match_clusters_across_halves(results['A'].centroids, results['B'].centroids) - assert len(matches) == 2 and all(d < 1.0 for _, d in matches.values()) - -# TestAlign: class containing unit tests for src/stamp/classify/align.py -class TestAlign: - def test_recovers_planted_rolls(self, tmp_path: Path): - '''Rolled copies of one motif align back to a common frame.''' - box = 21 - base = _asymmetric_blob(box) - planted = [0.0, 40.0, 120.0, 250.0, 300.0] - stack = np.stack([roll_about_normal(base, angle) for angle in planted]) - subvols = _subvols_from_array(tmp_path, stack) - angles = align_inplane(subvols, ['c00'] * len(planted), angular_step_degrees=10.0, iterations=4) - - aligned = np.stack([roll_about_normal(stack[i], angles[i]) for i in range(len(planted))]) - reference = aligned.mean(axis=0) - for frame in aligned: - assert np.corrcoef(frame.ravel(), reference.ravel())[0, 1] > 0.98 - - def test_alignment_checkpoint_resumes_per_cluster(self, tmp_path: Path, monkeypatch) -> None: - from stamp.classify import align as align_module - stack = np.random.default_rng(0).random((6, 15, 15, 15)) - subvols = _subvols_from_array(tmp_path / 'sv', stack) - cluster_ids = ['c00', 'c00', 'c00', 'c01', 'c01', 'c01'] - checkpoint = tmp_path / 'align' - first = align_inplane(subvols, cluster_ids, checkpoint_dir=checkpoint) - assert sorted(p.name for p in checkpoint.glob('*.json')) == ['c00.json', 'c01.json'] - - # simulate an abort before c01 finished - (checkpoint / 'c01.json').unlink() - aligned_clusters: list[list[int]] = [] - original = align_module._align_one_cluster - monkeypatch.setattr(align_module, '_align_one_cluster', lambda job: (aligned_clusters.append(job.member_indices), original(job))[1]) - assert align_inplane(subvols, cluster_ids, checkpoint_dir=checkpoint) == first - assert aligned_clusters == [[3, 4, 5]] - - # a cluster whose membership changed is recomputed - aligned_clusters.clear() - align_inplane(subvols, ['c00', 'c00', 'c01', 'c01', 'c01', 'c01'], checkpoint_dir=checkpoint) - assert sorted(aligned_clusters) == [[0, 1], [2, 3, 4, 5]] - - def test_noise_cluster_skipped(self, tmp_path: Path): - '''Noise rows get no angle.''' - stack = np.random.default_rng(0).random((4, 15, 15, 15)) - subvols = _subvols_from_array(tmp_path, stack) - angles = align_inplane(subvols, ['noise', 'noise', 'c00', 'c00']) - assert set(angles) == {2, 3} - -# TestVesicle: class containing unit tests for vesicle_id carry-through in classification -class TestVesicle: - def test_class_assignment_carries_vesicle_id(self, tmp_path: Path) -> None: - '''vesicle_id on a Particle survives unchanged into its ClassAssignment''' + volume = gaussian_filter(rng.normal(size=(17, 17, 17)).astype(np.float32), 2.0) + for angle in rng.uniform(-180, 180, 5): + rolled = roll_about_normal(volume, float(angle)) + moved = rotate_density(volume, azimuth_matrix(float(angle))) + inside = np.s_[4:-4, 4:-4, 4:-4] + assert np.allclose(rolled[inside], moved[inside], atol=1e-3) + + # test_azimuth_degrees_inverts_azimuth_matrix: angle round trip across the full range + def test_azimuth_degrees_inverts_azimuth_matrix(self) -> None: + for angle in (-170.0, -45.0, 0.0, 30.0, 179.0): + assert np.isclose(azimuth_degrees(azimuth_matrix(angle)), angle) + + # test_rotation_to_quaternion_round_trip: quaternion_to_matrix recovers the matrix, w is non-negative + def test_rotation_to_quaternion_round_trip(self) -> None: + rotation = azimuth_matrix(70.0) @ flip_matrix() + quaternion = rotation_to_quaternion(rotation) + assert quaternion[0] >= 0 and np.allclose(quaternion_to_matrix(quaternion), rotation) + + # test_off_axis_density_lands_on_the_normal: a density planted 8 voxels along a tilted normal sits on +z of the extracted box + def test_off_axis_density_lands_on_the_normal(self) -> None: + normal = np.array([0.6, 0.0, 0.8]) + position = np.array([30.0, 30.0, 30.0]) + tomogram = np.zeros((61, 61, 61), dtype=np.float32) # zyx array + target_xyz = position + 8.0 * normal + tomogram[int(round(target_xyz[2])), int(round(target_xyz[1])), int(round(target_xyz[0]))] = 1.0 + tomogram = gaussian_filter(tomogram, 1.0) + quaternion = quaternion_from_reference_to(normal) + box = extract_subvolume(tomogram, tuple(position), quaternion, 21) + assert _peak(box) == (10, 10, 18) # centre 10, plus 8 along +z + +# TestHalves: class containing unit tests for src/stamp/classify/halves.py +class TestHalves: + # test_half_a_does_not_read_half_b: replacing every half-B particle with noise leaves the half-A result bit-identical to the run that saw the real half B + def test_half_a_does_not_read_half_b(self, tmp_path: Path) -> None: + objects = [asymmetric_object(_REF_BOX, 1), asymmetric_object(_REF_BOX, 2)] + data = synthetic_set(tmp_path / 'data', objects, OrientationPrior.NORMAL, 30, seed=2) + indices, embeddings, seeds = _split(data) + real, _ = run_polish_by_half(data.store, indices, embeddings, seeds, _config(OrientationPrior.NORMAL)) + volumes = np.stack([data.store.volumes[i] for i in range(len(data.store))]) + volumes[indices['B']] = np.random.default_rng(9).normal(size=volumes[indices['B']].shape) + perturbed_dir = tmp_path / 'perturbed' + perturbed_dir.mkdir() + np.save(perturbed_dir / 'all.npy', volumes) + perturbed = ParticleStore(Subvolumes(perturbed_dir, [('all', i) for i in range(len(volumes))], _REF_BOX), data.store.orientations, data.store.tilt_max_degrees, data.store.tilt_axis_degrees) + alone = run_polish(perturbed.take(indices['A']), embeddings['A'], seeds['A'], _config(OrientationPrior.NORMAL)) # half B never enters + assert np.array_equal(real['A'].labels, alone.labels) and np.array_equal(real['A'].rotations, alone.rotations) + assert all(np.array_equal(a, b) for a, b in zip(real['A'].references, alone.references)) + + # test_halves_match_by_reference_and_share_a_frame: matched clusters are the same class, and half-B averages built with the re-expressed poses agree with half A + def test_halves_match_by_reference_and_share_a_frame(self, tmp_path: Path) -> None: + objects = [asymmetric_object(_REF_BOX, 1), asymmetric_object(_REF_BOX, 2)] + data = synthetic_set(tmp_path, objects, OrientationPrior.NORMAL, 40, noise_sigma=0.1, seed=3) + indices, embeddings, seeds = _split(data) + results, matches = run_polish_by_half(data.store, indices, embeddings, seeds, _config(OrientationPrior.NORMAL)) + assert len(matches) == 2 + majority = lambda half, label: np.bincount(data.labels[indices[half]][results[half].labels == label]).argmax() + assert all(majority('A', m.label_a) == majority('B', label_b) for label_b, m in matches.items()) + rotations, shifts = express_in_frame_of_a(results['B'], matches) + store_a, store_b = data.store.take(indices['A']), data.store.take(indices['B']) + for label_b, match in matches.items(): + members_b = np.where(results['B'].labels == label_b)[0] + members_a = np.where(results['A'].labels == match.label_a)[0] + average_a = weighted_average(*store_a.load(members_a), results['A'].rotations[members_a], results['A'].shifts[members_a]) + in_frame = weighted_average(*store_b.load(members_b), rotations[members_b], shifts[members_b]) + own_frame = weighted_average(*store_b.load(members_b), results['B'].rotations[members_b], results['B'].shifts[members_b]) + correlation = lambda x, y: float((x * y).sum() / np.linalg.norm(x) / np.linalg.norm(y)) + assert correlation(average_a, in_frame) > 0.6 and correlation(average_a, in_frame) > correlation(average_a, own_frame) + 0.15 + +# TestMatch: class containing unit tests for prior-aware particle alignment to reference +class TestMatch: + # test_rank_rotations_matches_masked_bank: the shared-bank score equals the brute-force score against a bank masked with each particle's own wedge + def test_rank_rotations_matches_masked_bank(self) -> None: rng = np.random.default_rng(0) - n_per_group, box = 6, 5 - centres = np.array([[0.0, 0.0], [20.0, 0.0]]) - features = np.vstack([rng.normal(centre, 1.0, size=(n_per_group, 2)) for centre in centres]) - n_particles = features.shape[0] - subvolumes = _subvols_from_array(tmp_path / 'subvolumes', np.zeros((n_particles, box, box, box), dtype=np.float32)) - - particles = [ - Particle( - particle_id=f'p{index:06d}', - tomogram_id='tomo000', - position=(0.0, 0.0, 0.0), - source_picker='stamp-native', - half_set=HalfSet.A if index % 2 == 0 else HalfSet.B, - vesicle_id=f'tomo000:v{(index % 2) + 1:04d}', - ) - for index in range(n_particles) - ] - - config = ClusteringConfig(method='kmeans', n_components=2, n_clusters=2) - align_settings = dict(enabled=False, angular_step_degrees=10.0, iterations=1) - assignments, _result_by_half, _averages_by_half = _classify_combined( - particles, subvolumes, features, config, tmp_path, voxel_size_angstrom=1.0, align_settings=align_settings, - ) - - assert len(assignments) == n_particles - for particle, assignment in zip(particles, assignments): - assert assignment.vesicle_id == particle.vesicle_id - - def test_class_assignment_vesicle_id_none_when_unset(self, tmp_path: Path) -> None: - '''Particles with no vesicle_id (default picking, no labels MRC) produce assignments with vesicle_id=None''' + reference = asymmetric_object(_BOX, 1) + space = search_space(OrientationPrior.NORMAL, _BOX, angular_step_degrees=60.0) + bank = rotated_bank(reference, space.rotations) + orientations = [_random_orientation(rng) for _ in range(3)] + wedges = np.stack([box_wedge(_BOX, o, 60.0, 90.0) for o in orientations]) + particles = np.stack([apply_wedge(rng.normal(size=(_BOX,) * 3), w) for w in wedges]) + fast, _norms = rank_rotations(wedge_filter(particles, wedges), wedges, bank, _BOX) + for i, wedge in enumerate(wedges): + for r, rotated in enumerate(bank): + masked = apply_wedge(rotated.reshape((_BOX,) * 3), wedge).ravel() + expected = (particles[i].ravel() @ masked) / (np.linalg.norm(particles[i]) * np.linalg.norm(masked)) + assert abs(fast[i, r] - expected) < 1e-3 + + # test_normal_prior_recovers_azimuth: azimuth error against known rotation, with a different wedge per particle and small shifts + def test_normal_prior_recovers_azimuth(self) -> None: + rng = np.random.default_rng(3) + reference = asymmetric_object(_BOX, 5) + space = search_space(OrientationPrior.NORMAL, _BOX, angular_step_degrees=10.0, shift_range_voxels=2) + truth = rng.uniform(0, 360, 40) + shifts = rng.integers(-1, 2, (40, 3)) + wedges = np.stack([box_wedge(_BOX, _random_orientation(rng), 60.0, 90.0) for _ in truth]) + particles = np.stack([make_particle(reference, azimuth_matrix(a), tuple(s), w, 0.05, rng) for a, s, w in zip(truth, shifts, wedges)]) + result = align_to_reference(particles, wedges, reference, space) + found = np.array([azimuth_degrees(space.rotations[i]) for i in result.rotation_index]) + error = _angle_error(found, truth) + assert np.median(error) <= 5.0 and np.percentile(error, 90) <= 10.0 + assert (result.shift == shifts).all(axis=1).mean() > 0.9 + + # test_axis_prior_recovers_azimuth_polarity_and_shift: rods with random polarity and axial offsets + def test_axis_prior_recovers_azimuth_polarity_and_shift(self) -> None: + rng = np.random.default_rng(4) + reference = rod_object(_BOX, 6, repeat=_BOX) # no helical degeneracy inside the box + space = search_space(OrientationPrior.AXIS, _BOX, angular_step_degrees=15.0) + n = 30 + azimuth = rng.uniform(0, 360, n) + flipped = rng.random(n) < 0.5 + axial = rng.integers(-5, 6, n) + wedges = np.stack([box_wedge(_BOX, _random_orientation(rng), 60.0, 90.0) for _ in range(n)]) + particles = np.stack([ + make_particle(reference, azimuth_matrix(a) @ (flip_matrix() if f else np.eye(3)), (0, 0, z), w, 0.05, rng) + for a, f, z, w in zip(azimuth, flipped, axial, wedges) + ]) + result = align_to_reference(particles, wedges, reference, space) + found_flip = space.polarity[result.rotation_index] < 0 + assert (found_flip == flipped).mean() >= 0.95 + assert (np.abs(result.shift[:, 2] - axial) <= 1).mean() >= 0.9 + found_azimuth = np.array([azimuth_degrees(space.rotations[i] @ (flip_matrix() if f else np.eye(3))) for i, f in zip(result.rotation_index, found_flip)]) + assert np.median(_angle_error(found_azimuth, azimuth)) <= 8.0 + + # test_none_prior_recovers_bank_rotation: a wedged rotated copy finds its own rotation in a noiseless bank (regression for the original brute-force search) + def test_none_prior_recovers_bank_rotation(self) -> None: + reference = asymmetric_object(_BOX, 7) + space = search_space(OrientationPrior.NONE, _BOX, n_rotations=200, shift_range_voxels=1) + wedge = box_wedge(_BOX, None, 60.0, 90.0) + target = 123 + particle = apply_wedge(rotate_density(reference, space.rotations[target]), wedge) + result = align_to_reference(particle[None], wedge[None], reference, space, top=5) + assert result.rotation_index[0] == target and result.cc[0] > 0.95 and not result.shift.any() + +# TestMerge: class containing unit tests for half-split ceilings, merging and phase-randomised null +class TestMerge: + # test_pair_threshold_ignores_inconsistent_reference: a junk reference with a low ceiling cannot lower the merge bar for real ones + def test_pair_threshold_ignores_inconsistent_reference(self) -> None: + similarity = np.array([[1.0, 0.5, 0.4], [0.5, 1.0, 0.4], [0.4, 0.4, 1.0]]) + assert len(np.unique(merge_groups(similarity, pair_thresholds(np.array([0.9, 0.9, 0.2]), 1.0)))) == 3 + + # test_merge_groups_joins_chains: similarity at or above the threshold links references transitively + def test_merge_groups_joins_chains(self) -> None: + similarity = np.array([[1.0, 0.9, 0.1], [0.9, 1.0, 0.9], [0.1, 0.9, 1.0]]) + assert len(np.unique(merge_groups(similarity, 0.8))) == 1 + + # test_rotated_copy_is_the_same_reference: a reference and a rotated, shifted copy are maximally similar and the pose that maps one onto the other is returned + def test_rotated_copy_is_the_same_reference(self) -> None: + from stamp.classify.frames import rotate_density + space = search_space(OrientationPrior.NORMAL, _REF_BOX, angular_step_degrees=15.0, shift_range_voxels=2) + reference = asymmetric_object(_REF_BOX, 1) + copy = rotate_density(reference, space.rotations[5]) + similarity, poses = pairwise_similarity([reference, copy, asymmetric_object(_REF_BOX, 2)], space) + assert similarity[0, 1] > 0.98 and similarity[0, 2] < 0.8 + assert np.allclose(poses[0][1][0], space.rotations[5]) + + # test_ceiling_drops_when_poses_are_wrong: half-split agreement is high for a label with correct poses and lower when the poses are scrambled + def test_ceiling_drops_when_poses_are_wrong(self, tmp_path: Path) -> None: + data = synthetic_set(tmp_path, [asymmetric_object(_REF_BOX, 1)], OrientationPrior.NORMAL, 40, seed=4) + space = search_space(OrientationPrior.NORMAL, _REF_BOX, angular_step_degrees=15.0, shift_range_voxels=2) + labels = np.zeros(len(data.labels), dtype=int) + scrambled = data.rotations[np.random.default_rng(0).permutation(len(labels))] + right = half_split_ceilings(data.store.batches(), labels, data.rotations, data.shifts, space, 1, _REF_BOX)[0] + wrong = half_split_ceilings(data.store.batches(), labels, scrambled, data.shifts, space, 1, _REF_BOX)[0] + assert right > 0.8 and wrong < right + + # test_null_is_below_real_signal: real particles beat the rejection threshold and the agreement bar is below a real pure label's ceiling + def test_null_is_below_real_signal(self, tmp_path: Path) -> None: + objects = [asymmetric_object(_REF_BOX, 1)] + data = synthetic_set(tmp_path, objects, OrientationPrior.NORMAL, 40, noise_sigma=0.1, seed=5) + space = search_space(OrientationPrior.NORMAL, _REF_BOX, angular_step_degrees=15.0, shift_range_voxels=2) + threshold = null_threshold(data.store, objects, space, quantile=0.95) + assignment = hard_assign(score_against_refs(data.store, objects, space), space) + assert (assignment.cc > threshold).mean() > 0.9 + bar = null_bar(data.store, objects[0], space, 30, sigmas=3.0) + ceiling = half_split_ceilings(data.store.batches(), assignment.labels, assignment.rotations, assignment.shifts, space, 1, _REF_BOX)[0] + assert ceiling > bar + +# TestPolish: class containing unit tests for polish step +class TestPolish: + # test_polish_repairs_corrupted_seeds: noisy seeds are polished into pure classes, for every prior + @pytest.mark.parametrize('prior', [OrientationPrior.NORMAL, OrientationPrior.AXIS, OrientationPrior.NONE]) + def test_polish_repairs_corrupted_seeds(self, tmp_path: Path, prior: OrientationPrior) -> None: + make = rod_object if prior is OrientationPrior.AXIS else asymmetric_object + objects = [make(_BOX, seed) if prior is not OrientationPrior.AXIS else rod_object(_BOX, seed, repeat=_BOX) for seed in (1, 2)] + data = synthetic_set(tmp_path / 'data', objects, prior, 30, noise_sigma=0.1, seed=3) + seeds, embedding = _corrupted_seeds(data.labels, 0.15, 4) + result = run_polish(data.store, embedding, seeds, _config(prior)) + assert _purity(result.labels, data.labels) > 0.9 + assert (result.labels >= 0).mean() > 0.7 + assert len(result.references) == 2 + + # test_polish_rejects_noise_only_particles: pure noise matches no reference above the null + def test_polish_rejects_noise_only_particles(self, tmp_path: Path) -> None: + objects = [asymmetric_object(_BOX, 1)] + data = synthetic_set(tmp_path / 'data', objects, OrientationPrior.NORMAL, 40, seed=5) + noise = synthetic_set(tmp_path / 'noise', [np.zeros_like(objects[0])], OrientationPrior.NORMAL, 20, noise_sigma=0.5, seed=6) + # one store holding both: build by stacking the volumes of the two sets + both = _concatenate(tmp_path / 'both', data, noise) + seeds = np.concatenate([np.zeros(40, dtype=int), np.full(20, -1)]) + embedding = np.zeros((60, 2)) + result = run_polish(both, embedding, seeds, _config(OrientationPrior.NORMAL)) + assert (result.labels[40:] == -1).mean() > 0.7 and (result.labels[:40] >= 0).mean() > 0.8 + + # test_polish_resumes_identically: a run stopped after the seeds and restarted gives identical output + def test_polish_resumes_identically(self, tmp_path: Path) -> None: + objects = [asymmetric_object(_BOX, 1), asymmetric_object(_BOX, 2)] + data = synthetic_set(tmp_path / 'data', objects, OrientationPrior.NORMAL, 25, seed=7) + seeds, embedding = _corrupted_seeds(data.labels, 0.1, 8) + config = _config(OrientationPrior.NORMAL) + fresh = run_polish(data.store, embedding, seeds, config, checkpoint_dir=tmp_path / 'ckpt') + for path in (tmp_path / 'ckpt').glob('round*.npz'): + path.unlink() # as if killed between the seed references and the first round + resumed = run_polish(data.store, embedding, seeds, config, checkpoint_dir=tmp_path / 'ckpt') + assert np.array_equal(fresh.labels, resumed.labels) and np.allclose(fresh.rotations, resumed.rotations) + + # test_polish_needs_a_seed: no seed cluster of the minimum size is an error + def test_polish_needs_a_seed(self, tmp_path: Path) -> None: + from stamp.utils.errors import StampPipelineError + data = synthetic_set(tmp_path / 'data', [asymmetric_object(_BOX, 1)], OrientationPrior.NORMAL, 12, seed=9) + with pytest.raises(StampPipelineError): + run_polish(data.store, np.zeros((12, 2)), np.full(12, -1), _config(OrientationPrior.NORMAL)) + + # test_polish_returns_an_empty_result_for_pure_noise: a decoy with no consistent structure rejects every particle instead of raising + def test_polish_returns_an_empty_result_for_pure_noise(self, tmp_path: Path) -> None: + noise = synthetic_set(tmp_path / 'noise', [np.zeros((_BOX,) * 3, dtype=np.float32)], OrientationPrior.NORMAL, 40, noise_sigma=0.5, seed=12) + seeds = np.zeros(40, dtype=int) + result = run_polish(noise.store, np.zeros((40, 2)), seeds, _config(OrientationPrior.NORMAL)) + assert (result.labels == -1).all() and result.references == [] and len(result.ceilings) == 0 + +# TestPrepare: class containing tests for subvolume preparation +class TestPrepare: + # test_working_box_is_odd: odd boxes bin to odd boxes so the centre stays on a voxel + def test_working_box_is_odd(self) -> None: + assert [working_box(n, 2) for n in (45, 47, 61)] == [23, 23, 31] + assert working_box(45, 1) == 45 + + # test_normalise_uses_masked_statistics: zero mean and unit variance inside the mask + def test_normalise_uses_masked_statistics(self) -> None: + rng = np.random.default_rng(0) + mask = soft_mask(21, 8.0) + out = normalise(rng.normal(5.0, 3.0, (21,) * 3).astype(np.float32), mask) + assert abs(out[mask > 0.5].mean()) < 1e-4 and abs(out[mask > 0.5].std() - 1.0) < 1e-3 + + # test_fourier_bin_preserves_a_smooth_object: a low-pass object keeps its shape after binning, checked at the centre voxel + def test_fourier_bin_preserves_a_smooth_object(self) -> None: + volume = asymmetric_object(45, 0, n_blobs=1, spread=0.0) + binned = fourier_bin(volume, 23) + assert binned.shape == (23,) * 3 and binned[11, 11, 11] > 0.9 * volume[22, 22, 22] + + # test_prepare_particle_shape: output is the working box + def test_prepare_particle_shape(self) -> None: + assert prepare_particle(np.random.default_rng(1).normal(size=(45,) * 3).astype(np.float32), 23).shape == (23,) * 3 + +# TestReferences: class containing unit tests for particle store and reference scoring +class TestReferences: + # test_store_serves_wedges_and_batches: batches cover every particle once and carry each particle's own wedge + def test_store_serves_wedges_and_batches(self, tmp_path: Path) -> None: + data = synthetic_set(tmp_path, [asymmetric_object(_REF_BOX, 1)], OrientationPrior.NORMAL, 12, seed=1) + seen = [] + for indices, volumes, wedges in data.store.batches(5): + assert volumes.shape == (len(indices), _REF_BOX, _REF_BOX, _REF_BOX) and wedges.shape == volumes.shape + assert np.array_equal(wedges[0], box_wedge(_REF_BOX, data.store.orientations[indices[0]], 60.0, 90.0)) + seen += indices + assert sorted(seen) == list(range(12)) + + # test_build_store_bins_and_normalises: the prepared store has the working box and matches prepare_particle + def test_build_store_bins_and_normalises(self, tmp_path: Path) -> None: + rng = np.random.default_rng(0) + raw = rng.normal(size=(4, 45, 45, 45)).astype(np.float32) + np.save(tmp_path / 't0.npy', raw) + store = build_store(Subvolumes(tmp_path, [('t0', i) for i in range(4)], 45), [None] * 4, 23, 60.0, 90.0, tmp_path / 'prepared') + assert store.volumes.box_voxels == 23 and len(store) == 4 + assert np.allclose(store.volumes[2], prepare_particle(raw[2], 23), atol=1e-5) + + # test_scoring_against_true_objects_recovers_classes: assignment against the generating objects labels particles correctly + def test_scoring_against_true_objects_recovers_classes(self, tmp_path: Path) -> None: + objects = [asymmetric_object(_REF_BOX, 1), asymmetric_object(_REF_BOX, 2)] + data = synthetic_set(tmp_path, objects, OrientationPrior.NORMAL, 20, seed=2) + space = search_space(OrientationPrior.NORMAL, _REF_BOX, angular_step_degrees=15.0, shift_range_voxels=2) + assignment = hard_assign(score_against_refs(data.store, objects, space), space) + assert (assignment.labels == data.labels).mean() > 0.95 + assert (assignment.margin > 0).all() + + # test_rebuild_from_true_poses_matches_object: references rebuilt from the true labels and poses correlate with the generating object + def test_rebuild_from_true_poses_matches_object(self, tmp_path: Path) -> None: + objects = [asymmetric_object(_REF_BOX, 1), asymmetric_object(_REF_BOX, 2)] + data = synthetic_set(tmp_path, objects, OrientationPrior.NONE, 25, noise_sigma=0.05, seed=3) + rebuilt = rebuild_references(data.store, data.labels, data.rotations, data.shifts, 2) + for reference, truth in zip(rebuilt, objects): + assert float((reference * truth).sum() / np.linalg.norm(reference) / np.linalg.norm(truth)) > 0.9 + +# TestSearch: class containing unit tests for per-prior alignment search space +class TestSearch: + # test_normal_space_is_z_rolls: 36 proper rotations about z at a 10 degree step, no polarity flips + def test_normal_space_is_z_rolls(self) -> None: + space = search_space(OrientationPrior.NORMAL, 25, angular_step_degrees=10.0) + assert len(space) == 36 and (space.polarity == 1).all() + assert np.allclose(space.rotations[:, 2], [0.0, 0.0, 1.0]) and np.allclose(space.rotations[:, :, 2], [0.0, 0.0, 1.0]) + assert np.allclose(np.linalg.det(space.rotations), 1.0) + + # test_axis_space_doubles_with_polarity: z-rolls and their flips, with an axial shift window of a quarter box + def test_axis_space_doubles_with_polarity(self) -> None: + space = search_space(OrientationPrior.AXIS, 25, angular_step_degrees=10.0) + assert len(space) == 72 and (space.polarity == -1).sum() == 36 + assert np.allclose(space.rotations[space.polarity < 0][:, 2, 2], -1.0) + assert space.max_shift == (3, 3, 6) + + # test_none_space_starts_at_identity: identity first, all proper rotations, reproducible from the seed + def test_none_space_starts_at_identity(self) -> None: + space = search_space(OrientationPrior.NONE, 25, n_rotations=50, seed=4) + assert len(space) == 50 and np.allclose(space.rotations[0], np.eye(3)) + assert np.allclose(np.linalg.det(space.rotations), 1.0) + assert np.array_equal(space.rotations, search_space(OrientationPrior.NONE, 25, n_rotations=50, seed=4).rotations) + + # test_rotated_bank_matches_rotate_density: threaded and serial banks agree with rotating one by one + def test_rotated_bank_matches_rotate_density(self) -> None: + reference = asymmetric_object(15, 0) + rotations = search_space(OrientationPrior.NONE, 15, n_rotations=6).rotations + serial = rotated_bank(reference, rotations) + assert np.allclose(serial, rotated_bank(reference, rotations, threads=3)) + assert np.allclose(serial[3], rotate_density(reference, rotations[3]).ravel()) + +# TestShFeatures: class containing unit tests for src/stamp/classify/shfeatures.py +class TestShFeatures: + # test_features_are_rotation_invariant: rotating an object leaves its features nearly unchanged without a wedge + def test_features_are_rotation_invariant(self) -> None: + volume = asymmetric_object(25, 1) + reference = sh_power(volume, None, 90.0) + for seed in range(3): + rotated = sh_power(rotate_density(volume, Rotation.random(random_state=seed).as_matrix()), None, 90.0) + assert np.linalg.norm(np.log(rotated) - np.log(reference)) / np.linalg.norm(np.log(reference)) < 0.15 + + # test_features_separate_classes_under_wedge: rotated, wedged, noisy copies of three objects group by object + def test_features_separate_classes_under_wedge(self, tmp_path: Path) -> None: + rng = np.random.default_rng(2) + objects = [asymmetric_object(25, seed) for seed in (1, 2, 3)] + labels = np.repeat([0, 1, 2], 16) + wedge = box_wedge(25, None, 60.0, 90.0) + volumes = np.stack([make_particle(objects[k], Rotation.random(random_state=rng.integers(1 << 30)).as_matrix(), (0, 0, 0), wedge, 0.1, rng) for k in labels]) + np.save(tmp_path / 't0.npy', volumes) + features = build_sh_feature_matrix(Subvolumes(tmp_path, [('t0', i) for i in range(len(labels))], 25), 60.0, 90.0) + distances = np.linalg.norm(features[:, None] - features[None], axis=2) + np.fill_diagonal(distances, np.inf) + assert (labels[distances.argmin(axis=1)] == labels).mean() >= 0.9 + +# TestSpherical: class containing unit tests for src/stamp/classify/spherical.py +class TestSpherical: + # test_sh_basis_is_orthonormal: quadrature of the basis gives the identity + def test_sh_basis_is_orthonormal(self) -> None: + xyz, weights = sphere_grid() + basis = real_sh_basis(xyz, lm_pairs(6, even_only=False)) + assert np.allclose(basis.T @ (basis * weights[:, None]), np.eye(basis.shape[1]), atol=1e-6) + + # test_masked_fit_recovers_coefficients: the ridge fit recovers a known even-degree function from half the sphere + def test_masked_fit_recovers_coefficients(self) -> None: + xyz, weights = sphere_grid() + pairs = lm_pairs(4, even_only=True) + basis = real_sh_basis(xyz, pairs) + truth = np.random.default_rng(0).normal(size=len(pairs)) + observed = np.abs(xyz[:, 2]) <= np.abs(xyz[:, 0]) + estimate = fit_matrix(basis, weights * observed, 1e-3) @ (basis @ truth) + assert np.allclose(estimate, truth, atol=0.1) + +# TestWedge: class containing tests for per-particle missing wedge +class TestWedge: + # test_identity_orientation_is_the_global_mask: tilt about y with identity orientation keeps |kz| <= |kx| tan(tilt) + def test_identity_orientation_is_the_global_mask(self) -> None: + box = 15 + freq = np.fft.fftfreq(box) + kx, _ky, kz = np.meshgrid(freq, freq, freq, indexing='ij') + expected = (np.abs(kz) <= np.abs(kx) * np.tan(np.radians(60.0))).astype(np.float32) + assert np.array_equal(box_wedge(box, None, 60.0, 90.0), expected) + + # test_rotated_wedge_matches_brute_force: random orientations and tilt axes agree with the explicit construction + def test_rotated_wedge_matches_brute_force(self) -> None: rng = np.random.default_rng(1) - n_per_group, box = 6, 5 - centres = np.array([[0.0, 0.0], [20.0, 0.0]]) - features = np.vstack([rng.normal(centre, 1.0, size=(n_per_group, 2)) for centre in centres]) - n_particles = features.shape[0] - subvolumes = _subvols_from_array(tmp_path / 'subvolumes', np.zeros((n_particles, box, box, box), dtype=np.float32)) - - particles = [ - Particle( - particle_id=f'p{index:06d}', - tomogram_id='tomo000', - position=(0.0, 0.0, 0.0), - source_picker='stamp-native', - half_set=HalfSet.A if index % 2 == 0 else HalfSet.B, - ) - for index in range(n_particles) - ] - - config = ClusteringConfig(method='kmeans', n_components=2, n_clusters=2) - align_settings = dict(enabled=False, angular_step_degrees=10.0, iterations=1) - assignments, _result_by_half, _averages_by_half = _classify_combined( - particles, subvolumes, features, config, tmp_path, voxel_size_angstrom=1.0, align_settings=align_settings, - ) - - assert all(assignment.vesicle_id is None for assignment in assignments) + for _ in range(3): + normal = rng.normal(size=3) + orientation = quaternion_from_reference_to(normal) + tilt_axis = float(rng.uniform(0, 180)) + fast = box_wedge(9, orientation, 55.0, tilt_axis) + slow = _brute_wedge(9, orientation, 55.0, tilt_axis) + assert (fast != slow).mean() < 0.01 # only voxels exactly on the edge may differ by rounding + + # test_wedge_is_centrosymmetric: the mask is symmetric under k -> -k so filtered volumes stay real + def test_wedge_is_centrosymmetric(self) -> None: + orientation = quaternion_from_reference_to(np.array([0.3, -0.5, 0.8])) + wedge = box_wedge(11, orientation, 50.0, 30.0) + assert np.array_equal(wedge, np.roll(wedge[::-1, ::-1, ::-1], 1, axis=(0, 1, 2))) + + # test_no_tilt_means_no_wedge: unset tilt keeps everything + def test_no_tilt_means_no_wedge(self) -> None: + assert box_wedge(7, None, None, 90.0).all() + assert observed_directions(np.eye(3), None, None, 90.0).all() + + # test_apply_wedge_is_idempotent: filtering twice changes nothing + def test_apply_wedge_is_idempotent(self) -> None: + rng = np.random.default_rng(2) + wedge = box_wedge(11, None, 60.0, 90.0) + once = apply_wedge(rng.normal(size=(11, 11, 11)), wedge) + assert np.allclose(apply_wedge(once, wedge), once, atol=1e-5) diff --git a/tests/unit/test_decoy.py b/tests/unit/test_decoy.py index 9cf98e7..bfcd2be 100644 --- a/tests/unit/test_decoy.py +++ b/tests/unit/test_decoy.py @@ -7,18 +7,12 @@ from pathlib import Path # Import internal STAMP objects -from stamp.decoy.generate import ( - _adaptive_decoy_count, - generate_rejected_surface_decoys, - generate_shifted_decoys, - generate_synthetic_noise_decoys, -) +from stamp.decoy.generate import DecoyGeometry, generate_shifted_decoys, generate_synthetic_noise_decoys from stamp.decoy.validate import ( assert_comparable, check_manifest_purity, is_decoy_particle_set, ) -from stamp.picking.native import NativePickerConfig, pick_tomogram from stamp.schemas.manifest import TomogramManifest from stamp.schemas.particles import HalfSet, Particle, ParticleSet from stamp.utils.errors import StampPipelineError, StampValidationError @@ -49,87 +43,31 @@ def _write_vesicle_pair(tmp_path: Path, tomogram_id: str = 'tomo000') -> Tomogra voxel_size_angstrom=10.0, ) -# _real_set_from_picker: run the native picker over a manifest and wrap its picks in a ParticleSet -def _real_set_from_picker(manifest: TomogramManifest, config: NativePickerConfig) -> ParticleSet: - picks = pick_tomogram( - manifest.segmentation_path, manifest.raw_tomogram_path, manifest.tomogram_id, config - ) +# _real_set: six fixed real particles inside the vesicle, 14 voxels from its centre +def _real_set(tomogram_id: str = 'tomo000') -> ParticleSet: + positions = ((30, 30, 44), (30, 30, 16), (30, 44, 30), (30, 16, 30), (44, 30, 30), (16, 30, 30)) return ParticleSet( particles=[ Particle( particle_id=f'p{index:06d}', - tomogram_id=pick.tomogram_id, - position=pick.position, - orientation=pick.orientation, - source_picker=pick.source_picker, - confidence=pick.confidence, + tomogram_id=tomogram_id, + position=tuple(float(c) for c in position), + source_picker='mine', half_set=HalfSet.A, ) - for index, pick in enumerate(picks) + for index, position in enumerate(positions) ], consensus_rule='union', - contributing_pickers=['stamp-native'], + contributing_pickers=['mine'], ) # TestDecoyGenerate: class containing unit tests for decoy/generate.py class TestDecoyGenerate: - def test_rejected_surface_decoys_avoid_real_picks(self, tmp_path: Path) -> None: - '''Every decoy is kept clear of real picks''' - manifest = _write_vesicle_pair(tmp_path) - config = NativePickerConfig(voxel_size_angstrom=10.0, n_mad=2.5, offset_windows_angstrom=((20.0, 80.0),)) - real_set = _real_set_from_picker(manifest, config) - assert real_set.particles, 'fixture produced no real picks' - - decoy_set = generate_rejected_surface_decoys( - real_particle_set=real_set, - manifests=[manifest], - config=config, - n_decoys_per_tomogram=10, - min_distance_from_real_angstrom=100.0, - seed=1, - ) - - assert decoy_set.particles - real_positions = np.array([p.position for p in real_set.particles]) - for particle in decoy_set.particles: - distances = np.linalg.norm(real_positions - np.array(particle.position), axis=1) - assert distances.min() >= 10.0 # 100 Angstrom at 10 A/voxel - assert particle.source_picker == 'decoy-rejected-surface' - - def test_rejected_surface_decoys_score_below_threshold(self, tmp_path: Path) -> None: - '''Decoys must come from points the picker rejected''' - manifest = _write_vesicle_pair(tmp_path) - config = NativePickerConfig(voxel_size_angstrom=10.0, n_mad=2.5, offset_windows_angstrom=((20.0, 80.0),)) - real_set = _real_set_from_picker(manifest, config) - - decoy_set = generate_rejected_surface_decoys( - real_particle_set=real_set, manifests=[manifest], config=config, - n_decoys_per_tomogram=10, min_distance_from_real_angstrom=100.0, seed=1, - ) - for particle in decoy_set.particles: - assert particle.confidence is not None - assert particle.confidence < config.n_mad - - def test_rejected_surface_decoys_are_deterministic(self, tmp_path: Path) -> None: - '''Same seed and parameters reproduce the same decoys''' - manifest = _write_vesicle_pair(tmp_path) - config = NativePickerConfig(voxel_size_angstrom=10.0, n_mad=2.5, offset_windows_angstrom=((20.0, 80.0),)) - real_set = _real_set_from_picker(manifest, config) - - kwargs = dict( - real_particle_set=real_set, manifests=[manifest], config=config, - n_decoys_per_tomogram=10, min_distance_from_real_angstrom=100.0, seed=7, - ) - first = generate_rejected_surface_decoys(**kwargs) - second = generate_rejected_surface_decoys(**kwargs) - assert [p.position for p in first.particles] == [p.position for p in second.particles] - def test_shifted_decoys_stay_away_from_surface(self, tmp_path: Path) -> None: '''Shifted decoys stay inside the volume and off the surface''' manifest = _write_vesicle_pair(tmp_path) - config = NativePickerConfig(voxel_size_angstrom=10.0, n_mad=2.5, offset_windows_angstrom=((20.0, 80.0),)) - real_set = _real_set_from_picker(manifest, config) - + config = DecoyGeometry(voxel_size_angstrom=10.0) + real_set = _real_set() decoy_set = generate_shifted_decoys( real_particle_set=real_set, manifests=[manifest], config=config, min_shift_angstrom=100.0, max_shift_angstrom=200.0, @@ -143,8 +81,8 @@ def test_shifted_decoys_stay_away_from_surface(self, tmp_path: Path) -> None: def test_shifted_decoys_are_oriented(self, tmp_path: Path) -> None: '''Shifted decoys have defined orientation.''' manifest = _write_vesicle_pair(tmp_path) - config = NativePickerConfig(voxel_size_angstrom=10.0, n_mad=2.5, offset_windows_angstrom=((20.0, 80.0),)) - real_set = _real_set_from_picker(manifest, config) + config = DecoyGeometry(voxel_size_angstrom=10.0) + real_set = _real_set() decoy_set = generate_shifted_decoys( real_particle_set=real_set, manifests=[manifest], config=config, min_shift_angstrom=100.0, max_shift_angstrom=200.0, @@ -153,9 +91,22 @@ def test_shifted_decoys_are_oriented(self, tmp_path: Path) -> None: for particle in decoy_set.particles: assert particle.orientation is not None + def test_shifted_decoys_are_deterministic(self, tmp_path: Path) -> None: + '''Same seed and parameters reproduce the same decoys''' + manifest = _write_vesicle_pair(tmp_path) + config = DecoyGeometry(voxel_size_angstrom=10.0) + kwargs = dict( + real_particle_set=_real_set(), manifests=[manifest], config=config, + min_shift_angstrom=100.0, max_shift_angstrom=200.0, + min_distance_from_surface_angstrom=50.0, min_pick_distance=60.0, seed=7, + ) + first = generate_shifted_decoys(**kwargs) + second = generate_shifted_decoys(**kwargs) + assert [p.position for p in first.particles] == [p.position for p in second.particles] + def test_synthetic_noise_writes_matched_pairs(self, tmp_path: Path) -> None: '''Synthetic-noise writes matched segmentation/tomogram pairs''' - config = NativePickerConfig(voxel_size_angstrom=10.0, offset_windows_angstrom=((20.0, 80.0),)) + config = DecoyGeometry(voxel_size_angstrom=10.0) decoy_set, manifests = generate_synthetic_noise_decoys( tomogram_shape=(40, 40, 40), n_tomograms=2, n_decoys_per_tomogram=5, output_dir=tmp_path / 'noise', config=config, seed=3, @@ -171,50 +122,17 @@ def test_synthetic_noise_writes_matched_pairs(self, tmp_path: Path) -> None: def test_synthetic_decoys_are_oriented(self, tmp_path: Path) -> None: '''Synthetic decoys have defined orientation.''' - config = NativePickerConfig(voxel_size_angstrom=10.0, offset_windows_angstrom=((20.0, 80.0),)) + config = DecoyGeometry(voxel_size_angstrom=10.0) decoy_set, manifests = generate_synthetic_noise_decoys( tomogram_shape=(40, 40, 40), n_tomograms=2, n_decoys_per_tomogram=5, output_dir=tmp_path / 'noise', config=config, seed=3, ) assert all(p.orientation is not None for p in decoy_set.particles) - def test__adaptive_decoy_count_matches_real_picks(self): - '''Default ratio targets the same count as real picks.''' - assert _adaptive_decoy_count(20) == 20 - assert _adaptive_decoy_count(7) == 7 - - def test__adaptive_decoy_count_floors_at_one(self): - '''Zero picks still requests at least one decoy.''' - assert _adaptive_decoy_count(0) >= 1 - - def test__adaptive_decoy_count_respects_custom_ratio(self): - '''target_ratio scales the target decoys returned.''' - assert _adaptive_decoy_count(10, target_ratio=0.5) == 5 - - def test_generate_rejected_surface_decoys_adaptive_default(self, tmp_path): - '''Derive count from real picks per tomogram.''' - manifest = _write_vesicle_pair(tmp_path) - config = NativePickerConfig(voxel_size_angstrom=10.0, n_mad=2.5, offset_windows_angstrom=((20.0, 80.0),)) - real_set = _real_set_from_picker(manifest, config) - assert real_set.particles, 'fixture produced no real picks' - - decoy_set = generate_rejected_surface_decoys( - real_particle_set=real_set, - manifests=[manifest], - config=config, - n_decoys_per_tomogram=None, - min_distance_from_real_angstrom=100.0, - seed=1, - ) - assert decoy_set is not None - assert len(decoy_set.particles) <= len(real_set.particles) - def test_generate_synthetic_noise_decoys_requires_explicit_count(self, tmp_path): '''n_decoys_per_tomogram=None raises for synthetic noise decoys.''' - manifest = _write_vesicle_pair(tmp_path) - config = NativePickerConfig(voxel_size_angstrom=10.0, n_mad=2.5, offset_windows_angstrom=((20.0, 80.0),)) - real_set = _real_set_from_picker(manifest, config) - assert real_set.particles, 'fixture produced no real picks' + config = DecoyGeometry(voxel_size_angstrom=10.0) + real_set = _real_set() with pytest.raises(StampValidationError): generate_synthetic_noise_decoys( tomogram_shape=(40, 40, 40), @@ -225,6 +143,12 @@ def test_generate_synthetic_noise_decoys_requires_explicit_count(self, tmp_path) seed=1, ) + def test_decoy_geometry_rejects_bad_values(self) -> None: + with pytest.raises(StampValidationError): + DecoyGeometry(voxel_size_angstrom=0.0) + with pytest.raises(StampValidationError): + DecoyGeometry(voxel_size_angstrom=10.0, density_sign=0) + # TestDecoyValidate: class containing unit tests for decoy/validate.py class TestDecoyValidate: def test_is_decoy_particle_set_detects_mixture(self) -> None: @@ -277,3 +201,55 @@ def _set(prefix: str, count: int, picker: str) -> ParticleSet: assert_comparable(real, small_decoy) assert_comparable(real, _set('d', 80, 'decoy-shifted')) # should not raise + + +# _real_set_for: a real particle set with the given prior and n particles clustered in the middle of a 60-voxel tomogram +def _real_set_for(prior, n: int = 12) -> ParticleSet: + rng = np.random.default_rng(0) + particles = [ + Particle(particle_id=f'p{i}', tomogram_id='tomo000', position=tuple(float(v) for v in rng.uniform(20, 40, 3)), source_picker='x', half_set=HalfSet.A if i % 2 else HalfSet.B) + for i in range(n) + ] + return ParticleSet(particles=particles, consensus_rule='union', contributing_pickers=['x'], orientation_prior=prior) + + +# TestRandomVolumeDecoys: class containing tests for the prior-agnostic decoy method +class TestRandomVolumeDecoys: + def test_avoids_real_picks_and_the_border(self, tmp_path: Path) -> None: + from stamp.decoy.generate import generate_random_volume_decoys + from scipy.spatial import cKDTree + from stamp.schemas.particles import OrientationPrior + manifest = _write_vesicle_pair(tmp_path) + real = _real_set_for(OrientationPrior.NONE) + decoys = generate_random_volume_decoys(real, [manifest], DecoyGeometry(voxel_size_angstrom=10.0), 60.0, 100.0, seed=1) + positions = np.array([p.position for p in decoys.particles]) + assert len(positions) == len(real.particles) + assert (cKDTree(np.array([p.position for p in real.particles])).query(positions)[0] >= 6.0).all() # 60 A at 10 A/voxel + assert (positions >= 10.0).all() and (positions <= 59 - 10.0).all() # 100 A border + assert decoys.orientation_prior is OrientationPrior.NONE and all(p.orientation is None for p in decoys.particles) + assert all(p.source_picker == 'decoy-random-volume' for p in decoys.particles) + + def test_axis_prior_gets_random_axes_and_is_deterministic(self, tmp_path: Path) -> None: + from stamp.decoy.generate import generate_random_volume_decoys + from stamp.schemas.particles import OrientationPrior + manifest = _write_vesicle_pair(tmp_path) + real = _real_set_for(OrientationPrior.AXIS) + first = generate_random_volume_decoys(real, [manifest], DecoyGeometry(voxel_size_angstrom=10.0), 60.0, 100.0, seed=2) + second = generate_random_volume_decoys(real, [manifest], DecoyGeometry(voxel_size_angstrom=10.0), 60.0, 100.0, seed=2) + assert all(p.orientation is not None for p in first.particles) and len({p.orientation for p in first.particles}) > 1 + assert first == second + + def test_refuses_the_membrane_prior(self, tmp_path: Path) -> None: + from stamp.decoy.generate import generate_random_volume_decoys + from stamp.schemas.particles import OrientationPrior + with pytest.raises(StampValidationError, match='shifted'): + generate_random_volume_decoys(_real_set_for(OrientationPrior.NORMAL), [_write_vesicle_pair(tmp_path)], DecoyGeometry(voxel_size_angstrom=10.0), 60.0, 100.0, seed=0) + + def test_comparable_requires_the_same_prior(self, tmp_path: Path) -> None: + from stamp.decoy.generate import generate_random_volume_decoys + from stamp.schemas.particles import OrientationPrior + real = _real_set_for(OrientationPrior.NONE) + decoys = generate_random_volume_decoys(real, [_write_vesicle_pair(tmp_path)], DecoyGeometry(voxel_size_angstrom=10.0), 60.0, 100.0, seed=1) + assert_comparable(real, decoys) + with pytest.raises(StampPipelineError, match='orientation prior'): + assert_comparable(real.model_copy(update={'orientation_prior': OrientationPrior.AXIS}), decoys) diff --git a/tests/unit/test_identify.py b/tests/unit/test_identify.py index 108d818..25b5ccb 100644 --- a/tests/unit/test_identify.py +++ b/tests/unit/test_identify.py @@ -4,13 +4,21 @@ # Import external dependencies import numpy as np, pytest -from scipy.ndimage import gaussian_filter +from scipy.ndimage import shift as shift_volume +from scipy.spatial.transform import Rotation # Import internal STAMP objects +from stamp.classify.frames import azimuth_matrix, rotate_density from stamp.identify.decoy_check import evaluate_decoy_control -from stamp.identify.fit import fit_candidate, rank_candidates +from stamp.identify.fit import rank_candidates from stamp.identify.panel import load_candidate_panel -from stamp.identify.simulate import azimuthal_smear, simulate_density, to_comparable +from stamp.identify.register import register_score +from stamp.identify.simulate import simulate_density +from stamp.schemas.particles import OrientationPrior +from synthetic import asymmetric_object + +# _REGISTER_BOX: box edge of the registration tests +_REGISTER_BOX = 25 # _write_panel: helper to drop a candidates.yaml plus a stub PDB next to it def _write_panel(tmp_path, body): @@ -19,10 +27,25 @@ def _write_panel(tmp_path, body): path.write_text(body) return path -def _blob(box, offset=0): - volume = np.zeros((box, box, box)) - volume[box // 2 + offset, box // 2, box // 2] = 1.0 - return gaussian_filter(volume, 2.0) +# _write_cloud: a PDB of eight Gaussian-scattered atom clusters, different for each seed, so rotated copies are distinguishable from other clouds +def _write_cloud(path, seed): + rng = np.random.default_rng(seed) + centres = rng.normal(scale=22.0, size=(8, 3)) + atoms = np.vstack([c + rng.normal(scale=4.0, size=(6, 3)) for c in centres]) + path.write_text(''.join(f'ATOM {i + 1:>5} CA ALA A{i + 1:>4} {x:8.3f}{y:8.3f}{z:8.3f} 1.00 0.00 C\n' for i, (x, y, z) in enumerate(atoms))) + +# TestAlignedIdentify: class containing tests for scoring candidates against 3D-aligned class averages +class TestAlignedIdentify: + # test_aligned_average_picks_its_own_candidate_in_any_orientation: a randomly rotated average of candidate a scores highest against a + def test_aligned_average_picks_its_own_candidate_in_any_orientation(self, tmp_path): + from stamp.commands.identify import _score_panel + for name in ('a', 'b'): + _write_cloud(tmp_path / f'{name}.pdb', {'a': 1, 'b': 2}[name]) + (tmp_path / 'candidates.yaml').write_text('candidates:\n - name: a\n structure_path: a.pdb\n - name: b\n structure_path: b.pdb\n') + panel = load_candidate_panel(tmp_path / 'candidates.yaml') + average = rotate_density(simulate_density(tmp_path / 'a.pdb', 25, 4.0, 16.0), Rotation.random(random_state=3).as_matrix()) + scores = _score_panel({'c00': (average, 4.0)}, panel, 16.0, 'native', 'local', aligned_prior=OrientationPrior.NONE)['c00'] + assert scores['a'] > 0.9 and scores['a'] > scores['b'] + 0.08 # TestPanel: class containing unit tests for src/stamp/identify/panel.py class TestPanel: @@ -47,6 +70,30 @@ def test_rejects_empty_list(self, tmp_path): with pytest.raises(ValueError, match='candidates'): load_candidate_panel(path) +# TestRegister: class containing unit tests for src/stamp/identify/register.py +class TestRegister: + # test_registration_finds_the_matching_candidate_after_any_rotation: for the none prior a randomly rotated and shifted copy of candidate A scores far above candidate B + def test_registration_finds_the_matching_candidate_after_any_rotation(self) -> None: + candidate_a, candidate_b = asymmetric_object(_REGISTER_BOX, 1), asymmetric_object(_REGISTER_BOX, 2) + average = shift_volume(rotate_density(candidate_a, Rotation.random(random_state=5).as_matrix()), (1, -1, 0), order=1) + score_a = register_score(average, candidate_a, OrientationPrior.NONE, n_rotations=800) + score_b = register_score(average, candidate_b, OrientationPrior.NONE, n_rotations=800) + assert score_a > 0.85 and score_a > score_b + 0.2 + + # test_registration_matches_through_inverted_contrast: a class average with opposite contrast still matches when match_contrast is on + def test_registration_matches_through_inverted_contrast(self) -> None: + candidate = asymmetric_object(_REGISTER_BOX, 3) + average = -rotate_density(candidate, azimuth_matrix(40.0)) + assert register_score(average, candidate, OrientationPrior.NORMAL) > 0.85 + assert register_score(average, candidate, OrientationPrior.NORMAL, match_contrast=False) < 0.5 + + # test_normal_prior_searches_only_azimuth_and_flip: an off-axis tilt of 60 degrees is not recovered by the membrane search, unlike the none prior + def test_normal_prior_searches_only_azimuth_and_flip(self) -> None: + candidate = asymmetric_object(_REGISTER_BOX, 4) + tilted = rotate_density(candidate, Rotation.from_euler('x', 70, degrees=True).as_matrix()) + assert register_score(tilted, candidate, OrientationPrior.NORMAL, n_local=1) < 0.7 + assert register_score(tilted, candidate, OrientationPrior.NONE, n_rotations=800) > 0.85 + # TestSimulate: class containing unit tests for src/stamp/identify/simulate.py class TestSimulate: def test_simulated_map_is_centred(self, tmp_path): @@ -56,13 +103,6 @@ def test_simulated_map_is_centred(self, tmp_path): centre = np.array(np.unravel_index(np.argmax(volume), volume.shape)) assert np.allclose(centre, 10, atol=1) - def test_smear_is_rotation_invariant(self): - rng = np.random.default_rng(0) - volume = rng.random((16, 16, 16)) - smeared = azimuthal_smear(volume, n_angles=36) - rotated = azimuthal_smear(np.rot90(volume, k=1, axes=(0, 1)), n_angles=36) - assert np.corrcoef(smeared.ravel(), np.rot90(rotated, k=-1, axes=(0, 1)).ravel())[0, 1] > 0.95 - def test_orient_puts_slab_normal_on_z(self): from stamp.identify.simulate import orient_to_membrane_slab rng = np.random.default_rng(0) @@ -80,78 +120,14 @@ def test_blank_element_column_is_hydrogen(self, tmp_path): _coords, weights, elements = read_pdb_atoms(pdb) assert weights[0] == 1.0 and elements[0] == 'H' -# TestFit: class containing unit tests for src/stamp/identify/fit.py -class TestFit: - def test_fit_recovers_planted_match(self): - target = _blob(21) - match_score = fit_candidate(target, target.copy()) - mismatch_score = fit_candidate(target, np.random.default_rng(1).random((21, 21, 21))) - assert match_score > mismatch_score - assert match_score > 0.8 - +# TestRank: class containing unit tests for src/stamp/identify/fit.py +class TestRank: def test_gap_widens_without_distractor(self): with_distractor = rank_candidates('c00', {'real': 0.9, 'near': 0.85, 'far': 0.2}, 'm') without = rank_candidates('c00', {'real': 0.9, 'far': 0.2}, 'm') assert without.score_gap_to_runner_up > with_distractor.score_gap_to_runner_up assert with_distractor.candidate_protein == 'real' - def test_species_discrimination(self): - box, voxel, resolution = 32, 4.0, 20.0 - - def cylinder(height_voxels): - centre = box // 2 - yy, xx = np.ogrid[-centre:box - centre, -centre:box - centre] - disk = (xx * xx + yy * yy) <= 16 - mask = np.zeros((box, box, box), dtype=bool) - z0, z1 = centre - height_voxels // 2, centre + height_voxels // 2 - mask[..., z0:z1] = disk[..., None] - volume = np.zeros((box, box, box)) - volume[mask] = 1.0 - return volume - - tall_template = to_comparable(cylinder(20), voxel, resolution) - short_template = to_comparable(cylinder(6), voxel, resolution) - - rng = np.random.default_rng(0) - average = -1.0 * cylinder(20) + rng.normal(0.0, 0.2, (box, box, box)) - comparable_average = to_comparable(average, voxel, resolution) - - tall_score = fit_candidate(comparable_average, tall_template) - short_score = fit_candidate(comparable_average, short_template) - assert tall_score > short_score - - def test_matches_through_opposite_contrast(self): - # a protein-dark class average must recognise its own (protein-bright) template, flipped the way _score_panel flips it, above a mismatched one - box, voxel, resolution = 32, 4.0, 20.0 - - def cylinder(height_voxels): - centre = box // 2 - yy, xx = np.ogrid[-centre:box - centre, -centre:box - centre] - disk = (xx * xx + yy * yy) <= 16 - mask = np.zeros((box, box, box), dtype=bool) - z0, z1 = centre - height_voxels // 2, centre + height_voxels // 2 - mask[..., z0:z1] = disk[..., None] - volume = np.zeros((box, box, box)) - volume[mask] = 1.0 - return volume - - rng = np.random.default_rng(0) - average = to_comparable(-1.0 * cylinder(20) + rng.normal(0.0, 0.2, (box, box, box)), voxel, resolution) - tall = -to_comparable(cylinder(20), voxel, resolution) - short = -to_comparable(cylinder(6), voxel, resolution) - - assert fit_candidate(average, tall) > 0.3 - assert fit_candidate(average, tall) > fit_candidate(average, short) - - def test_fit_is_contrast_blind(self): - target = _blob(21) - assert fit_candidate(target, -target.copy()) > 0.8 - - def test_fit_recovers_ninety_degree_misorientation(self): - target = _blob(21) + _blob(21, offset=5) - rolled = np.rot90(target, 1, axes=(0, 1)) - assert fit_candidate(target, rolled) > 0.8 - def test_single_candidate_has_no_gap(self): result = rank_candidates('c00', {'only': 0.7}, 'm') assert result.score_gap_to_runner_up is None @@ -183,3 +159,8 @@ def test_rank_test_still_vetoes_when_powered(self): result = evaluate_decoy_control([0.95, 0.50, 0.49, 0.10], [0.60, 0.55, 0.45, 0.05]) assert not result.passed assert 'Mann-Whitney' in result.reason + + # test_decoy_control_passes_when_the_decoy_matched_nothing: no decoy classes is the best outcome, not an error + def test_decoy_control_passes_when_the_decoy_matched_nothing(self) -> None: + result = evaluate_decoy_control([0.8, 0.7], []) + assert result.passed and 'no classes' in result.reason diff --git a/tests/unit/test_importers.py b/tests/unit/test_importers.py new file mode 100644 index 0000000..5989dc8 --- /dev/null +++ b/tests/unit/test_importers.py @@ -0,0 +1,177 @@ +''' +STAMP: unit tests for the picks importer +''' + +# Import external dependencies +import json, numpy as np, pandas as pd, pytest, starfile +from pathlib import Path + +# Import internal STAMP objects +from stamp.picking.geometry import quaternion_from_reference_to +from stamp.picking.importers import infer_orientations, map_tomogram_ids, read_picks +from stamp.schemas.manifest import TomogramManifest +from stamp.schemas.picks import RawPick +from stamp.utils.errors import StampValidationError +from stamp.utils.io import new_mrc + +# _manifest: a manifest with placeholder paths +def _manifest(tomogram_id: str) -> TomogramManifest: + return TomogramManifest(tomogram_id=tomogram_id, segmentation_path=Path(f'{tomogram_id}.mrc'), raw_tomogram_path=Path('raw.mrc'), voxel_size_angstrom=10.0) + +# _raw: a RawPick for id mapping tests +def _raw(tomogram_id: str) -> RawPick: + return RawPick(tomogram_id=tomogram_id, position=(0.0, 0.0, 0.0), source_picker='mine') + +# _slab_manifest: flat one-voxel membrane at x=30 in a 60^3 volume, voxel size 10 Å +def _slab_manifest(tmp_path: Path) -> TomogramManifest: + segmentation = np.zeros((60, 60, 60), dtype=np.float32) + segmentation[:, :, 30] = 1.0 + new_mrc(tmp_path / 't00.mrc', segmentation) + new_mrc(tmp_path / 't00_raw.mrc', np.zeros_like(segmentation)) + return TomogramManifest(tomogram_id='t00', segmentation_path=tmp_path / 't00.mrc', raw_tomogram_path=tmp_path / 't00_raw.mrc', voxel_size_angstrom=10.0) + +# _at: a RawPick at an (x, y, z) position in t00 +def _at(position: tuple[float, float, float], **fields) -> RawPick: + return RawPick(tomogram_id='t00', position=position, source_picker='mine', **fields) + +# TestApplyPrior: class containing tests for apply_prior in src/stamp/picking/importers.py +class TestApplyPrior: + # test_apply_prior_per_prior: normal passes picks through, axis demands orientations, none strips orientation and membrane fields + def test_apply_prior_per_prior(self) -> None: + from stamp.picking.importers import apply_prior + from stamp.schemas.particles import OrientationPrior + from stamp.schemas.picks import RawPick + bare = RawPick(tomogram_id='t', position=(1.0, 2.0, 3.0), source_picker='a') + oriented = bare.model_copy(update={'orientation': (1.0, 0.0, 0.0, 0.0), 'beam_angle_deviation_degrees': 10.0, 'vesicle_id': 'v1'}) + assert apply_prior([bare], OrientationPrior.NORMAL) == [bare] + assert apply_prior([oriented], OrientationPrior.AXIS) == [oriented] + with pytest.raises(StampValidationError, match='1 of 2'): + apply_prior([bare, oriented], OrientationPrior.AXIS) + stripped = apply_prior([oriented], OrientationPrior.NONE)[0] + assert stripped.orientation is None and stripped.beam_angle_deviation_degrees is None and stripped.vesicle_id is None and stripped.position == oriented.position + +# TestReadPicks: class containing tests for read_picks +class TestReadPicks: + def test_csv_round_trip(self, tmp_path: Path) -> None: + path = tmp_path / 'picks.csv' + path.write_text('tomogram_id,x,y,z,confidence\nt00,1.5,2.5,3.5,0.9\nt01,4,5,6,\n') + picks = read_picks(path, source_picker='mine') + assert [p.tomogram_id for p in picks] == ['t00', 't01'] + assert picks[0].position == (1.5, 2.5, 3.5) + assert picks[0].confidence == 0.9 and picks[1].confidence is None + assert all(p.source_picker == 'mine' and p.orientation is None for p in picks) + + def test_csv_quaternion_is_kept(self, tmp_path: Path) -> None: + path = tmp_path / 'picks.csv' + path.write_text('tomogram_id,x,y,z,qw,qx,qy,qz\nt00,1,2,3,1,0,0,0\n') + assert read_picks(path, source_picker='mine')[0].orientation == (1.0, 0.0, 0.0, 0.0) + + def test_csv_partial_quaternion_columns_are_rejected(self, tmp_path: Path) -> None: + path = tmp_path / 'picks.csv' + path.write_text('tomogram_id,x,y,z,qw\nt00,1,2,3,1\n') + with pytest.raises(StampValidationError, match='all of'): + read_picks(path, source_picker='mine') + + def test_csv_missing_column_is_rejected(self, tmp_path: Path) -> None: + path = tmp_path / 'picks.csv' + path.write_text('tomogram_id,x,y\nt00,1,2\n') + with pytest.raises(StampValidationError, match="'z'"): + read_picks(path, source_picker='mine') + + def test_csv_bad_row_reports_line_number(self, tmp_path: Path) -> None: + path = tmp_path / 'picks.csv' + path.write_text('tomogram_id,x,y,z\nt00,1,2,3\nt00,oops,2,3\n') + with pytest.raises(StampValidationError, match='line 3'): + read_picks(path, source_picker='mine') + + def test_csv_non_unit_quaternion_is_rejected(self, tmp_path: Path) -> None: + path = tmp_path / 'picks.csv' + path.write_text('tomogram_id,x,y,z,qw,qx,qy,qz\nt00,1,2,3,2,0,0,0\n') + with pytest.raises(StampValidationError, match='line 2'): + read_picks(path, source_picker='mine') + + def test_star_round_trip(self, tmp_path: Path) -> None: + path = tmp_path / 'picks.star' + table = pd.DataFrame({ + 'rlnTomoName': ['t00', 't00'], + 'rlnCoordinateX': [10.0, 20.0], + 'rlnCoordinateY': [11.0, 21.0], + 'rlnCoordinateZ': [12.0, 22.0], + 'rlnAutopickFigureOfMerit': [0.5, 0.7], + }) + starfile.write({'particles': table}, path) + picks = read_picks(path, source_picker='relion') + assert [p.position for p in picks] == [(10.0, 11.0, 12.0), (20.0, 21.0, 22.0)] + assert [p.confidence for p in picks] == [0.5, 0.7] + + def test_star_without_coordinates_is_rejected(self, tmp_path: Path) -> None: + path = tmp_path / 'picks.star' + starfile.write({'particles': pd.DataFrame({'rlnTomoName': ['t00'], 'rlnOriginXAngst': [1.0]})}, path) + with pytest.raises(StampValidationError, match='rlnCoordinateX'): + read_picks(path, source_picker='relion') + + def test_json_overwrites_source_picker(self, tmp_path: Path) -> None: + path = tmp_path / 'picks.json' + path.write_text(json.dumps([{'tomogram_id': 't00', 'position': [1, 2, 3], 'source_picker': 'other'}])) + assert read_picks(path, source_picker='mine')[0].source_picker == 'mine' + + def test_jsonl_reads_one_record_per_line(self, tmp_path: Path) -> None: + path = tmp_path / 'picks.jsonl' + path.write_text('\n'.join(json.dumps({'tomogram_id': 't00', 'position': [i, 0, 0], 'source_picker': 'x'}) for i in range(3))) + assert len(read_picks(path, source_picker='mine')) == 3 + + def test_unknown_suffix_and_empty_file_are_rejected(self, tmp_path: Path) -> None: + (tmp_path / 'picks.txt').write_text('') + with pytest.raises(StampValidationError, match='unsupported'): + read_picks(tmp_path / 'picks.txt', source_picker='mine') + (tmp_path / 'empty.csv').write_text('tomogram_id,x,y,z\n') + with pytest.raises(StampValidationError, match='no picks'): + read_picks(tmp_path / 'empty.csv', source_picker='mine') + +# TestMapTomogramIds: class containing tests for map_tomogram_ids +class TestMapTomogramIds: + def test_exact_match_is_unchanged(self) -> None: + assert map_tomogram_ids([_raw('t00')], [_manifest('t00')])[0].tomogram_id == 't00' + + def test_segmented_suffix_is_ignored_on_either_side(self) -> None: + manifests = [_manifest('a_segmented'), _manifest('b')] + mapped = map_tomogram_ids([_raw('a'), _raw('b_segmented')], manifests) + assert [p.tomogram_id for p in mapped] == ['a_segmented', 'b'] + + def test_unknown_ids_are_listed(self) -> None: + with pytest.raises(StampValidationError, match="'nope'"): + map_tomogram_ids([_raw('t00'), _raw('nope')], [_manifest('t00')]) + +# TestInferOrientations: class containing tests for infer_orientations +class TestInferOrientations: + def test_normal_points_from_surface_towards_the_pick(self, tmp_path: Path) -> None: + manifest = _slab_manifest(tmp_path) + right, left = infer_orientations([_at((35.0, 20.0, 20.0)), _at((25.0, 20.0, 20.0))], [manifest]) + assert np.allclose(right.orientation, quaternion_from_reference_to(np.array([1.0, 0.0, 0.0])), atol=1e-6) + assert np.allclose(left.orientation, quaternion_from_reference_to(np.array([-1.0, 0.0, 0.0])), atol=1e-6) + assert right.beam_angle_deviation_degrees == pytest.approx(0.0, abs=1e-6) # normal in the xy plane + + def test_picks_beyond_max_distance_stay_unoriented(self, tmp_path: Path) -> None: + manifest = _slab_manifest(tmp_path) + near, far = infer_orientations([_at((32.0, 20.0, 20.0)), _at((50.0, 20.0, 20.0))], [manifest], max_surface_distance_angstrom=50.0) + assert near.orientation is not None and far.orientation is None + + def test_supplied_quaternion_is_kept_and_sets_beam_angle(self, tmp_path: Path) -> None: + manifest = _slab_manifest(tmp_path) + (pick,) = infer_orientations([_at((35.0, 20.0, 20.0), orientation=(1.0, 0.0, 0.0, 0.0))], [manifest]) + assert pick.orientation == (1.0, 0.0, 0.0, 0.0) + assert pick.beam_angle_deviation_degrees == pytest.approx(90.0) # +z is beam-aligned + + def test_vesicle_id_is_filled_from_labels(self, tmp_path: Path) -> None: + manifest = _slab_manifest(tmp_path) + labels = np.zeros((60, 60, 60), dtype=np.int16) + labels[:, :, 29:32] = 3 + new_mrc(tmp_path / 't00_labelled.mrc', labels) + (pick,) = infer_orientations([_at((35.0, 20.0, 20.0))], [manifest], vesicle_labels_by_tomogram={'t00': tmp_path / 't00_labelled.mrc'}) + assert pick.vesicle_id == 't00:v0003' + + def test_empty_segmentation_leaves_picks_untouched(self, tmp_path: Path) -> None: + manifest = _slab_manifest(tmp_path) + new_mrc(manifest.segmentation_path, np.zeros((60, 60, 60), dtype=np.float32)) + (pick,) = infer_orientations([_at((35.0, 20.0, 20.0))], [manifest]) + assert pick.orientation is None diff --git a/tests/unit/test_picking.py b/tests/unit/test_picking.py index d82ee64..b531962 100644 --- a/tests/unit/test_picking.py +++ b/tests/unit/test_picking.py @@ -1,5 +1,5 @@ ''' -STAMP: unit tests for picking functions, including geometric primitives, native picker and consensus reconciliation +STAMP: unit tests for picking functions, including geometric primitives, and consensus reconciliation ''' # Import external dependencies @@ -8,22 +8,13 @@ # Import internal STAMP objects from stamp.picking.consensus import build_particle_set, reconcile_picks -from stamp.utils.errors import StampPipelineError, StampValidationError +from stamp.utils.errors import StampValidationError from stamp.picking.geometry import ( beam_angle_deviation_degrees, compose_roll_about_normal, - downsample_points, - exclude_near_boundary, extract_surface, - local_normalise, - max_order_statistic_offset, - non_maximum_suppression, quaternion_from_reference_to, - robust_normalise, - sample_along_normals, - score_membrane_faces ) -from stamp.picking.native import NativePickerConfig, pick_tomogram from stamp.picking.vesicles import ( load_vesicle_labels, summarise_vesicles, @@ -45,33 +36,6 @@ def _write_mrc(path: Path, volume: np.ndarray) -> None: with mrcfile.new(path, overwrite=True) as mrc: mrc.set_data(volume.astype(np.float32)) -# _vesicle_with_particles: a hollow-sphere segmentation plus a tomogram with dark blobs outside the shell -def _vesicle_with_particles(shape=(60, 60, 60), radius=18.0, thickness=2.0, particle_offsets=((0, 0, 1),)): - '''A hollow sphere segmentation plus a matching tomogram with dark blobs planted just outside the shell along the given directions''' - centre = np.array(shape) / 2.0 - grid = np.stack(np.meshgrid(*[np.arange(s) for s in shape], indexing='ij'), axis=-1) - distance = np.linalg.norm(grid - centre, axis=-1) - segmentation = ( - (distance > radius - thickness) & (distance < radius + thickness) - ).astype(np.float32) - # Membrane itself is dark; particles are darker still, sitting ~6 voxels out - tomogram = np.zeros(shape, dtype=np.float32) - tomogram[segmentation > 0] = -1.0 - expected_positions_zyx = [] - for direction in particle_offsets: - unit = np.array(direction, dtype=float) - unit /= np.linalg.norm(unit) - position = centre + unit * (radius + 6.0) - expected_positions_zyx.append(position) - index = np.round(position).astype(int) - # A small dark blob - tomogram[ - index[0] - 2 : index[0] + 3, - index[1] - 2 : index[1] + 3, - index[2] - 2 : index[2] + 3, - ] = -8.0 - return segmentation, tomogram, expected_positions_zyx - # _pick: return a RawPick instance for use in tests def _pick(tomogram_id: str, position, picker: str, confidence=0.8, orientation=None) -> RawPick: return RawPick( @@ -82,81 +46,6 @@ def _pick(tomogram_id: str, position, picker: str, confidence=0.8, orientation=N source_picker=picker, ) -# _linear_gradient_vesicle: hollow-sphere segmentation on a tomogram whose background ramps linearly along x, with identical particle blobs planted at both ends -def _linear_gradient_vesicle(shape=(80, 80, 120), radius=20.0, thickness=2.0) -> tuple[np.ndarray, np.ndarray]: - centre = np.array(shape) / 2.0 - grid = np.stack(np.meshgrid(*[np.arange(s) for s in shape], indexing='ij'), axis=-1) - distance = np.linalg.norm(grid - centre, axis=-1) - segmentation = ((distance > radius - thickness) & (distance < radius + thickness)).astype(np.float32) - # Background ramps from 0 at x=0 to -4 at x=max to mimic thickness/defocus gradient - x_ramp = -4.0 * (np.arange(shape[2]) / (shape[2] - 1)) - tomogram = np.broadcast_to(x_ramp[None, None, :], shape).astype(np.float32).copy() - # Small noise floor: real tomograms are never noiseless, and MAD needs ambient - # variance to behave as a stable scale estimator rather than tracking blob contamination directly - tomogram = tomogram + np.random.default_rng(0).normal(scale=0.3, size=shape).astype(np.float32) - tomogram[segmentation > 0] = np.median(tomogram[segmentation <= 0]) - # Identical dark particle blobs just outside the shell, at low-x and high-x poles - for x_index in (shape[2] // 2 - int(radius) - 5, shape[2] // 2 + int(radius) + 5): - centre_particle = np.array([shape[0] / 2, shape[1] / 2, x_index]) - particle_distance = np.linalg.norm(grid - centre_particle, axis=-1) - tomogram[particle_distance < 3.0] -= 3.0 - return segmentation, tomogram - -# _particle_free_vesicle: a spherical shell segmentation with a tomogram of pure background noise, no planted density, for measuring false-positive rate -def _particle_free_vesicle(seed: int) -> tuple[np.ndarray, np.ndarray]: - shape = (60, 60, 60) - centre = np.array(shape) / 2.0 - zz, yy, xx = np.mgrid[0:shape[0], 0:shape[1], 0:shape[2]] - radius = np.sqrt((zz - centre[0]) ** 2 + (yy - centre[1]) ** 2 + (xx - centre[2]) ** 2) - segmentation = ((radius > 18.0) & (radius < 20.0)).astype(np.float32) - rng = np.random.default_rng(seed) - tomogram = rng.normal(0.0, 1.0, size=shape).astype(np.float32) - return segmentation, tomogram - -# _vesicle_with_two_protrusion_heights: a hollow-sphere segmentation with two planted particles at distinct offsets from the membrane, on opposite sides so NMS keeps them apart -def _vesicle_with_two_protrusion_heights( - shape=(120, 120, 120), radius=20.0, thickness=2.0, - small_offset_angstrom=35.0, large_offset_angstrom=130.0, voxel_size_angstrom=10.0, -): - centre = np.array(shape) / 2.0 - grid = np.stack(np.meshgrid(*[np.arange(s) for s in shape], indexing='ij'), axis=-1) - distance = np.linalg.norm(grid - centre, axis=-1) - segmentation = ((distance > radius - thickness) & (distance < radius + thickness)).astype(np.float32) - tomogram = np.zeros(shape, dtype=np.float32) - tomogram[segmentation > 0] = -1.0 - - expected_positions_zyx = [] - for direction, offset_angstrom in (((0, 0, 1), small_offset_angstrom), ((0, 0, -1), large_offset_angstrom)): - unit = np.array(direction, dtype=float) - unit /= np.linalg.norm(unit) - offset_voxels = offset_angstrom / voxel_size_angstrom - position = centre + unit * (radius + offset_voxels) - expected_positions_zyx.append(position) - index = np.round(position).astype(int) - tomogram[ - index[0] - 2 : index[0] + 3, - index[1] - 2 : index[1] + 3, - index[2] - 2 : index[2] + 3, - ] = -8.0 - return segmentation, tomogram, expected_positions_zyx - -# _count_above_threshold_uncorrected: repeat the pre-NMS scoring step at plain n_mad (no order-statistic correction), for comparison against the corrected threshold -def _count_above_threshold_uncorrected(tmp_path: Path, config: NativePickerConfig, n_mad: float) -> int: - with mrcfile.open(str(tmp_path / 'seg.mrc'), permissive=True) as mrc: - segmentation = np.asarray(mrc.data) - with mrcfile.open(str(tmp_path / 'tomo.mrc'), permissive=True) as mrc: - tomogram = np.asarray(mrc.data).astype(np.float32).copy() - tomogram[segmentation > 0] = np.median(tomogram[segmentation <= 0]) - vertices, normals = extract_surface(segmentation) - vertices, normals = downsample_points(vertices, normals, config.to_voxels(config.surface_spacing_angstrom)) - inside = exclude_near_boundary(vertices, segmentation.shape, config.to_voxels(config.max_offset_angstrom)) - vertices, normals = vertices[inside], normals[inside] - windows = [(config.to_voxels(lo), config.to_voxels(hi)) for lo, hi in config.offset_windows_angstrom] - _points, _n, scores, _w, _used_fallback, _mean, _profile = score_membrane_faces( - tomogram, vertices, normals, windows, config.n_samples, config.density_sign, scoring_mode=config.scoring_mode, - ) - return int(np.sum(scores >= n_mad)) - # TestGeometry: class containing unit tests for test_geometry.py class TestGeometry: def test_extract_surface_returns_unit_normals(self) -> None: @@ -171,65 +60,6 @@ def test_extract_surface_rejects_empty_segmentation(self) -> None: with pytest.raises(StampValidationError, match='no voxels above'): extract_surface(np.zeros((10, 10, 10), dtype=np.float32)) - def test_downsample_reduces_points_and_is_deterministic(self) -> None: - '''Downsampling shrinks the set reproducibly.''' - vertices, normals = extract_surface(_hollow_sphere()) - first_points, first_normals = downsample_points(vertices, normals, spacing_voxels=4.0) - second_points, _ = downsample_points(vertices, normals, spacing_voxels=4.0) - assert first_points.shape[0] < vertices.shape[0] - assert first_normals.shape[0] == first_points.shape[0] - np.testing.assert_array_equal(first_points, second_points) - - def test_sample_along_normals_finds_a_planted_blob(self) -> None: - '''The point under a planted blob scores highest''' - # Flat membrane in the z=20 plane, with a bright blob sitting above it. - volume = np.zeros((40, 40, 40), dtype=np.float32) - volume[25, 20, 20] = 10.0 - - points = np.array([[20.0, 20.0, 20.0], [20.0, 30.0, 30.0]]) - normals = np.array([[1.0, 0.0, 0.0], [1.0, 0.0, 0.0]]) - - densities = sample_along_normals( - volume, points, normals, - offset_min_voxels=4.0, offset_max_voxels=6.0, n_samples=3, direction=1, - ) - # The point under the blob scores higher than the bare one. - assert densities[0] > densities[1] - - def test_sample_along_normals_direction_matters(self) -> None: - '''Sampling along the normal beats sampling against it''' - volume = np.zeros((40, 40, 40), dtype=np.float32) - volume[25, 20, 20] = 10.0 - points = np.array([[20.0, 20.0, 20.0]]) - normals = np.array([[1.0, 0.0, 0.0]]) - - along = sample_along_normals(volume, points, normals, 4.0, 6.0, 3, direction=1) - against = sample_along_normals(volume, points, normals, 4.0, 6.0, 3, direction=-1) - assert along[0] > against[0] - - def test_robust_normalise_handles_flat_input(self) -> None: - '''A flat input normalises to zeros''' - normalised, _used_fallback = robust_normalise(np.ones(10)) - np.testing.assert_array_equal(normalised, np.zeros(10)) - - def test_robust_normalise_scales_outlier(self) -> None: - '''A lone outlier normalises well above threshold''' - values = np.concatenate([np.zeros(99), [100.0]]) - normalised, _used_fallback = robust_normalise(values) - assert normalised[-1] > 3.0 - - def test_non_maximum_suppression_keeps_highest(self) -> None: - '''NMS keeps the higher-scoring point in a close pair''' - points = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [50.0, 0.0, 0.0]]) - scores = np.array([1.0, 5.0, 3.0]) - kept = non_maximum_suppression(points, scores, min_distance_voxels=10.0) - assert set(kept.tolist()) == {1, 2} - - def test_non_maximum_suppression_empty_input(self) -> None: - '''NMS on an empty input returns an empty result''' - kept = non_maximum_suppression(np.empty((0, 3)), np.empty(0), 10.0) - assert kept.size == 0 - def test_quaternion_is_unit_length_and_rotates_correctly(self) -> None: '''Every returned quaternion is unit-length''' for vector in ([0, 0, 1], [1, 0, 0], [0, 1, 0], [1, 1, 1]): @@ -246,58 +76,6 @@ def test_quaternion_antiparallel_case_is_unit_length(self) -> None: quaternion = quaternion_from_reference_to(np.array([0.0, 0.0, -1.0])) assert abs(np.linalg.norm(quaternion) - 1.0) < 1e-6 - def test_exclude_near_boundary(self) -> None: - '''Points within the margin of a face are masked out''' - points = np.array([[1.0, 1.0, 1.0], [20.0, 20.0, 20.0]]) - mask = exclude_near_boundary(points, (40, 40, 40), margin_voxels=5.0) - assert mask.tolist() == [False, True] - - def test_faces_share_one_scale(self): - '''A bright blob off one face does not inflate the other face's z-scores.''' - tomo = np.zeros((40, 40, 40), dtype=np.float32) - tomo[25, 20, 20] = -50.0 # dark blob on the +normal side of the y=20 vertex only - ys = np.array([5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 35.0]) - vertices = np.stack([np.full_like(ys, 20.0), ys, np.full_like(ys, 20.0)], axis=1) - normals = np.tile([1.0, 0.0, 0.0], (vertices.shape[0], 1)) - n_points = vertices.shape[0] - contaminated = int(np.where(ys == 20.0)[0][0]) - _points, _n, scores, _w, _used_fallback, _mean, _profile = score_membrane_faces(tomo, vertices, normals, [(3.0, 6.0)], 3, -1) - assert scores.shape == (2 * n_points,) - pos_face, neg_face = scores[:n_points], scores[n_points:] - clean = [i for i in range(n_points) if i != contaminated] - # the blob sits only on the +normal face of the contaminated vertex - assert abs(pos_face[contaminated]) > abs(neg_face[contaminated]) - # every clean vertex, on either face, stays near the untouched baseline - for i in clean: - assert abs(pos_face[i]) < 1e-6 - assert abs(neg_face[i]) < 1e-6 - - def test_score_membrane_faces_reports_winning_window(self) -> None: - '''A point with density only in the second window is won by that window, not the first.''' - tomo = np.zeros((60, 60, 60), dtype=np.float32) - tomo[20, 20, 55] = -5.0 # offset 35 voxels along +x from the point below - vertices = np.array([[20.0, 20.0, 20.0]]) - normals = np.array([[0.0, 0.0, 1.0]]) - windows = [(2.0, 10.0), (30.0, 40.0)] - _points, _n, scores, winning_window, _used_fallback, _mean, _profile = score_membrane_faces(tomo, vertices, normals, windows, 5, -1) - # two faces per point; the +x face (index 0) sees the density, the -x face (index 1) sees nothing - assert winning_window[0] == 1 - assert scores[0] > scores[1] - - def test_max_order_statistic_offset_zero_for_single_window(self) -> None: - assert max_order_statistic_offset(1) == 0.0 - - def test_max_order_statistic_offset_increases_with_window_count(self) -> None: - assert 0.0 < max_order_statistic_offset(2) < max_order_statistic_offset(4) < max_order_statistic_offset(8) - - def test_max_order_statistic_offset_rejects_zero_windows(self) -> None: - with pytest.raises(ValueError, match='n_windows'): - max_order_statistic_offset(0) - - def test_score_membrane_faces_rejects_no_windows(self) -> None: - with pytest.raises(ValueError, match='offset_windows_voxels'): - score_membrane_faces(np.zeros((10, 10, 10)), np.zeros((1, 3)), np.array([[0.0, 0.0, 1.0]]), [], 5, -1) - # test_compose_roll_is_identity_at_zero: zero angle leaves the normal quaternion unchanged def test_compose_roll_is_identity_at_zero(self): base = quaternion_from_reference_to(np.array([0.3, -0.5, 0.8])) @@ -314,54 +92,6 @@ def test_compose_roll_preserves_normal(self): moved = quaternion_to_matrix(rolled) @ np.array([0.0, 0.0, 1.0]) assert np.allclose(moved, target, atol=1e-6) - def test_global_normalisation_biases_picks_toward_low_background_end(self, tmp_path: Path) -> None: - segmentation, tomogram = _linear_gradient_vesicle() - seg_path, tomo_path = tmp_path / 'seg.mrc', tmp_path / 'tomo.mrc' - _write_mrc(seg_path, segmentation) - _write_mrc(tomo_path, tomogram) - config = NativePickerConfig(voxel_size_angstrom=10.0, n_mad=1.5, normalisation='global', scoring_mode='mean') - picks = pick_tomogram(seg_path, tomo_path, 'gradient', config) - # Both particles are equally strong so global threshold should favour low-background (high-x, deep-ramp) end - x_positions = [pick.position[0] for pick in picks] - assert len(x_positions) > 0 - low_x_count = sum(1 for x in x_positions if x < tomogram.shape[2] / 2) - high_x_count = len(x_positions) - low_x_count - assert high_x_count > low_x_count - - def test_local_normalisation_does_not_bias_picks(self, tmp_path: Path) -> None: - segmentation, tomogram = _linear_gradient_vesicle() - seg_path, tomo_path = tmp_path / 'seg.mrc', tmp_path / 'tomo.mrc' - _write_mrc(seg_path, segmentation) - _write_mrc(tomo_path, tomogram) - config = NativePickerConfig(voxel_size_angstrom=10.0, n_mad=1.5, normalisation='local', local_radius_angstrom=250.0, min_local_neighbours=5, scoring_mode='mean') - picks = pick_tomogram(seg_path, tomo_path, 'gradient', config) - x_positions = [pick.position[0] for pick in picks] - assert len(x_positions) > 0 - low_x_count = sum(1 for x in x_positions if x < tomogram.shape[2] / 2) - high_x_count = len(x_positions) - low_x_count - assert low_x_count > 0 and high_x_count > 0 - - def test_beam_aligned_and_orthogonal_particles_get_correct_deviation(self, tmp_path: Path) -> None: - '''A particle planted beam-aligned (normal along z) reads ~90 deg; one beam-orthogonal (normal in-plane) reads ~0 deg.''' - segmentation, tomogram, _ = _vesicle_with_particles(particle_offsets=((0, 0, 1), (1, 0, 0)),) - _write_mrc(tmp_path / 'seg.mrc', segmentation) - _write_mrc(tmp_path / 'tomo.mrc', tomogram) - - config = NativePickerConfig( - voxel_size_angstrom=10.0, - offset_windows_angstrom=((40.0, 80.0),), - surface_spacing_angstrom=20.0, - min_particle_distance_angstrom=80.0, - n_mad=3.0, - ) - picks = pick_tomogram(tmp_path / 'seg.mrc', tmp_path / 'tomo.mrc', 'tomo000', config) - assert picks, 'picker found nothing where particles were planted' - - deviations = np.array([p.beam_angle_deviation_degrees for p in picks]) - # nearest-beam-aligned pick and nearest-beam-orthogonal pick, by deviation - assert deviations.max() > 60.0, 'expected a near-beam-aligned pick close to 90 deg' - assert deviations.min() < 30.0, 'expected a near-beam-orthogonal pick close to 0 deg' - def test_beam_angle_deviation_matches_closed_form(self) -> None: '''Directly check the deviation formula against known normals.''' assert beam_angle_deviation_degrees(np.array([0.0, 0.0, 1.0])) == pytest.approx(90.0) @@ -389,139 +119,6 @@ def test_filter_retains_all_when_disabled(self) -> None: ] assert len(kept) == 2 - -# TestNativePicker: class containing unit tests for test_native_picker.py -class TestNativePicker: - def test_picker_finds_planted_particle(self, tmp_path: Path) -> None: - '''The picker returns a pick near each planted particle''' - segmentation, tomogram, expected_zyx = _vesicle_with_particles() - _write_mrc(tmp_path / 'seg.mrc', segmentation) - _write_mrc(tmp_path / 'tomo.mrc', tomogram) - - config = NativePickerConfig( - voxel_size_angstrom=10.0, - offset_windows_angstrom=((40.0, 80.0),), - surface_spacing_angstrom=20.0, - min_particle_distance_angstrom=80.0, - n_mad=3.0, - density_sign=-1, - ) - picks = pick_tomogram(tmp_path / 'seg.mrc', tmp_path / 'tomo.mrc', 'tomo000', config) - - assert picks, 'picker found nothing where a particle was planted' - - # Pick positions are (x, y, z); expected are (z, y, x). - expected_xyz = np.array([position[::-1] for position in expected_zyx]) - found_xyz = np.array([pick.position for pick in picks]) - distances = np.linalg.norm(found_xyz[:, None, :] - expected_xyz[None, :, :], axis=-1) - assert distances.min() < 10.0, ( - f'nearest pick was {distances.min():.1f} voxels from the planted particle' - ) - - def test_picker_returns_nothing_on_featureless_membrane(self, tmp_path: Path) -> None: - '''A vesicle with no particles should yield few or no picks (robust normalisation means some points always sit above the median, so this asserts a low count rather than exactly zero)''' - segmentation, tomogram, _ = _vesicle_with_particles(particle_offsets=()) - _write_mrc(tmp_path / 'seg.mrc', segmentation) - _write_mrc(tmp_path / 'tomo.mrc', tomogram) - - config = NativePickerConfig(voxel_size_angstrom=10.0, n_mad=4.0) - picks = pick_tomogram(tmp_path / 'seg.mrc', tmp_path / 'tomo.mrc', 'tomo000', config) - assert len(picks) <= 3, f'expected few picks on a featureless membrane, got {len(picks)}' - - def test_picker_output_conventions(self, tmp_path: Path) -> None: - '''Every pick carries the expected id, picker, orientation and bounds''' - segmentation, tomogram, _ = _vesicle_with_particles() - _write_mrc(tmp_path / 'seg.mrc', segmentation) - _write_mrc(tmp_path / 'tomo.mrc', tomogram) - - config = NativePickerConfig(voxel_size_angstrom=10.0, n_mad=2.0) - picks = pick_tomogram(tmp_path / 'seg.mrc', tmp_path / 'tomo.mrc', 'tomo000', config) - - for pick in picks: - assert pick.tomogram_id == 'tomo000' - assert pick.source_picker == 'stamp-native' - assert pick.orientation is not None # unit-length enforced by the schema - assert pick.confidence is not None - for coordinate, extent in zip(pick.position, (60, 60, 60)): - assert 0 <= coordinate <= extent - - def test_picker_rejects_mismatched_shapes(self, tmp_path: Path) -> None: - '''Mismatched segmentation/tomogram shapes raise a clear error''' - _write_mrc(tmp_path / 'seg.mrc', np.ones((20, 20, 20), dtype=np.float32)) - _write_mrc(tmp_path / 'tomo.mrc', np.zeros((30, 30, 30), dtype=np.float32)) - config = NativePickerConfig(voxel_size_angstrom=10.0) - with pytest.raises(StampValidationError, match='does not match tomogram shape'): - pick_tomogram(tmp_path / 'seg.mrc', tmp_path / 'tomo.mrc', 'tomo000', config) - - def test_config_rejects_bad_density_sign(self) -> None: - '''A density_sign other than +1 or -1 raises''' - with pytest.raises(StampPipelineError, match='density_sign'): - NativePickerConfig(voxel_size_angstrom=10.0, density_sign=0) - - def test_sparse_neighbourhood_falls_back_to_global(self) -> None: - rng = np.random.default_rng(0) - # A dense cluster near the origin, plus one isolated point far away with no neighbours within radius: the isolated point should fall back to global stats - dense_points = rng.normal(size=(50, 3)) * 5.0 - isolated_point = np.array([[500.0, 500.0, 500.0]]) - points = np.vstack([dense_points, isolated_point]) - values = rng.normal(size=51) - normalised, used_fallback = local_normalise(values, points, radius_voxels=20.0, min_neighbours=10) - assert not used_fallback[:50].any() - assert used_fallback[50] - global_median = np.median(values) - global_mad = np.median(np.abs(values - global_median)) - global_scale = 1.4826 * global_mad if global_mad > 0.0 else values.std() - expected_isolated = (values[50] - global_median) / global_scale - assert normalised[50] == pytest.approx(expected_isolated) - - def test_robust_normalise_local_mode_requires_points(self) -> None: - with pytest.raises(ValueError): - robust_normalise(np.ones(10), mode='local') - - def test_multiscale_offsets_separate_two_protrusion_heights(self, tmp_path: Path) -> None: - '''Two particles at distinct protrusion heights are each best scored by the window whose range covers that height, and the recorded winning window separates them.''' - segmentation, tomogram, _ = _vesicle_with_two_protrusion_heights(small_offset_angstrom=35.0, large_offset_angstrom=130.0) - _write_mrc(tmp_path / 'seg.mrc', segmentation) - _write_mrc(tmp_path / 'tomo.mrc', tomogram) - - config = NativePickerConfig(voxel_size_angstrom=10.0, n_mad=2.0) - picks = pick_tomogram(tmp_path / 'seg.mrc', tmp_path / 'tomo.mrc', 'tomo000', config) - - small_picks = [p for p in picks if p.offset_window_angstrom is not None and p.offset_window_angstrom[1] <= 80.0] - large_picks = [p for p in picks if p.offset_window_angstrom is not None and p.offset_window_angstrom[0] >= 70.0] - assert small_picks, 'the 35A protrusion should be won by a small offset window' - assert large_picks, 'the 130A protrusion should be won by a large offset window' - assert {p.offset_window_angstrom for p in small_picks}.isdisjoint( - {p.offset_window_angstrom for p in large_picks} - ) - - def test_single_window_config_matches_pre_6g_threshold(self) -> None: - '''A single-element offset_windows_angstrom has no order-statistic correction to apply.''' - config = NativePickerConfig(voxel_size_angstrom=10.0, offset_windows_angstrom=((40.0, 80.0),), n_mad=3.0) - assert config.effective_n_mad == pytest.approx(3.0) - - def test_multiscale_threshold_correction_holds_false_positive_rate(self, tmp_path: Path) -> None: - ''' - On a particle-free tomogram, scoring four windows and thresholding at effective_n_mad doesn't pass more points than scoring one window at n_mad. - An uncorrected max over the same four windows, thresholded at plain n_mad, does pass more points that scoring a single window. - ''' - segmentation, tomogram = _particle_free_vesicle(seed=0) - _write_mrc(tmp_path / 'seg.mrc', segmentation) - _write_mrc(tmp_path / 'tomo.mrc', tomogram) - - n_mad = 2.5 - single = NativePickerConfig(voxel_size_angstrom=10.0, offset_windows_angstrom=((40.0, 80.0),), n_mad=n_mad, scoring_mode='mean') - multi = NativePickerConfig(voxel_size_angstrom=10.0, n_mad=n_mad, scoring_mode='mean') # default 4 windows - - single_picks = pick_tomogram(tmp_path / 'seg.mrc', tmp_path / 'tomo.mrc', 'tomo000', single) - multi_picks = pick_tomogram(tmp_path / 'seg.mrc', tmp_path / 'tomo.mrc', 'tomo000', multi) - - # uncorrected: same tomogram & windows, thresholded at plain n_mad instead of effective_n_mad - uncorrected_above = _count_above_threshold_uncorrected(tmp_path, multi, n_mad) - - assert len(multi_picks) <= len(single_picks) + 1, f'corrected multi-window picking should not produce more false positives than single-window picking on a particle-free tomogram (single: {len(single_picks)}; multi: {len(multi_picks)})' - assert uncorrected_above > len(multi_picks), f'uncorrected thresholding passes more candidates than the corrected version (single: {len(single_picks)}; uncorrected: {uncorrected_above}; corrected: {len(multi_picks)})' - # TestConsensusRules: class containing tests for consensus rules (intersection/union) class TestConsensusRules: def test_intersection_merges_close_picks_from_different_pickers(self) -> None: @@ -672,71 +269,6 @@ def test_summarise_vesicles_includes_zero_pick_vesicles(self) -> None: assert summaries['t01:v0001'].n_picks == 0 assert summaries['t01:v0001'].picks_per_1000_angstrom2 == 0.0 - def test_normalise_per_vesicle_without_labels_mrc_raises(self) -> None: - '''normalise_per_vesicle needs a labels MRC to normalise against''' - with pytest.raises(StampPipelineError): - NativePickerConfig(voxel_size_angstrom=10.0, normalise_per_vesicle=True) - - def test_picker_wires_vesicle_id_onto_picks(self, tmp_path: Path) -> None: - '''Picks from a labelled vesicle carry that vesicle_id; unlabelled points fall back to None''' - segmentation, tomogram, _ = _vesicle_with_particles() - _write_mrc(tmp_path / 'seg.mrc', segmentation) - _write_mrc(tmp_path / 'tomo.mrc', tomogram) - labels_path = tmp_path / 'labels.mrc' - _write_mrc(labels_path, np.where(segmentation > 0, 1.0, 0.0)) - - config = NativePickerConfig( - voxel_size_angstrom=10.0, - offset_windows_angstrom=((40.0, 80.0),), - surface_spacing_angstrom=20.0, - min_particle_distance_angstrom=80.0, - n_mad=3.0, - density_sign=-1, - vesicle_labels_mrc=labels_path, - ) - picks = pick_tomogram(tmp_path / 'seg.mrc', tmp_path / 'tomo.mrc', 'tomo000', config) - assert picks, 'picker found nothing where a particle was planted' - assert all(pick.vesicle_id in (None, 'tomo000:v0001') for pick in picks) - - def test_picker_without_labels_mrc_leaves_vesicle_id_none(self, tmp_path: Path) -> None: - '''Default behaviour (no --vesicle-labels-mrc) is unchanged: vesicle_id stays None''' - segmentation, tomogram, _ = _vesicle_with_particles() - _write_mrc(tmp_path / 'seg.mrc', segmentation) - _write_mrc(tmp_path / 'tomo.mrc', tomogram) - - config = NativePickerConfig( - voxel_size_angstrom=10.0, - offset_windows_angstrom=((40.0, 80.0),), - surface_spacing_angstrom=20.0, - min_particle_distance_angstrom=80.0, - n_mad=3.0, - density_sign=-1, - ) - picks = pick_tomogram(tmp_path / 'seg.mrc', tmp_path / 'tomo.mrc', 'tomo000', config) - assert picks - assert all(pick.vesicle_id is None for pick in picks) - - def test_picker_normalise_per_vesicle_runs_end_to_end(self, tmp_path: Path) -> None: - '''normalise_per_vesicle=True with a labels MRC scores and picks without error''' - segmentation, tomogram, _ = _vesicle_with_particles() - _write_mrc(tmp_path / 'seg.mrc', segmentation) - _write_mrc(tmp_path / 'tomo.mrc', tomogram) - labels_path = tmp_path / 'labels.mrc' - _write_mrc(labels_path, np.where(segmentation > 0, 1.0, 0.0)) - - config = NativePickerConfig( - voxel_size_angstrom=10.0, - offset_windows_angstrom=((40.0, 80.0),), - surface_spacing_angstrom=20.0, - min_particle_distance_angstrom=80.0, - n_mad=3.0, - density_sign=-1, - vesicle_labels_mrc=labels_path, - normalise_per_vesicle=True, - ) - picks = pick_tomogram(tmp_path / 'seg.mrc', tmp_path / 'tomo.mrc', 'tomo000', config) - assert picks, 'picker found nothing under per-vesicle normalisation' - def test_reconciled_pick_keeps_vesicle_id(self) -> None: '''Consensus reconciliation preserves the representative pick's vesicle_id''' picks_by_picker = { diff --git a/tests/unit/test_refine.py b/tests/unit/test_refine.py index 8413fbe..d3483e6 100644 --- a/tests/unit/test_refine.py +++ b/tests/unit/test_refine.py @@ -105,3 +105,17 @@ def test_assert_distinct_references_rejects_shared_seed(self, tmp_path): def test_output_tree_is_separate_per_half(self, tmp_path): tree = refine_output_tree(tmp_path, 'c00') assert tree['A'] != tree['B'] and tree['A'].is_dir() and tree['B'].is_dir() + +# TestRefineCommand: class containing tests for src/stamp/commands/refine.py +class TestRefineCommand: + # test_full_poses_come_from_assignments_the_polish_step_posed: only rows with a rotation produce a pose, a missing shift is zero + def test_full_poses_come_from_assignments_the_polish_step_posed(self) -> None: + from stamp.commands.refine import _full_poses + from stamp.schemas.particles import ClassAssignment + rows = [ + ClassAssignment(particle_id='a', cluster_id='c00', classifier='x', rotation=(1.0, 0.0, 0.0, 0.0), shift_voxels=(1.0, 2.0, 3.0)), + ClassAssignment(particle_id='b', cluster_id='c00', classifier='x', rotation=(1.0, 0.0, 0.0, 0.0)), + ClassAssignment(particle_id='c', cluster_id='c00', classifier='x', inplane_angle_degrees=10.0), + ] + poses = _full_poses(rows) + assert set(poses) == {'a', 'b'} and list(poses['a'][1]) == [1.0, 2.0, 3.0] and not poses['b'][1].any() diff --git a/tests/unit/test_run.py b/tests/unit/test_run.py index 4293792..7d8e3a7 100644 --- a/tests/unit/test_run.py +++ b/tests/unit/test_run.py @@ -27,6 +27,7 @@ }, 'decoy': {'enabled': True}, 'stage': { + 'pick': {'picks_files': ['picks.csv']}, 'identify': {'candidates': 'candidates.yaml', 'resolution': 25.0}, 'refine': {'tool': 'relion', 'backend': 'local'}, }, @@ -191,4 +192,19 @@ def test_cluster_resume_skips_completed_dependency(self, tmp_path, fake_config, for command in job.commands: command.working_directory.mkdir(parents=True, exist_ok=True) submit_pipeline(fake_config, tmp_path, ['refine'], ClusterProfile(partition='cpu')) - assert submits == [[]] \ No newline at end of file + assert submits == [[]] + +# TestRunConfig: class containing tests for the cross-field rules of the run config +class TestRunConfig: + # test_run_config_prior_rules: the normal prior needs a segmentation directory, other priors need none but a random-volume decoy + def test_run_config_prior_rules(self) -> None: + def build(run_extra: dict, drop_seg: bool = False, decoy: dict | None = None) -> RunConfig: + run = {**_CONFIG_DICT['run'], **run_extra} + if drop_seg: + del run['segmentation_dir'] + return RunConfig.model_validate({**_CONFIG_DICT, 'run': run, 'decoy': decoy or _CONFIG_DICT['decoy']}) + assert build({'orientation_prior': 'none'}, drop_seg=True, decoy={'enabled': True, 'method': 'random-volume'}).run.segmentation_dir is None + with pytest.raises(StampPipelineError, match='segmentation_dir is required'): + build({}, drop_seg=True) + with pytest.raises(StampPipelineError, match='membrane-based'): + build({'orientation_prior': 'axis'}, drop_seg=True) diff --git a/tests/unit/test_schemas.py b/tests/unit/test_schemas.py index 07dc180..8534d3a 100644 --- a/tests/unit/test_schemas.py +++ b/tests/unit/test_schemas.py @@ -9,11 +9,13 @@ from pydantic import ValidationError # Import schemas +from stamp.schemas.config import RunSettings from stamp.schemas.manifest import TomogramManifest from stamp.schemas.particles import ( ClassAssignment, HalfSet, IdentificationResult, + OrientationPrior, Particle, ParticleSet, ) @@ -128,6 +130,17 @@ def test_identification_result_construction(self): ) assert result.candidate_protein == 'Prot001' + # test_class_assignment_pose_fields_are_optional: assignments without pose fields still load, pose fields validate when present + def test_class_assignment_pose_fields_are_optional(self) -> None: + legacy = ClassAssignment.model_validate({'particle_id': 'p0', 'cluster_id': 'c00', 'classifier': 'x', 'inplane_angle_degrees': 12.0}) + assert legacy.rotation is None and legacy.polarity is None + full = ClassAssignment(particle_id='p0', cluster_id='c00', classifier='x', rotation=(1.0, 0.0, 0.0, 0.0), shift_voxels=(1.0, 0.0, -2.0), cc=0.5, margin=0.1, polarity=-1) + assert ClassAssignment.model_validate_json(full.model_dump_json()) == full + with pytest.raises(StampPipelineError): + ClassAssignment(particle_id='p0', cluster_id='c00', classifier='x', rotation=(2.0, 0.0, 0.0, 0.0)) + with pytest.raises(ValidationError): + ClassAssignment(particle_id='p0', cluster_id='c00', classifier='x', polarity=0) + # TestProvenanceSchema: class containing unit tests for schemas/provenance.py class TestProvenanceSchema: def test_provenance_sidecar_construction(self): @@ -200,3 +213,25 @@ def test_write_rolled_produces_a_readable_subvols(self, tmp_path): new_subvols = subvols.write_rolled(rolled, tmp_path / 'rolled') for i in range(len(subvols)): np.testing.assert_array_equal(new_subvols[i], subvols[i] * 2) + + +# test_particle_set_without_prior_loads_as_normal: particle sets written before orientation priors existed load as membrane sets and round-trip +def test_particle_set_without_prior_loads_as_normal() -> None: + legacy = { + 'particles': [{'particle_id': 'p0', 'tomogram_id': 't0', 'position': [1.0, 2.0, 3.0], 'source_picker': 'x', 'half_set': 'A'}], + 'consensus_rule': 'union', + 'contributing_pickers': ['x'], + } + loaded = ParticleSet.model_validate(legacy) + assert loaded.orientation_prior is OrientationPrior.NORMAL + assert ParticleSet.model_validate(loaded.model_dump(mode='json')) == loaded + + +# test_run_settings_orientation_prior: the run table accepts a prior and a tilt range and rejects an impossible tilt +def test_run_settings_orientation_prior() -> None: + base = dict(segmentation_dir='s', raw_tomogram_dir='r', output_dir='o') + settings = RunSettings(**base, orientation_prior='axis', tilt_max_degrees=60.0, tilt_axis_degrees=85.0) + assert settings.orientation_prior is OrientationPrior.AXIS + assert RunSettings(**base).tilt_max_degrees is None + with pytest.raises(ValidationError): + RunSettings(**base, tilt_max_degrees=95.0) diff --git a/tests/unit/test_utils.py b/tests/unit/test_utils.py index 03a37f5..a6841ca 100644 --- a/tests/unit/test_utils.py +++ b/tests/unit/test_utils.py @@ -193,6 +193,16 @@ def test_archive_and_remove_directory(self, tmp_path): names = set(tar.getnames()) assert names == {'raw', 'raw/a.txt', 'raw/b.txt'} + # test_manifests_without_a_segmentation_directory: every raw tomogram gets a manifest with no segmentation + def test_manifests_without_a_segmentation_directory(self, tmp_path: Path) -> None: + for name in ('t0', 't1'): + with mrcfile.new(tmp_path / f'{name}.mrc') as mrc: + mrc.set_data(np.zeros((4, 4, 4), dtype=np.float32)) + mrc.voxel_size = 7.0 + manifests = io_utils.load_tomogram_manifests(None, tmp_path, None) + assert sorted(m.tomogram_id for m in manifests) == ['t0', 't1'] + assert all(m.segmentation_path is None and m.voxel_size_angstrom == 7.0 for m in manifests) + class TestIoMatchByStem: def test_exact_match(self) -> None: raw = [Path('/raw/tomo000.mrc'), Path('/raw/tomo001.mrc')] @@ -436,6 +446,21 @@ def test_signatures_change_with_file_content(self, tmp_path: Path) -> None: assert directory_signatures(tmp_path) != first assert signatures({'a': tmp_path / 'a.mrc'}, content=True) == signatures({'a': tmp_path / 'a.mrc'}, content=True) +# TestPhase: class containing unit tests for phase randomisation +class TestPhase: + # test_phase_randomise_keeps_amplitudes: amplitudes survive, phases change except inside the kept shell + def test_phase_randomise_keeps_amplitudes(self) -> None: + from stamp.utils.phase import phase_randomise + rng = np.random.default_rng(0) + volume = rng.normal(size=(12, 12, 12)) + out = phase_randomise(volume, np.random.default_rng(1)) + assert np.allclose(np.abs(np.fft.fftn(out)), np.abs(np.fft.fftn(volume)), rtol=1e-3, atol=1e-3) + assert not np.allclose(out, volume) + freq = np.fft.fftfreq(12) + keep = np.sqrt(sum(f**2 for f in np.meshgrid(freq, freq, freq, indexing='ij'))) < 0.2 # symmetric under k -> -k, as a shell mask is + kept = np.fft.fftn(phase_randomise(volume, np.random.default_rng(1), keep=keep)) + assert np.allclose(kept[keep], np.fft.fftn(volume)[keep], atol=1e-3) + # TestPickCache: class containing unit tests for cache_tomogram_picks and load_cached_picks in src/stamp/utils/io.py class TestPickCache: def test_round_trip_and_truncated_file_is_skipped(self, tmp_path: Path) -> None: @@ -446,5 +471,3 @@ def test_round_trip_and_truncated_file_is_skipped(self, tmp_path: Path) -> None: (tmp_path / 'cache' / 't1.json').write_text('[{"tomogram_id": ') # truncated loaded = load_cached_picks(tmp_path / 'cache', ['t0', 't1']) assert [p.tomogram_id for p in loaded] == ['t0'] - - diff --git a/uv.lock b/uv.lock index 71e4652..1c0031b 100644 --- a/uv.lock +++ b/uv.lock @@ -140,6 +140,26 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/82/f8/7188153c4b265c899cd035de6a062677d51f67118a4ba640902bd9683e90/fonttools-4.64.0-py3-none-any.whl", hash = "sha256:4a05783ff54ce4c7a28f18e5772efdf63c219374bd9ffc55452182e1cef8be60", size = 1195327, upload-time = "2026-08-31T15:44:31.741Z" }, ] +[[package]] +name = "igraph" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "texttable" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/23/be/56bef1919005b4caf1f71522b300d359f7faeb7ae93a3b0baa9b4f146a87/igraph-1.0.0.tar.gz", hash = "sha256:2414d0be2e4d77ee5357807d100974b40f6082bb1bb71988ec46cfb6728651ee", size = 5077105, upload-time = "2025-10-23T12:22:50.127Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a5/03/3278ad0ceb3ea0e84d8ae3a85bdded4d0e57853aeb802a200feb43847b93/igraph-1.0.0-cp39-abi3-macosx_10_15_x86_64.whl", hash = "sha256:c2cbc415e02523e5a241eecee82319080bf928a70b1ba299f3b3e25bf029b6d4", size = 2257415, upload-time = "2025-10-23T12:22:27.246Z" }, + { url = "https://files.pythonhosted.org/packages/0d/bc/6281ec7f9baaf71ee57c3b1748da2d3148d15d253e1a03006f204aa68ca5/igraph-1.0.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:1a27753cd80680a8f676c2d5a467aaa4a95e510b30748398ec4e4aeb982130e8", size = 2048555, upload-time = "2025-10-23T12:22:29.49Z" }, + { url = "https://files.pythonhosted.org/packages/2a/38/3cd6428a4ed4c09a56df05998438e7774fd1d799ee4fb8fc481674f5f7fc/igraph-1.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a55dc3a2a4e3fc3eba42479910c1511bfc3ecb33cdf5f0406891fd85f14b5aee", size = 5314141, upload-time = "2025-10-23T12:22:31.023Z" }, + { url = "https://files.pythonhosted.org/packages/7d/da/dd2867c25adbb41563720f14b5fc895c98bf88be682a3faff4f7b3118d2a/igraph-1.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:2d04c2c76f686fb1f554ee35dfd3085f5e73b7965ba6b4cf06d53e66b1955522", size = 5683134, upload-time = "2025-10-23T12:22:32.423Z" }, + { url = "https://files.pythonhosted.org/packages/e5/40/243c118d34ab80382d7009c4dcb99b887384c3d2ce84d29eeac19e2a007a/igraph-1.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:f2b52dc1757fff0fed29a9f7a276d971a11db4211569ed78b9eab36288dfcc9d", size = 6211583, upload-time = "2025-10-23T12:22:34.238Z" }, + { url = "https://files.pythonhosted.org/packages/1d/b7/88f433819c54b496cb0315fce28e658970cb20ff5dbd52a5a605ce2888de/igraph-1.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:05c79a2a8fca695b2f217a6fa7f2549f896f757d4db41be32a055400cb19cc30", size = 6594509, upload-time = "2025-10-23T12:22:35.831Z" }, + { url = "https://files.pythonhosted.org/packages/7b/5d/8f7f6f619d374e959aa3664ebc4b24c10abc90c2e8efbed97f2623fadaf5/igraph-1.0.0-cp39-abi3-win32.whl", hash = "sha256:c2bce3cd472fec3dd9c4d8a3ea5b6b9be65fb30edf760beb4850760dd4f2d479", size = 2725406, upload-time = "2025-10-23T12:22:37.588Z" }, + { url = "https://files.pythonhosted.org/packages/af/77/a85b3745cf40a0572bae2de8cd9c2a2a8af78e5cf3e880fc0a249114e609/igraph-1.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:faeff8ede0cf15eb4ded44b0fcea6e1886740146e60504c24ad2da14e0939563", size = 3221663, upload-time = "2025-10-23T12:22:39.404Z" }, + { url = "https://files.pythonhosted.org/packages/ef/7e/5df541c37bdf6493035e89c22bd53f30d99b291bcda6c78e9a8afeecec2b/igraph-1.0.0-cp39-abi3-win_arm64.whl", hash = "sha256:b607cafc24b10a615e713ee96e58208ef27e0764af80140c7cc45d4724a3f2df", size = 2785701, upload-time = "2025-10-23T12:22:41.03Z" }, +] + [[package]] name = "imageio" version = "2.37.4" @@ -260,6 +280,26 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8a/a1/8d812e53a5da1687abb10445275d41a8b13adb781bbf7196ddbcf8d88505/lazy_loader-0.5-py3-none-any.whl", hash = "sha256:ab0ea149e9c554d4ffeeb21105ac60bed7f3b4fd69b1d2360a4add51b170b005", size = 8044, upload-time = "2026-03-06T15:45:07.668Z" }, ] +[[package]] +name = "leidenalg" +version = "0.12.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "igraph" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/82/b7/45bae25ab59321a14902bec2f47e32b92e76f8b4b3887a13ee69a0b32c60/leidenalg-0.12.0.tar.gz", hash = "sha256:c81a45a2fb874fe71e903d43a869d0efeb7f907af70476c03f6945ef0e8f44c5", size = 453641, upload-time = "2026-05-24T10:17:53.556Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/53/7f/0900c05ccbb27744f9dd11321dc2978e9f5ffe678db54f23eb94cf4e5951/leidenalg-0.12.0-cp38-abi3-macosx_10_9_x86_64.whl", hash = "sha256:96eec407f540d9ddb0c103dadc632d5519cfcdb39689fb21ae0ceeaa97bb2ec3", size = 2257399, upload-time = "2026-05-24T10:17:32.257Z" }, + { url = "https://files.pythonhosted.org/packages/72/f6/d15c889c7c65dbc41c84fe83243c203b083f70cef62ed0acc630098b2012/leidenalg-0.12.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:2e0e1c2321c2e06a7f4f8a73ca15fcd54e0139a62afb448933c42badcfab8adc", size = 1926700, upload-time = "2026-05-24T10:17:33.946Z" }, + { url = "https://files.pythonhosted.org/packages/cf/36/7480eef0473bd87f69826e0dfb6bb1c1ee0915fa6d31be445d0bfcbd3a1a/leidenalg-0.12.0-cp38-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5f6a97f698f13a588e1ae7344908cddee9f87d33acc226fc5c5b99752ebd71f8", size = 2546580, upload-time = "2026-05-24T10:17:35.133Z" }, + { url = "https://files.pythonhosted.org/packages/5f/45/cf5eb36b4517bb85397760a6033628695e8b0723b45f10f487b07cec84df/leidenalg-0.12.0-cp38-abi3-manylinux_2_26_i686.manylinux_2_28_i686.whl", hash = "sha256:78df2e463f3ffffffda590e9b0d790107e59f722f095731b78a58803d1ca92e5", size = 2845846, upload-time = "2026-05-24T10:17:37.115Z" }, + { url = "https://files.pythonhosted.org/packages/f7/be/dba31e662c2ee028e20dd0308c1bc6e398dd7a1786fdd0821722537b4124/leidenalg-0.12.0-cp38-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fcbd89655243cc739d28ba23fe894587d8d7235124a9248ba375819585e70090", size = 2739255, upload-time = "2026-05-24T10:17:38.376Z" }, + { url = "https://files.pythonhosted.org/packages/e1/02/22597cf6d7ee093523ad5885a31499d698812db5744d98086383c3da08b5/leidenalg-0.12.0-cp38-abi3-musllinux_1_2_i686.whl", hash = "sha256:c6a6231d3db490ee3cc4004f214b0bb947dc3fabde75bd61d878bc3fb9685d06", size = 4072277, upload-time = "2026-05-24T10:17:39.881Z" }, + { url = "https://files.pythonhosted.org/packages/05/e5/2f3322376fddd6b85790eaddcd314c9402bf81e984b35870acb4cfcbd0e1/leidenalg-0.12.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:63b49f5716c7cb155f3a3e25505bcc33f3c8c62105734fc152bc07518e63e9ab", size = 3799963, upload-time = "2026-05-24T10:17:41.035Z" }, + { url = "https://files.pythonhosted.org/packages/d1/35/f4f07ddac6718a11c70d858fd4afcc849ca84f485b5d7092bcf09492ec06/leidenalg-0.12.0-cp38-abi3-win32.whl", hash = "sha256:283cd987623e2c5e7b11ed3f15b7805d597a934bf387a7e820d2f673001b635f", size = 1675833, upload-time = "2026-05-24T10:17:42.663Z" }, + { url = "https://files.pythonhosted.org/packages/ea/77/0c8fb67729e83bddd43971cd4851f497a96810fca63f8029e3f008e82b1b/leidenalg-0.12.0-cp38-abi3-win_amd64.whl", hash = "sha256:f5d9529b44d5f6add0847d68fa6ced99f581357f6ca02b54c049eb3a2f45ff04", size = 1990568, upload-time = "2026-05-24T10:17:44.071Z" }, +] + [[package]] name = "llvmlite" version = "0.50.0" @@ -854,6 +894,8 @@ version = "0.14.0" source = { editable = "." } dependencies = [ { name = "fast-hdbscan" }, + { name = "igraph" }, + { name = "leidenalg" }, { name = "loguru" }, { name = "matplotlib" }, { name = "mrcfile" }, @@ -877,6 +919,8 @@ dev = [ [package.metadata] requires-dist = [ { name = "fast-hdbscan", specifier = ">=0.3.2" }, + { name = "igraph", specifier = ">=1.0.0" }, + { name = "leidenalg", specifier = ">=0.12.0" }, { name = "loguru", specifier = ">=0.7.3" }, { name = "matplotlib", specifier = ">=3.11.1" }, { name = "mrcfile", specifier = ">=1.5.4" }, @@ -910,6 +954,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/0b/d4/a4e3e0237574058d3b901971f185a22cb4d1751151b224d4cc44b023f1fa/starfile-0.5.13-py3-none-any.whl", hash = "sha256:2a8cd876121e9183b4594442bc3bd0818964aba66da964e5b2c373984b3c0ce7", size = 10614, upload-time = "2025-06-02T19:34:07.532Z" }, ] +[[package]] +name = "texttable" +version = "1.7.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/03/19/9590fd39a668ea0a0869493441fe65852246a3ec67616877baad98bcb039/texttable-1.7.2.tar.gz", hash = "sha256:dc16ea6b35fbf5291ba6ef79d79e37d9b3ca6acd7bae3ca3450488d7c2e19c99", size = 15400, upload-time = "2026-10-18T17:32:36.017Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b9/4d/4de8896d9edcfb421e54d236b22a62be3827ca195ff649cad6fcae660f04/texttable-1.7.2-py2.py3-none-any.whl", hash = "sha256:a381e1ed30e4d4bd24cdacabe26463b7a570c0e964fc0b35d8d9276b2fcbe252", size = 10862, upload-time = "2026-10-18T17:32:34.587Z" }, +] + [[package]] name = "threadpoolctl" version = "3.6.0"