diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cca45e7..a4ab0ca1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,72 @@ The design is [`docs/design-v0.4.md`](docs/design-v0.4.md), imported unchanged f are in [docs/plan.md](docs/plan.md) §12. (The v0.3 to v0.4 migration guide was removed in v0.5.1: no run before v0.5.1 is read.) +## Unreleased (after v0.10.0) + +**Volumes (Z-stacks), the first step of #438** (MorphoBricks-Spec ADR 0010, proposed; built ahead +of its acceptance as a draft). A **breaking change** of the run manifest (version 7) and of the +resolver contract (version 5): every consumer re-pins `SUPPORTED_RESOLVER_VERSIONS` to `{5}` and +every run folder is run again. + +### Changed + +- **The Spec pin moves from `232fb38` to `5aad8d3`** (the merge of ADR 0010, accepted 3 December + 2026, after ADR 0009): only the vendored `experiment-v1.md` changes (volumes, §1, §4.5, §8); the + fixtures are the same. Notebook drafts written under the old pin are refused + (`spec_commit_mismatch`): start the draft again from the folders; a published + `morphobricks.toml` is untouched. +- **A Z-stack is described, tagged and calibrated as a volume** (VZ1). The description-step error + `z_stack_not_supported` is removed (header check, axis review, `convert`), and with it + `check_metadata(allow_z=)` and `inspect_images(allow_z=)`. A volume is an image whose + **confirmed** `Z` role has more than one slice; a one-slice `Z` is a plane image. Projection stays + an explicit, recorded choice with no default: the notebook's Axes step asks to either *Keep the + 3-D stacks* (now enabled) or write projected copies before the roles can be confirmed. +- **Run manifest version 7** (written; versions 6 and 5 are read only for a new run's inputs and + refused by `RunInputs.open` with `RUN_FOLDER_VERSION`). Every file entry records `shape`, + `z_count`, `t_count`, `c_count`, `image_kind` (`plane` or `volume`), `plane_statistics` + (`computed` or `not_computed_volume`), `plane_count` (now the physical planes, `t_count × + z_count`) and `statistics_rows` (VC2, VC3), each checked against the others by the writer and the + reader. `pixel_sizes` entries gain `reason` and write `source = "unknown"` where nothing gives a + size (VC4; the conversion and projection records keep their codec). New required top-level keys + `checks` (one run-level `W_AXIS_UNCALIBRATED`, `W_MIXED_PLANES_AND_VOLUMES`; derived from the entries + and recomputed by `RunInputs.open`, VC5) and `statistics_artifacts` (VC1). +- **Histograms, normalization and QC metrics are not computed for volumes** (VZ2): a volume's + pixels are not read by the run, it has no row in `plane_histograms.parquet` or `image_qc.csv`, + and a run of volumes only writes **neither table** (both digests and `image_qc` null, + `statistics_artifacts = {"state": "not_computed", "reason": "all_volumes"}`, VZ29) and removes the + tables of an earlier run in the same output folder. Plane images in the same run are unaffected. +- **Keeping Z-stacks is an explicit, recorded choice** (VZ32): a run with volumes needs it (the + notebook's *Keep the 3-D stacks*, `run --keep-z-stacks`, `RunMode(keep_z_stacks=True)`), given or + recorded by the earlier run; without it the run stops before any read (`z_stacks_not_chosen`). The + manifest records `z_handling`: `null`, `"kept"` or `{"projected": method}`. +- **Unknown steps are recorded, never guessed** (VZ9, VZ12, VZ18, VZ30): an `X` or `Y` without a + length, and the `Z` of a volume without one, carry `W_AXIS_UNCALIBRATED` in their `pixel_sizes` + (also for `pixels`, VZ24); `checks` and the run report give it **once per run** with the axes and + how many images lack each, and the fix; nothing is blocked. The Axes step's calibration card lists + them as soon as the roles are confirmed. +- **Mixed runs are checked early and warned, never refused** (VZ4, VZ8, VZ19, VZ31): + `W_MIXED_PLANES_AND_VOLUMES` gives the counts, every place holding both kinds, what it means + downstream (MorphoFeature refuses such a run) and the fix, at the axis review (the notebook's Axes + step and keep-or-project card, `check`), in the run's `checks` and report, and in the run summary. +- **`R_UNIT_NOT_HOMOGENEOUS` compares the confirmed roles other than `Z` and `T`** (VC11, VZ34), so a + plain stack confirmed `ZYX` joins a unit of `YX` images. +- **Resolver contract version 5** (with ADR 0002 AR12 in the same wave, so version 4 is never + released, VZ27): `Request.fov_subset` (`A_FOV_NOT_IN_RUN`) and `Request.z_indices` (VC13); a + `plane` request without `z_indices` on a volume is `A_VOLUME_NOT_SUPPORTED` (rule (b)); an index + an image lacks is `A_Z_INDEX_NOT_IN_IMAGE` (`run_inputs_request.z_index_refusals`); BM5 is kept for + explicit planes; `Provenance.fov_scope` records `z_indices`, and its `scope_digest` covers it. +- **`RunInputs`**: `Fov.z_count`, `t_count` and `c_count` come from the manifest, never from rows; + `histograms(fovs=None)`, the new `image_qc(fovs=None)` and `require_plane_statistics(fovs)` refuse + volumes with `VOLUME_STATISTICS_NOT_COMPUTED` (`run_inputs_statistics.refuse_volume_statistics`, + VC6; "Plane histograms are / Normalization is / QC metrics are not computed for volumes", + VZ33) and check the rows against the manifest; `records` is internal (`_records`); + `read_plane(fov, z=None, ...)` refuses an omitted `z` on a volume and `read_image(fov, *, + volume=False)` a volume without `volume=True` (B2); the new `read_mask_volume` (VC9, VZ28); + `read_objects` refuses a plane outside its selection (VC8); `pixel_sizes` gives `unknown` and + `reason`; the new `check_consumer(...)` applies a consumer's `volume_support`, + `mixed_volume_support` and `requires_calibration` (ADR 0009 O9, O10; + `R_CONSUMER_DIMENSIONS_NOT_ALLOWED`). `fit_scaling` calls `require_plane_statistics` first. + ## v0.10.0 (3 December 2026) Minor release with a **breaking change of file format**: the histogram table is diff --git a/README.md b/README.md index 4392d910..67224c0a 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,11 @@ The preprocessing brick of MorphoBricks. It reads an experiment folder of microscopy TIFFs, computes one intensity histogram per channel of every plane, and writes them, with each plane's experimental labels, to `plane_histograms.csv`: one row per plane -(an image at one time point), each channel in its own columns. MorphoBricks v1 analyses 2-D -planes: a Z-stack (more than one depth slice) is refused (`z_stack_not_supported`); make -recorded 2-D projected copies first with `convert --project max|mean|sum`, and use the copies. Later bricks +(an image at one time point), each channel in its own columns. A Z-stack (more than one depth +slice) is either kept as a **volume** (`run --keep-z-stacks`, the notebook's *Keep the 3-D +stacks*: described and handed to tools that declare volume support, with no histograms, +normalization or QC computed for it) or projected first into recorded 2-D copies with +`convert --project max|mean|sum`; there is no default (Spec ADR 0010). Later bricks (for example patch extraction) use that table to calculate normalization parameters for any group of images without rereading the pixels. diff --git a/docs/colab-release-check.md b/docs/colab-release-check.md index f8a2a516..b48247db 100644 --- a/docs/colab-release-check.md +++ b/docs/colab-release-check.md @@ -227,10 +227,13 @@ again on the tagged commit. ## C. Z-stacks, time-lapse and the OME-Zarr copy (Colab) 17. **Z-stacks** (a new output folder). - - [ ] Scan and read the headers; the viewer has a **z** slider. On Axes the stacks are - still refused (`z_stack_not_supported`) and the card **Z-stacks: save the dataset as - projections** appears: the method list starts on "— choose a method —" (maximum, mean, - sum; no default) and the slices are all unless changed. + - [ ] Scan and read the headers; the viewer has a **z** slider. On Axes no error is + shown for the stacks (they are volumes, Spec ADR 0010) and the card **Z-stacks: save the + dataset as projections** appears; *Confirm axis roles* stays closed until **Keep the 3-D + stacks** is ticked or a projection is written: the method list starts on "— choose a + method —" (maximum, mean, sum; no default) and the slices are all unless changed. + - [ ] With **Keep the 3-D stacks** ticked, the run says "not computed: volume" before and + after it runs, and with stacks only no `plane_histograms.parquet` is written. - [ ] **Show this projection of the image above** shows the projection of the example. **Write the projected copies and continue with them** is greyed, with its reason, until a method is chosen and the example is checked; then it writes diff --git a/docs/contract.md b/docs/contract.md index 0a46176c..1553b2a0 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -87,7 +87,7 @@ channel order; an image without a C axis has one channel. | Experiment mapping | Defined on the TIFF arrangement when the experiment has TIFF files; in an experiment of OME-Zarr images only, on their arrangement with the most axes. | | Channel names, significant bits | Recorded in the run manifest when metadata provides them; not part of the CSV. Channel names that differ at the same channel index are the error `channel_names_differ` (issue #37): channels are matched by their number, so two stains at one number would be pooled as one channel. Only named channels are compared; a channel without a name in some images is not. Names are read without leading and trailing whitespace, for every image (TIFF, OME-Zarr and this brick's own copies), so `DAPI ` and `DAPI` are one name; the manifest records it (`channel_names_trimmed`, §9). Whitespace inside a name is compared exactly (`DA PI` and `DAPI` differ), with no override. An OME-Zarr channel label that is not text is malformed metadata: the image is unreadable (`unreadable_ome_zarr`), never read as an unnamed channel. | | Physical sizes | Read with the header, not part of the CSV or the manifest, and compared between images in the folder check (§11, in micrometres with each axis's own unit; a size without a known unit cannot be compared): `PhysicalSizes` with the size of one step along X, Y, Z and T and each axis's unit (OME-NGFF unit names). TIFF: OME `PhysicalSize{X,Y,Z}` with their own units (micrometres when left out) and `TimeIncrement`, or ImageJ resolution, `spacing` and `finterval` with `unit`, `yunit`, `zunit`. OME-Zarr (0.4 and 0.5): the `scale` of level 0's `coordinateTransformations`, times the multiscales entry's own `scale` when given, with each axis's `unit` (common spellings such as `µm`, `um`, `micron` and `s` given as UDUNITS-2 names, others as written). Length units are the microscopy units of MorphoBricks decision D-a2 (§16): `pm`, `Å`/`angstrom`, `nm`, `µm` (`um`, `micron(s)`, `micrometer(s)`, `micrometre(s)`), `mm`, `cm`, `m`, and the names of each in US and British spelling (`nanometre`, ...); ImageJ's escaped micro sign (`\u00B5m`) is recognised. A size in any other unit (`inch`, `decimeter`, ...) is not converted to micrometres, so it cannot be compared: that axis is uncalibrated, and the unit as written is kept in `PhysicalSizes.unsupported_units` (axis letter and unit, information only, not part of equality) so that the folder check names it (`unsupported_pixel_size_unit`, §11). A plain TIFF's resolution tags (no OME or ImageJ metadata, for example 300 dpi with the unit inch) are never a pixel size (decision D-c): such an image has no calibration. Nothing is guessed: what the metadata does not give is None. Nothing is dropped silently either (issue #94): a calibration given but malformed (`coordinateTransformations` that are not a list, a transformation of a type other than `scale`, `translation` and `identity`, more than one scale, a scale in a separate file (`path`) or not one number per axis) gives no sizes, and a scale value of X, Y, Z or T that is not a positive finite number gives none on that axis; each is recorded with what is wrong (`PhysicalSizes.invalid`, `ngff_scale.read_scale`) and named by the warning `invalid_physical_calibration` (§11). The same holds for a size that is not a positive finite length in micrometres once converted (issue #93: `1e308 m` overflows to infinity, `1e-320 pm` underflows to zero; also an OME-Zarr level-0 scale times the image's scale that does so), from any TIFF or OME-Zarr metadata: the size is None, never `inf`, and `PhysicalSizes.invalid` gives the axis and the value; an OME-Zarr scale without a unit is kept with the unit None (in `PhysicalSizes`, with `""` in `unsupported_units`; the run records it as unknown, audit I3, and `unsupported_pixel_size_unit` names it), except on the axes a multiscales entry's `metadata` lists as `unknown_scale` (copies written by this brick up to v0.3, §10), whose sizes are None. | -| Depth slices (v0.4.0) | MorphoBricks v1 analyses 2-D planes (owner decision of 5 November 2026; 3-D feature extraction is a separate project). An image with more than one depth slice is the **error** `z_stack_not_supported`, naming every such image with its number of slices: from the Z axis its header names (`metadata.check_metadata`, before any role is confirmed: an ImageJ hyperstack, OME-TIFF, shaped TIFF or OME-Zarr image) and again under each image's confirmed roles (`review_axes`, which supersedes it; `size_checks.z_stack_issues`): a plain stack confirmed with a Z role is refused, and an image the mapping does not fit is measured by its header. An image whose header names Z but whose roles are confirmed otherwise (an ImageJ stack of time points that tifffile reads as Z, confirmed `T`) is the axis error `axes_contradict_header` instead, never read, so that its fix, named-axis copies (`convert`, §17), is not blocked. It is found before any pixel is read, so `check`, `run` and `convert` stop before writing anything but the report. A Z axis of one slice, named by the header or not, and an image without one are accepted as they are; nothing is squeezed, projected or guessed. The fix is an explicit, recorded step, never an implicit projection when an image is read: `convert --project max|mean|sum` writes 2-D projected copies (§17, plan §12 question 77) and the run is made on the copies. Time-lapses (T > 1) are accepted; their masks need the same T (§15). | +| Depth slices (Spec ADR 0010) | An image whose **confirmed** Z role has more than one slice is a **volume**; any other image is a plane image (a one-slice Z included). A volume is described, tagged and calibrated as it is (the error `z_stack_not_supported` of v0.4.0 is removed, #438): its pixels are not read by the run, and histograms, normalization and QC metrics are not computed for it (`plane_statistics = "not_computed_volume"`, §9). Header letters are evidence only: a plain stack confirmed with a Z role is a volume. A run mixing plane images and volumes records `W_MIXED_PLANES_AND_VOLUMES`; nothing refuses it here. The hand-off is the one Z gate (`RunInputs`, resolver contract version 5): a `plane` request on a volume names its `z_indices`, and a whole volume needs `volume_support`. Projection stays an explicit, recorded step (`convert --project max|mean|sum`, §17), never implicit. Time-lapses (T > 1) are accepted; their masks need the same T (§15), and so do the masks of a volume (its Z). | | Plane counts | Images may have different numbers of time points or planes along an unassigned dimension; this is a warning (§11). | | Channel counts | Stage 3 S3.3 (owner decision of 11 November 2026; normalization N43 replaced by per-row presence, ADR 0003): imaging units may have different channels. Each unit lists its channels by canonical ID in the published description (experiment-v1 §4.4: entry *i* is C*i*); the same ID is the same stain; an image's channel count must match its unit (`R_CHANNEL_COUNT_MISMATCH`). Inside one unit (a leaf folder) every image has the same number of channels: along the C axis, 1 without one (also when a missing C axis is confirmed as length 1). A different number there is the error `different_channel_counts` naming the folder, found from the headers before any pixel is read: in the folder check (the `C` dimension, or the RGB samples `S` when there is no `C`), and again with the confirmed axis roles, which decide (§11); a run names it `R_UNIT_NOT_HOMOGENEOUS`. Images of different folders are never compared. Units of different image types (RGB beside channel units, Spec `v29`) stay refused with `R_HETEROGENEOUS_LAYOUT_NOT_ENABLED`. | @@ -212,7 +212,7 @@ method is an offset and a scale, `(pixels − offset) / scale`. | Severity | Situations | Effect | |---|---|---| -| Error | Experiment design not confirmed (`design_not_confirmed`) or a repeat group holding two folders of one condition (`repeat_group_conflict`), when a design is used (§12); image type RGB for images that are not three channels of an integer type (`rgb_not_possible`, §13); mixed dtypes; images with different numbers of channels (`different_channel_counts`, §2) or different channel names at the same channel number (`channel_names_differ`, §2); unreadable TIFF (header or pixel data) or OME-Zarr folder in a leaf folder that is not excluded; OME-Zarr images without the `zarr` extra; OME-Zarr images whose declared axes do not fit the experiment's roles or that the confirmed roles contradict (`ome_zarr_axes_mismatch`, §2); OME-Zarr images that do not name their axes, and every OME-NGFF 0.1 or 0.2 store (`unreadable_ome_zarr`, §2); every image excluded; more than one image series in a file; unsupported sample format or axis; an image with more than one depth slice (`z_stack_not_supported`, §2; MorphoBricks v1 analyses 2-D planes); missing/duplicate X or Y, duplicate roles, unassigned non-singleton axis, inconsistent mapping; an image whose confirmed roles swap Y and X, contradict its header or put X before Y (`axes_yx_swapped`, `axes_contradict_header`, `axes_x_before_y`, §2); plane that cannot be read within the memory limit, not even in blocks (for example a plane stored compressed in one piece); a plane over the memory limit stored with a TIFF compression whose decoding memory is not measured, which is never read in blocks (`compression_not_bounded`, §9.1 *Codecs*, #356); folder named `single` in another case, or beside other folders (§1); folders of one level differing only in case, anywhere in the experiment (`case_conflict`); folder or image names with outer whitespace or reading as a missing value (`invalid_name`, §1); images in one leaf folder with the same position identifier (§1); links that leave the experiment or masks folder, loop, or reach one file twice (`link_outside_folder`, `link_loop`, `linked_twice`, §1); a mount point below the experiment or masks folder (`mounted_folder`, §1); folder below the technical-repeat level; images in a folder that also holds subfolders (`tiff_outside_leaf`, §1); output folder inside the experiment or inside the masks folder (`output_inside_masks`, §15); experiment or named-axis copies inside the masks folder (`experiment_inside_masks`, `copies_inside_masks`, §15); images named as masks of other images (`image_named_as_mask`, §1); no usable planes; no axis roles given or recorded (`axes_not_confirmed`, §9.2); another run holding the output folder's lock (`output_locked`, §9.2); a copy tree whose conversion record cannot be read (`conversion_record_unreadable`, §17), or whose copies changed, went missing or were added since the conversion (`copy_changed_after_conversion`, §17; owner decision of 2 November 2026, PP-12: the bricks would refuse the run); an image that changed or went missing while the run checked or read it (`source_changed_during_run`, §9.4; no scientific outputs are published and sources are untouched; the discovery report is written); a mask that changed while its header was read (`mask_changed_during_check`) or after it, before the run's commit (`mask_changed_during_run`, §9.4, issue #160; the same); a recorded `experiment_design.csv` that cannot be read (`design_unreadable`); a `calibration.csv` that cannot be read (`calibration_unreadable`) or that states sizes for a target that is neither a folder nor an image of the experiment (`calibration_target_not_found`, §9.3); no experiment folder given or recorded (`experiment_not_recorded`, §9.2); when masks are given, a masks folder missing or inside the experiment, mask names differing only in case, two masks of one type for an image, a mask whose name could belong to two images or types, or a mask that is unreadable, has axes other than Y, X and named or stated Z/T (`mask_not_2d`), has stated axes that do not fit it or contradict the axes its metadata names (`invalid_mask_axes`, `mask_axes_contradict_header`), is stated `YX` (`shared_mask_not_supported`, §15), is stored with X before Y (its header's or its stated axes; refused by `check` and `run` too, never recorded with empty axes) or with its image's Y and X sizes swapped (`mask_layout`; never transposed), is of another size than its image (in `run`, its image's Y and X under the confirmed roles; not reported for an image with an axis error), is not of integers or booleans, has other depth slices or time points than the image's other masks or, in `run`, than the image (§15) | Processing is blocked | +| Error | Experiment design not confirmed (`design_not_confirmed`) or a repeat group holding two folders of one condition (`repeat_group_conflict`), when a design is used (§12); image type RGB for images that are not three channels of an integer type (`rgb_not_possible`, §13); mixed dtypes; images with different numbers of channels (`different_channel_counts`, §2) or different channel names at the same channel number (`channel_names_differ`, §2); unreadable TIFF (header or pixel data) or OME-Zarr folder in a leaf folder that is not excluded; OME-Zarr images without the `zarr` extra; OME-Zarr images whose declared axes do not fit the experiment's roles or that the confirmed roles contradict (`ome_zarr_axes_mismatch`, §2); OME-Zarr images that do not name their axes, and every OME-NGFF 0.1 or 0.2 store (`unreadable_ome_zarr`, §2); every image excluded; more than one image series in a file; unsupported sample format or axis; missing/duplicate X or Y, duplicate roles, unassigned non-singleton axis, inconsistent mapping; an image whose confirmed roles swap Y and X, contradict its header or put X before Y (`axes_yx_swapped`, `axes_contradict_header`, `axes_x_before_y`, §2); plane that cannot be read within the memory limit, not even in blocks (for example a plane stored compressed in one piece); a plane over the memory limit stored with a TIFF compression whose decoding memory is not measured, which is never read in blocks (`compression_not_bounded`, §9.1 *Codecs*, #356); folder named `single` in another case, or beside other folders (§1); folders of one level differing only in case, anywhere in the experiment (`case_conflict`); folder or image names with outer whitespace or reading as a missing value (`invalid_name`, §1); images in one leaf folder with the same position identifier (§1); links that leave the experiment or masks folder, loop, or reach one file twice (`link_outside_folder`, `link_loop`, `linked_twice`, §1); a mount point below the experiment or masks folder (`mounted_folder`, §1); folder below the technical-repeat level; images in a folder that also holds subfolders (`tiff_outside_leaf`, §1); output folder inside the experiment or inside the masks folder (`output_inside_masks`, §15); experiment or named-axis copies inside the masks folder (`experiment_inside_masks`, `copies_inside_masks`, §15); images named as masks of other images (`image_named_as_mask`, §1); no usable planes; no axis roles given or recorded (`axes_not_confirmed`, §9.2); another run holding the output folder's lock (`output_locked`, §9.2); a copy tree whose conversion record cannot be read (`conversion_record_unreadable`, §17), or whose copies changed, went missing or were added since the conversion (`copy_changed_after_conversion`, §17; owner decision of 2 November 2026, PP-12: the bricks would refuse the run); an image that changed or went missing while the run checked or read it (`source_changed_during_run`, §9.4; no scientific outputs are published and sources are untouched; the discovery report is written); a mask that changed while its header was read (`mask_changed_during_check`) or after it, before the run's commit (`mask_changed_during_run`, §9.4, issue #160; the same); a recorded `experiment_design.csv` that cannot be read (`design_unreadable`); a `calibration.csv` that cannot be read (`calibration_unreadable`) or that states sizes for a target that is neither a folder nor an image of the experiment (`calibration_target_not_found`, §9.3); no experiment folder given or recorded (`experiment_not_recorded`, §9.2); when masks are given, a masks folder missing or inside the experiment, mask names differing only in case, two masks of one type for an image, a mask whose name could belong to two images or types, or a mask that is unreadable, has axes other than Y, X and named or stated Z/T (`mask_not_2d`), has stated axes that do not fit it or contradict the axes its metadata names (`invalid_mask_axes`, `mask_axes_contradict_header`), is stated `YX` (`shared_mask_not_supported`, §15), is stored with X before Y (its header's or its stated axes; refused by `check` and `run` too, never recorded with empty axes) or with its image's Y and X sizes swapped (`mask_layout`; never transposed), is of another size than its image (in `run`, its image's Y and X under the confirmed roles; not reported for an image with an axis error), is not of integers or booleans, has other depth slices or time points than the image's other masks or, in `run`, than the image (§15) | Processing is blocked | | Warning | Images whose metadata does not name their axes, read with the confirmed roles (`axes_not_named`, §2); images or masks with other names, hard links (`hard_linked_file`, §1); in a tree of named-axis copies, sources changed or gone since the conversion (`conversion_source_changed`, §17); folders named like a masks folder holding images named as masks (`mask_folder_in_experiment`, §1); intensity checks of the written table (`image_intensity_outlier`, `repeat_intensity_shift`, `saturated_image`, `no_intensity_spread`, `channel_without_finite_pixels`, §14), reported apart from the run's issues; channels of a unit that do not look like the same channels of the other units (`channel_unlike_others`, `possible_channel_swap`, `ambiguous_channel_swap`, §14.1), reported the same way; files that are not images; empty folders; images excluded by the user, or excluded paths that match no image; non-finite pixels; different image widths or heights; different numbers of depth slices, time points or other planes; physical pixel sizes that differ or are known for only some images; a stated pixel size that differs from the header (`calibration_differs_from_header`, §9.3; the stated size is used); unbalanced numbers of images; biological repeats missing from some conditions (§11); planes without finite pixels while others remain; channels whose central intensity range covers too few histogram bins (`narrow_histogram_range`, §4); planes over the memory limit that are read in blocks; images without a mask of a type other images have, masks matching no image, masks of excluded images, files outside the mask-type folders (§15) | Processing continues; the item is reported | Every message states what happened in plain language, lists the affected paths, and @@ -277,7 +277,7 @@ interpretation. | Key | Meaning | |---|---| -| `manifest_version`, `schema_version` | Manifest format (`"6"`) and histogram table format (`"6"`), written as JSON **strings**, not numbers. **Version 6** (v0.10.0, Spec ADR 0008) is the only manifest version written; **versions 6 and 5 are read** (owner decision 10 of 1 December 2026): a version 5 manifest (its table `plane_histograms.csv`, `csv_sha256`) reads, but its table is refused where it would be used (`RunInputs.open`: `RUN_FOLDER_VERSION`, run preprocessing again; a new run recomputes every row). Before: version 5 was the only manifest version written and read (v0.5.2, Stage 3 S3.3; version 4 was the only one in v0.5.1, owner ruling 16, ADR 0002 AR11): every manifest carries `experiment_description`, and holds a `content_sha256` in every file entry exactly when `settings.verify_content` is true (a content-verification run, which every run is unless it opts out, #159). The reader and the writer refuse a manifest without `experiment_description` or with content hashes that do not match `verify_content`. Any other version (`"1"` before v0.4.0; `"2"` and `"3"`, the undescribed runs of v0.4.0 and v0.5.0; `"4"`, the runs of v0.5.1 with their schema version 4 table; a later one) is refused with `ManifestFormatError: Manifest version '…' is not supported … Run preprocessing again …`: by `read_manifest`, `RunInputs.open` and `check_sources`; the next run in that output folder reads every image again and replaces it. Nothing is converted. Switching between a strict and a default run recomputes every row. A manifest whose `schema_version` is not the current one makes the next run recompute every row. | +| `manifest_version`, `schema_version` | Manifest format (`"7"`) and histogram table format (`"6"`), written as JSON **strings**, not numbers. **Version 7** (Spec ADR 0010, after v0.10.0: volumes) is the only manifest version written; `RunInputs.open` uses version 7 only and refuses an older run with `RUN_FOLDER_VERSION` (run preprocessing again), so no reader takes a Z extent from histogram rows. Versions 6 and 5 are still **read** for the inputs a new run takes from the earlier one. Version 6 (v0.10.0, Spec ADR 0008) was the one written before; **versions 6 and 5 were read** (owner decision 10 of 1 December 2026): a version 5 manifest (its table `plane_histograms.csv`, `csv_sha256`) reads, but its table is refused where it would be used (`RunInputs.open`: `RUN_FOLDER_VERSION`, run preprocessing again; a new run recomputes every row). Before: version 5 was the only manifest version written and read (v0.5.2, Stage 3 S3.3; version 4 was the only one in v0.5.1, owner ruling 16, ADR 0002 AR11): every manifest carries `experiment_description`, and holds a `content_sha256` in every file entry exactly when `settings.verify_content` is true (a content-verification run, which every run is unless it opts out, #159). The reader and the writer refuse a manifest without `experiment_description` or with content hashes that do not match `verify_content`. Any other version (`"1"` before v0.4.0; `"2"` and `"3"`, the undescribed runs of v0.4.0 and v0.5.0; `"4"`, the runs of v0.5.1 with their schema version 4 table; a later one) is refused with `ManifestFormatError: Manifest version '…' is not supported … Run preprocessing again …`: by `read_manifest`, `RunInputs.open` and `check_sources`; the next run in that output folder reads every image again and replaces it. Nothing is converted. Switching between a strict and a default run recomputes every row. A manifest whose `schema_version` is not the current one makes the next run recompute every row. | | `written_at` | UTC time of writing, ISO 8601. `written_at` is the only field excluded from byte identity (owner decision of 16 November 2026): two runs of the same inputs and settings write byte-identical outputs except for this value (and the manifest SHA-256 the report names, which follows from it), whatever their number of workers; the tests compare the manifest's raw bytes under a fixed clock, never with the field deleted. A rerun whose manifest would differ from the earlier one only in `written_at` keeps the earlier time, so the manifest's bytes and SHA-256, which later bricks pin, stay the same (cross-brick test F10, 3 November 2026); the report still records the rerun. | | `experiment_root` | Absolute path of the experiment folder, for information. | | `dtype` | Pixel type of the experiment. | @@ -285,6 +285,10 @@ interpretation. | `axis_mapping` | `axes` (file axis labels) and `roles` (`X`, `Y`, `Z`, `C`, `T` or null per axis). | | `labels` | One entry per leaf folder: `folder` (relative path, `.` for the root) and its three labels. | | `files` | One entry per analysed file, sorted by path: `relative_path`, `size` (bytes), `mtime_ns`, the three labels, `axes`, `singleton_roles`, `plane_count` (its rows in the table: XYC planes), `channel_names` (list, null for unnamed channels; empty if none in metadata), `significant_bits` (null if not in metadata), `read_in_blocks` (true when the image's planes are over the memory limit and are read in blocks; the histogram rows are the same either way, but the image QC rows are not, so with it a changed memory limit recomputes them, §19; required), `position_id` (the image's position identifier, §1: its name without the extension, never edited; required: an entry without it, with null, or with another value than `position_id(relative_path)` is refused naming the entry, by the reader and the writer, round-2 audit A-m5), `channel_names_trimmed` (true when leading or trailing whitespace was removed from the image's channel names as they were read, §2; `channel_names` holds the trimmed names; required), `channel_ids` (manifest version 5, Stage 3: the image's canonical channel IDs in source order, its unit's confirmed list; required; part of the row key, so rows recorded under other IDs are recomputed), `roles` (the role of each of the file's `axes`, `X`, `Y`, `Z`, `C`, `T` or null, from the file's own mapping: an OME-Zarr image in another order than `axis_mapping` has its own roles, so later bricks read these rather than rebuild them from `axis_mapping`; required). For an OME-Zarr image, `size` is the total size of its files, `mtime_ns` the time of its newest file, and `inventory_sha256` (v0.4.0, PP-12, issue #86; only for OME-Zarr images) the SHA-256 of its inventory: one line per file (its path relative to the image with `/`, a NUL, its size, a NUL, its `mtime_ns`, a newline), sorted by path, its root `labels` group left out; links to folders inside the image are followed, as the reader follows them, and links that reach one folder twice are refused. Adding, removing, renaming, resizing or touching any chunk or metadata file changes it; an OME-Zarr image recorded without it (v0.4.0rc3 and earlier) counts as changed (recomputed; `RunInputs` refuses it). Like a TIFF file's size and time it is metadata only (design v0.4 §1): a file rewritten with the same size and its time set back is not seen, only hashing the content would. **Version 2 (v0.4.0):** `roles` is required, with `axes_from` (required): `header` when the metadata names every axis and the roles agree, `confirmed` for a plain stack whose roles the user confirmed (§2); and `pixel_sizes`, one entry per role `X`, `Y`, `Z`, `T` with `value`, `unit` (OME-NGFF name) and `source`: `header` (the image's metadata) or `stated` (`calibration.csv`, §9.3) with a value, or `pixels` (stated as deliberately uncalibrated) with `value` and `unit` null; `value` and `source` null for an axis nothing gives a size (never guessed). A `header` or `stated` size without a value, or a value with no source or with `pixels`, is refused. The reader refuses an entry without `roles`, `axes_from` or `pixel_sizes`, and the writer refuses to write one (no older manifest is read leniently, SWEEP-PP). `content_sha256` (only in a `verify_content` run): the SHA-256 of the image's bytes, or for an OME-Zarr image of one line per file (its path relative to the image with `/`, a NUL, the file's SHA-256, a newline) over the files its inventory covers, in path order (`source_content.source_content_sha256`). | +| `files` (version 7, Spec ADR 0010) | Each entry also records `shape` (one positive integer per axis letter, the sizes the image was read with), `z_count`, `t_count`, `c_count` (the sizes of the confirmed `Z`, `T` and `C` roles, 1 when absent), `image_kind` (`"plane"`, or `"volume"` exactly when `z_count` > 1), `plane_statistics` (`"computed"`, or `"not_computed_volume"` for a volume), `plane_count` (the physical XYC planes, `t_count × z_count`) and `statistics_rows` (its rows in the histogram table: `t_count` for a plane image, 0 for a volume); all required and checked against each other when written and read (VC2, VC3). Each `pixel_sizes` entry is `{role, value, unit, source, reason}`: `source` is `header`, `stated`, `pixels` or `unknown` (never null), `value` and `unit` are null except for `header` and `stated` (a length unit for X, Y and Z, a time unit for T, which is never stated), and `reason` is derived: `W_AXIS_UNCALIBRATED` for an X or Y whose source is `pixels` or `unknown`, and for the Z of a volume likewise; null otherwise (VC4). The conversion and projection records keep their own codec (null source, no `reason`). | +| `checks` (version 7) | Required list, derived from the entries and the description and recomputed by `RunInputs.open` (VC5): one run-level `{"code": "W_AXIS_UNCALIBRATED", "axis": null, "counts": {"x": n, ...}, "images": [...], "places": []}` when any entry carries the reason (counts: how many images lack each axis; VZ30), and one `{"code": "W_MIXED_PLANES_AND_VOLUMES", "axis": null, "counts": {"planes", "volumes"}, "images": [every image], "places": [...]}` when the run holds both kinds; images `{fov_key, path, z_count, source}` sorted by FOV key then path; places `{level, key}` for each condition, biological repeat and imaging unit holding both kinds (canonical IDs), then `{"level": "run", "key": []}`. Sorted by code, then axis (null first). | +| `z_handling` (version 7) | Required: `null` (no Z-stack to choose for), `"kept"` (the run holds volumes, run on the user's explicit choice: `run --keep-z-stacks`, the notebook's *Keep the 3-D stacks*; without it `z_stacks_not_chosen`) or `{"projected": method}` (a run on projected copies). Derived from the entries and `projection`, refused when it disagrees (VZ32). | +| `statistics_artifacts` (version 7) | Required: `{"state": "computed"}` when at least one image is a plane image (the tables hold the plane images' rows only), or `{"state": "not_computed", "reason": "all_volumes"}` when every image is a volume: no `plane_histograms.parquet` and no `image_qc.csv` are written, `histogram_table_sha256`, `histogram_table_content_sha256` and `image_qc` are present and null, and such a run removes the tables of an earlier run in its output folder (VC1). | | `histogram_table_sha256` | SHA-256 of the bytes of the table written with this manifest (`plane_histograms.parquet`): **integrity**, compared by `RunInputs`, reuse and publication. Required in version 6. | | `histogram_table_content_sha256` | The table's content digest (Spec ADR 0008 PQ6): **identity**, the same whatever `pyarrow` version or platform wrote the bytes; what consumers record as provenance (ADR 0007's `run_folder` entry, the scaling fit's record). `RunInputs` reads the table through normalization's checks and refuses one whose content digest differs. Required in version 6. A version 6 manifest missing either digest, or holding `csv_sha256` (version 5's key, no alias), is refused as a manifest of another version (ADR 0002 AR11 (7)). | | `versions` | Also records `pyarrow`'s version (it writes the table): recorded, never compared. | @@ -1671,15 +1675,14 @@ image headers and run the header checks without a run. The stable entry points a |---|---| | `inspect_tiff(path)`, `inspect_image(path)` (also `.zarr`) | A `TiffMetadata`: shape, dtype, axes the header names, channel names, series count, physical sizes; no pixels are read | | `read_physical_sizes(path)` | A `PhysicalSizes`: pixel sizes X and Y, z-step, time step (`t`, with `time_unit`) and a unit per axis; ImageJ `finterval` and OME `TimeIncrement` are read | -| `check_metadata(files, allow_z=True)`, `inspect_images(root, paths, allow_z=True)` | The `ValidationIssue` list of the header checks (§8) | +| `check_metadata(files)`, `inspect_images(root, paths)` | The `ValidationIssue` list of the header checks (§8) | -Z is read: ImageJ and OME TZYX stacks give axes `TZYX` and the Z size. Only preprocessing's own -experiment checks refuse Z by default (`z_stack_not_supported`, §2): `check_metadata(files)` and -`inspect_experiment` keep that refusal, and `allow_z=True` switches off that one error; unreadable -files, several series, pixel types, arrangement, channel counts and names, sizes, plane counts, -pixel sizes and units are checked as before. `case_conflict` is not a header check: it comes from +Z is read: ImageJ and OME TZYX stacks give axes `TZYX` and the Z size. No header check refuses +Z (Spec ADR 0010; `z_stack_not_supported` and `allow_z` are removed): unreadable files, several +series, pixel types, arrangement, channel counts and names, sizes, plane counts, pixel sizes and +units are checked as before. `case_conflict` is not a header check: it comes from folder discovery (`discover_experiment`, §1), so it is not reported from headers alone. Moving the -Z gate out of the header checks is issue #438. +Z gate out of the header checks was issue #438. The base install depends on `morphobricks-normalization` through a git URL (a release tag, not on PyPI), so a tool that installs this package needs git access to that repository. diff --git a/docs/plan.md b/docs/plan.md index a391f787..966be962 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -1819,3 +1819,21 @@ Raised during review; to be decided before the milestones that need them: hashes is `RUN_FOLDER_CONTENT_NOT_RECORDED` (ahead of the ADR, Spec issue 84); masks stay `fingerprint` for now (the run records no mask hash; a separate issue). +93. How are Z-stacks described and handed off (issue #438; MorphoBricks-Spec ADR 0010, Proposed, + with the part of ADR 0009 it needs)? *Built as a draft ahead of acceptance (owner, 2 December + 2026; CellMigrationLab/morphobricks-preprocessing#617):* a Z-stack is a volume, described and + run without statistics; question 76's `z_stack_not_supported` is removed. *Decided (owner, + 2 December 2026, ADR 0010 VZ30-VZ35):* `W_AXIS_UNCALIBRATED` is one run-level warning with + the axes and how many images lack each (VZ30); a run mixing plane images and volumes is + checked at the axis review (notebook Axes step and keep-or-project card, `check`) and at the + run, and reported, never refused here (VZ31); keeping the stacks is an explicit choice with no + default (`run --keep-z-stacks`, *Keep the 3-D stacks*, `RunMode(keep_z_stacks=True)`, else + `z_stacks_not_chosen`), recorded as the manifest's `z_handling` (VZ32); the + `VOLUME_STATISTICS_NOT_COMPUTED` message names what in words (VZ33); `R_UNIT_NOT_HOMOGENEOUS` + compares the confirmed roles other than Z and T (VZ34); modelling choices 17-20, AR12 in the + same wave (resolver contract 3 to 5), `convert` without `--project` keeping volumes and the + public `RunInputs.check_consumer` are accepted (VZ35). *Decided (owner, 2 December 2026, on + #617):* the conformance rows that test a consumer's own behaviour (P92-P94, P96) are tested in + each consumer, not here; ADR 0009's consumer-manifest part lands, once accepted, in two pull + requests: first the file, its validator, the choice, the early checks and the + `consumer_check` record, then the discovery hardening. diff --git a/docs/user_guide.md b/docs/user_guide.md index 1d4ade7c..05fec7b2 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -442,10 +442,13 @@ run the experiment in the app of cell 3. Then: separately or exclude it. - **Pixel types:** 8-, 16-, 32- and 64-bit signed or unsigned integers, 32- and 64-bit floats. All images of an experiment must have the same pixel type. -- **2-D planes only:** MorphoBricks v1 analyses 2-D planes. An image with more than one - depth slice (a Z-stack) is refused (`z_stack_not_supported`), every such image named: - make recorded 2-D projected copies first with `convert --project max|mean|sum` (below), - and use the copies. A Z axis of one slice is fine. Time-lapses are supported. +- **Planes and volumes (Spec ADR 0010):** an image whose confirmed Z role has more than one + depth slice (a Z-stack) is a **volume**: it is described, tagged and calibrated as it is. + Histograms, normalization and QC metrics are not computed for volumes (the run records + "not computed: volume"); only tools that declare volume support take them, and MorphoFeature + refuses them. To analyse 2-D planes instead, make recorded projected copies with + `convert --project max|mean|sum` (below). A Z axis of one slice is a plane image. + Time-lapses are supported. - **Dimensions:** every image is split into planes along T (time); a plane holds every channel (C) of the image at that time point, one row of the table. All TIFF images must have their dimensions in the same order; the number of slices, time points @@ -795,9 +798,10 @@ editing, or the confirmed ones. An image that cannot be drawn gets a sentence sa plain text of `discovery_report.txt` folded last). **Time-lapses and Z-stacks.** A time-lapse goes through the steps as it is: each time point -is a plane of its own, and the viewer's **t** slider shows any of them. A Z-stack is refused -(`z_stack_not_supported`: MorphoBricks analyses 2-D planes), and the Axes step then shows -**Z-stacks: save the dataset as projections**. Look at the stack with the viewer's **z** +is a plane of its own, and the viewer's **t** slider shows any of them. For Z-stacks the Axes +step shows **Z-stacks: keep them as volumes or project them**, and the roles are confirmed only once +you choose: tick **Keep the 3-D stacks** (they are described as volumes; histograms, +normalization and QC are not computed for them), or project them. Look at the stack with the viewer's **z** slider, choose the **Projection** (maximum, mean or sum; there is no default) and, if not all, the slices used; **Show this projection of the image above** draws it for looking. After **Yes, the example looks right**, **Write the projected copies and continue with them** writes @@ -806,8 +810,13 @@ a 2-D copy of every image, with the conversion record, into the output folder --project` does (§5), and opens the copies as the experiment: they are scanned and checked again, a line says what they are copies of, and you confirm their axes and go on. Masks are never projected. The original stacks are only read, never changed or deleted, and the record -lists each one (folder, path, fingerprint, SHA-256, slices used). **Keep the 3-D stacks for -3-D-capable tools (fiberfeatures)** is shown greyed out: 3-D analysis is not enabled yet. +lists each one (folder, path, fingerprint, SHA-256, slices used). Keeping the stacks is recorded +in the run manifest (`z_handling = "kept"`; a run on projected copies records the method), and +only tools that declare volume support take volumes: MorphoFeature refuses them. When some images +are Z-stacks and others are not, the card and the axis check say so as soon as the roles are +confirmed (`W_MIXED_PLANES_AND_VOLUMES`, with the counts and the folders holding both), and the run +summary says it again: nothing is refused here, but tools that need one kind per run refuse such a +run, so split it into two experiments or project the stacks. When you open the stacks again with the same output folder, the copies written earlier are offered (**Continue with the copies written earlier**). Copies whose conversion record cannot be used (one written before v0.5.2, of version 3) are not offered, and a line says so and why: @@ -925,6 +934,7 @@ the same bytes in every file except that time (and the manifest SHA-256 the repo | `--workers N\|auto` | How many images are read at once, each in its own thread (default 1: one after another). `auto`: at most the number of CPUs, and with `--max-ram` as many as the largest image's estimated working memory fits. The results are exactly the same with any value; it is not recorded and changes nothing on the next run | | `--max-ram SIZE` | With `--workers auto`: the memory the run may use, e.g. `8GiB` (256 MiB of it kept for the run itself). An image that alone needs more stops the run before any pixel is read (`image_over_max_ram`) | | `--missing-as-singleton`, `--no-missing-as-singleton` | Confirm that images lacking some dimensions have one plane along them (`check` and `run`; default: the earlier run's answer, else no). `check` then reports what `run` will: an experiment of 2D images and Z-stacks passes `check` once confirmed, and the suggested option says `--axes ZCYX --missing-as-singleton` | +| `--keep-z-stacks`, `--no-keep-z-stacks` | Run Z-stacks as volumes, without projection: histograms, normalization and QC metrics are not computed for them, and the choice is recorded (`z_handling`). Required when the confirmed roles give Z-stacks (no default; left out: as in the earlier run), else `z_stacks_not_chosen`. To project them instead, use `convert --project` and run on the copies | | `--image-type fluorescence\|rgb` | The image type (default: the earlier run's, else the suggested one, printed) | | `--mode restart\|full` | `restart` (default) reuses the rows of unchanged images; `full` recomputes every row and check. Both keep your confirmations and replace the results only when the run succeeds | | `--verify-content`, `--no-verify-content` | Reuse rows (earlier or staged) only when each image's content SHA-256 is the one recorded with them, not only its size and modification time; every image is read once more. Default: the earlier run's choice, else on; `--no-verify-content` opts out and the manifest records it. Turning it on or off recomputes every row. With `masks`: also compare each mask's content SHA-256 before and after it is read (same default) | @@ -1255,8 +1265,8 @@ those files (or convert into a new folder), then convert again. A file or folder it is not the conversion's. Images of 64-bit integers cannot be saved as OME-TIFF (`cannot_convert_pixel_type`). **Z-stacks: recorded 2-D projections.** -A Z-stack is still refused by `check` and `run` (`z_stack_not_supported`). To analyse one, -make a projected copy first: +A Z-stack is described and run as a volume (Spec ADR 0010). To analyse its 2-D projection +instead, make a projected copy first: `convert EXPERIMENT --to FOLDER --axes ZCYX --project max` (or `mean` or `sum`; there is no default method; `--z-range 2:10` uses only those slices of every image, zero-based with the end excluded, `4:5` is the single slice 4, and every image must have them), or in Python @@ -1655,7 +1665,9 @@ continues. | `missing_xy_axis`, `duplicate_axis_role` | Error | X/Y missing or a role used twice. Correct the axis roles. | | `unassigned_axis` | Error | A dimension with several planes has no role. Choose Z, C or T. | | `unsupported_axis` | Error | A position or tile dimension. Export each position separately. | -| `z_stack_not_supported` | Error | Images have more than one depth slice (Z-stacks); every such image is named with its number of slices. MorphoBricks v1 analyses 2-D planes. Make 2-D projected copies first (`convert EXPERIMENT --to FOLDER --axes ROLES --project max|mean|sum`; the originals are only read) and run on the copies; or exclude the images. A Z axis of one slice is accepted. Found from the header's Z axis, and again from the axis roles you confirm (a plain stack given a Z role). | +| `W_AXIS_UNCALIBRATED` | Warning | An X or Y step (any image) or a Z step (a volume) has no length: nothing gives it (`unknown`) or it is stated as `pixels`. Recorded per image (the `reason` of its pixel size) and once per run in the run manifest's `checks` and the report, with the axes and how many images lack each; it blocks nothing and is never guessed. A tool that needs the step refuses these images. State the step in `calibration.csv` and run again. | +| `z_stacks_not_chosen` | Error | Some images are Z-stacks under the confirmed roles and no choice was made for them: keeping them as volumes and projecting them are both explicit choices, with no default. Tick **Keep the 3-D stacks** in the notebook (or `run --keep-z-stacks`), or make projected copies (`convert --project max|mean|sum`). The choice is recorded in the run manifest (`z_handling`). | +| `W_MIXED_PLANES_AND_VOLUMES` | Warning | The run holds plane images and volumes (Z-stacks): the counts, every image and every condition, biological repeat and imaging unit holding both are named and recorded in the run manifest's `checks`. Said as soon as the axis roles are confirmed (Axes step, `check`) and again in the run summary. It is published; MorphoFeature refuses this run as it stands: split it into two experiments, or project the stacks. | | `plane_over_memory_limit` | Error | A plane cannot be read within the memory limit, not even in blocks (for example, it is stored compressed in one piece). Raise the limit, or save the images again as tiled or uncompressed TIFF files or as OME-Zarr with smaller chunks. | | `compression_not_bounded` | Error | Planes too large to read whole within the memory limit are stored with a TIFF compression whose decoding memory has not been measured (old-style JPEG, PackBits, Zstandard, WebP, JPEG 2000, ..., or JPEG in another form than 8-bit greyscale, RGB or YCbCr), so they are not read in blocks: only uncompressed, deflate (zlib), LZW, LZMA and 8-bit greyscale, RGB or YCbCr JPEG TIFF images are (decoded by imagecodecs, a required dependency: an image is also refused when the installed imagecodecs is missing, older than 2024.12.30 or, for JPEG, not built on libjpeg-turbo 3, and the message says so). The message names the compression. Save the images again as uncompressed, deflate, LZW or LZMA TIFF files (tiled, for large images) or as OME-Zarr, or raise the memory limit so that their planes are read whole. The same refusal, from the header and before any pixel is read, stops window reads and `RunInputs.read_plane` of such an image whatever its size. | | `unsupported_layout` | Error | The image cannot be read one plane at a time. Check the axis roles or export again. | diff --git a/pyproject.toml b/pyproject.toml index ffde5b95..2325503a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -283,6 +283,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.preview_render" = "pure" "morphobricks_preprocessing.cli" = "ui" "morphobricks_preprocessing.cli_run" = "ui" +"morphobricks_preprocessing.cli_volumes" = "ui" "morphobricks_preprocessing.cli_calibrate" = "ui" "morphobricks_preprocessing.cli_masks" = "ui" "morphobricks_preprocessing.cli_describe" = "ui" @@ -355,6 +356,12 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.required_description" = "io" "morphobricks_preprocessing.run_inputs_semantic" = "io" "morphobricks_preprocessing.run_inputs_request" = "pure" +"morphobricks_preprocessing.run_inputs_scope" = "pure" +"morphobricks_preprocessing.run_inputs_volume" = "pure" +"morphobricks_preprocessing.run_inputs_consumer" = "pure" +"morphobricks_preprocessing.run_inputs_planes" = "io" +"morphobricks_preprocessing.run_inputs_statistics" = "io" +"morphobricks_preprocessing.manifest_volume" = "pure" "morphobricks_preprocessing.run_inputs_resolve" = "io" "morphobricks_preprocessing.run_inputs_image" = "pure" "morphobricks_preprocessing.description_layouts" = "pure" diff --git a/src/morphobricks_preprocessing/axes.py b/src/morphobricks_preprocessing/axes.py index 563d202a..4000c96f 100644 --- a/src/morphobricks_preprocessing/axes.py +++ b/src/morphobricks_preprocessing/axes.py @@ -72,7 +72,6 @@ "different_channel_counts", "different_sizes", "different_plane_counts", - "z_stack_not_supported", } ) @@ -263,8 +262,8 @@ def combined_issues(self, metadata: MetadataReport) -> tuple[ValidationIssue, .. The review checks the arrangement of dimensions and the numbers of channels again against the confirmed mapping, so the metadata's - ``missing_axes``, ``inconsistent_dimensions``, ``different_channel_counts`` and - ``z_stack_not_supported`` issues are replaced by the review's own. The + ``missing_axes``, ``inconsistent_dimensions`` and ``different_channel_counts`` + issues are replaced by the review's own. The ``different_sizes`` and ``different_plane_counts`` warnings are computed again with each image's confirmed roles (issue #74; :func:`.metadata.dimension_issues`), except for an image whose roles contradict its header (:attr:`axis_error_files`, never read), diff --git a/src/morphobricks_preprocessing/axis_review.py b/src/morphobricks_preprocessing/axis_review.py index 4ca5b27c..d801ad8d 100644 --- a/src/morphobricks_preprocessing/axis_review.py +++ b/src/morphobricks_preprocessing/axis_review.py @@ -7,7 +7,7 @@ from __future__ import annotations -from collections.abc import Iterable +from collections.abc import Iterable, Mapping from dataclasses import dataclass, field from .axes import ( @@ -26,18 +26,17 @@ check_header_axes, confirmation_of, ) +from .manifest_volume import MIXED, mixed_texts from .metadata import ( MetadataReport, TiffMetadata, - header_depth_slices, ) from .size_checks import ( CONVERT_KEEPS_ORDER, channel_count_issues, role_plane_counts, - z_stack_issues, ) -from .validation import ValidationIssue, error, plural +from .validation import ValidationIssue, error, plural, warning def _one_dimensional(mapping: AxisMapping, paths: list[str]) -> ValidationIssue: @@ -195,9 +194,7 @@ def review_axes( the experiment's roles or that the confirmed roles contradict, whatever their arrangement (``ome_zarr_axes_mismatch``, issue #72), files with different numbers of channels - along the C axis (``different_channel_counts``; 1 without one), images with more - than one depth slice (``z_stack_not_supported``; MorphoBricks v1 analyses 2-D - planes), and the + along the C axis (``different_channel_counts``; 1 without one), and the axis check of every TIFF against its header (:func:`header_axis_issue`), each naming its files with their header axes and confirmed roles: the errors ``axes_yx_swapped`` and ``axes_contradict_header`` (with the likely @@ -255,6 +252,7 @@ def review_axes( ) ) issues.extend(_count_issues(readable, file_mappings)) + issues.extend(early_mixed_warning(readable, file_mappings)) # VZ4, VZ19: inform early # Each file's confirmed roles against the axes its own header names. Files the mapping # does not fit already have their error; OME-Zarr images take their roles from their # metadata, checked against the confirmed roles above (ome_zarr_mapping, issue #72). @@ -363,23 +361,37 @@ def _ome_zarr_issues( def _count_issues( readable: list[TiffMetadata], file_mappings: dict[str, AxisMapping] ) -> list[ValidationIssue]: - """Report different channel counts and Z-stacks under each file's confirmed roles. + """Report different channel counts under each file's confirmed roles. - An image is a Z-stack when its confirmed Z role has more than one slice (a plain stack - confirmed ``ZYX`` too; owner decision of 5 November 2026); a file the mapping does not - fit is measured by the Z its header names. An ImageJ time-lapse whose header names Z - and whose roles are confirmed ``T`` is the axis error ``axes_contradict_header``, never - read, whose fix (named-axis copies, ``convert``) this error would otherwise block. + A Z-stack is not refused here (Spec ADR 0010 VZ1): an image whose confirmed Z role has + more than one slice is a volume (:func:`volume_slices`), described and recorded as one. """ - channels, slices = {}, {} + channels = {} for f in readable: mapping = file_mappings.get(f.relative_path) - if mapping is None: - slices[f.relative_path] = header_depth_slices(f) + if mapping is not None: + channels[f.relative_path] = channel_count(f, mapping) + return channel_count_issues(channels) + + +def volume_slices( + files: Iterable[TiffMetadata], file_mappings: Mapping[str, AxisMapping] +) -> dict[str, int]: + """Return the depth slices of every volume, by path, under its confirmed roles. + + A volume is an image whose **confirmed** Z role has more than one slice (Spec ADR 0010, + "What a described volume is"): header letters are evidence only, so a file the mapping + does not fit (or does not cover) is left out. A one-slice Z, or none, is a plane image. + """ + found = {} + for f in files: + mapping = file_mappings.get(f.relative_path) + if mapping is None or not f.readable or len(f.shape) != len(mapping.roles): continue - slices[f.relative_path] = role_plane_counts(f.shape, mapping.roles)["Z"] - channels[f.relative_path] = channel_count(f, mapping) - return [*channel_count_issues(channels), *z_stack_issues(slices)] + slices = role_plane_counts(f.shape, mapping.roles)["Z"] + if slices > 1: + found[f.relative_path] = slices + return dict(sorted(found.items())) def channel_count(f: TiffMetadata, mapping: AxisMapping) -> int: @@ -410,3 +422,23 @@ def _paths_with_long(files: list[TiffMetadata], mapping: AxisMapping, dims: list if any(sizes.get(d, 1) > 1 for d in dims): paths.append(f.relative_path) return paths + + +def early_mixed_warning( + files: Iterable[TiffMetadata], file_mappings: Mapping[str, AxisMapping] +) -> list[ValidationIssue]: + """Return ``W_MIXED_PLANES_AND_VOLUMES`` as soon as the roles say the images mix kinds. + + Preprocessing checks and informs, never refuses (Spec ADR 0010 VZ4, VZ8, VZ19; owner + clarification of 2 December 2026): at the axis review, so the notebook's Axes step and the + command line's ``check``, ``describe`` and ``run`` say it before the run. Places are the + folders (condition, biological repeat, imaging unit, then the run); the run's published + record names the canonical IDs. + """ + files = list(files) + paths = sorted(f.relative_path for f in files if f.relative_path in file_mappings) + volumes = volume_slices(files, file_mappings) + if not volumes or len(volumes) == len(paths): + return [] + message, fix = mixed_texts(paths, volumes) + return [warning(MIXED, message, paths, fix)] diff --git a/src/morphobricks_preprocessing/cli_run.py b/src/morphobricks_preprocessing/cli_run.py index 4292e5f6..f41beb66 100644 --- a/src/morphobricks_preprocessing/cli_run.py +++ b/src/morphobricks_preprocessing/cli_run.py @@ -31,6 +31,7 @@ from .axes import AxisMapping, reference_axes from .axis_review import review_axes from .channel_identity import channel_identity_text +from .cli_volumes import add_keep_option, run_mode_of from .discovery import default_output_folder from .image_type import IMAGE_TYPES, RGB, ImageTypeReview, review_image_type from .intensity import intensity_text @@ -46,7 +47,7 @@ run_summary, ) from .required_description import description_required_issue, is_published -from .run import MODES, RESTART, Preflight, RunMode, preflight, run_experiment +from .run import MODES, RESTART, Preflight, preflight, run_experiment from .run.recorded import usable from .run.reuse import read_previous, recorded_experiment_root from .validation import ValidationIssue, error @@ -297,6 +298,7 @@ def _run_inputs(run: argparse.ArgumentParser) -> None: "recomputes every row; on by default: as in the earlier run, else yes; " "--no-verify-content opts out and the manifest records that)", ) + add_keep_option(run) def _run_settings(run: argparse.ArgumentParser) -> None: @@ -399,7 +401,7 @@ def run_command(args: argparse.Namespace) -> int: memory_limit=args.memory_limit, missing_as_singleton=args.missing_as_singleton, exclude=[] if args.no_exclude else args.exclude or None, - mode=RunMode(args.mode, args.verify_content, links, args.workers, args.max_ram), + mode=run_mode_of(args, links), progress=print_progress, masks_folder=False if args.no_masks else args.masks, mask_axes=args.mask_axes or None, diff --git a/src/morphobricks_preprocessing/cli_volumes.py b/src/morphobricks_preprocessing/cli_volumes.py new file mode 100644 index 00000000..f5c8e279 --- /dev/null +++ b/src/morphobricks_preprocessing/cli_volumes.py @@ -0,0 +1,35 @@ +"""The ``run`` command's choice for Z-stacks (Spec ADR 0010; owner answer of 2 December 2026). + +``--keep-z-stacks`` is the explicit, recorded choice to describe and run Z-stacks as volumes, +without projection (``RunMode(keep_z_stacks=True)``, the run manifest's ``z_handling``): +there is no default, so a run with volumes and no choice is refused (``z_stacks_not_chosen``). +""" + +from __future__ import annotations + +import argparse + +from .run import RunMode + + +def add_keep_option(run: argparse.ArgumentParser) -> None: + """Add ``--keep-z-stacks`` / ``--no-keep-z-stacks`` to the ``run`` command.""" + run.add_argument( + "--keep-z-stacks", + action=argparse.BooleanOptionalAction, + help="run Z-stacks as volumes, without projection: histograms, normalization and QC " + "are not computed for them, and the choice is recorded. Required for Z-stacks (no " + "default); left out: as in the earlier run", + ) + + +def run_mode_of(args: argparse.Namespace, links: object) -> RunMode: + """Return the run's :class:`RunMode` from the command line, the choice for Z-stacks included.""" + return RunMode( + args.mode, + args.verify_content, + links, + args.workers, + args.max_ram, + keep_z_stacks=getattr(args, "keep_z_stacks", None), + ) diff --git a/src/morphobricks_preprocessing/conversion_plan.py b/src/morphobricks_preprocessing/conversion_plan.py index bb69d706..23d900d9 100644 --- a/src/morphobricks_preprocessing/conversion_plan.py +++ b/src/morphobricks_preprocessing/conversion_plan.py @@ -55,7 +55,6 @@ from .projection_masks import projection_mask_issues from .projection_plan import plan_projection from .run.preflight import Preflight, preflight -from .size_checks import Z_STACK_CODE from .validation import ValidationIssue, has_errors _NOT_IN_OME = frozenset({"int64", "uint64"}) @@ -95,9 +94,8 @@ def plan_conversion( memory_limit As :func:`convert_experiment`. projection - As :func:`convert_experiment`: every image is planned as a projected copy, and - ``z_stack_not_supported`` no longer stops the plan (the projection is what it asks - for); the refusals of :func:`.projection_plan.plan_projection` and of the masks + As :func:`convert_experiment`: every image is planned as a projected copy; the + refusals of :func:`.projection_plan.plan_projection` and of the masks (``masks_folder``, :func:`.projection_masks.projection_mask_issues`) do. masks_folder The masks folder, scanned for 3-D masks when ``projection`` is given. @@ -147,8 +145,6 @@ def _plan( review = review_axes(pre.metadata, mapping, missing_as_singleton=missing_as_singleton) others = [issue for issue in pre.issues if issue not in pre.metadata.issues] issues = [*others, *review.combined_issues(pre.metadata)] - if projection is not None: - issues = [i for i in issues if not (i.is_error and i.code == Z_STACK_CODE)] if any(i.is_error and i.code not in AXIS_ERROR_CODES for i in issues): return (), [i for i in issues if not (i.is_error and i.code in AXIS_ERROR_CODES)] # The axis errors and unnamed axes are what is corrected (each entry records its code). diff --git a/src/morphobricks_preprocessing/draft_format.py b/src/morphobricks_preprocessing/draft_format.py index 814450a6..15f88bd0 100644 --- a/src/morphobricks_preprocessing/draft_format.py +++ b/src/morphobricks_preprocessing/draft_format.py @@ -42,7 +42,7 @@ DRAFT_VERSION = 4 IMAGE_TYPES = ("rgb", "channels") """The image types a draft may hold: ``channels`` is the answer "ordinary channel image".""" -SPEC_COMMIT = "232fb38880cc487510532d99dc71d46a27005f23" +SPEC_COMMIT = "5aad8d3ecf0088e9eb443ad79dafedab86977376" """The MorphoBricks-Spec commit the rules of this brick are pinned to (``tests/spec_fixtures``).""" BASE_MISSING = "R_DRAFT_BASE_MISSING" SHA256 = re.compile(r"[0-9a-f]{64}") diff --git a/src/morphobricks_preprocessing/fov_identity.py b/src/morphobricks_preprocessing/fov_identity.py index 73302ba3..2609a536 100644 --- a/src/morphobricks_preprocessing/fov_identity.py +++ b/src/morphobricks_preprocessing/fov_identity.py @@ -12,11 +12,17 @@ from __future__ import annotations +from collections.abc import Iterable from dataclasses import dataclass +from typing import TYPE_CHECKING from .description import Description, Unit +from .manifest_volume import CheckedImage from .run_inputs_request import CHANNELS, RGB +if TYPE_CHECKING: + from .manifest_files import FileEntry + @dataclass(frozen=True) class FovIdentity: @@ -70,3 +76,31 @@ def fov_identity(description: Description, labels: tuple[str, str, str]) -> FovI f"{len(found)} units of the description, not one" ) return found[0] + + +def checked_images( + description: Description, entries: Iterable[FileEntry] +) -> tuple[CheckedImage, ...]: + """Return what the run's ``checks`` are computed from, per included image (Spec ADR 0010 VC5). + + Each image's FOV key (its source labels and position ID) and its imaging unit's canonical + ``(condition ID, repeat group, technical repeat ID)``, from the published description. + + Raises + ------ + LookupError + When an entry's folders name no unit of the description, or more than one. + """ + found = [] + for entry in entries: + identity = fov_identity(description, entry.labels) + found.append( + CheckedImage( + (*entry.labels, entry.position_id or ""), + entry.relative_path, + entry.z_count or 1, + entry.pixel_sizes, + (identity.condition_id, identity.repeat_group, identity.technical_repeat_id), + ) + ) + return tuple(found) diff --git a/src/morphobricks_preprocessing/manifest.py b/src/morphobricks_preprocessing/manifest.py index a1382548..1d3a6137 100644 --- a/src/morphobricks_preprocessing/manifest.py +++ b/src/morphobricks_preprocessing/manifest.py @@ -59,14 +59,21 @@ from .manifest_files import ( file_entry_with as file_entry_with, # re-exported (moved) ) -from .manifest_versions import MANIFEST_VERSION as MANIFEST_VERSION from .manifest_versions import ( + EARLIER_VERSION, RERUN, TABLE_DIGESTS, UnsupportedVersionError, check_version, recorded_version, ) +from .manifest_versions import MANIFEST_VERSION as MANIFEST_VERSION +from .manifest_volume import ( + ARTIFACTS_COMPUTED, + check_volume_record, + volume_record, + volume_record_data, +) from .narrow_ranges import NarrowRange from .projection_run import KEY as PROJECTION_KEY from .projection_run import recorded_projection @@ -177,11 +184,12 @@ class RunManifest: SHA-256 of the bytes of the histogram table written with this manifest (``plane_histograms.parquet``): its integrity, so a table changed or replaced afterwards is detected. In a version 5 manifest, its ``csv_sha256`` (of - ``plane_histograms.csv``). + ``plane_histograms.csv``). None (written as null) when the run's images are all + volumes: no table is written (Spec ADR 0010 VC1). histogram_table_content_sha256 The table's content digest (Spec ADR 0008 PQ6): its identity, the same whatever ``pyarrow`` version or platform wrote the bytes; what consumers record as provenance. - None only in a version 5 manifest, which has none. + None in a version 5 manifest, which has none, and with no table (VC1). versions Versions of this package, NumPy, tifffile and Python. written_at @@ -226,12 +234,20 @@ class RunManifest: image_qc The image QC table written with the run (:mod:`.image_qc_record`: file, SHA-256, metric version and settings); None (key left out) in manifests written before it. + checks + The run's recorded warnings (Spec ADR 0010 VC5): one run-level ``W_AXIS_UNCALIBRATED`` + with its counts per axis, and ``W_MIXED_PLANES_AND_VOLUMES``, derived from the entries + (:func:`.manifest_volume.compute_checks`); required in version 7, None before it. + statistics_artifacts + ``{"state": "computed"}``, or ``{"state": "not_computed", "reason": "all_volumes"}`` + when every image is a volume and no histogram or QC table is written (VC1); required + in version 7, None before it. schema_version Version of the histogram table format, as text: ``"6"`` (``"5"`` in a version 5 manifest). manifest_version - Version of the manifest format (:mod:`.manifest_versions`): ``"6"``, the only one - written; ``"5"`` is read too (owner decision 10), any other is refused. + Version of the manifest format (:mod:`.manifest_versions`): ``"7"``, the only one + written; ``"6"`` and ``"5"`` are read too, any other is refused. """ experiment_root: str @@ -239,7 +255,7 @@ class RunManifest: settings: RunSettings mapping: AxisMapping files: tuple[FileEntry, ...] - histogram_table_sha256: str + histogram_table_sha256: str | None histogram_table_content_sha256: str | None = None versions: dict[str, str] = field(default_factory=dict) written_at: str = "" @@ -256,9 +272,17 @@ class RunManifest: projection: dict | None = None lab_links: dict | None = None image_qc: dict | None = None + checks: tuple[dict, ...] | None = None + statistics_artifacts: dict | None = None + z_handling: str | dict | None = None schema_version: str = str(SCHEMA_VERSION) manifest_version: str = MANIFEST_VERSION + @property + def statistics_computed(self) -> bool: + """False when every image is a volume: no histogram or QC table exists (VC1).""" + return (self.statistics_artifacts or ARTIFACTS_COMPUTED) == ARTIFACTS_COMPUTED + @property def leaves(self) -> dict[str, tuple[str, str, str]]: """Labels of each leaf folder, keyed by its relative path.""" @@ -277,15 +301,17 @@ def to_dict(self) -> dict: Raises ------ ValueError - If it is not a version 6 manifest with both table digests (only version 6 is - written), or its version does not match its content verification + If it is not a version 7 manifest (only version 7 is written) whose table digests, + ``image_qc``, ``statistics_artifacts`` and ``checks`` agree with its entries + (Spec ADR 0010 VC1, VC5), or its version does not match its content verification (:func:`.manifest_versions.check_version`): the reader would refuse it. """ - if self.manifest_version != MANIFEST_VERSION or not self.histogram_table_content_sha256: + if self.manifest_version != MANIFEST_VERSION: raise ValueError( - f"only a version {MANIFEST_VERSION} manifest with both histogram table digests " - f"is written; this one is version {self.manifest_version!r}" + f"only a version {MANIFEST_VERSION} manifest is written; this one is version " + f"{self.manifest_version!r}" ) + check_volume_record(self) check_version( self.manifest_version, recorded_flag(self.settings.verify_content, "verify_content"), @@ -336,8 +362,8 @@ def to_dict(self) -> dict: optional = {"masks": self.masks, DESCRIPTION_KEY: self.experiment_description} optional[PROJECTION_KEY] = self.projection optional[LAB_LINKS_KEY] = recorded_lab_links(self.lab_links) - optional[IMAGE_QC_KEY] = recorded_image_qc(self.image_qc) data.update({key: value for key, value in optional.items() if value is not None}) + data.update(volume_record_data(self)) # image_qc (null without a table), checks... return data @classmethod @@ -353,48 +379,49 @@ def from_dict(cls, data: dict) -> RunManifest: version = recorded_version(data) settings = data["settings"] mapping = data["axis_mapping"] - return cls( - experiment_root=str(data["experiment_root"]), - dtype=str(data["dtype"]), - settings=RunSettings( - bin_count=int(settings["bin_count"]), - memory_limit=int(settings["memory_limit"]), - missing_as_singleton=recorded_flag(settings["missing_as_singleton"]), - exclude=tuple(str(p) for p in settings["exclude"]), - histogram=HistogramSettings.from_dict(settings["histogram"]), - verify_content=recorded_flag(settings["verify_content"], "verify_content"), - ), - mapping=AxisMapping(str(mapping["axes"]), tuple(mapping["roles"])), - files=tuple(file_from_data(f) for f in data["files"]), - **_table_digests(data, version), - versions={str(k): str(v) for k, v in data.get("versions", {}).items()}, - written_at=str(data.get("written_at", "")), - experiment_design_sha256=optional_text(data.get("experiment_design_sha256")), - masks=recorded_masks(data.get("masks")), - image_type=None if data.get("image_type") is None else str(data["image_type"]), - channels_from_rgb_samples=( - None - if data.get("channels_from_rgb_samples") is None - else recorded_flag(data["channels_from_rgb_samples"]) - ), - intensity_checks=( - None - if data.get("intensity_checks") is None - else IntensityCheckSettings.from_dict(data["intensity_checks"]) - ), - channel_identity=recorded_settings(data.get("channel_identity")), - narrow_ranges=tuple( - NarrowRange.from_dict(entry) - for entry in data.get("narrow_histogram_ranges") or () - ), - conversion_record_sha256=optional_text(data.get("conversion_record_sha256")), - calibration_sha256=optional_text(data.get("calibration_sha256")), - experiment_description=_recorded_description(data.get(DESCRIPTION_KEY)), - projection=recorded_projection(data.get(PROJECTION_KEY)), - lab_links=recorded_lab_links(data.get(LAB_LINKS_KEY)), - image_qc=recorded_image_qc(data.get(IMAGE_QC_KEY)), - schema_version=str(data["schema_version"]), - manifest_version=str(version), + return _checked( + cls( + experiment_root=str(data["experiment_root"]), + dtype=str(data["dtype"]), + settings=RunSettings( + bin_count=int(settings["bin_count"]), + memory_limit=int(settings["memory_limit"]), + missing_as_singleton=recorded_flag(settings["missing_as_singleton"]), + exclude=tuple(str(p) for p in settings["exclude"]), + histogram=HistogramSettings.from_dict(settings["histogram"]), + verify_content=recorded_flag(settings["verify_content"], "verify_content"), + ), + mapping=AxisMapping(str(mapping["axes"]), tuple(mapping["roles"])), + files=tuple(file_from_data(f, version) for f in data["files"]), + versions={str(k): str(v) for k, v in data.get("versions", {}).items()}, + written_at=str(data.get("written_at", "")), + experiment_design_sha256=optional_text(data.get("experiment_design_sha256")), + masks=recorded_masks(data.get("masks")), + image_type=None if data.get("image_type") is None else str(data["image_type"]), + channels_from_rgb_samples=( + None + if data.get("channels_from_rgb_samples") is None + else recorded_flag(data["channels_from_rgb_samples"]) + ), + intensity_checks=( + None + if data.get("intensity_checks") is None + else IntensityCheckSettings.from_dict(data["intensity_checks"]) + ), + channel_identity=recorded_settings(data.get("channel_identity")), + narrow_ranges=tuple( + NarrowRange.from_dict(entry) + for entry in data.get("narrow_histogram_ranges") or () + ), + conversion_record_sha256=optional_text(data.get("conversion_record_sha256")), + calibration_sha256=optional_text(data.get("calibration_sha256")), + experiment_description=_recorded_description(data.get(DESCRIPTION_KEY)), + projection=recorded_projection(data.get(PROJECTION_KEY)), + lab_links=recorded_lab_links(data.get(LAB_LINKS_KEY)), + **_version_fields(data, version), + schema_version=str(data["schema_version"]), + manifest_version=str(version), + ) ) except ManifestFormatError: raise @@ -423,7 +450,7 @@ def _table_digests(data: dict, version: str) -> dict[str, str | None]: is a manifest of another version). Version 5: its ``csv_sha256`` (no content digest). """ keys = TABLE_DIGESTS[version] - others = [key for v, held in TABLE_DIGESTS.items() if v != version for key in held] + others = {key for held in TABLE_DIGESTS.values() for key in held if key not in keys} stray = [key for key in others if key in data] if stray: raise ManifestFormatError( @@ -431,16 +458,44 @@ def _table_digests(data: dict, version: str) -> dict[str, str | None]: f"{version} manifest never records: it is a manifest of another version. {RERUN}" ) values = [data[key] for key in keys] # a missing digest: KeyError, refused as incomplete + if version == MANIFEST_VERSION and values == [None, None]: # no table (VC1), checked after + return {"histogram_table_sha256": None, "histogram_table_content_sha256": None} if any(not isinstance(value, str) or len(value) != 64 for value in values): raise ManifestFormatError( f"The manifest's {', '.join(keys)} must be SHA-256 digests (64 hexadecimal " f"characters). {RERUN}" ) - if version == MANIFEST_VERSION: + if version != EARLIER_VERSION: return {"histogram_table_sha256": values[0], "histogram_table_content_sha256": values[1]} return {"histogram_table_sha256": values[0], "histogram_table_content_sha256": None} +def _version_fields(data: dict, version: str) -> dict: + """Return the fields whose rules depend on the version: digests, QC, checks, artifacts.""" + return { + **_table_digests(data, version), + "image_qc": recorded_image_qc(_image_qc_value(data, version)), + **_volume_record(data, version), + } + + +def _image_qc_value(data: dict, version: str) -> object: + """Return the manifest's ``image_qc``: required in version 7 (null without a QC table).""" + return data[IMAGE_QC_KEY] if version == MANIFEST_VERSION else data.get(IMAGE_QC_KEY) + + +def _volume_record(data: dict, version: str) -> dict: + """Return the version 7 ``checks``, ``statistics_artifacts`` and ``z_handling``.""" + return volume_record(data, version, current=version == MANIFEST_VERSION) + + +def _checked(manifest: RunManifest) -> RunManifest: + """Return a manifest read, its version 7 record checked against its entries (VC1, VZ32).""" + if manifest.manifest_version == MANIFEST_VERSION: + check_volume_record(manifest) + return manifest + + def _recorded_description(value: object) -> dict | None: """Return :func:`.description_record.recorded_description`, its coded refusals kept coded.""" try: diff --git a/src/morphobricks_preprocessing/manifest_files.py b/src/morphobricks_preprocessing/manifest_files.py index 23bc7735..c4b9fa3f 100644 --- a/src/morphobricks_preprocessing/manifest_files.py +++ b/src/morphobricks_preprocessing/manifest_files.py @@ -11,7 +11,7 @@ from __future__ import annotations import os -from dataclasses import dataclass +from dataclasses import dataclass, replace from pathlib import Path from .axes import AxisMapping @@ -27,8 +27,15 @@ recorded_raw_names, recorded_roles, ) -from .manifest_versions import CONTENT_KEY -from .recorded_sizes import RecordedSize, sizes_from_data, sizes_to_data +from .manifest_versions import CONTENT_KEY, MANIFEST_VERSION +from .manifest_volume import ( + VOLUME, + acquisition, + check_entry_sizes, + manifest_sizes_from_data, + manifest_sizes_to_data, +) +from .recorded_sizes import RecordedSize, sizes_from_data AXES_FROM = ("header", "confirmed") """Where a file's roles come from (:attr:`FileEntry.axes_from`).""" @@ -55,7 +62,8 @@ class FileEntry: singleton_roles Roles of the experiment mapping the file lacks, read as length 1. plane_count - Number of rows the file has in the table. + Version 7 (Spec ADR 0010 VC2): the physical number of XYC planes, ``t_count × z_count``. + In a version 6 or 5 manifest: the number of rows the file has in the table. channel_names Channel names from metadata; empty when not given. significant_bits @@ -98,6 +106,13 @@ class FileEntry: ``channels`` list (Stage 3, S3.3; units may list different channels). Required when written and read; part of the row key (:class:`.fingerprint.RowKey`), so rows named by other IDs are never reused. + shape, z_count, t_count, c_count, image_kind, plane_statistics, statistics_rows + Version 7 (Spec ADR 0010 VC2, VC3; :mod:`.manifest_volume`): the sizes the image was + read with (one per axis letter), the sizes of its confirmed ``Z``, ``T`` and ``C`` + roles (1 when absent), ``"plane"`` or ``"volume"``, ``"computed"`` or + ``"not_computed_volume"``, and its rows in the histogram table (``t_count``, or 0 for + a volume). Required in version 7 and checked against each other; None only in an + entry of an older manifest (read only to reuse its inputs, never by ``RunInputs``). """ relative_path: str @@ -119,6 +134,38 @@ class FileEntry: content_sha256: str | None = None raw_channel_names: tuple[str | None, ...] = () channel_ids: tuple[str, ...] = () + shape: tuple[int, ...] | None = None + z_count: int | None = None + t_count: int | None = None + c_count: int | None = None + image_kind: str | None = None + plane_statistics: str | None = None + statistics_rows: int | None = None + + @property + def volume(self) -> bool: + """True for a volume (``image_kind = "volume"``, Spec ADR 0010).""" + return self.image_kind == VOLUME + + @property + def rows_expected(self) -> int: + """The rows the image has in the histogram table (``plane_count`` before version 7).""" + return self.plane_count if self.statistics_rows is None else self.statistics_rows + + def with_acquisition(self) -> FileEntry: + """Return the entry with the version 7 sizes its ``shape`` and ``roles`` give (VC2).""" + found = acquisition(self.shape or (), self.roles or ()) + return replace( + self, + shape=found.shape, + z_count=found.z_count, + t_count=found.t_count, + c_count=found.c_count, + image_kind=found.image_kind, + plane_statistics=found.plane_statistics, + plane_count=found.plane_count, + statistics_rows=found.statistics_rows, + ) def same_source(self, other: FileEntry) -> bool: """Return True if ``other`` describes the same unchanged file, read the same way.""" @@ -193,13 +240,16 @@ def file_entry_with( def file_dict(entry: FileEntry) -> dict: - """Return a file entry as manifest data; its roles, their source and position are required. + """Return a file entry as version 7 manifest data; every version 7 field is required. - The writer refuses what the reader would refuse, so a written manifest always reads back. + The writer refuses what the reader would refuse, so a written manifest always reads back: + the sizes must be the ones ``shape`` and ``roles`` give (Spec ADR 0010 VC3) and every pixel + size one row of VC4's matrix. """ if entry.roles is None or entry.axes_from not in AXES_FROM: raise ValueError(f"the entry of {entry.relative_path!r} has no roles or axes_from") recorded_position_id(entry.position_id, entry.relative_path) + found = acquisition(entry.shape or (), entry.roles) data = { "relative_path": entry.relative_path, "size": entry.size, @@ -209,7 +259,14 @@ def file_dict(entry: FileEntry) -> dict: "technical_repeat": entry.labels[2], "axes": entry.axes, "singleton_roles": list(entry.singleton_roles), + "shape": list(found.shape), + "z_count": entry.z_count, + "t_count": entry.t_count, + "c_count": entry.c_count, + "image_kind": entry.image_kind, + "plane_statistics": entry.plane_statistics, "plane_count": entry.plane_count, + "statistics_rows": entry.statistics_rows, "channel_names": list(entry.channel_names), "significant_bits": entry.significant_bits, "read_in_blocks": recorded_flag(entry.read_in_blocks, "read_in_blocks"), @@ -219,9 +276,9 @@ def file_dict(entry: FileEntry) -> dict: ), "roles": None if entry.roles is None else list(entry.roles), "axes_from": entry.axes_from, - "pixel_sizes": sizes_to_data(entry.pixel_sizes), + "pixel_sizes": manifest_sizes_to_data(entry.pixel_sizes, found.image_kind == VOLUME), } - sizes_from_data(data["pixel_sizes"]) # one positive finite size per role, as read (#389) + check_entry_sizes(entry.relative_path, data, found) if entry.inventory_sha256 is not None: data[INVENTORY_KEY] = entry.inventory_sha256 if entry.content_sha256 is not None: @@ -232,17 +289,44 @@ def file_dict(entry: FileEntry) -> dict: return data -def file_from_data(data: dict) -> FileEntry: +def file_from_data(data: dict, version: str = MANIFEST_VERSION) -> FileEntry: """Read a file entry; every key the writer always writes is required, none defaulted. The roles, their source (``axes_from``), the pixel sizes and the ``position_id`` (the one the entry's name gives, round-2 audit A-m5) are required. Only ``inventory_sha256``, ``content_sha256`` and ``raw_channel_names`` may be absent: the writer leaves them out when - they do not apply. + they do not apply. In version 7 the acquisition fields are required and checked against + ``shape`` and ``roles`` (Spec ADR 0010 VC3), and the pixel sizes are read with the version 7 + codec (VC4); an older version's entry has none of them and its own pixel size codec. """ bits, path = data["significant_bits"], str(data["relative_path"]) if data.get("roles") is None or data.get("axes_from") not in AXES_FROM: raise ValueError(f"the entry of {path!r} has no roles or axes_from") + if version == MANIFEST_VERSION: + return _volume_fields(_entry(data, bits, path, version), data) + return _entry(data, bits, path, version) + + +def _volume_fields(entry: FileEntry, data: dict) -> FileEntry: + """Return a version 7 entry with its acquisition fields, checked against each other (VC3).""" + found = acquisition(data["shape"], entry.roles or ()) + check_entry_sizes(entry.relative_path, data, found) + return replace( + entry, + shape=found.shape, + z_count=found.z_count, + t_count=found.t_count, + c_count=found.c_count, + image_kind=found.image_kind, + plane_statistics=found.plane_statistics, + statistics_rows=found.statistics_rows, + pixel_sizes=manifest_sizes_from_data(data["pixel_sizes"], found.image_kind == VOLUME), + ) + + +def _entry(data: dict, bits: object, path: str, version: str) -> FileEntry: + """Read the fields every version of a file entry has (version 7's sizes read after).""" + sizes = data["pixel_sizes"] return FileEntry( relative_path=path, size=int(data["size"]), @@ -262,7 +346,7 @@ def file_from_data(data: dict) -> FileEntry: channel_names_trimmed=recorded_flag(data["channel_names_trimmed"], "channel_names_trimmed"), roles=recorded_roles(data["roles"], str(data["axes"])), axes_from=str(data["axes_from"]), - pixel_sizes=sizes_from_data(data["pixel_sizes"]), + pixel_sizes=() if version == MANIFEST_VERSION else sizes_from_data(sizes), inventory_sha256=optional_text(data.get(INVENTORY_KEY)), content_sha256=optional_text(data.get(CONTENT_KEY)), raw_channel_names=recorded_raw_names(data.get(RAW_NAMES_KEY), path), diff --git a/src/morphobricks_preprocessing/manifest_versions.py b/src/morphobricks_preprocessing/manifest_versions.py index cc85d5f8..3412ec71 100644 --- a/src/morphobricks_preprocessing/manifest_versions.py +++ b/src/morphobricks_preprocessing/manifest_versions.py @@ -1,9 +1,19 @@ -"""The run manifest version: version 6 is written; versions 6 and 5 are read (contract §9). +"""The run manifest version: version 7 is written; versions 7, 6 and 5 are read (contract §9). A manifest's ``manifest_version`` says what its rows were checked against, so that a reader that does not know a rule refuses the manifest rather than read it under a weaker one. -- **Version 6** (Spec ADR 0008, v0.10.0) is the one written: a described run's manifest whose +- **Version 7** (Spec ADR 0010, after v0.10.0) is the one written: version 6 with volumes. Every + file entry records ``shape``, ``z_count``, ``t_count``, ``c_count``, ``image_kind``, + ``plane_statistics``, ``plane_count`` (physical planes) and ``statistics_rows``, and its + ``pixel_sizes`` with an ``unknown`` source and the derived ``reason``; the manifest records + ``checks`` and ``statistics_artifacts`` (:mod:`.manifest_volume`). A run whose images are all + volumes writes no histogram or QC table: both digests and ``image_qc`` are present and null + (VC1). Only version 7 is used by ``RunInputs``: an older run is refused with + ``RUN_FOLDER_VERSION`` (run preprocessing again), so no reader infers a Z extent from + histogram rows again. Versions 6 and 5 are still **read** for the inputs a new run takes from + the earlier one (its axis roles, settings and rows), never handed to a brick. +- **Version 6** (Spec ADR 0008, v0.10.0): a described run's manifest whose table is ``plane_histograms.parquet`` schema version 6. It records the table's two digests, ``histogram_table_sha256`` (the file's bytes: integrity) and ``histogram_table_content_sha256`` (its content digest: identity, PQ6), both mandatory, and @@ -34,16 +44,20 @@ from .description_record import KEY as DESCRIPTION_KEY from .manifest_fields import recorded_flag -MANIFEST_VERSION = "6" -"""The version of every run manifest this package writes (a described run, schema 6 table).""" +MANIFEST_VERSION = "7" +"""The version of every run manifest this package writes (Spec ADR 0010: volumes).""" +PARQUET_VERSION = "6" +"""The version written by v0.10.0 (Spec ADR 0008): read for a new run's inputs, refused by +``RunInputs`` (it records no acquisition sizes, so a volume would read as one plane).""" EARLIER_VERSION = "5" """The earlier version this package still reads (owner decision 10): its table is version 5.""" CONTENT_KEY = "content_sha256" """The key of a source's content SHA-256 in a manifest entry (``verify_content`` runs).""" -READ_VERSIONS = (MANIFEST_VERSION, EARLIER_VERSION) -"""The versions this package reads: the current one and version 5 (owner decision 10).""" +READ_VERSIONS = (MANIFEST_VERSION, PARQUET_VERSION, EARLIER_VERSION) +"""The versions this package reads: the current one, 6 and 5 (owner decision 10).""" TABLE_DIGESTS = { MANIFEST_VERSION: ("histogram_table_sha256", "histogram_table_content_sha256"), + PARQUET_VERSION: ("histogram_table_sha256", "histogram_table_content_sha256"), EARLIER_VERSION: ("csv_sha256",), } """The keys of the histogram table's digests in a manifest of each version read.""" @@ -86,8 +100,8 @@ def check_version( if version not in READ_VERSIONS: raise UnsupportedVersionError( f"Manifest version {version!r} is not supported: this version of preprocessing " - f"reads versions {MANIFEST_VERSION!r} and {EARLIER_VERSION!r} only (older runs are " - f"not converted). {RERUN}" + f"reads versions {MANIFEST_VERSION!r}, {PARQUET_VERSION!r} and {EARLIER_VERSION!r} " + f"only (older runs are not converted). {RERUN}" ) if not described: raise ValueError( diff --git a/src/morphobricks_preprocessing/manifest_volume.py b/src/morphobricks_preprocessing/manifest_volume.py new file mode 100644 index 00000000..700b9b28 --- /dev/null +++ b/src/morphobricks_preprocessing/manifest_volume.py @@ -0,0 +1,569 @@ +"""What a run manifest of version 7 records about planes and volumes (Spec ADR 0010, VC1-VC5). + +An included image is a **volume** when its confirmed ``Z`` role has more than one slice; +otherwise it is a **plane image** (a one-slice ``Z`` is a plane, ADR 0002 AR3). From version 7 +every file entry records, besides ``axes`` and ``roles``: + +- ``shape`` (one positive integer per axis letter, the sizes the image was read with), and from + it and the roles, never from statistics rows (VC2): ``z_count``, ``t_count``, ``c_count`` + (the sizes of the confirmed ``Z``, ``T`` and ``C`` roles, 1 for an absent role); +- ``image_kind`` (``"plane"`` or ``"volume"``) and ``plane_statistics`` (``"computed"`` or + ``"not_computed_volume"``, VZ2, VZ26): histograms, normalization and QC metrics are not + computed for a volume; +- ``plane_count`` (the physical XYC planes, ``t_count × z_count``) and ``statistics_rows`` + (the rows it has in the histogram table: ``t_count`` for a plane image, 0 for a volume); +- ``pixel_sizes`` in the version 7 codec (:func:`manifest_sizes_to_data`, VC4): ``source`` + ``unknown`` where nothing gives a size, and the derived ``reason`` ``W_AXIS_UNCALIBRATED`` for an + uncalibrated ``X`` or ``Y`` (any image) or ``Z`` of a volume. + +The top-level ``checks`` (:func:`compute_checks`, VC5) and ``statistics_artifacts`` +(:func:`artifacts_state`, VC1) are derived from the entries; the writer and the reader check +every field against the others (VC3) and refuse, never repair. Pure: no I/O. +""" + +from __future__ import annotations + +import math +from collections.abc import Callable, Iterable, Mapping, Sequence +from dataclasses import dataclass, replace + +from .length_units import _MICROMETERS +from .recorded_sizes import HEADER, PIXELS, SIZE_ROLES, STATED, RecordedSize + +PLANE = "plane" +VOLUME = "volume" +IMAGE_KINDS = (PLANE, VOLUME) +COMPUTED = "computed" +NOT_COMPUTED_VOLUME = "not_computed_volume" +PLANE_STATISTICS = (COMPUTED, NOT_COMPUTED_VOLUME) +UNKNOWN = "unknown" +"""The version 7 source of a size nothing gives (a ``null`` source is refused in version 7).""" +SOURCES_V7 = (HEADER, STATED, PIXELS, UNKNOWN) +AXIS_UNCALIBRATED = "W_AXIS_UNCALIBRATED" +MIXED = "W_MIXED_PLANES_AND_VOLUMES" +ALL_VOLUMES = "all_volumes" +ARTIFACTS_COMPUTED = {"state": COMPUTED} +ARTIFACTS_NOT_COMPUTED = {"state": "not_computed", "reason": ALL_VOLUMES} +SIZE_KEYS = ("role", "value", "unit", "source", "reason") +CHECK_KEYS = ("code", "axis", "counts", "images", "places") +IMAGE_KEYS = ("fov_key", "path", "z_count", "source") +PLACE_LEVELS = ("condition", "biological_repeat", "imaging_unit", "run") +TIME_UNITS = frozenset( + { + "attosecond", "centisecond", "day", "decisecond", "exasecond", "femtosecond", + "gigasecond", "hectosecond", "hour", "kilosecond", "megasecond", "microsecond", + "millisecond", "minute", "nanosecond", "petasecond", "picosecond", "second", + "terasecond", "yoctosecond", "yottasecond", "zeptosecond", "zettasecond", + } +) # fmt: skip +"""The OME-NGFF time unit names a ``T`` size may have.""" + + +@dataclass(frozen=True) +class Acquisition: + """The acquisition sizes of one image under its confirmed roles (VC2).""" + + shape: tuple[int, ...] + z_count: int + t_count: int + c_count: int + + @property + def image_kind(self) -> str: + """``"volume"`` when the confirmed ``Z`` has more than one slice, else ``"plane"``.""" + return VOLUME if self.z_count > 1 else PLANE + + @property + def plane_statistics(self) -> str: + """``"not_computed_volume"`` for a volume, ``"computed"`` for a plane image (VZ2).""" + return NOT_COMPUTED_VOLUME if self.image_kind == VOLUME else COMPUTED + + @property + def plane_count(self) -> int: + """The physical XYC planes, ``t_count × z_count``.""" + return self.t_count * self.z_count + + @property + def statistics_rows(self) -> int: + """The image's rows in the histogram table: ``t_count``, or 0 for a volume.""" + return 0 if self.image_kind == VOLUME else self.t_count + + +def acquisition(shape: Sequence[int], roles: Sequence[str | None]) -> Acquisition: + """Return the sizes of the confirmed ``Z``, ``T`` and ``C`` roles (1 when absent). + + Raises + ------ + ValueError + When ``shape`` is not one positive integer (never a boolean) per role. + """ + sizes = tuple(shape) + if len(sizes) != len(roles) or not all(_positive_int(n) for n in sizes): + raise ValueError(f"the shape {list(sizes)!r} is not one positive integer per axis") + lengths = dict(zip(roles, sizes, strict=True)) + return Acquisition(sizes, lengths.get("Z", 1), lengths.get("T", 1), lengths.get("C", 1)) + + +def _positive_int(value: object) -> bool: + """Return True for a positive ``int`` that is not a boolean.""" + return isinstance(value, int) and not isinstance(value, bool) and value > 0 + + +def check_entry_sizes(path: str, recorded: Mapping[str, object], found: Acquisition) -> None: + """Refuse an entry whose recorded sizes are not the ones its shape and roles give (VC3). + + ``recorded`` holds the entry's ``z_count``, ``t_count``, ``c_count``, ``image_kind``, + ``plane_statistics``, ``plane_count`` and ``statistics_rows`` as written. + + Raises + ------ + ValueError + Naming the image and the first field that disagrees. + """ + expected = { + "z_count": found.z_count, + "t_count": found.t_count, + "c_count": found.c_count, + "image_kind": found.image_kind, + "plane_statistics": found.plane_statistics, + "plane_count": found.plane_count, + "statistics_rows": found.statistics_rows, + } + for key, value in expected.items(): + given = recorded.get(key) + if isinstance(given, bool) or type(given) is not type(value) or given != value: + raise ValueError( + f"the entry of {path!r} records {key} = {given!r}, but its shape and roles give " + f"{value!r}" + ) + + +# The calibration codec of version 7 (VC4) -------------------------------------------------- + + +def size_reason(role: str, source: str | None, volume: bool) -> str | None: + """Return the derived ``reason`` of one size: ``W_AXIS_UNCALIBRATED`` or None (VZ18, I3).""" + uncalibrated = source in (None, UNKNOWN, PIXELS) + if role in ("X", "Y") and uncalibrated: + return AXIS_UNCALIBRATED + if role == "Z" and volume and uncalibrated: + return AXIS_UNCALIBRATED + return None + + +def _check_size(item: Mapping, volume: bool) -> None: + """Refuse one version 7 size that is not exactly one row of VC4's matrix.""" + if not isinstance(item, Mapping) or tuple(sorted(item)) != tuple(sorted(SIZE_KEYS)): + raise ValueError(f"the pixel size {item!r} does not hold exactly {', '.join(SIZE_KEYS)}") + role, value, unit, source = item["role"], item["value"], item["unit"], item["source"] + if role not in SIZE_ROLES or source not in SOURCES_V7: + raise ValueError(f"the pixel size {dict(item)!r} has an unknown role or source") + if source in (HEADER, STATED): + family = role != "T" + if not _positive(value) or not _unit_of(unit, family): + raise ValueError( + f"the pixel size {dict(item)!r} needs a positive finite value and a supported " + f"{'length' if family else 'time'} unit with the source {source}" + ) + if source == STATED and role == "T": + raise ValueError(f"the pixel size {dict(item)!r}: a time step is never stated") + elif value is not None or unit is not None: + raise ValueError(f"the pixel size {dict(item)!r} has a value or unit with {source}") + elif source == PIXELS and role == "T": + raise ValueError(f"the pixel size {dict(item)!r}: a time step is never pixels") + if item["reason"] != size_reason(role, source, volume): + raise ValueError( + f"the pixel size {dict(item)!r} records the reason {item['reason']!r}; its source " + f"gives {size_reason(role, source, volume)!r}" + ) + + +def _positive(value: object) -> bool: + """Return True for a positive, finite JSON number (a boolean or text is not one).""" + if isinstance(value, bool) or not isinstance(value, int | float): + return False + return math.isfinite(value) and value > 0 + + +def _unit_of(unit: object, length: bool) -> bool: + """Return True when ``unit`` is a supported length (``length``) or time unit.""" + return isinstance(unit, str) and (unit in _MICROMETERS if length else unit in TIME_UNITS) + + +def manifest_sizes_to_data(sizes: Iterable[RecordedSize], volume: bool) -> list[dict]: + """Return an entry's sizes in the version 7 codec, one per role, refusing a contradiction. + + The in-memory sizes keep the conversion record's form (a ``None`` source where nothing gives + a size, no reason); the run manifest writes ``unknown`` and the derived ``reason``. + """ + data = [ + { + "role": s.role, + "value": s.value, + "unit": s.unit, + "source": UNKNOWN if s.source is None else s.source, + "reason": size_reason(s.role, s.source, volume), + } + for s in sizes + ] + manifest_sizes_from_data(data, volume) # the writer refuses what the reader would refuse + return data + + +def manifest_sizes_from_data(data: object, volume: bool) -> tuple[RecordedSize, ...]: + """Read an entry's version 7 sizes into the in-memory form (``unknown`` as a None source). + + Raises + ------ + ValueError + Not a list of one size per role in the order ``X``, ``Y``, ``Z``, ``T``, a size that is + not exactly one row of VC4's matrix, or a ``reason`` other than the derived one. + """ + roles = ( + [i.get("role") for i in data if isinstance(i, Mapping)] if isinstance(data, list) else [] + ) + if not isinstance(data, list) or roles != list(SIZE_ROLES) or len(roles) != len(data): + raise ValueError(f"the pixel sizes {data!r} are not one size per role X, Y, Z, T") + for item in data: + _check_size(item, volume) + return tuple( + RecordedSize( + i["role"], + None if i["value"] is None else float(i["value"]), + i["unit"], + None if i["source"] == UNKNOWN else i["source"], + ) + for i in data + ) + + +def size_view(sizes: Iterable[RecordedSize], volume: bool) -> dict[str, RecordedSize]: + """Return the sizes as ``RunInputs.pixel_sizes`` gives them: ``unknown`` and the reason.""" + return { + s.role: replace( + s, + source=UNKNOWN if s.source is None else s.source, + reason=size_reason(s.role, s.source, volume), + ) + for s in sizes + } + + +# The statistics artifacts (VC1) ------------------------------------------------------------- + + +def artifacts_state(kinds: Iterable[str]) -> dict: + """Return ``statistics_artifacts`` for the included images' kinds (VC1, VZ29).""" + kinds = list(kinds) + if kinds and all(kind == VOLUME for kind in kinds): + return dict(ARTIFACTS_NOT_COMPUTED) + return dict(ARTIFACTS_COMPUTED) + + +def check_artifacts(value: object, kinds: Iterable[str]) -> dict: + """Refuse a ``statistics_artifacts`` that is not the state the entries give (VC1).""" + expected = artifacts_state(kinds) + if value != expected or type(value) is not dict: + raise ValueError( + f"statistics_artifacts is {value!r}, but the image entries give {expected!r}" + ) + return expected + + +# The run's checks (VC5) --------------------------------------------------------------------- + + +@dataclass(frozen=True) +class CheckedImage: + """What :func:`compute_checks` reads of one included image. + + ``fov_key`` holds the source labels and the position ID; ``unit`` the canonical + ``(condition ID, repeat group, technical repeat ID)`` of its imaging unit. + """ + + fov_key: tuple[str, str, str, str] + path: str + z_count: int + sizes: tuple[RecordedSize, ...] + unit: tuple[str, str, str] + + @property + def volume(self) -> bool: + """True for a volume.""" + return self.z_count > 1 + + +def compute_checks(images: Iterable[CheckedImage]) -> list[dict]: + """Return the run's ``checks``: derived from the entries, sorted by code then axis (VC5). + + One run-level ``W_AXIS_UNCALIBRATED`` when any entry carries the reason (owner answer of + 2 December 2026, VZ30): ``counts`` gives, per axis that has any, how many images lack it, + ``images`` every such image once (its per-axis sources are its ``pixel_sizes``, which say + ``unknown`` or ``pixels``). One ``W_MIXED_PLANES_AND_VOLUMES`` when the run holds both + kinds (every image, the counts, and every condition, biological repeat and imaging unit + holding both, then the run; VZ4, VZ8, VZ19: warned, never refused). Images sorted by FOV + key then path. + """ + ordered = sorted(images, key=lambda i: (i.fov_key, i.path)) + found = [] + lacking = { + image.path: { + s.role.lower() for s in image.sizes if size_reason(s.role, s.source, image.volume) + } + for image in ordered + } + counts = { + axis: sum(1 for axes in lacking.values() if axis in axes) + for axis in ("x", "y", "z") + if any(axis in axes for axes in lacking.values()) + } + if counts: + found.append( + { + "code": AXIS_UNCALIBRATED, + "axis": None, + "counts": counts, + "images": [_image(i, None) for i in ordered if lacking[i.path]], + "places": [], + } + ) + volumes = sum(1 for i in ordered if i.volume) + if 0 < volumes < len(ordered): + found.append( + { + "code": MIXED, + "axis": None, + "counts": {"planes": len(ordered) - volumes, "volumes": volumes}, + "images": [_image(i, None) for i in ordered], + "places": _mixed_places(ordered), + } + ) + return sorted(found, key=lambda c: (c["code"], c["axis"] is not None, c["axis"] or "")) + + +def _image(image: CheckedImage, source: str | None) -> dict: + """Return one image of a ``checks`` object.""" + return { + "fov_key": list(image.fov_key), + "path": image.path, + "z_count": image.z_count, + "source": source, + } + + +def _mixed_places(images: Sequence[CheckedImage]) -> list[dict]: + """Return every condition, biological repeat and imaging unit holding both kinds, then run.""" + levels: dict[str, Callable[[CheckedImage], tuple[str, ...]]] = { + "condition": lambda i: (i.unit[0],), + "biological_repeat": lambda i: (i.unit[1],), + "imaging_unit": lambda i: i.unit, + } + places = [] + for level, key in levels.items(): + kinds: dict[tuple[str, ...], set[bool]] = {} + for image in images: + kinds.setdefault(key(image), set()).add(image.volume) + places.extend({"level": level, "key": list(k)} for k in sorted(kinds) if len(kinds[k]) == 2) + return [*places, {"level": "run", "key": []}] + + +def check_checks_shape(value: object) -> list[dict]: + """Refuse a ``checks`` value that is not a list of closed objects (VC5's shape, P68). + + Its content is compared with :func:`compute_checks` where the description is known + (``RunInputs.open``); here each object is checked on its own. + """ + if not isinstance(value, list): + raise ValueError(f"checks must be a list, not {value!r}") + for item in value: + if not isinstance(item, dict) or sorted(item) != sorted(CHECK_KEYS): + raise ValueError(f"the check {item!r} does not hold exactly {', '.join(CHECK_KEYS)}") + if item["code"] not in (AXIS_UNCALIBRATED, MIXED) or not isinstance(item["images"], list): + raise ValueError(f"the check {item!r} has an unknown code or no list of images") + for image in item["images"]: + if not isinstance(image, dict) or sorted(image) != sorted(IMAGE_KEYS): + raise ValueError(f"the image {image!r} of a check is not {', '.join(IMAGE_KEYS)}") + if not isinstance(item["places"], list) or any( + not isinstance(p, dict) + or sorted(p) != ["key", "level"] + or p["level"] not in PLACE_LEVELS + for p in item["places"] + ): + raise ValueError(f"the places of the check {item!r} are malformed") + return value + + +# The run report's texts (VZ4, VZ12) ---------------------------------------------------------- + +MORPHOFEATURE_REFUSES = ( + "MorphoFeature refuses this run as it stands: split it into two experiments, or project the " + "stacks" +) +"""The mixed-run warning's text (Spec ADR 0010 VZ4); the report's, not the manifest's.""" + + +def mixed_texts( + paths: Sequence[str], volumes: Mapping[str, int], places: Sequence[str] | None = None +) -> tuple[str, str]: + """Return the mixed-run warning's message and fix (VZ4, VZ19; checking and informing). + + The counts of plane images and volumes, the volumes, every place holding both (the run's + canonical places when given, else the image folders: condition, biological repeat, imaging + unit, then the run), what it means downstream, and the fix. It never blocks. + """ + if places is None: + places = _folder_places(paths, volumes) + shown = "; ".join(f"{p} ({n} Z planes)" for p, n in list(volumes.items())[:5]) + more = f"; and {len(volumes) - 5} more" if len(volumes) > 5 else "" + message = ( + f"This run mixes {len(paths) - len(volumes)} plane image(s) and {len(volumes)} " + f"volume(s) (Z-stacks): {shown}{more}. Places holding both: {', '.join(places)}. " + "Preprocessing describes and publishes it (nothing is refused here), but tools that " + "need one kind per run refuse it: " + + MORPHOFEATURE_REFUSES + + " (W_MIXED_PLANES_AND_VOLUMES)." + ) + return message, "Split it into two experiments (planes, volumes), or project the stacks." + + +def _folder_places(paths: Sequence[str], volumes: Mapping[str, int]) -> list[str]: + """Return the folders holding both kinds, by level, then the run (before the description).""" + levels = { + "condition": lambda p: p.split("/")[:1], + "biological_repeat": lambda p: p.split("/")[:2], + "imaging_unit": lambda p: p.split("/")[:-1], + } + places = [] + for level, key in levels.items(): + kinds: dict[str, set[bool]] = {} + for path in paths: + kinds.setdefault("/".join(key(path)), set()).add(path in volumes) + places.extend(f"{level} {k}" for k in sorted(kinds) if len(kinds[k]) == 2) + return [*places, "run"] + + +STATE_THE_STEP = "State the step in calibration.csv and run again." +"""The calibration warning's fix (Spec ADR 0010 VZ12).""" + + +def check_texts(check: Mapping) -> tuple[str, str]: + """Return the run report's message and fix of one ``checks`` object.""" + if check["code"] == MIXED: + images = check["images"] + volumes = {i["path"]: i["z_count"] for i in images if i["z_count"] > 1} + places = [f"{p['level']} {'/'.join(p['key'])}".rstrip() for p in check["places"]] + return mixed_texts([i["path"] for i in images], volumes, places) + lacking = ", ".join(f"{axis} in {n} image(s)" for axis, n in check["counts"].items()) + message = ( + f"Some steps have no length in a unit (unknown, or stated as pixels): {lacking}. Each " + "image's pixel sizes record which, with W_AXIS_UNCALIBRATED. Nothing is guessed and " + "nothing is blocked; a tool that needs a step refuses these images (W_AXIS_UNCALIBRATED)." + ) + return message, STATE_THE_STEP + + +def uncalibrated_axes( + sizes: Mapping[str, Iterable[RecordedSize]], volumes: Iterable[str] +) -> dict[str, list[tuple[str, str]]]: + """Return, per axis ``x``, ``y``, ``z``, every image whose step carries the reason, with source. + + For the Axes step's calibration card, as soon as the roles are confirmed (Spec ADR 0010: + the user meets an unknown step early; it blocks nothing). ``volumes`` are the images whose + confirmed ``Z`` has more than one slice: a plane image's ``Z`` is never listed (I3). + """ + volume = set(volumes) + found: dict[str, list[tuple[str, str]]] = {} + for path, recorded in sorted(sizes.items()): + for s in recorded: + if s.role in ("X", "Y", "Z") and size_reason(s.role, s.source, path in volume): + found.setdefault(s.role.lower(), []).append((path, s.source or UNKNOWN)) + return {axis: found[axis] for axis in ("x", "y", "z") if axis in found} + + +# The keep/project choice (owner answer of 2 December 2026, VZ32) ----------------------------- + +KEPT = "kept" +PROJECTED = "projected" + + +def z_handling(kinds: Iterable[str], projection_method: str | None) -> str | dict | None: + """Return the run's ``z_handling``: ``{"projected": method}``, ``"kept"`` or None. + + ``{"projected": method}`` for a run on projected copies; ``"kept"`` for a run holding + volumes (which the run accepts only on the user's explicit choice); None when there was no + Z-stack to choose for. + """ + if projection_method is not None: + return {PROJECTED: projection_method} + return KEPT if any(kind == VOLUME for kind in kinds) else None + + +def check_z_handling(value: object, kinds: Iterable[str], projection_method: str | None) -> None: + """Refuse a ``z_handling`` that is not the one the entries and the projection give.""" + expected = z_handling(kinds, projection_method) + if value != expected or type(value) is not type(expected): + raise ValueError( + f"z_handling is {value!r}, but the entries and projection give {expected!r}" + ) + + +# The version 7 record of a manifest (VC1, VC5, VZ32) ----------------------------------------- + +V7_KEYS = ("checks", "statistics_artifacts", "z_handling") + + +def volume_record(data: Mapping, version: str, *, current: bool) -> dict: + """Return ``checks``, ``statistics_artifacts`` and ``z_handling`` as read. + + Required in the current version, absent (None) before it; held by an older one: refused. + """ + if not current: + stray = [key for key in V7_KEYS if key in data] + if stray: + raise ValueError( + f"the manifest says version {version} but holds {', '.join(stray)}, which only " + "a version 7 manifest records" + ) + return dict.fromkeys(V7_KEYS) + found = {key: data[key] for key in V7_KEYS} + found["checks"] = tuple(check_checks_shape(found["checks"])) + return found + + +def volume_record_data(manifest: object) -> dict: + """Return the version 7 keys a manifest writes. + + ``image_qc`` (null without a QC table, VC1), ``checks``, ``statistics_artifacts`` and + ``z_handling``. + """ + from .image_qc_record import KEY, recorded_image_qc + + return { + KEY: recorded_image_qc(manifest.image_qc), + "checks": [dict(check) for check in check_checks_shape(list(manifest.checks or ()))], + "statistics_artifacts": dict(manifest.statistics_artifacts or {}), + "z_handling": manifest.z_handling, + } + + +def check_volume_record(manifest: object) -> None: + """Refuse a version 7 record that disagrees with the entries, digests, QC or projection. + + ``statistics_artifacts`` must be the state the entries give: in ``computed`` both table + digests and ``image_qc`` are recorded, in ``not_computed`` all three are null (VC1); + ``z_handling`` must be the one the entries and the projection give (VZ32). + """ + kinds = [f.image_kind for f in manifest.files] + check_z_handling(manifest.z_handling, kinds, (manifest.projection or {}).get("method")) + state = check_artifacts(manifest.statistics_artifacts, kinds) + digests = (manifest.histogram_table_sha256, manifest.histogram_table_content_sha256) + if state == ARTIFACTS_COMPUTED: + wrong = None in digests or manifest.image_qc is None + else: + wrong = digests != (None, None) or manifest.image_qc is not None + if wrong: + raise ValueError( + f"statistics_artifacts is {state!r}, but the histogram table digests or image_qc " + "say otherwise: with every image a volume, no table is written and both digests " + "and image_qc are null; otherwise all three are recorded" + ) diff --git a/src/morphobricks_preprocessing/metadata.py b/src/morphobricks_preprocessing/metadata.py index e51faf5f..b7873e39 100644 --- a/src/morphobricks_preprocessing/metadata.py +++ b/src/morphobricks_preprocessing/metadata.py @@ -39,7 +39,6 @@ plane_count_issues, role_plane_counts, role_size, - z_stack_issues, ) from .tiff_axes import series_axes_from_metadata from .tiff_colour import colour_header @@ -359,7 +358,7 @@ def inspect_image(path: str | os.PathLike, relative_path: str | None = None) -> def inspect_images( - experiment_root: str | os.PathLike, relative_paths: Iterable[str], *, allow_z: bool = False + experiment_root: str | os.PathLike, relative_paths: Iterable[str] ) -> MetadataReport: """Inspect the headers of the given images and check them together. @@ -369,8 +368,6 @@ def inspect_images( The experiment folder. relative_paths Image paths relative to the root, with ``/`` separators. - allow_z - Passed to :func:`check_metadata`: True for a tool that reads Z-stacks. Returns ------- @@ -380,7 +377,7 @@ def inspect_images( """ root = Path(experiment_root) files = tuple(inspect_image(root / rel, rel) for rel in sorted(relative_paths)) - return MetadataReport(files=files, issues=tuple(check_metadata(files, allow_z=allow_z))) + return MetadataReport(files=files, issues=tuple(check_metadata(files))) def inspect_experiment(discovery: DiscoveryResult) -> MetadataReport: @@ -388,9 +385,7 @@ def inspect_experiment(discovery: DiscoveryResult) -> MetadataReport: return inspect_images(discovery.root, discovery.images) -def check_metadata( - files: Iterable[TiffMetadata], *, allow_z: bool = False -) -> list[ValidationIssue]: +def check_metadata(files: Iterable[TiffMetadata]) -> list[ValidationIssue]: """Check image headers against the experiment-wide rules. Reports, as errors: images that do not open (``unreadable_tiff``, @@ -400,10 +395,10 @@ def check_metadata( dimensions are arranged differently, and images with different numbers of channels (``different_channel_counts``; the C axis, or the RGB samples without one, until the axis roles are confirmed), and channel names that differ at the - same channel (``channel_names_differ``), and images whose header names a Z axis of - more than one depth slice (``z_stack_not_supported``: MorphoBricks v1 analyses 2-D - planes; a plain stack is checked once its roles are confirmed). OME-Zarr images declare - their axes, so their arrangement is checked by role during the axis review instead. + same channel (``channel_names_differ``). OME-Zarr images declare their axes, so their + arrangement is checked by role during the axis review instead. A Z-stack is not refused + (Spec ADR 0010 VZ1: the Z gate moved to the hand-off; ``z_stack_not_supported`` and the + ``allow_z`` option are gone): it is described as a volume. Reports, as warnings: images of different widths or heights (``different_sizes``), different numbers of depth slices, time points @@ -418,11 +413,8 @@ def check_metadata( Parameters ---------- files - Headers from :func:`inspect_image`. - allow_z - True for a tool that reads Z-stacks: ``z_stack_not_supported`` is not reported and - every other check runs unchanged (default False). ``case_conflict`` is not checked - here: it comes from folder discovery (:func:`discover_experiment`). + Headers from :func:`inspect_image`. ``case_conflict`` is not checked here: it comes + from folder discovery (:func:`discover_experiment`). Returns ------- @@ -513,7 +505,7 @@ def check_metadata( issues.extend(dtype_issues(readable)) issues.extend(arrangement_issues([f for f in readable if not f.is_ome_zarr])) issues.extend(_check_channel_names(readable)) - issues.extend(_check_counts(readable, allow_z=allow_z)) + issues.extend(channel_count_issues(_header_channel_counts(readable))) issues.extend(dimension_issues(readable)) issues.extend(pixel_size_issues(readable)) return issues @@ -558,26 +550,16 @@ def _check_channel_names(files: list[TiffMetadata]) -> list[ValidationIssue]: ] +def _header_channel_counts(files: list[TiffMetadata]) -> dict[str, int]: + """Return each image's channel count by the axes its header names.""" + return {f.relative_path: header_channel_count(f) for f in files} + + def header_channel_count(f: TiffMetadata) -> int: """Return the channel count the header suggests: the C axis, else the RGB samples.""" return f.length("C") if "C" in f.axes else f.length("S") -def header_depth_slices(f: TiffMetadata) -> int: - """Return the depth slices of the Z axis the header names; 1 when it names none.""" - named = named_axes(f) - return f.shape[named.index("Z")] if "Z" in named else 1 - - -def _check_counts(files: list[TiffMetadata], *, allow_z: bool = False) -> list[ValidationIssue]: - """Report different channel counts and, unless ``allow_z``, Z-stacks, by the header axes.""" - depths = {} if allow_z else {f.relative_path: header_depth_slices(f) for f in files} - return [ - *channel_count_issues({f.relative_path: header_channel_count(f) for f in files}), - *z_stack_issues(depths), - ] - - def dimension_issues( files: Iterable[TiffMetadata], roles: Mapping[str, Sequence[str | None]] | None = None ) -> list[ValidationIssue]: diff --git a/src/morphobricks_preprocessing/notebook_axes_quick.py b/src/morphobricks_preprocessing/notebook_axes_quick.py index ae622dcd..8e910062 100644 --- a/src/morphobricks_preprocessing/notebook_axes_quick.py +++ b/src/morphobricks_preprocessing/notebook_axes_quick.py @@ -25,7 +25,7 @@ from . import notebook_style as ui from .axes import AxisMapping, axis_name from .axis_check import ConfirmedAxes -from .axis_review import review_axes +from .axis_review import review_axes, volume_slices from .description_reconcile import CHANNELS_CHANGED from .fingerprint import unchanged_confirmation from .notebook_render import blocked_line @@ -90,6 +90,7 @@ def _quick_mapping(self) -> AxisMapping | None: or len(review.file_mappings) != len(readable) or any(m.singleton_roles for m in review.file_mappings.values()) or not set(review.confirmed_files) <= covered + or volume_slices(readable, review.file_mappings) # keep or project first (ADR 0010) ): return None return mapping diff --git a/src/morphobricks_preprocessing/notebook_calibration.py b/src/morphobricks_preprocessing/notebook_calibration.py index 71595441..2d1bc963 100644 --- a/src/morphobricks_preprocessing/notebook_calibration.py +++ b/src/morphobricks_preprocessing/notebook_calibration.py @@ -33,6 +33,7 @@ calibration_entry, ) from .calibration_io import CalibrationFormatError, read_calibration +from .manifest_volume import uncalibrated_axes from .notebook_options import _WIDE from .notebook_render import issues_html from .notebook_values import size_rows @@ -392,7 +393,40 @@ def _show_calibration(self) -> None: ) self.calibration_table.value = ui.help_text(note).value + ui.table(rows) issues = [i for i in shown.metadata.issues if i.code in CALIBRATION_ISSUE_CODES] - self.calibration_issues.value = issues_html(issues) if issues else "" + unknown = self._unknown_steps(shown, roles) + self.calibration_issues.value = unknown + (issues_html(issues) if issues else "") + + def _unknown_steps(self, shown: Preflight, roles: dict | None) -> str: + """Say, once the roles are confirmed, which steps are unknown (Spec ADR 0010 VZ12). + + Every space axis without a length (unknown, or stated as pixels) is listed with its + images: ``x`` and ``y`` of any image, ``z`` of a volume only. It is recorded with + ``W_AXIS_UNCALIBRATED`` and blocks nothing; the step is never guessed. + """ + if roles is None: + return "" + shapes = {f.relative_path: f.shape for f in shown.metadata.files if f.readable} + volumes = [ + path + for path, given in roles.items() + if len(shapes.get(path, ())) == len(given) + and dict(zip(given, shapes[path], strict=True)).get("Z", 1) > 1 + ] + found = uncalibrated_axes(shown.calibration.sizes, volumes) + lines = [ + f"{axis}: {len(images)} image(s) ({', '.join(sorted({s for _, s in images}))}), " + f"e.g. {images[0][0]}" + for axis, images in found.items() + ] + if not lines: + return "" + return ui.status( + "warn", + "Some steps are not known; they are recorded as unknown with W_AXIS_UNCALIBRATED " + "and block nothing. A tool that needs a step refuses these images; state it here " + "(per experiment, folder or image) to record it.", + lines, + ) _one_line_sizes = False """True in the shipped notebook: sizes that differ are one line, a folded table and the diff --git a/src/morphobricks_preprocessing/notebook_projection.py b/src/morphobricks_preprocessing/notebook_projection.py index 7f730585..011069b1 100644 --- a/src/morphobricks_preprocessing/notebook_projection.py +++ b/src/morphobricks_preprocessing/notebook_projection.py @@ -1,24 +1,27 @@ -"""Z-stacks in the shipped notebook: save the dataset as recorded projections, and go on. - -MorphoBricks v1 analyses 2-D planes, so an image with more than one depth slice is refused -(``z_stack_not_supported``). Owner (11 November 2026): when the roles on Axes give a depth -dimension with several slices, the app offers the path the refusal names, right there: the -user looks at the stack in the viewer (its z slider), **chooses the projection** (a method, -with no default, and the slices), and one click writes a projected 2-D copy of every image -with :func:`.conversion.convert_experiment` (issue #176: the copies, their conversion record -version 4, every refusal before anything is written). The later steps then use the copies: -the app opens the copy tree as the experiment (scanned and checked again, nothing confirmed for -the user), with the same output folder. +"""Z-stacks in the shipped notebook: keep them as volumes, or save recorded projections. + +A Z-stack is described, tagged and calibrated as a **volume** (Spec ADR 0010 VZ1: the Z gate +moved to the hand-off). Projection stays an explicit, recorded choice with **no default**, +offered beside keeping the stacks: when the roles on Axes give a depth dimension with several +slices, the card asks the user to choose one of the two before the roles can be confirmed. + +- *Keep the 3-D stacks* (:data:`KEEP_3D`): the stacks are described as they are. The run + records each as ``image_kind = "volume"``; histograms, normalization and QC are not computed + for them (``plane_statistics = "not_computed_volume"``, VZ2), and only a tool that declares + ``volume_support`` takes them (the hand-off refuses the others). +- *Project*: owner (11 November 2026): the user looks at the stack in the viewer (its z + slider), **chooses the projection** (a method, with no default, and the slices), and one + click writes a projected 2-D copy of every image with :func:`.conversion.convert_experiment` + (issue #176: the copies, their conversion record version 4, every refusal before anything is + written). The later steps then use the copies: the app opens the copy tree as the experiment + (scanned and checked again, nothing confirmed for the user), with the same output folder. **The original stacks are kept.** They are only read: never changed, moved or deleted. The conversion record in the copy tree names the folder they are in (``source_root``) and, per image, the same relative path, the stack's fingerprint and content SHA-256, its depth axis and size, and the slices used; a run on the copies records that record's SHA-256, and ``RunInputs.projection`` hands these to the bricks. A tool that analyses volumes can therefore -be given the original stack of any analysed image later, without any migration. Until a -consumer declares it (``Capabilities.volume_support``; today a volume request is refused with -``A_VOLUME_NOT_SUPPORTED``), the option *Keep the 3-D stacks for 3-D-capable tools* is shown -greyed out with its reason. +be given the original stack of any analysed image later, without any migration. The copies are written into ``/projected_[_z-]``: an output folder may hold the experiment it describes (contract §15). Masks are never projected; @@ -34,6 +37,7 @@ import ipywidgets as widgets from . import notebook_style as ui +from .axis_review import early_mixed_warning, volume_slices from .conversion import ConversionResult, convert_experiment from .conversion_record import ( RECORD_FILENAME, @@ -47,7 +51,6 @@ from .notebook_viewer import READ_ERRORS from .ome_zarr_copy import OME_TIFF, OME_ZARR, ZARR_COPY_SUFFIX from .projection import METHODS, Projection -from .size_checks import Z_STACK_CODE from .validation import plural CHOOSE = "— choose a method —" @@ -58,14 +61,27 @@ ("Sum: the total along Z (written in a wider type)", "sum"), ] WRITE_LABEL = " Write the projected copies and continue with them" -KEEP_3D = "Keep the 3-D stacks for 3-D-capable tools (fiberfeatures)" -NOT_ENABLED = "3-D analysis is not enabled yet" +KEEP_3D = "Keep the 3-D stacks: describe them as volumes, without projection" +MIXED_TITLE = "Some images are Z-stacks and some are not: this run will mix both kinds" +"""The card's title when plane images and volumes are mixed (W_MIXED_PLANES_AND_VOLUMES).""" +NOT_COMPUTED = ( + "Kept stacks are volumes: plane histograms, normalization and QC metrics are not computed " + "for them (not computed: volume), and only tools that declare volume support take them; " + "MorphoFeature refuses them." +) +"""What keeping the stacks means, said beside the choice (Spec ADR 0010 VZ2).""" +CHOOSE_STACKS = ( + "the images are Z-stacks: tick Keep the 3-D stacks, or choose a projection under Z-stacks " + "below and continue with the projected copies" +) +"""What blocks *Confirm axis roles* while no choice is made for the stacks (no default).""" FOLDER_PREFIX = "projected_" INTRO = ( - "MorphoBricks analyses 2-D planes, and these images are Z-stacks. Look at the stack in " - "the example above (the z slider), then choose how each stack becomes one plane. " - "One click writes a projected copy of every image, with a conversion record, into the " - "output folder; the later steps use the copies. Nothing is chosen for you." + "These images are Z-stacks. Choose what to do with them: keep them as 3-D stacks " + "(volumes), or make a projected 2-D copy of each. To project, look at the stack in the " + "example above (the z slider), then choose how each stack becomes one plane; one " + "click writes a projected copy of every image, with a conversion record, into the output " + "folder, and the later steps use the copies. Nothing is chosen for you." ) TICKED = "Example checked. Now click Confirm axis roles below." TICKED_STACKS = "Example checked. Now choose the projection under Z-stacks below." @@ -153,12 +169,12 @@ def _build_projection_card(self) -> None: self.projection_caption = widgets.HTML() self.projection_keep = widgets.Checkbox( value=False, - disabled=True, description=KEEP_3D, indent=False, layout=widgets.Layout(width="auto"), ) self.projection_where = widgets.HTML() + self.projection_mixed = widgets.HTML() # plane images and volumes together (VZ4, VZ19) self.projection_button = ui.button(WRITE_LABEL, style="success", icon="clone", main=True) self.projection_blocker = widgets.HTML() self.projection_status = widgets.HTML() @@ -172,6 +188,7 @@ def _build_projection_card(self) -> None: for box in (self.projection_method, self.projection_first, self.projection_last): box.observe(lambda _: self._projection_changed(), names="value") self.preview_checked.observe(lambda _: self._projection_changed()) + self.projection_keep.observe(lambda _: self._kept_changed(), names="value") self.projection_look.on_click(lambda _: self._show_projection()) self.projection_button.on_click(lambda _: self._write_projection()) @@ -179,7 +196,7 @@ def _lay_out_projection_card(self) -> None: """Put the card's widgets in one column: the choice, the look, what is kept, the click.""" row = widgets.Layout(align_items="center", flex_flow="row wrap") self.projection_card = ui.card( - "Z-stacks: save the dataset as projections", + "Z-stacks: keep them as volumes or project them", [ widgets.HTML(f"
{INTRO}
"), self.projection_earlier, @@ -197,9 +214,9 @@ def _lay_out_projection_card(self) -> None: self.projection_look, self.projection_tiles, self.projection_caption, - widgets.HBox( - [self.projection_keep, widgets.HTML(blocked_line([NOT_ENABLED]))], layout=row - ), + self.projection_keep, + widgets.HTML(f"
{NOT_COMPUTED}
"), + self.projection_mixed, widgets.HTML(f"
{KEPT}
"), self.projection_where, self.projection_button, @@ -225,8 +242,14 @@ def _refresh_projection_card(self, review: object) -> None: if getattr(self, "projection_card", None) is None: return self._forget_projection_of_another_check() - stacks = [i for i in getattr(review, "issues", ()) if i.code == Z_STACK_CODE] - offered = bool(stacks) and self.preflight is not None and self.confirmed_mapping is None + files = () if self.preflight is None else self.preflight.metadata.files + mappings = getattr(review, "file_mappings", None) or {} + self._volumes = volume_slices(files, mappings) + mixed = early_mixed_warning(files, mappings) # checked and said where the user decides + self.projection_mixed.value = ( + ui.status("warn", MIXED_TITLE, [mixed[0].message, mixed[0].action]) if mixed else "" + ) + offered = bool(self._volumes) and self.confirmed_mapping is None ui.set_visible(self.projection_card, offered) # With Z-stacks the tick leads to the projection, not to Confirm axis roles. self.preview_checked.confirmed_text = TICKED_STACKS if offered else TICKED @@ -253,6 +276,7 @@ def _forget_projection_of_another_check(self) -> None: return self._projection_check = check self.projection_method.value = "" + self.projection_keep.value = False # keeping is a choice too: never carried over self._z_slices = 0 # the slices are set again to the whole stack below def _stack_slices(self) -> int: @@ -265,6 +289,24 @@ def _stack_slices(self) -> int: ] return min(sizes, default=1) + def _kept(self) -> bool: + """Return True while *Keep the 3-D stacks* is ticked.""" + keep = getattr(self, "projection_keep", None) + return keep is not None and bool(keep.value) + + def _stacks_undecided(self) -> bool: + """Return True while the roles give volumes and neither choice is made (no default).""" + if getattr(self, "projection_card", None) is None or self.confirmed_mapping is not None: + return False + return bool(getattr(self, "_volumes", None)) and not self.projection_keep.value + + def _kept_changed(self) -> None: + """Say what keeping the stacks means, and let *Confirm axis roles* go on.""" + self._projection_changed() + update = getattr(self, "_update_confirm_button", None) + if update is not None: + update() + def _projection_changed(self) -> None: """Say where the copies go and what still stops the click; clear an earlier look.""" if getattr(self, "projection_card", None) is None or self.preflight is None: @@ -280,6 +322,8 @@ def _projection_changed(self) -> None: reasons.append("no projection method is chosen") if not self.preview_checked.value: reasons.append("the example is not ticked: click Yes, the example looks right above") + if self.projection_keep.value: + reasons = ["the 3-D stacks are kept: untick Keep the 3-D stacks to project instead"] self.projection_button.disabled = bool(reasons) self.projection_look.disabled = chosen is None self.projection_blocker.value = blocked_line(reasons) @@ -445,7 +489,7 @@ def _show_copy_note(self) -> None: [ f"Conversion record: {Path(pre.discovery.root) / conversion.record}", "The originals are kept where they are, unchanged." - + (f" They are recorded for 3-D-capable tools; {NOT_ENABLED}." if made else ""), + + (" They are recorded for 3-D-capable tools." if made else ""), ], ) @@ -453,8 +497,9 @@ def _show_copy_note(self) -> None: __all__ = [ "CHOOSE", "FOLDER_PREFIX", + "CHOOSE_STACKS", "KEEP_3D", - "NOT_ENABLED", + "NOT_COMPUTED", "_ProjectionCard", "copies_folder", "earlier_projections", diff --git a/src/morphobricks_preprocessing/notebook_run.py b/src/morphobricks_preprocessing/notebook_run.py index 5c76850c..0785ec79 100644 --- a/src/morphobricks_preprocessing/notebook_run.py +++ b/src/morphobricks_preprocessing/notebook_run.py @@ -37,6 +37,7 @@ from .notebook_progress import BUSY_NOTE, COUNTED_PHASES, PREPARING from .notebook_render import _bins_help, _label, blocked_line, change_lines, issues_html from .notebook_run_attempt import _RunAttempt +from .notebook_run_plan import not_computed_lines from .report import issue_counts, rebuild_line from .run import Preflight, RunMode, RunResult, run_experiment from .run.modes import AUTO @@ -253,6 +254,8 @@ def _run_mode(self, verify_content: bool | None) -> RunMode: checking=self._checking, memo=getattr(self, "_press_memo", None), # cell 5's press (content_memo) expected=getattr(self, "_press_expected", None), # its segmented images (bc B2) + # Keep the 3-D stacks ticked: the explicit, recorded choice (ADR 0010 VZ32). + keep_z_stacks=True if getattr(self, "_volumes", None) and self._kept() else None, ) def _build_histogram_range(self) -> list[widgets.Widget]: @@ -479,9 +482,10 @@ def _finish_run(self, result: RunResult) -> None: if result.written: self._recorded_after_run() self._refresh_mask_step(open_run=True) # the press opens the run it wrote (bc B4) - self._show_run_checks(result.csv_path) + if result.csv_path.exists(): # a run of volumes only writes no table (ADR 0010) + self._show_run_checks(result.csv_path) self._show_log() - if result.written: + if result.written and result.csv_path.exists(): # A new table, even at the same path: its earlier statistics and answers go (#524). self._forget_comparison() self.csv_file.value = str(result.csv_path) @@ -502,8 +506,11 @@ def _show_run_result(self, result: RunResult) -> None: self._show_stopped(result) return lines = [ - html.escape(f"Table: {result.csv_path}"), + html.escape(f"Table: {result.csv_path}") + if result.csv_path.exists() + else "Table: none (every image is a volume)", html.escape(f"Manifest: {result.manifest_path}"), + *not_computed_lines(result.volumes), ] if result.design_path is not None: lines.append(html.escape(f"Experiment design: {result.design_path}")) diff --git a/src/morphobricks_preprocessing/notebook_run_plan.py b/src/morphobricks_preprocessing/notebook_run_plan.py index 2f97fcfe..01382be5 100644 --- a/src/morphobricks_preprocessing/notebook_run_plan.py +++ b/src/morphobricks_preprocessing/notebook_run_plan.py @@ -16,6 +16,7 @@ from . import notebook_style as ui from .axes import AxisReview +from .axis_review import volume_slices from .discovery import default_output_folder from .discovery_report import REPORT_TEXT_FILENAME from .manifest import MANIFEST_FILENAME, ManifestFormatError, read_manifest @@ -28,6 +29,19 @@ from .validation import plural +def not_computed_lines(volumes: tuple[str, ...]) -> list[str]: + """Return the run step's "not computed: volume" line, or nothing (Spec ADR 0010 VZ2).""" + if not volumes: + return [] + shown = ", ".join(html.escape(path) for path in volumes[:3]) + more = f" and {len(volumes) - 3:,} more" if len(volumes) > 3 else "" + return [ + f"Histograms, normalization and QC metrics: not computed: volume for " + f"{plural(len(volumes), 'volume')} ({shown}{more}). Tools that declare volume support " + "read them; the others refuse them." + ] + + class _RunPlan: """Step 3's "What will happen" card, and the inputs given to the run.""" @@ -43,6 +57,9 @@ def _plan_html(self, review: AxisReview | None = None) -> str: blocks_line, over_card = self._memory_plan(review) if review is not None else ("", "") if blocks_line: lines.append(blocks_line) + if review is not None: # said where the step would run (Spec ADR 0010 VZ2) + volumes = volume_slices(self.preflight.metadata.files, review.file_mappings) + lines.extend(not_computed_lines(tuple(volumes))) lines.extend(self._plan_mode_lines(output)) return "
    " + "".join(f"
  • {line}
  • " for line in lines) + "
" + over_card diff --git a/src/morphobricks_preprocessing/notebook_steps.py b/src/morphobricks_preprocessing/notebook_steps.py index 625175bd..125cc839 100644 --- a/src/morphobricks_preprocessing/notebook_steps.py +++ b/src/morphobricks_preprocessing/notebook_steps.py @@ -38,7 +38,7 @@ from .notebook_design_step import _DesignStep from .notebook_image_type_line import ImageTypeLine from .notebook_masks_screen import INTRO as MASKS_INTRO -from .notebook_projection import _ProjectionCard +from .notebook_projection import CHOOSE_STACKS, _ProjectionCard from .notebook_quick_scan import _QuickScan from .notebook_scan_axes import _ScanAxes from .notebook_step_states import _StepStates @@ -334,13 +334,14 @@ def _refresh_convert_card(self, review: object) -> None: self._refresh_zarr_card() def _confirm_blockers(self) -> list[str]: - """Name the projection card when Z-stacks are all that stops the confirmation.""" + """Name the projection card while no choice is made for the Z-stacks (no default). + + Keeping the stacks (volumes) or projecting them is the user's explicit choice (Spec + ADR 0010 VZ1); until one is made, *Confirm axis roles* stays closed. + """ blockers = super()._confirm_blockers() - if getattr(self, "_review_errors", ()) == ("z stack not supported",) and blockers: - blockers[0] = ( - "the images are Z-stacks: choose a projection under Z-stacks below and " - "continue with the projected copies" - ) + if self._stacks_undecided(): + blockers.insert(0, CHOOSE_STACKS) return blockers def _refresh_type_rows(self) -> None: diff --git a/src/morphobricks_preprocessing/notebook_zarr_copy.py b/src/morphobricks_preprocessing/notebook_zarr_copy.py index 8f83216b..6eb942c1 100644 --- a/src/morphobricks_preprocessing/notebook_zarr_copy.py +++ b/src/morphobricks_preprocessing/notebook_zarr_copy.py @@ -29,7 +29,6 @@ from .notebook_progress import Wait from .notebook_render import blocked_line, issues_brief_html from .ome_zarr_copy import OME_TIFF, OME_ZARR -from .size_checks import Z_STACK_CODE OPTION_LABEL = "Also save a copy as OME-Zarr (in the output folder)" OPTION_HELP = ( @@ -98,9 +97,8 @@ def _refresh_zarr_card(self) -> None: return pre = self.preflight files = [] if pre is None else [f for f in pre.metadata.files if f.readable] - stacks = any( - c == Z_STACK_CODE.replace("_", " ") for c in getattr(self, "_review_errors", ()) - ) + undecided = getattr(self, "_stacks_undecided", None) + stacks = undecided is not None and undecided() # keep or project first (no default) offered = self.zarr_option.value and bool(files) and not stacks ui.set_visible(self.zarr_card, offered) if not offered: diff --git a/src/morphobricks_preprocessing/physical_unit.py b/src/morphobricks_preprocessing/physical_unit.py index 2b5626c6..bf02a287 100644 --- a/src/morphobricks_preprocessing/physical_unit.py +++ b/src/morphobricks_preprocessing/physical_unit.py @@ -84,7 +84,14 @@ def layout_of( header override (:func:`.rgb_override.effectively_rgb`), so that images differing only in colour interpretation are homogeneous (experiment-v1 4.4b). """ - axes = named_axes(meta).replace("T", "") + # Spec ADR 0010 VC11: with confirmed roles, the compared axes are those roles other than Z + # and T (size and presence), in the image's order; header letters are evidence only, so a + # plain stack confirmed ZYX joins a unit of YX images. Before the roles are confirmed, the + # axes the header names, without T and Z. A unit mixing planes and volumes is warned. + if roles is not None and len(roles) == len(meta.shape): + axes = "".join(r for r in roles if r is not None and r not in ("Z", "T")) + else: + axes = named_axes(meta).replace("T", "").replace("Z", "") if meta.rgb_samples or rgb: count: int | None = header_channel_count(meta) elif roles is not None: diff --git a/src/morphobricks_preprocessing/recorded_sizes.py b/src/morphobricks_preprocessing/recorded_sizes.py index 9b6ccd1a..0fc64aa7 100644 --- a/src/morphobricks_preprocessing/recorded_sizes.py +++ b/src/morphobricks_preprocessing/recorded_sizes.py @@ -41,13 +41,20 @@ class RecordedSize: Its unit as an OME-NGFF name (``"micrometer"``, ``"second"``), or None. source ``"header"`` or ``"stated"`` with a value; ``"pixels"`` (deliberately uncalibrated, - no value); None when nothing gives a size. + no value); None when nothing gives a size. ``RunInputs.pixel_sizes`` gives the run + manifest's view (version 7, Spec ADR 0010 VC4): ``"unknown"`` there instead of None. + reason + In ``RunInputs.pixel_sizes`` only: ``"W_AXIS_UNCALIBRATED"`` for an ``X`` or ``Y`` + without a length, or a ``Z`` without one on a volume; else None. Derived, never + chosen (:func:`.manifest_volume.size_reason`); not written by :meth:`to_dict`, which + is the conversion and projection records' codec, unchanged. """ role: str value: float | None = None unit: str | None = None source: str | None = None + reason: str | None = None def to_dict(self) -> dict: """Return the size as JSON-compatible data.""" diff --git a/src/morphobricks_preprocessing/run/check_step.py b/src/morphobricks_preprocessing/run/check_step.py index d0452fcf..83f2cc96 100644 --- a/src/morphobricks_preprocessing/run/check_step.py +++ b/src/morphobricks_preprocessing/run/check_step.py @@ -16,6 +16,7 @@ from ..axis_review import review_axes from ..discovery import check_output_folder, default_output_folder from ..discovery_report import RunOutcome, build_report +from ..manifest_volume import MIXED from ..validation import ValidationIssue from .lock import OutputLockedError, lock_issue, output_lock from .output_guard import output_masks_issues @@ -35,7 +36,8 @@ def suggested_review( ``missing_axes`` error is replaced by the review's ``missing_axes`` or ``ambiguous_missing_axes``, which ``missing_as_singleton`` answers as it does for ``run`` (F10, matrix run of 3 November 2026). The review's other issues are about - roles not confirmed yet, so ``check`` leaves them to ``run``. + roles not confirmed yet, so ``check`` leaves them to ``run``, except the warning + ``W_MIXED_PLANES_AND_VOLUMES`` (Spec ADR 0010 VZ4, VZ19: checked and said early). Parameters ---------- @@ -59,11 +61,15 @@ def suggested_review( ) fitted = fit_calibration(pre, review)[0] found = fitted.metadata.issues - if not any(issue.code == MISSING_AXES for issue in found): + # A run mixing planes and volumes under the suggested roles is said here too (VZ4, VZ19). + mixed = [issue for issue in review.issues if issue.code == MIXED] + if not any(issue.code == MISSING_AXES for issue in found) and not mixed: return fitted, review kept = [issue for issue in found if issue.code != MISSING_AXES] missing = [issue for issue in review.issues if issue.code in _MISSING_CODES] - issues = sorted([*kept, *missing], key=lambda issue: not issue.is_error) + if not any(issue.code == MISSING_AXES for issue in found): + missing = [] + issues = sorted([*kept, *missing, *mixed], key=lambda issue: not issue.is_error) return replace(fitted, metadata=replace(fitted.metadata, issues=tuple(issues))), review diff --git a/src/morphobricks_preprocessing/run/entries.py b/src/morphobricks_preprocessing/run/entries.py index aee7ea27..5cd6b08f 100644 --- a/src/morphobricks_preprocessing/run/entries.py +++ b/src/morphobricks_preprocessing/run/entries.py @@ -75,7 +75,8 @@ def file_entries( axes_from=review.axes_from.get(rel), pixel_sizes=pre.calibration.sizes[rel], channel_ids=tuple(channels.get(rel, ())), - ) + shape=tuple(header.shape), + ).with_acquisition() # z_count, t_count, c_count, image_kind... (Spec ADR 0010 VC2) if header.channel_names_trimmed: logger.info( "Leading or trailing whitespace was removed from the channel names of %s", rel @@ -144,7 +145,7 @@ def compare_with_previous( same = RowKey.of(before, settings, previous.experiment_root) == RowKey.of( entry, settings, root.as_posix() ) - complete = rebuild or len(previous_records.get(rel, ())) == before.plane_count + complete = rebuild or len(previous_records.get(rel, ())) == before.rows_expected (unchanged if same and complete else changed).append(rel) removed = sorted( f.relative_path diff --git a/src/morphobricks_preprocessing/run/generation.py b/src/morphobricks_preprocessing/run/generation.py index 8ebe1297..8fc2238a 100644 --- a/src/morphobricks_preprocessing/run/generation.py +++ b/src/morphobricks_preprocessing/run/generation.py @@ -71,11 +71,13 @@ REPORT_FILENAME, ) """The files moved into place after the commit, in this order (the manifest is the commit).""" -REMOVABLE = (MASK_REPORT_FILENAME, EARLIER_FILENAME) +REMOVABLE = (MASK_REPORT_FILENAME, EARLIER_FILENAME, OUTPUT_FILENAME, IMAGE_QC_FILENAME) """The only output files a publication may remove (#398): a record naming any other entry is refused, never followed, so a damaged or edited record cannot remove another file. The schema version 5 ``plane_histograms.csv`` of an earlier run is removed when a run publishes -``plane_histograms.parquet`` (Spec ADR 0008), so no table of another generation is left.""" +``plane_histograms.parquet`` (Spec ADR 0008), so no table of another generation is left; the +histogram and QC tables of an earlier run are removed by a run whose images are all volumes, +which writes neither (Spec ADR 0010 VC1, P99).""" class PublicationIncompleteError(RuntimeError): diff --git a/src/morphobricks_preprocessing/run/modes.py b/src/morphobricks_preprocessing/run/modes.py index 83510578..411cbcf6 100644 --- a/src/morphobricks_preprocessing/run/modes.py +++ b/src/morphobricks_preprocessing/run/modes.py @@ -109,6 +109,12 @@ class RunMode: the one masks were segmented from, for the notebook's **Register the masks** (v0.9.1, review bc B2). A run whose images are not it is refused (``source_not_segmented``) and publishes nothing. Not recorded; None (the default): no such constraint. + keep_z_stacks + True: the user's explicit choice to describe and run Z-stacks as volumes, without + projection (owner answer of 2 December 2026, Spec ADR 0010 VZ32). Recorded in the run + manifest as ``z_handling = "kept"``; a run with volumes and no such choice is refused + (``z_stacks_not_chosen``), never kept by default. None (the default): as the earlier + run recorded, False without one. """ name: str = RESTART @@ -119,6 +125,7 @@ class RunMode: checking: Callable[[str, int, int, str], None] | None = field(default=None, compare=False) memo: ContentMemo | None = field(default=None, compare=False) expected: ExpectedSources | None = field(default=None, compare=False) + keep_z_stacks: bool | None = None def run_mode(mode: object) -> RunMode: @@ -156,6 +163,8 @@ def run_mode(mode: object) -> RunMode: raise ValueError(f"memo must be a ContentMemo or None; found {mode.memo!r}") if mode.expected is not None and not isinstance(mode.expected, ExpectedSources): raise ValueError(f"expected must be ExpectedSources or None; found {mode.expected!r}") + if mode.keep_z_stacks is not None and not isinstance(mode.keep_z_stacks, bool): + raise ValueError(f"keep_z_stacks must be True, False or None; found {mode.keep_z_stacks!r}") return RunMode( check_mode(mode.name), mode.verify_content, @@ -165,6 +174,7 @@ def run_mode(mode: object) -> RunMode: mode.checking, mode.memo, mode.expected, + mode.keep_z_stacks, ) diff --git a/src/morphobricks_preprocessing/run/outputs.py b/src/morphobricks_preprocessing/run/outputs.py index bc6e9e60..e68fb584 100644 --- a/src/morphobricks_preprocessing/run/outputs.py +++ b/src/morphobricks_preprocessing/run/outputs.py @@ -8,6 +8,7 @@ from __future__ import annotations from collections import Counter +from collections.abc import Iterable, Mapping from dataclasses import replace from datetime import UTC, datetime from pathlib import Path @@ -18,11 +19,13 @@ from ..channel_identity import ChannelIdentityReport from ..design import DESIGN_FILENAME, write_experiment_design from ..discovery_report import REPORT_FILENAME, REPORT_TEXT_FILENAME +from ..fov_identity import checked_images from ..image_qc_record import IMAGE_QC_FILENAME, image_qc_entry from ..image_qc_table import write_image_qc from ..intensity import IntensityReport from ..manifest import ( MANIFEST_FILENAME, + FileEntry, RunManifest, RunSettings, file_sha256, @@ -30,6 +33,7 @@ write_manifest, ) from ..manifest_versions import MANIFEST_VERSION +from ..manifest_volume import ARTIFACTS_COMPUTED, artifacts_state, compute_checks, z_handling from ..mask_scan import MASK_REPORT_FILENAME from .description_run import manifest_entry from .modes import FULL @@ -38,6 +42,12 @@ from .state import RunState from .steps import Rows +NO_STATISTICS = ( + "every image is a volume: histograms and QC metrics are not computed for volumes, so no " + "table is written (not computed: volume)" +) +"""Why a run of volumes only removes the earlier tables (Spec ADR 0010 VC1, P99).""" + def write_generation( run: RunState, @@ -51,13 +61,26 @@ def write_generation( ``checks`` are the masks entry, the intensity and the channel checks. Returns the manifest's SHA-256 (the report, which names it, is written once the images are checked again). + + A volume has no row and no QC row (Spec ADR 0010 VZ2); a run whose images are all volumes + writes no histogram table and no QC table, and its manifest records both digests and + ``image_qc`` as null with ``statistics_artifacts`` ``not_computed`` (VC1, VZ29). """ - pre, design, ids = run.pre, run.checked.design, run.checked.channel_ids + pre, design = run.pre, run.checked.design masks, intensity, identity = checks described = run.description - per_file = Counter(record.source_relative_path for record in records) - table = write_plane_histograms(records, staged / OUTPUT_FILENAME, channel_ids=ids) - qc_sha256 = file_sha256(write_image_qc(rows.qc, staged / IMAGE_QC_FILENAME)) + entries = _counted(rows.entries, records) + state = artifacts_state(entry.image_kind for entry in entries) + digests: tuple[str | None, str | None] = (None, None) + qc_entry = None + if state == ARTIFACTS_COMPUTED: + table = write_plane_histograms( + records, staged / OUTPUT_FILENAME, channel_ids=run.checked.channel_ids + ) + # Both digests (Spec ADR 0008 PQ6): the file's bytes (integrity, compared by RunInputs + # and reuse) and the content digest of the table as read back and checked (identity). + digests = (file_sha256(table), content_sha256(table)) + qc_entry = image_qc_entry(file_sha256(write_image_qc(rows.qc, staged / IMAGE_QC_FILENAME))) design_sha256 = None if design is not None: design_sha256 = file_sha256(write_experiment_design(design, staged / DESIGN_FILENAME)) @@ -66,13 +89,9 @@ def write_generation( dtype=pre.metadata.dtype.name, settings=settings, mapping=run.checked.review.mapping, - files=tuple( - replace(entry, plane_count=per_file[rel]) for rel, entry in sorted(rows.entries.items()) - ), - # Both digests (Spec ADR 0008 PQ6): the file's bytes (integrity, compared by RunInputs - # and reuse) and the content digest of the table as read back and checked (identity). - histogram_table_sha256=file_sha256(table), - histogram_table_content_sha256=content_sha256(table), + files=entries, + histogram_table_sha256=digests[0], + histogram_table_content_sha256=digests[1], versions=package_versions(), written_at=datetime.now(UTC).isoformat(timespec="seconds"), experiment_design_sha256=design_sha256, @@ -87,13 +106,34 @@ def write_generation( projection=_projection(pre), experiment_description=manifest_entry(described, masks, run.output, len(rows.entries)), lab_links=None if run.lab_links is None else run.lab_links.to_dict(), - image_qc=image_qc_entry(qc_sha256), + image_qc=qc_entry, + checks=tuple(compute_checks(checked_images(described.description, entries))), + statistics_artifacts=state, + z_handling=z_handling( + (entry.image_kind for entry in entries), (_projection(pre) or {}).get("method") + ), manifest_version=MANIFEST_VERSION, ) manifest = _kept_time(manifest, run.previous[0]) return file_sha256(write_manifest(manifest, staged / MANIFEST_FILENAME)) +def _counted(entries: Mapping[str, FileEntry], records: list) -> tuple[FileEntry, ...]: + """Return the entries sorted by path, each with exactly its recorded rows (VC3). + + A plane image has one row per time point; a volume none. Any other count is a defect of + the run, refused before anything is published (never repaired). + """ + per_file = Counter(record.source_relative_path for record in records) + for rel, entry in entries.items(): + if per_file[rel] != entry.statistics_rows: + raise ValueError( + f"{rel} has {per_file[rel]} histogram rows; its shape and roles give " + f"{entry.statistics_rows} ({entry.image_kind})" + ) + return tuple(entry for _, entry in sorted(entries.items())) + + def _projection(pre: Preflight) -> dict | None: """Return the manifest's ``projection`` entry for projected copies, else None.""" found = None if pre.conversion is None else pre.conversion.projection @@ -108,16 +148,20 @@ def _kept_time(manifest: RunManifest, earlier: RunManifest | None) -> RunManifes still records the rerun. """ if earlier is None or earlier.manifest_version != MANIFEST_VERSION: - return manifest # a version 5 manifest is read, never written again (owner decision 10) + return manifest # an older manifest is read, never written again (owner decision 10) same = replace(manifest, written_at=earlier.written_at) return same if same.to_dict() == earlier.to_dict() else manifest -def replaced_files(run: RunState, masks: dict | None) -> dict[str, str]: +def replaced_files( + run: RunState, masks: dict | None, entries: Iterable[FileEntry] = () +) -> dict[str, str]: """Return the earlier output files the run replaces or removes, and why. ``mask_relationships.json`` is removed when the masks changed since the earlier run - (or nothing usable records them), and in ``full`` mode, which recomputes every check. + (or nothing usable records them), and in ``full`` mode, which recomputes every check. The + histogram and QC tables are removed when every one of ``entries`` (the run's images) is a + volume: the run writes neither (Spec ADR 0010 VC1). """ names = [ OUTPUT_FILENAME, @@ -129,6 +173,12 @@ def replaced_files(run: RunState, masks: dict | None) -> dict[str, str]: if run.checked.design is not None: names.append(DESIGN_FILENAME) replaced = {name: "replaced" for name in names if name in run.found} + entries = list(entries) + if entries and all(entry.volume for entry in entries): + # VC1 (P99): a run of volumes only writes no table; an earlier one never stays beside it. + for name in (OUTPUT_FILENAME, IMAGE_QC_FILENAME): + if name in run.found: + replaced[name] = f"removed: {NO_STATISTICS}" if EARLIER_FILENAME in run.found: replaced[EARLIER_FILENAME] = ( f"removed: a schema version 5 table, replaced by {OUTPUT_FILENAME} (schema version 6)" diff --git a/src/morphobricks_preprocessing/run/pipeline.py b/src/morphobricks_preprocessing/run/pipeline.py index 45036811..4353eae8 100644 --- a/src/morphobricks_preprocessing/run/pipeline.py +++ b/src/morphobricks_preprocessing/run/pipeline.py @@ -31,10 +31,12 @@ build_report, ) from ..fingerprint import Fingerprint +from ..fov_identity import checked_images from ..intensity import IntensityReport, check_intensities from ..manifest import ( RunSettings, ) +from ..manifest_volume import MIXED, check_texts, compute_checks from ..mask_binding import ( changed_masks, content_changed_masks, @@ -214,6 +216,7 @@ def run_experiment( # noqa: PLR0913 intensity_settings=intensity_settings, histogram_settings=histogram_settings, verify_content=chosen.verify_content, + keep_z_stacks=chosen.keep_z_stacks, ) output.mkdir(parents=True, exist_ok=True) try: @@ -300,6 +303,22 @@ def _locked_run(given: GivenInputs, output: Path, options: RunOptions) -> RunRes return _publish(run, base, rows, settings) +def volume_warnings(run: RunState, rows: Rows) -> list[ValidationIssue]: + """Return the run report's ``W_AXIS_UNCALIBRATED`` and ``W_MIXED_PLANES_AND_VOLUMES``. + + The same records as the manifest's ``checks`` (Spec ADR 0010 VC5), as warnings: they never + block anything in preprocessing (VZ4, VZ8, VZ20). + """ + # The axis review's early warning names folders; the published one, canonical places. + run.checked.issues[:] = [i for i in run.checked.issues if i.code != MIXED] + images = checked_images(run.description.description, rows.entries.values()) + found = [] + for check in compute_checks(images): + message, fix = check_texts(check) + found.append(warning(check["code"], message, [i["path"] for i in check["images"]], fix)) + return found + + def _not_expected( options: RunOptions, inputs: object, @@ -404,13 +423,19 @@ def _publish(run: RunState, base: RunOutcome, rows: Rows, settings: RunSettings) Every mask likewise (issue #160): ``mask_changed_during_run``. """ output, pre, design = run.output, run.pre, run.checked.design + run.checked.issues.extend(volume_warnings(run, rows)) # recorded in checks too (ADR 0010) records = sorted(rows.records, key=_row_order) # From the rows in memory: no image is read again. intensity = check_intensities(records, run.inputs.intensity_settings) identity = check_channel_identity(intensity.summaries) # its default limits, recorded masks = None if pre.masks is None else mask_manifest(pre.masks, pre.discovery.root) - outcome = replace(outcome_of(rows, base), replaced=replaced_files(run, masks)) - removes = [name for name in REMOVABLE if name in outcome.replaced] + entries = list(rows.entries.values()) + outcome = replace(outcome_of(rows, base), replaced=replaced_files(run, masks, entries)) + removes = [ + name + for name, why in outcome.replaced.items() + if name in REMOVABLE and why.startswith("removed") + ] final_check = _final_content_check(run, rows, settings) try: with staged_generation(output, removes, final_check) as staged: @@ -451,6 +476,7 @@ def _publish(run: RunState, base: RunOutcome, rows: Rows, settings: RunSettings) replaced=tuple(sorted(outcome.replaced)), input_changes=run.inputs.changes, report_written=True, + volumes=tuple(sorted(rel for rel, entry in rows.entries.items() if entry.volume)), **counts(rows), ) diff --git a/src/morphobricks_preprocessing/run/recorded.py b/src/morphobricks_preprocessing/run/recorded.py index 42908da4..cf735653 100644 --- a/src/morphobricks_preprocessing/run/recorded.py +++ b/src/morphobricks_preprocessing/run/recorded.py @@ -68,6 +68,7 @@ class GivenInputs: intensity_settings: IntensityCheckSettings | None = None histogram_settings: HistogramSettings | None = None verify_content: bool | None = None + keep_z_stacks: bool | None = None @dataclass(frozen=True) @@ -133,6 +134,9 @@ class ResolvedInputs: bins_recorded_for: str | None = None verify_content: bool = False changes: tuple[InputChange, ...] = field(default=()) + keep_z_stacks: bool = False + """The user's choice to keep Z-stacks as volumes: given, else as recorded (``z_handling`` + ``"kept"``), else False (Spec ADR 0010 VZ32).""" def usable(manifest: RunManifest | None) -> RunManifest | None: @@ -188,6 +192,7 @@ def resolve_inputs(given: GivenInputs, previous: RunManifest | None) -> Resolved histogram_settings=given.histogram_settings or settings.histogram, bins_recorded_for=before.dtype if given.bin_count is None else None, verify_content=_first(given.verify_content, settings.verify_content), + keep_z_stacks=_first(given.keep_z_stacks, before.z_handling == "kept"), ) return _with_changes(resolved, given, before) @@ -325,6 +330,7 @@ def _defaults(given: GivenInputs) -> ResolvedInputs: # Content hashing is on unless the caller opted out (#159); an earlier run's choice is # kept by _with_changes, so an existing output is not silently recomputed. verify_content=True if given.verify_content is None else bool(given.verify_content), + keep_z_stacks=bool(given.keep_z_stacks), ) diff --git a/src/morphobricks_preprocessing/run/result.py b/src/morphobricks_preprocessing/run/result.py index e27b788d..30d5b8e9 100644 --- a/src/morphobricks_preprocessing/run/result.py +++ b/src/morphobricks_preprocessing/run/result.py @@ -102,6 +102,10 @@ class RunResult: input_changes: tuple[InputChange, ...] = () report_written: bool = False workers: int = 1 + volumes: tuple[str, ...] = () + """The images described as volumes (confirmed Z > 1), sorted: histograms, normalization and + QC metrics are not computed for them (Spec ADR 0010 VZ2); none of their rows is in the table, + and with only volumes no table is written.""" @property def ok(self) -> bool: diff --git a/src/morphobricks_preprocessing/run/steps.py b/src/morphobricks_preprocessing/run/steps.py index e5667a47..81ac5891 100644 --- a/src/morphobricks_preprocessing/run/steps.py +++ b/src/morphobricks_preprocessing/run/steps.py @@ -15,7 +15,7 @@ from morphobricks_normalization.records import PlaneRecord from ..axes import AxisReview -from ..axis_review import review_axes +from ..axis_review import review_axes, volume_slices from ..content_memo import ContentMemo from ..dataset import check_dataset from ..design import DesignTable, design_issues, reconcile_design @@ -27,7 +27,7 @@ from ..mask_checks import mask_issues from ..planes import check_planes from ..source_content import with_content -from ..validation import ValidationIssue, error, has_errors, plural +from ..validation import ValidationIssue, agree, error, has_errors, plural from .entries import Comparison, compare_with_previous, file_entries from .modes import FULL from .phases import CONTENTS @@ -128,6 +128,7 @@ def header_checks( *dataset.issues, *(mask_issues(pre.masks, pre.metadata, review) if pre.masks is not None else ()), *(pre.conversion.issues if pre.conversion is not None else ()), + *z_choice_issues(volume_slices(pre.metadata.files, review.file_mappings), inputs), ] if design is not None: issues = [issue for issue in issues if issue.code not in GLOBAL_CHANNEL_CODES] @@ -145,6 +146,32 @@ def header_checks( return Checked(review, type_review, design, issues, bins) +def z_choice_issues(volumes: Mapping[str, int], inputs: ResolvedInputs) -> list[ValidationIssue]: + """Return ``z_stacks_not_chosen`` when volumes are run without the choice to keep them. + + Keeping Z-stacks as volumes or projecting them is the user's explicit, recorded choice with + no default (Spec ADR 0010 VZ1; owner answer of 2 December 2026, VZ32): a run with volumes + needs ``RunMode(keep_z_stacks=True)`` (CLI ``--keep-z-stacks``; the notebook's *Keep the + 3-D stacks*), given or recorded by the earlier run. Nothing is read before. + """ + if not volumes or inputs.keep_z_stacks: + return [] + listed = "; ".join(f"{path}: {n} Z planes" for path, n in list(volumes.items())[:5]) + more = f"; and {len(volumes) - 5} more" if len(volumes) > 5 else "" + return [ + error( + "z_stacks_not_chosen", + f"{plural(len(volumes), 'image')} {agree(volumes, 'is a Z-stack', 'are Z-stacks')} " + f"under the confirmed roles ({listed}{more}), and no choice was made for them: " + "keeping them as volumes and projecting them are both explicit choices.", + list(volumes), + "Keep them as volumes (the notebook's Keep the 3-D stacks; the CLI's " + "--keep-z-stacks; RunMode(keep_z_stacks=True)), or make projected copies first " + "(convert --project max|mean|sum) and run on the copies.", + ) + ] + + def _bins(pre: Preflight, inputs: ResolvedInputs, issues: list[ValidationIssue]) -> int | None: """Return the bins per plane, adding ``invalid_bin_count`` to ``issues`` when refused. @@ -310,10 +337,12 @@ def compute_rows( narrow.extend(entry for entry in previous[0].narrow_ranges if entry.relative_path == rel) job = FileJob(pre, review, settings, entries, output, mode == FULL) changed = changed_during_check(job) + # A volume has no histogram or QC row (Spec ADR 0010 VZ2): its pixels are not read here. + volumes = {rel for rel, entry in entries.items() if entry.volume} to_read = [ rel for rel in sorted([*found.new, *found.changed, *(found.unchanged if reason else ())]) - if rel not in changed and rel not in unhashed + if rel not in changed and rel not in unhashed and rel not in volumes ] kept = set(found.unchanged) if not reason else set() new = new_rows(job, to_read, kept, reporting.reading, workers) diff --git a/src/morphobricks_preprocessing/run_inputs.py b/src/morphobricks_preprocessing/run_inputs.py index 70a9ed4b..5d40a319 100644 --- a/src/morphobricks_preprocessing/run_inputs.py +++ b/src/morphobricks_preprocessing/run_inputs.py @@ -43,7 +43,6 @@ from dataclasses import dataclass, field from pathlib import Path -import numpy as np from morphobricks_normalization.records import PlaneRecord from morphobricks_normalization.table_format import OUTPUT_FILENAME @@ -65,9 +64,6 @@ from .mask_record import shared_mask_text from .masks import FOLDER from .open_checks import RELATIVE, Checking, counted, quiet -from .plane_channels import read_xyc_plane -from .planes import DEFAULT_MEMORY_LIMIT -from .recorded_sizes import RecordedSize from .required_description import FIX, is_published, required_message from .run.generation import published_path, read_stable from .run_folder_errors import ( @@ -87,8 +83,10 @@ read_records, refuse_moved, refuse_stale_images, + refuse_stale_statistics, verifying, ) +from .run_inputs_consumer import ConsumerInputs from .run_inputs_error import ( DescriptionRequiredError, ZarrNotInstalledError, @@ -97,15 +95,18 @@ from .run_inputs_groups import GroupInputs from .run_inputs_image import LazyImage as LazyImage # re-exported (moved) from .run_inputs_mask import MaskInputs, given_masks_root +from .run_inputs_planes import PlaneInputs from .run_inputs_projection import ProjectionInputs from .run_inputs_resolve import ResolvingInputs from .run_inputs_semantic import ( SemanticInputs, check_channel_coverage, check_description, + check_recorded_checks, check_section_digests, with_identity, ) +from .run_inputs_statistics import StatisticsInputs, check_rows from .run_inputs_stopped import stopped_run_refusal from .run_inputs_text import ( _ZARR_MISSING, @@ -113,7 +114,7 @@ _without_axes_text, ) from .run_inputs_tissue import TissueMaskInputs -from .run_inputs_window import WindowInputs, _check_planes, _coordinate, _mapping +from .run_inputs_window import WindowInputs from .source_content import ContentMemo, content_changed from .unrecorded import UnrecordedFiles, unrecorded_files from .zarr_input import NgffError, ZarrUnavailableError @@ -156,7 +157,8 @@ class Fov: relative_path The image, relative to the experiment root. plane_ids - The ``plane_id`` of each of its rows in the table, in table order. + The ``plane_id`` of each of its rows in the table, in table order: its statistics rows + only, empty for a volume (Spec ADR 0010 VC2). Never an acquisition size. axes, roles The image's axes and the role of each (``None`` for a length-1 axis without one). axes_from @@ -168,7 +170,9 @@ class Fov: significant_bits Significant bits from the metadata, or None. z_count, t_count, c_count - Depth slices, time points and channels. + Depth slices, time points and channels: the sizes of the confirmed ``Z``, ``T`` and + ``C`` roles (1 when absent), as the manifest records them, never read from statistics + rows (Spec ADR 0010 VC2). The image is a volume when ``z_count`` > 1. repeat_group, condition_id, technical_repeat_id The canonical repeat, condition and technical repeat IDs of the position, added beside the unchanged ``key`` (experiment-v1 §3.4), from the run's published @@ -201,9 +205,17 @@ class Fov: channel_ids: tuple[str, ...] | None = None image_type: str | None = None + @property + def volume(self) -> bool: + """True for a volume: the confirmed ``Z`` role has more than one slice (ADR 0010).""" + return self.z_count > 1 + @dataclass(frozen=True) class RunInputs( + PlaneInputs, + StatisticsInputs, + ConsumerInputs, SemanticInputs, GroupInputs, ProjectionInputs, @@ -227,8 +239,9 @@ class RunInputs( Where the masks folder's masks are read from, or None. manifest The run manifest. - records - The table's rows, as read when opened. + _records + The table's rows, as read when opened; internal (Spec ADR 0010 VC6): a consumer reads + them through :meth:`histograms` only, which refuses volumes. manifest_sha256 The SHA-256 of the exact ``run_manifest.json`` bytes ``manifest`` was parsed from, taken when opened (never the file's later): a brick names the run it read by it and refuses a @@ -239,7 +252,7 @@ class RunInputs( experiment_root: Path masks_root: Path | None manifest: RunManifest - records: tuple[PlaneRecord, ...] + _records: tuple[PlaneRecord, ...] manifest_sha256: str | None = field(default=None, compare=False) @classmethod @@ -304,8 +317,21 @@ def _read( """Read the manifest and the files it names, checking their SHA-256.""" manifest, digest = _manifest(output) check_table_version(output, manifest) # a version 5 run: refused with the fix - table = published_path(output, OUTPUT_FILENAME, manifest.histogram_table_sha256) - check_sha(table, manifest.histogram_table_sha256) + if manifest.manifest_version != MANIFEST_VERSION: # version 6: no acquisition sizes + raise run_folder_version( + output / MANIFEST_FILENAME, + "run manifest", + manifest.manifest_version, + MANIFEST_VERSION, + ) + records: tuple[PlaneRecord, ...] = () + if manifest.statistics_computed: # a run of volumes only has no table (ADR 0010 VC1) + table = published_path(output, OUTPUT_FILENAME, manifest.histogram_table_sha256) + check_sha(table, manifest.histogram_table_sha256) + records = read_records(table, manifest) + check_rows(records, manifest) + else: + refuse_stale_statistics(output) if manifest.experiment_design_sha256 is not None: design = published_path(output, DESIGN_FILENAME, manifest.experiment_design_sha256) check_sha(design, manifest.experiment_design_sha256) @@ -313,6 +339,7 @@ def _read( description = check_description(output, manifest) # A_DRAFT_REFUSED, or changed check_section_digests(manifest, description) # the digests a consumer keys on (#490) check_channel_coverage(manifest, description) # recorded as the description's (#490) + check_recorded_checks(manifest, description) # derived from the entries (ADR 0010 VC5) root = Path(experiment_root or manifest.experiment_root).resolve() check_conversion(root, manifest) # A masks folder given is used as given, never replaced by the recorded one (#487). @@ -330,14 +357,14 @@ def _read( experiment_root=root, masks_root=None if masks is None else Path(masks).resolve(), manifest=manifest, - records=read_records(table, manifest), + _records=records, manifest_sha256=digest, ) def fovs(self) -> tuple[Fov, ...]: """Return every position of the run, sorted by image path.""" rows: dict[str, list[PlaneRecord]] = {} - for record in self.records: + for record in self._records: rows.setdefault(record.source_relative_path, []).append(record) described = self.description() return tuple( @@ -349,66 +376,6 @@ def files(self) -> tuple[FileEntry, ...]: """The manifest entry of every image, sorted by path.""" return tuple(sorted(self.manifest.files, key=lambda e: e.relative_path)) - def pixel_sizes(self, fov: Fov | str) -> dict[str, RecordedSize]: - """Return the recorded size of one step along X, Y, Z and T, by role. - - Each has its value, unit and source: ``"header"`` (the image's metadata), - ``"stated"`` (``calibration.csv``) or ``"pixels"`` (stated as deliberately - uncalibrated, no value). A size nothing gives has no value and no source - (uncalibrated). Nothing is guessed. - """ - return {size.role: size for size in self._entry(fov).pixel_sizes} - - def read_plane( - self, fov: Fov | str, z: int = 0, t: int = 0, *, memory_limit: int = DEFAULT_MEMORY_LIMIT - ) -> np.ndarray: - """Read one plane, every channel, as a ``(C, Y, X)`` array of the stored values. - - Raises - ------ - TypeError - If ``z`` or ``t`` is not a whole number (a ``plane_id`` is not a coordinate). - RunInputsError - If the image changed since the run. - IndexError - If ``z`` or ``t`` is outside the image. - PlaneMemoryError - If reading the plane whole, every channel, needs more working memory than - ``memory_limit``: the decoded page, its encoded bytes and the ``(C, Y, X)`` - result (for OME-Zarr, also the plane zarr returns). Nothing is decoded then. - """ - z, t = (_coordinate(v, k, "read_plane(fov, z, t)") for k, v in (("z", z), ("t", t))) - entry = self._checked(fov) - _check_planes(entry.relative_path, self._fov(entry), z, t) - mapping = _mapping(entry) - path = self.experiment_root / entry.relative_path - coordinates = {} - for role, index in (("Z", z), ("T", t)): - if mapping.index_of(role) is None: - if index != 0: - raise IndexError(f"{entry.relative_path} has no {role} {index}") - continue - coordinates[role.lower()] = index - has_c = mapping.index_of("C") is not None - channels = self._fov(entry).c_count if has_c else 1 - # One (C, Y, X) array filled from each page decoded once, its whole memory checked - # before any pixel is read (issue #344). - return read_xyc_plane( - path, mapping, channel_count=channels, memory_limit=memory_limit, **coordinates - ) - - def read_image(self, fov: Fov | str) -> LazyImage: - """Return the image as a lazy ``(T, Z, C, Y, X)`` array: planes are read when indexed.""" - entry = self._checked(fov) - first = self.read_plane(fov) - found = self._fov(entry) - shape = (found.t_count, found.z_count, *first.shape) - return LazyImage(self, entry.relative_path, shape, first.dtype) - - def histograms(self) -> tuple[PlaneRecord, ...]: - """Return the table's rows, as read when the run was opened.""" - return self.records - def _check_files( self, checking: Checking = quiet, memo: ContentMemo | None = None, verify: object = None ) -> None: @@ -454,7 +421,7 @@ def _check_files( def _fov(self, entry: FileEntry) -> Fov: """Describe one position from its entry and its rows of the snapshot.""" - rows = [r for r in self.records if r.source_relative_path == entry.relative_path] + rows = [r for r in self._records if r.source_relative_path == entry.relative_path] return _fov(entry, rows, self.manifest) def _entry(self, fov: Fov | str) -> FileEntry: @@ -562,12 +529,13 @@ def _fov( ) -> Fov: """Describe one position from its manifest entry and its table rows. + The sizes are the entry's (``z_count``, ``t_count``, ``c_count``, from its shape and + confirmed roles), never the rows' (Spec ADR 0010 VC2); the rows give ``plane_ids`` only. With the published ``description`` the canonical identity is added beside the key; the unit's channels must be the image's channels (nothing is guessed when they are not). """ - zs = {r.z for r in rows} or {0} - ts = {r.t for r in rows} or {0} - channels = rows[0].channel_count if rows else len(entry.channel_names) or 1 + if None in (entry.z_count, entry.t_count, entry.c_count): # only a version 7 entry is used + raise RunInputsError(f"The run records no acquisition sizes for {entry.relative_path}.") if entry.position_id is None: # never an empty name in the key (round-2 audit A-m5) raise RunInputsError(f"The run records no position_id for {entry.relative_path}.") fov = Fov( @@ -580,9 +548,9 @@ def _fov( channel_names=entry.channel_names, dtype=manifest.dtype, significant_bits=entry.significant_bits, - z_count=max(zs) + 1, - t_count=max(ts) + 1, - c_count=channels, + z_count=entry.z_count, + t_count=entry.t_count, + c_count=entry.c_count, ) # Without one, only the shape (internal reads); fovs() always gives the identity. return fov if description is None else with_identity(fov, entry, description) diff --git a/src/morphobricks_preprocessing/run_inputs_checks.py b/src/morphobricks_preprocessing/run_inputs_checks.py index a1835fab..55c85df2 100644 --- a/src/morphobricks_preprocessing/run_inputs_checks.py +++ b/src/morphobricks_preprocessing/run_inputs_checks.py @@ -23,6 +23,7 @@ from morphobricks_normalization.records import PlaneRecord from morphobricks_normalization.table_format import ( EARLIER_FILENAME, + OUTPUT_FILENAME, SCHEMA_VERSION, PlaneHistogramsError, ) @@ -30,6 +31,7 @@ from .content_memo import ContentMemo from .conversion_check import conversion_problem from .conversion_record import RECORD_FILENAME, RECORD_VERSION +from .image_qc_record import IMAGE_QC_FILENAME from .manifest import FileEntry, RunManifest, file_sha256 from .run_folder_errors import ( run_folder_content_not_recorded, @@ -180,3 +182,14 @@ def read_records(table: Path, manifest: RunManifest) -> tuple[PlaneRecord, ...]: "image. Run preprocessing again." ) return tuple(records) + + +def refuse_stale_statistics(output: Path) -> None: + """Refuse a run of volumes only beside a histogram or QC table (Spec ADR 0010 VC1, P99). + + Such a run writes neither: a table there is of another generation, never read as this + run's (``RUN_FOLDER_STALE``, reason ``added``). + """ + found = [name for name in (OUTPUT_FILENAME, IMAGE_QC_FILENAME) if (output / name).exists()] + if found: + raise run_folder_stale(found, "added") diff --git a/src/morphobricks_preprocessing/run_inputs_consumer.py b/src/morphobricks_preprocessing/run_inputs_consumer.py new file mode 100644 index 00000000..43405c15 --- /dev/null +++ b/src/morphobricks_preprocessing/run_inputs_consumer.py @@ -0,0 +1,159 @@ +"""A consumer's declared Z and calibration rules, checked against a run (Spec ADR 0009, ADR 0010). + +The minimal part of Spec ADR 0009's consumer manifest that the volume hand-off needs: the rules +``volume_support`` (``none``, ``planes`` or ``volumes``; O9, ADR 0010 VZ13), +``mixed_volume_support`` and ``requires_calibration`` (``x``, ``y``, ``z``; O10, VZ14), applied +to the run's recorded sizes and calibration (``Fov.z_count``, the version 7 ``pixel_sizes``). +The discovery of a consumer's ``morphobricks_consumer.toml``, its pinned check at ``describe`` +and the run, and the ``consumer_check`` record are not implemented here: a consumer passes its +declared rules, as its own runtime guard (ADR 0009 "The consumer's own runtime guards"). + +- :func:`capabilities_for` maps a ``volume_support`` word to the resolver's boolean + ``Capabilities.volume_support`` (CM5 routing): ``volumes`` is True, ``none`` and ``planes`` + False (so a whole ``volume`` request of a ``planes`` consumer is ``A_VOLUME_NOT_SUPPORTED``). +- :func:`dimension_refusal` returns the one ``R_CONSUMER_DIMENSIONS_NOT_ALLOWED`` listing every + offending image (FOV key, path) with every kind found in it (``volume``, ``calibration``), + then the run-level kind ``mixed_volumes`` with both groups in full and their counts, or None. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping, Sequence + +from .manifest_volume import AXIS_UNCALIBRATED +from .run_inputs_error import RunInputsError +from .run_inputs_request import Capabilities + +NONE = "none" +PLANES = "planes" +VOLUMES = "volumes" +VOLUME_SUPPORT = (NONE, PLANES, VOLUMES) +AXES = ("x", "y", "z") +CODE = "R_CONSUMER_DIMENSIONS_NOT_ALLOWED" + + +class ConsumerDimensionsNotAllowedError(RunInputsError): + """``R_CONSUMER_DIMENSIONS_NOT_ALLOWED``: the run breaks a consumer's declared rules.""" + + code = CODE + + +def check_rules( + volume_support: object, mixed_volume_support: object, requires_calibration: object +) -> tuple[str, bool, tuple[str, ...]]: + """Refuse malformed rules (``ValueError``), as ADR 0009's file rules would. + + ``volume_support`` is one of ``none``, ``planes``, ``volumes`` (a boolean is refused, never + mapped); ``mixed_volume_support`` a ``bool``, not ``True`` with ``none`` (a self-withdrawn + permission); ``requires_calibration`` a tuple or list of distinct ``x``, ``y``, ``z``. + """ + if not isinstance(volume_support, str) or volume_support not in VOLUME_SUPPORT: + raise ValueError(f"volume_support must be one of {VOLUME_SUPPORT}, not {volume_support!r}") + if not isinstance(mixed_volume_support, bool): + raise ValueError(f"mixed_volume_support must be a bool, not {mixed_volume_support!r}") + if mixed_volume_support and volume_support == NONE: + raise ValueError("mixed_volume_support = true with volume_support = 'none' admits no mix") + axes = tuple(requires_calibration) if isinstance(requires_calibration, list | tuple) else None + if axes is None or any(a not in AXES for a in axes) or len(set(axes)) != len(axes): + raise ValueError( + f"requires_calibration must list distinct x, y, z, not {requires_calibration!r}" + ) + return volume_support, mixed_volume_support, axes + + +def capabilities_for(volume_support: str, **others: bool) -> Capabilities: + """Return the resolver's ``Capabilities`` of a consumer declaring ``volume_support`` (CM5).""" + check_rules(volume_support, False, ()) + return Capabilities(volume_support=volume_support == VOLUMES, **others) + + +def dimension_refusal( + consumer: str, + images: Sequence[tuple[tuple[str, ...], str, int, Mapping[str, object]]], + rules: tuple[str, bool, tuple[str, ...]], +) -> ConsumerDimensionsNotAllowedError | None: + """Return the one refusal of a run for a consumer's declared rules, or None. + + Parameters + ---------- + consumer + The consumer's ID, named in the message. + images + Each included image as ``(fov_key, path, z_count, pixel_sizes)`` with the sizes as + ``RunInputs.pixel_sizes`` gives them (``source`` and ``reason``). + rules + :func:`check_rules`' answer. + """ + volume_support, mixed, axes = rules + ordered = sorted(images, key=lambda i: (tuple(i[0]), i[1])) + lines = [] + for key, path, z_count, sizes in ordered: + kinds = [] + if volume_support == NONE and z_count > 1: + kinds.append(f"volume: Z = {z_count}, consumer allows Z = 1") + for axis in axes: + size = sizes.get(axis.upper()) + if getattr(size, "reason", None) == AXIS_UNCALIBRATED: + kinds.append( + f"calibration: {axis} step {size.source} ({AXIS_UNCALIBRATED}, axis " + f"{axis}), consumer requires {', '.join(axes)}" + ) + if kinds: + lines.append(f" - {tuple(key)!r} {path}: {'; '.join(kinds)}") + lines.extend(_mixed(ordered, volume_support, mixed)) + if not lines: + return None + return ConsumerDimensionsNotAllowedError( + f"The run breaks the declared rules of the consumer {consumer!r}:\n" + + "\n".join(lines) + + "\nNothing is dropped, sliced, projected or converted. Choose another consumer, " + "project the stacks, split the experiment, or state the missing steps in " + f"calibration.csv and run again ({CODE})." + ) + + +def _mixed(images: Iterable[tuple], volume_support: str, mixed: bool) -> list[str]: + """Return the ``mixed_volumes`` lines: both groups in full, then the counts (ADR 0009 B7).""" + images = list(images) + volumes = [i for i in images if i[2] > 1] + planes = [i for i in images if i[2] <= 1] + if mixed or volume_support == NONE or not volumes or not planes: + return [] # with none, each volume is refused as kind volume, the mix not again + return [ + " mixed_volumes: the run holds plane images and volumes, and the consumer takes one " + "kind per run; volumes:", + *(f" - {tuple(k)!r} {p}: Z = {z}" for k, p, z, _ in volumes), + " plane images:", + *(f" - {tuple(k)!r} {p}" for k, p, _, _ in planes), + f" {len(volumes)} volume(s), {len(planes)} plane image(s)", + ] + + +class ConsumerInputs: + """``RunInputs.check_consumer``: a consumer's declared rules against this run.""" + + def check_consumer( + self, + consumer: str, + *, + volume_support: str, + mixed_volume_support: bool, + requires_calibration: Sequence[str], + ) -> None: + """Refuse this run for a consumer whose declared rules it breaks; None when it passes. + + The consumer's own runtime guard (Spec ADR 0009, every route): call it before any + read, with the rules of its consumer manifest. + + Raises + ------ + ValueError + For malformed rules (:func:`check_rules`). + ConsumerDimensionsNotAllowedError + ``R_CONSUMER_DIMENSIONS_NOT_ALLOWED``, listing every offending image and kind. + """ + rules = check_rules(volume_support, mixed_volume_support, requires_calibration) + images = [(f.key, f.relative_path, f.z_count, self.pixel_sizes(f)) for f in self.fovs()] + refusal = dimension_refusal(consumer, images, rules) + if refusal is not None: + raise refusal diff --git a/src/morphobricks_preprocessing/run_inputs_mask.py b/src/morphobricks_preprocessing/run_inputs_mask.py index 78b01033..08555709 100644 --- a/src/morphobricks_preprocessing/run_inputs_mask.py +++ b/src/morphobricks_preprocessing/run_inputs_mask.py @@ -28,11 +28,13 @@ from .masks.objects import ObjectsReadPlan, objects_read_plan from .masks.read import read_mask_plane from .masks.window import mask_window_plan, read_mask_window -from .planes import DEFAULT_MEMORY_LIMIT +from .plane_errors import PlaneMemoryError +from .planes import DEFAULT_MEMORY_LIMIT, format_bytes from .run_folder_errors import run_folder_stale from .run_inputs_error import ( MasksFolderNotFoundError, MasksFolderUnreadableError, + RunInputsError, ) from .run_inputs_request import ( BINARY, @@ -126,11 +128,13 @@ def read_objects(self, selection: FovSelection, mask_id: str, t: int, z: int) -> MaskContradictsRepresentationError ``R_MASK_CONTRADICTS_REPRESENTATION`` from ``label_binary``. TypeError, IndexError, RunInputsError, MaskUncheckedError - As :meth:`read_mask`. + As :meth:`read_mask`. ``RunInputsError`` also when the selection is not of an image + of this run, or ``(t, z)`` is not one of ``selection.planes`` (Spec ADR 0010 VC8). """ call = "read_objects(selection, mask_id, t, z)" z, t = (_coordinate(v, k, call) for k, v in (("z", z), ("t", t))) use = _objects_use(selection, mask_id) + self._in_selection(selection, t, z) # Spec ADR 0010 VC8: before any pixel is read mask, folder = self._recorded_mask(selection.relative_path, use.source_type, z, t) pixels = read_mask_plane(mask, folder, self.experiment_root, z=z, t=t) if use.conversion == CONNECTED_COMPONENTS: @@ -138,6 +142,85 @@ def read_objects(self, selection: FovSelection, mask_id: str, t: int, z: int) -> check_labels(pixels, f"the mask {mask.path}") return pixels.astype(np.int32) + def read_mask_volume( + self, + fov: Fov | str, + mask_type: str, + *, + t: int | None = None, + memory_limit: int = DEFAULT_MEMORY_LIMIT, + ) -> np.ndarray: + """Read a mask's whole Z at one time point as a ``(Z, Y, X)`` array (Spec ADR 0010 VC9). + + ``Z`` is the image's ``z_count`` (1 for a plane image). The mask is found by the + recorded pairing and checked as :meth:`read_mask` checks it; its labels are checked + over the whole volume (:func:`.masks.check_labels`) and kept as stored, in the stored + pixel type: never relabelled, and a ``binary`` mask is never labelled here (BM5). + :meth:`read_mask` keeps refusing an omitted ``z`` on a mask with several Z planes; this + is the one whole-volume mask read, for a consumer whose ``volume_support`` is + ``volumes``. + + Parameters + ---------- + fov + The position, as a :class:`.run_inputs.Fov` or its image path. + mask_type + The recorded mask type. + t + The time point: required when the mask has more than one, else 0 or None. + memory_limit + Largest working memory allowed, in bytes, checked before any pixel is read. + + Raises + ------ + TypeError + If ``t`` is neither None nor a whole number. + IndexError + If ``t`` is outside the image. + RunInputsError + As :meth:`read_mask`; also an omitted ``t`` on a mask with several time points. + PlaneMemoryError + If the volume and one stored plane need more than ``memory_limit``. + ValueError + For a label outside 0 to the int32 limit. + """ + t = None if t is None else _coordinate(t, "t", "read_mask_volume(fov, mask_type, t=)") + mask, folder = self._recorded_mask(fov, mask_type, None, t) + depth, times = mask.planes["Z"], mask.planes["T"] + if t is None and times > 1: + raise RunInputsError( + f"The mask {mask.path} has {times} time points; say which one to read (t=)." + ) + height, width = _yx(mask.axes, mask.shape) + need = (depth + 1) * height * width * np.dtype(mask.dtype).itemsize + if need > memory_limit: + raise PlaneMemoryError( + f"Reading the mask {mask.path} whole ({depth} Z planes) needs " + f"{format_bytes(need)}, more than the limit of {format_bytes(memory_limit)}. " + "Raise memory_limit, or read it plane by plane with read_mask(fov, type, z=, t=)." + ) + planes = [ + read_mask_plane(mask, folder, self.experiment_root, z=z if depth > 1 else None, t=t) + for z in range(depth) + ] + volume = np.stack(planes) + check_labels(volume, f"the mask {mask.path}") + return volume + + def _in_selection(self, selection: FovSelection, t: int, z: int) -> None: + """Refuse a coordinate outside a resolved selection, or a selection of another run.""" + if self.manifest.file(selection.relative_path) is None: + raise RunInputsError(f"{selection.relative_path} is not an image of this run.") + allowed = [(p.t, plane) for p in selection.planes for plane in p.z] + if (t, z) not in allowed: + shown = ", ".join(f"(t={a}, z={b})" for a, b in allowed[:10]) + more = f" and {len(allowed) - 10} more" if len(allowed) > 10 else "" + raise RunInputsError( + f"(t={t}, z={z}) is not a plane of the selection of {selection.relative_path}; " + f"its planes are {shown}{more}. A read made for a resolved request stays inside " + "it (Spec ADR 0010 VC8)." + ) + def objects_read_plan(self, selection: FovSelection, mask_id: str) -> ObjectsReadPlan: """Return what one :meth:`read_objects` plane costs, from the mask's header only. diff --git a/src/morphobricks_preprocessing/run_inputs_planes.py b/src/morphobricks_preprocessing/run_inputs_planes.py new file mode 100644 index 00000000..692da6d0 --- /dev/null +++ b/src/morphobricks_preprocessing/run_inputs_planes.py @@ -0,0 +1,121 @@ +"""The plane reads of :class:`.run_inputs.RunInputs`: ``read_plane``, ``read_image``, sizes. + +Moved from :mod:`.run_inputs`. No plane of a volume is chosen for the caller (Spec ADR 0010 +B2): ``read_plane`` has no default ``z`` on a volume and ``read_image`` reads a volume whole +only with ``volume=True``. ``pixel_sizes`` gives the version 7 calibration record (VC4). +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import numpy as np + +from .manifest import FileEntry +from .manifest_volume import size_view +from .plane_channels import read_xyc_plane +from .planes import DEFAULT_MEMORY_LIMIT +from .recorded_sizes import RecordedSize +from .run_inputs_error import RunInputsError +from .run_inputs_image import LazyImage +from .run_inputs_text import _no_z_text, _whole_volume_text +from .run_inputs_window import _check_planes, _coordinate, _mapping + +if TYPE_CHECKING: + from .run_inputs import Fov + + +class PlaneInputs: + """The plane reads of ``RunInputs``; they use its ``_entry``, ``_checked`` and ``_fov``.""" + + def pixel_sizes(self, fov: Fov | str) -> dict[str, RecordedSize]: + """Return the recorded size of one step along X, Y, Z and T, by role (ADR 0010 VC4). + + Each has its value, unit and source: ``"header"`` (the image's metadata), + ``"stated"`` (``calibration.csv``), ``"pixels"`` (stated as deliberately + uncalibrated, no value) or ``"unknown"`` (nothing gives a size: no value, no unit), and + its ``reason``: ``"W_AXIS_UNCALIBRATED"`` for an ``X`` or ``Y`` without a length, and + for a ``Z`` without one on a volume; None otherwise (always for ``T``, and for the + ``Z`` of a plane image). The one place consumers read calibration from. Nothing is + guessed: an unknown step is never 0, 1 or another axis's size. + """ + entry = self._entry(fov) + return size_view(entry.pixel_sizes, entry.volume) + + def read_plane( + self, + fov: Fov | str, + z: int | None = None, + t: int = 0, + *, + memory_limit: int = DEFAULT_MEMORY_LIMIT, + ) -> np.ndarray: + """Read one plane, every channel, as a ``(C, Y, X)`` array of the stored values. + + ``z`` has no default index on a volume (Spec ADR 0010 B2): a call without it on an + image whose ``z_count`` > 1 is refused, never read as slice 0. On a plane image a + missing ``z`` reads ``z = 0``. + + Raises + ------ + TypeError + If ``z`` or ``t`` is not a whole number (a ``plane_id`` is not a coordinate). + RunInputsError + If the image changed since the run, or ``z`` is omitted on a volume. + IndexError + If ``z`` or ``t`` is outside the image. + PlaneMemoryError + If reading the plane whole, every channel, needs more working memory than + ``memory_limit``: the decoded page, its encoded bytes and the ``(C, Y, X)`` + result (for OME-Zarr, also the plane zarr returns). Nothing is decoded then. + """ + if z is None: + z = self._default_z(self._entry(fov)) + z, t = (_coordinate(v, k, "read_plane(fov, z, t)") for k, v in (("z", z), ("t", t))) + entry = self._checked(fov) + _check_planes(entry.relative_path, self._fov(entry), z, t) + mapping = _mapping(entry) + path = self.experiment_root / entry.relative_path + coordinates = {} + for role, index in (("Z", z), ("T", t)): + if mapping.index_of(role) is None: + if index != 0: + raise IndexError(f"{entry.relative_path} has no {role} {index}") + continue + coordinates[role.lower()] = index + has_c = mapping.index_of("C") is not None + channels = self._fov(entry).c_count if has_c else 1 + # One (C, Y, X) array filled from each page decoded once, its whole memory checked + # before any pixel is read (issue #344). + return read_xyc_plane( + path, mapping, channel_count=channels, memory_limit=memory_limit, **coordinates + ) + + def read_image(self, fov: Fov | str, *, volume: bool = False) -> LazyImage: + """Return the image as a lazy ``(T, Z, C, Y, X)`` array: planes are read when indexed. + + On a volume it is refused unless ``volume=True``, which states that the caller reads a + whole volume (Spec ADR 0010 B2): a consumer whose ``volume_support`` is not + ``volumes`` never passes it. Its first plane is read with an explicit ``z = 0``. + + Raises + ------ + RunInputsError + For a volume without ``volume=True``, naming the image, its ``z_count`` and the fix. + """ + if not isinstance(volume, bool): + raise TypeError(f"volume must be True or False, not {volume!r}") + entry = self._checked(fov) + found = self._fov(entry) + if found.volume and not volume: + raise RunInputsError(_whole_volume_text(entry.relative_path, found.z_count)) + first = self.read_plane(fov, z=0) + shape = (found.t_count, found.z_count, *first.shape) + return LazyImage(self, entry.relative_path, shape, first.dtype) + + @staticmethod + def _default_z(entry: FileEntry) -> int: + """Return ``z = 0`` for a plane image; refuse an omitted ``z`` on a volume (B2).""" + if entry.volume: + raise RunInputsError(_no_z_text(entry.relative_path, entry.z_count or 1)) + return 0 diff --git a/src/morphobricks_preprocessing/run_inputs_request.py b/src/morphobricks_preprocessing/run_inputs_request.py index f21d06a3..cf202bbb 100644 --- a/src/morphobricks_preprocessing/run_inputs_request.py +++ b/src/morphobricks_preprocessing/run_inputs_request.py @@ -1,4 +1,4 @@ -"""The request resolver's types and pure rules (resolver contract version 3). +"""The request resolver's types and pure rules (resolver contract version 5). ``RunInputs.resolve_request`` (:mod:`.run_inputs_resolve`) is the one interpreter of an experiment description for an analysis run, on every route (a direct brick run and a run @@ -48,21 +48,33 @@ CONNECTED_COMPONENTS, OBJECTS, MaskConversion, - mask_uses, objects_conflict, ) from .mask_requests import LABELLER as LABELLER # re-exported: the record's names from .mask_requests import LABELLER_CONNECTIVITY as LABELLER_CONNECTIVITY from .mask_requests import conversion_record as conversion_record from .mask_requests import mask_ids as mask_ids +from .mask_requests import mask_uses as mask_uses # re-exported: the resolver's from .mask_rules import refuse_not_instances, stale_check_message from .run_inputs_error import RunInputsError - -RESOLVER_VERSION = 3 -"""The resolver contract version a :class:`Provenance` records: 3 since Spec ADR 0005 (the -conversion record ``Provenance.mask_conversions``, the refusal of a conversion on a Z-stack, and -mask requests identified by ``(mask_id, role)``; Spec ADR 0002 "Resolver contract version 3"). -Version 2 added parent-label masks.""" +from .run_inputs_scope import check_subset, check_z_indices +from .run_inputs_volume import FovNotInRunError as FovNotInRunError # re-exported +from .run_inputs_volume import PlaneSelection as PlaneSelection +from .run_inputs_volume import Refusal as Refusal +from .run_inputs_volume import VolumeNotSupportedError as VolumeNotSupportedError +from .run_inputs_volume import ZIndexNotInImageError as ZIndexNotInImageError +from .run_inputs_volume import plane_selections as plane_selections +from .run_inputs_volume import volume_refusals as volume_refusals +from .run_inputs_volume import z_index_refusals as z_index_refusals + +RESOLVER_VERSION = 5 +"""The resolver contract version a :class:`Provenance` records: 5 since Spec ADR 0010 (volumes: +``Request.z_indices``, rule (b) of ``A_VOLUME_NOT_SUPPORTED``, ``A_Z_INDEX_NOT_IN_IMAGE``, and +``z_indices`` in ``fov_scope`` and its ``scope_digest``), implemented in one wave with Spec ADR +0002 AR12 (version 4: ``Request.fov_subset``, ``A_FOV_NOT_IN_RUN``, ``Provenance.fov_scope``), +so version 4 is never released (ADR 0010 VZ27). Version 3 (Spec ADR 0005) added the conversion +record ``Provenance.mask_conversions``, the refusal of a conversion on a Z-stack and mask +requests identified by ``(mask_id, role)``; version 2 parent-label masks.""" REGION = "region" MASK_ROLES = (OBJECTS, REGION) @@ -104,18 +116,6 @@ CHECKED = "checked" -class VolumeNotSupportedError(RunInputsError): - """A Z-volume was requested without ``volume_support``, or a Z-stack would be converted. - - The resolver contract's own code: 3-D is enabled later, by its own decision, for the - consumers that declare the capability; nothing enables it by default. A - ``binary_mask_policy`` on a position with more than one Z plane is refused with it too, - with or without the capability (Spec ADR 0005 BM5): the labeller labels 2-D planes only. - """ - - code = "A_VOLUME_NOT_SUPPORTED" - - @dataclass(frozen=True) class Capabilities: """What the consumer declares it can take; the resolver refuses what it does not. @@ -176,7 +176,7 @@ class Request: masks The masks used, with their roles and conversions. planes - ``plane`` (one selection per time point and Z slice, today's behaviour) or + ``plane`` (one selection per time point, and per listed Z index of a volume) or ``volume`` (one selection per time point holding every Z slice). capabilities The consumer's declared capabilities. @@ -184,6 +184,16 @@ class Request: ``cpu`` or ``cuda``, the explicit device the kernels run on. Recorded; the resolver runs no kernel and does not check that a GPU exists (the consumer refuses, never switches). + fov_subset + None (every image of the run, recorded as ``"all"``) or a non-empty tuple of FOV keys + (condition, biological_repeat, technical_repeat, position_id): the images the request + covers (Spec ADR 0002 AR12). A key the run does not have is ``A_FOV_NOT_IN_RUN``. + z_indices + None, or the Z positions to read of every volume the request covers, a non-empty, + strictly increasing tuple of ``int`` (Spec ADR 0010 VZ11, VC13); only with ``planes = + "plane"``. A ``plane`` request without it on a volume is ``A_VOLUME_NOT_SUPPORTED``; + an index a covered image lacks is ``A_Z_INDEX_NOT_IN_IMAGE``. Recorded in + ``Provenance.fov_scope`` and its ``scope_digest``. """ channel_ids: tuple[str, ...] = () @@ -191,16 +201,8 @@ class Request: planes: str = PLANE capabilities: Capabilities = field(default_factory=Capabilities) device: str = CPU - - -@dataclass(frozen=True) -class Refusal: - """One reason the request is refused, with its Spec code.""" - - code: str - subject: str - message: str - files: tuple[str, ...] = () + fov_subset: tuple[tuple[str, str, str, str], ...] | None = None + z_indices: tuple[int, ...] | None = None @dataclass(frozen=True) @@ -214,14 +216,6 @@ class RepeatCoverage: total: int -@dataclass(frozen=True) -class PlaneSelection: - """The planes of one read: time point ``t`` and the Z slices, one for a plane.""" - - t: int - z: tuple[int, ...] - - @dataclass(frozen=True) class MaskSelection: """One ``(mask_id, role)`` of the request as the consumer reads it. @@ -287,6 +281,12 @@ class Provenance: that selection (empty for a refused request, which selects nothing); a consumer copies ``[c.as_record() for c in mask_conversions]`` under ``mask_conversions`` in its run record, with no key added, renamed, dropped or converted. + + ``fov_scope`` is the request's scope record (Spec ADR 0002 AR12, ADR 0010 I4: + :data:`.run_inputs_scope.SCOPE_KEYS`, ``z_indices`` included, and its ``scope_digest``), + given for every request whose ``fov_subset`` keys are all of the run, refused or not; None + for ``A_FOV_NOT_IN_RUN``. A consumer copies it as is into its run record and keys every + output and cache entry by ``fov_scope["scope_digest"]``. """ resolver_version: int @@ -294,6 +294,7 @@ class Provenance: section_digests: tuple[tuple[str, str], ...] request: Request mask_conversions: tuple[MaskConversion, ...] = () + fov_scope: dict | None = field(default=None, hash=False) @dataclass(frozen=True) @@ -361,9 +362,12 @@ def check_request(request: Request, declared_masks: Mapping[str, str]) -> None: role, one mask ID requested as ``objects`` with two different conversions (a policy and none count as two; contract version 3, :func:`objects_conflict`), an unknown plane kind, or a device that is neither ``cpu`` nor ``cuda``. A mask ID may appear in several - entries (one per use). + entries (one per use). A malformed ``fov_subset`` (:func:`.run_inputs_scope.check_subset`) + or ``z_indices`` (:func:`.run_inputs_scope.check_z_indices`, Spec ADR 0010 VC13). """ _check_shape(request) + check_subset(request.fov_subset) + check_z_indices(request.z_indices, request.planes) if len(set(request.channel_ids)) != len(request.channel_ids): raise ValueError("a channel ID is requested twice") if request.planes not in PLANE_KINDS: @@ -475,13 +479,6 @@ def coverage( return tuple(found) -def plane_selections(t_count: int, z_count: int, kind: str) -> tuple[PlaneSelection, ...]: - """Return the planes to read of one image: per (t, z), or every Z per t for a volume.""" - if kind == VOLUME: - return tuple(PlaneSelection(t, tuple(range(z_count))) for t in range(t_count)) - return tuple(PlaneSelection(t, (z,)) for t in range(t_count) for z in range(z_count)) - - def mask_representation_refusal(mask: MaskRequest, representation: str) -> Refusal | None: """Return ``A_MASK_NOT_INSTANCES`` for a non-instances mask used as objects without a policy. @@ -552,49 +549,3 @@ def rgb_refusal(capabilities: Capabilities, rgb_images: Iterable[str]) -> Refusa "rgb_support; nothing is converted to grey or split (A_RGB_NOT_SUPPORTED).", images, ) - - -def volume_refusals(request: Request, z_counts: Mapping[str, int]) -> tuple[Refusal, ...]: - """Return every ``A_VOLUME_NOT_SUPPORTED`` refusal of a request: the one place that builds it. - - Parameters - ---------- - request - The request. - z_counts - Each position's image path to its number of Z planes (``Fov.z_count``). - - Returns - ------- - tuple of Refusal - First a ``volume`` request without ``volume_support``; then, for each mask ID with a - ``binary_mask_policy`` (in request order), one refusal per position with more than one - Z plane (sorted by path), as a ``plane`` or a ``volume`` request, with or without - ``volume_support`` (Spec ADR 0005 BM5: the labeller labels 2-D planes only). - """ - found = [] - if request.planes == VOLUME and not request.capabilities.volume_support: - found.append( - Refusal( - VolumeNotSupportedError.code, - VOLUME, - "A Z-volume selection was requested and this consumer does not declare " - "volume_support; ask for planes (A_VOLUME_NOT_SUPPORTED).", - ) - ) - stacks = sorted((path, count) for path, count in z_counts.items() if count > 1) - for mask in mask_uses(request.masks): - if mask.binary_mask_policy is None: - continue - found.extend( - Refusal( - VolumeNotSupportedError.code, - mask.mask_id, - f"{mask.mask_id!r} would be converted by {mask.binary_mask_policy}, which labels " - f"2-D planes only; the images of {path} have {count} Z planes. Converting a " - "Z-stack is not supported (A_VOLUME_NOT_SUPPORTED).", - (path,), - ) - for path, count in stacks - ) - return tuple(found) diff --git a/src/morphobricks_preprocessing/run_inputs_resolve.py b/src/morphobricks_preprocessing/run_inputs_resolve.py index 2ff6f55d..a6b678be 100644 --- a/src/morphobricks_preprocessing/run_inputs_resolve.py +++ b/src/morphobricks_preprocessing/run_inputs_resolve.py @@ -14,15 +14,20 @@ (experiment-v1 sections 4.5a, 4.5b, 4.5c, 8); a ``parent_labels`` region for a consumer without ``parent_labels_support`` is selected with ``conversion = "parent_labels_as_area"``; one selection per ``(mask_id, role)``, entries of one use collapsed (contract version 3); +- the covered images: every image of the run, or the request's ``fov_subset`` (Spec ADR 0002 + AR12); a key the run does not have is ``A_FOV_NOT_IN_RUN`` alone, with no ``fov_scope``; - ``rgb`` units refused as ``A_RGB_NOT_SUPPORTED`` unless the consumer declares ``rgb_support`` - (section 4.4b), a Z-volume refused as ``A_VOLUME_NOT_SUPPORTED`` unless it declares - ``volume_support``, and a ``binary_mask_policy`` on a position with more than one Z plane - refused as ``A_VOLUME_NOT_SUPPORTED`` always (Spec ADR 0005 BM5); + (section 4.4b); then ``A_VOLUME_NOT_SUPPORTED`` (Spec ADR 0010): (a) a Z-volume unless the + consumer declares ``volume_support``, (b) a ``plane`` request without ``z_indices`` on a + volume, always, and (c) a ``binary_mask_policy`` on a position with more than one Z plane, + always (Spec ADR 0005 BM5); then ``A_Z_INDEX_NOT_IN_IMAGE`` for a requested Z index a + covered image lacks; - the coverage of every biological repeat (``repeat_group``) per channel and mask: full, partial or unavailable, reported whether or not the request is refused; - the provenance: the resolver contract version, the description's SHA-256 and section - digests as the manifest recorded them, the request itself (its device included), and the - conversion records (``mask_conversions``, one per converted mask ID). + digests as the manifest recorded them, the request itself (its device included), the + conversion records (``mask_conversions``, one per converted mask ID) and the scope record + ``fov_scope`` with its ``z_indices`` and ``scope_digest``. It reads only the manifest, the published description (checked against the run's SHA-256) and the mask step's status file: no pixel, no brick, no CellPatcher module. Every run is described: @@ -63,14 +68,16 @@ scope_refusal, unchecked_refusal, volume_refusals, + z_index_refusals, ) +from .run_inputs_scope import FOV_NOT_IN_RUN, fov_not_in_run, fov_scope, unknown_keys if TYPE_CHECKING: from .run_inputs import Fov class ResolvingInputs: - """The ``resolve_request`` method of ``RunInputs`` (resolver contract version 3).""" + """The ``resolve_request`` method of ``RunInputs`` (resolver contract version 5).""" output_folder: Path manifest: RunManifest @@ -107,7 +114,16 @@ def resolve_request(self, request: Request) -> ResolvedRequest: """ description = self.description() check_request(request, {k: m.representation for k, m in description.masks.items()}) - fovs = self.fovs() + every = self.fovs() + unknown = unknown_keys(request.fov_subset, (f.key for f in every)) + if unknown: # AR12: the request's only refusal, and no scope is recorded + refusal = Refusal(FOV_NOT_IN_RUN, "fov_subset", fov_not_in_run(unknown, len(every))) + return ResolvedRequest((), (refusal,), (), self._provenance(request, (), None)) + scope = fov_scope( + [(f.key, f.repeat_group) for f in every], request.fov_subset, request.z_indices + ) + chosen = set(request.fov_subset or ()) + fovs = every if request.fov_subset is None else tuple(f for f in every if f.key in chosen) repeats = _repeats(fovs) refusals: list[Refusal] = [] covered: list[RepeatCoverage] = [] @@ -129,17 +145,19 @@ def resolve_request(self, request: Request) -> ResolvedRequest: asked = set(request.channel_ids) rgb = [f.relative_path for f in fovs if f.image_type == RGB and asked & set(f.channel_ids)] refusals.extend(_some(rgb_refusal(request.capabilities, rgb))) - refusals.extend(volume_refusals(request, {f.relative_path: f.z_count for f in fovs})) + z_counts = {f.relative_path: f.z_count for f in fovs} + refusals.extend(volume_refusals(request, z_counts)) # (a), (b), (c): ADR 0010 + refusals.extend(z_index_refusals(request.z_indices, z_counts)) if refusals: return ResolvedRequest( - (), tuple(refusals), tuple(covered), self._provenance(request, ()) + (), tuple(refusals), tuple(covered), self._provenance(request, (), scope) ) masks = self._mask_selections(uses, description, request) return ResolvedRequest( self._selections(request, masks, fovs), (), tuple(covered), - self._provenance(request, _records(masks)), + self._provenance(request, _records(masks), scope), ) def _mask( @@ -209,16 +227,22 @@ def _selections( channel_ids=request.channel_ids, channel_indices=tuple(fov.channel_ids.index(c) for c in request.channel_ids), masks=masks, - planes=plane_selections(fov.t_count, fov.z_count, request.planes), + planes=plane_selections( + fov.t_count, fov.z_count, request.planes, request.z_indices + ), ) for fov in fovs ) - def _provenance(self, request: Request, conversions: tuple[MaskConversion, ...]) -> Provenance: + def _provenance( + self, request: Request, conversions: tuple[MaskConversion, ...], scope: dict | None + ) -> Provenance: """Return the provenance from the manifest's description record (always present).""" recorded = self.manifest.experiment_description digests = tuple(sorted(recorded["section_digests"].items())) - return Provenance(RESOLVER_VERSION, recorded["sha256"], digests, request, conversions) + return Provenance( + RESOLVER_VERSION, recorded["sha256"], digests, request, conversions, scope + ) def _records(masks: tuple[MaskSelection, ...]) -> tuple[MaskConversion, ...]: diff --git a/src/morphobricks_preprocessing/run_inputs_scope.py b/src/morphobricks_preprocessing/run_inputs_scope.py new file mode 100644 index 00000000..9bfd2e91 --- /dev/null +++ b/src/morphobricks_preprocessing/run_inputs_scope.py @@ -0,0 +1,190 @@ +"""The request's scope: the recorded FOV subset and the explicit Z indices (resolver version 5). + +Pure rules of the resolver contract that need no file (Spec ADR 0002 AR12, version 4, and +Spec ADR 0010 VZ11, VZ23, VC13, version 5; the two are implemented in one wave, so the code +goes from version 3 to version 5 directly and version 4 is never released, ADR 0010 VZ27): + +- ``Request.fov_subset`` (:func:`check_subset`): None (every image of the run, recorded as + ``"all"``) or a non-empty tuple of FOV keys, each a tuple of four ``str``; a key the run does + not have is ``A_FOV_NOT_IN_RUN`` (:func:`fov_not_in_run`), the request's only refusal, and no + ``fov_scope`` is recorded; +- ``Request.z_indices`` (:func:`check_z_indices`): None, or a non-empty, strictly increasing + ``tuple`` of ``int`` (``type(i) is int``: a ``bool``, a NumPy integer or a float is refused) + each at least 0; only with ``planes = "plane"``. A malformed value is ``ValueError``, never a + refusal; +- the ``fov_scope`` record (:func:`fov_scope`), with ``z_indices`` after ``excluded`` and + before ``scope_digest``, and the ``scope_digest`` over ``fov_subset``, ``fovs`` and + ``z_indices`` (:func:`scope_digest`, the canonical JSON of ADR 0004 EW11). + +Nothing here reads a file. +""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Iterable, Sequence + +ALL = "all" +EXPLICIT = "explicit" +FOV_NOT_IN_RUN = "A_FOV_NOT_IN_RUN" +"""The resolver-contract code of a ``fov_subset`` key the run does not have (AR12).""" +SCOPE_KEYS = ( + "fov_subset", + "selected", + "run_images", + "repeats", + "selected_biological_repeats", + "fovs", + "excluded", + "z_indices", + "scope_digest", +) +"""The keys of the ``fov_scope`` record, in this order (closed; ADR 0010 I4).""" +LISTED = 10 +"""Unknown FOVs named one per line in the ``A_FOV_NOT_IN_RUN`` refusal before ``... and m more``.""" + +FovKey = tuple[str, str, str, str] + + +def check_subset(subset: object) -> None: + """Refuse a malformed ``fov_subset`` (``ValueError``), before anything is classified. + + None is valid (every image of the run). Otherwise a non-empty tuple of FOV keys, each a + tuple of exactly four ``str`` (condition, biological_repeat, technical_repeat, + position_id), none twice. An index, a path, a list or a key of another length is malformed: + a FOV is never named by position. + """ + if subset is None: + return + if not isinstance(subset, tuple) or not all( + isinstance(k, tuple) and len(k) == 4 and all(isinstance(p, str) for p in k) for k in subset + ): + raise ValueError( + "fov_subset must be None or a tuple of FOV keys, each a tuple of four str " + f"(condition, biological_repeat, technical_repeat, position_id), not {subset!r}" + ) + if not subset: + raise ValueError( + "fov_subset is empty; name at least one FOV by its key, or leave it unset (None) to " + "use every image of the run" + ) + seen: set[FovKey] = set() + for key in subset: + if key in seen: + raise ValueError(f"the FOV {key!r} is named twice in fov_subset") + seen.add(key) + + +def check_z_indices(z_indices: object, planes: str) -> None: + """Refuse a malformed ``z_indices`` (``ValueError``; ADR 0010 VC13), before anything is read. + + None is valid. Otherwise a ``tuple`` (a list or another sequence is refused) of ``int`` + with ``type(i) is int`` (a ``bool``, a NumPy integer or a float is refused: the caller + converts with ``int(...)``), non-empty, strictly increasing, each at least 0, and only with + ``planes = "plane"``. + """ + if z_indices is None: + return + if not isinstance(z_indices, tuple) or not all(type(i) is int for i in z_indices): + raise ValueError( + "z_indices must be None or a tuple of int (type int exactly: not bool, not a NumPy " + f"integer, not float), not {z_indices!r}" + ) + if not z_indices: + raise ValueError("z_indices is empty; name at least one Z index, or leave it unset") + if any(i < 0 for i in z_indices): + raise ValueError(f"z_indices must be 0 or more, not {z_indices!r}") + if any(a >= b for a, b in zip(z_indices, z_indices[1:], strict=False)): + raise ValueError(f"z_indices must be strictly increasing (no repeat), not {z_indices!r}") + if planes != "plane": + raise ValueError( + f"z_indices names planes of a volume: it is only valid with planes='plane', not " + f"{planes!r}" + ) + + +def unknown_keys(subset: tuple[FovKey, ...] | None, keys: Iterable[FovKey]) -> tuple[FovKey, ...]: + """Return the keys of ``subset`` the run does not have, sorted (empty for None).""" + if subset is None: + return () + known = set(keys) + return tuple(sorted(k for k in subset if k not in known)) + + +def fov_not_in_run(unknown: Sequence[FovKey], run_images: int) -> str: + """Return the exact ``A_FOV_NOT_IN_RUN`` message: unknown keys sorted, at most ten listed.""" + keys = tuple(sorted(unknown)) + shown = "\n".join(f" - {key!r}" for key in keys[:LISTED]) + more = f"\n ... and {len(keys) - LISTED} more" if len(keys) > LISTED else "" + return ( + f"The requested FOV subset names {len(keys)} FOV(s) that this run does not have:\n" + f"{shown}{more}\nNothing was selected or read. Name each FOV by its key (condition, " + "biological_repeat, technical_repeat, position_id) exactly as RunInputs.fovs() lists it, " + f"or leave fov_subset unset to use all {run_images} images of the run " + f"({FOV_NOT_IN_RUN})." + ) + + +def canonical_json(value: object) -> str: + """Return the canonical JSON of ADR 0004 EW11: sorted keys, ``,`` and ``:``, ASCII escapes.""" + return json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False + ) + + +def scope_digest(mode: str, fovs: Sequence[FovKey], z_indices: tuple[int, ...] | None) -> str: + """Return the SHA-256 of ``{"fov_subset", "fovs", "z_indices"}`` (always the three keys).""" + value = { + "fov_subset": mode, + "fovs": [list(k) for k in sorted(fovs)], + "z_indices": None if z_indices is None else list(z_indices), + } + return hashlib.sha256(canonical_json(value).encode("utf-8")).hexdigest() + + +def fov_scope( + run: Sequence[tuple[FovKey, str]], + subset: tuple[FovKey, ...] | None, + z_indices: tuple[int, ...] | None, +) -> dict: + """Return the ``fov_scope`` record of a request whose keys are all known. + + Parameters + ---------- + run + Every FOV of the run as ``(key, repeat_group)``. + subset + ``Request.fov_subset``: None (every image) or the explicit keys, all of the run. + z_indices + ``Request.z_indices``: None or the explicit Z indices. + + Returns + ------- + dict + The keys of :data:`SCOPE_KEYS`, in that order. + """ + keys = {key for key, _ in run} + chosen = keys if subset is None else set(subset) + mode = ALL if subset is None else EXPLICIT + fovs = sorted(chosen) + repeats: dict[str, list[int]] = {} + for key, group in run: + counts = repeats.setdefault(group, [0, 0]) + counts[0] += key in chosen + counts[1] += 1 + return { + "fov_subset": mode, + "selected": len(fovs), + "run_images": len(keys), + "repeats": [ + {"repeat_group": g, "selected": s, "run_images": n} + for g, (s, n) in sorted(repeats.items()) + ], + # How many biological repeats have a chosen image; not the inferential N of a comparison. + "selected_biological_repeats": sum(1 for s, _ in repeats.values() if s > 0), + "fovs": [list(k) for k in fovs], + "excluded": [list(k) for k in sorted(keys - chosen)], + "z_indices": None if z_indices is None else list(z_indices), + "scope_digest": scope_digest(mode, fovs, z_indices), + } diff --git a/src/morphobricks_preprocessing/run_inputs_semantic.py b/src/morphobricks_preprocessing/run_inputs_semantic.py index 4b80590c..bc582483 100644 --- a/src/morphobricks_preprocessing/run_inputs_semantic.py +++ b/src/morphobricks_preprocessing/run_inputs_semantic.py @@ -33,8 +33,9 @@ from .description_unnamed import FIELD as UNNAMED_FIELD from .description_write import SECTIONS from .description_write import section_digests as published_digests -from .fov_identity import FovIdentity, fov_identity +from .fov_identity import FovIdentity, checked_images, fov_identity from .manifest import FileEntry, RunManifest, file_sha256 +from .manifest_volume import compute_checks from .mask_representation import CHECKED, file_status, predates_value_rule, read_checked from .mask_rules import stale_check_message from .run_folder_errors import run_folder_stale @@ -368,3 +369,24 @@ def require_checked(self, recorded: Mapping, mask_type: str) -> None: f"its declared representation ({mask.representation}). Run the masks " "step on this output folder first (A_MASK_UNCHECKED)." ) + + +def check_recorded_checks(manifest: RunManifest, description: Description) -> None: + """Refuse a manifest whose ``checks`` are not the ones its entries give (ADR 0010 VC5). + + ``checks`` is derived from the included image entries and the description's canonical + identities; any difference (a missing or extra object, other counts, images or places) is + refused before anything is served, never repaired. + """ + try: + expected = compute_checks(checked_images(description, manifest.files)) + except LookupError as exc: + raise RunInputsError( + f"The run's image folders do not match its description: {exc}. Run preprocessing again." + ) from exc + if list(manifest.checks or ()) != expected: + raise RunInputsError( + "The run manifest's checks are not the ones its image entries give " + "(W_AXIS_UNCALIBRATED, W_MIXED_PLANES_AND_VOLUMES): it was changed after the run. " + "Run preprocessing again." + ) diff --git a/src/morphobricks_preprocessing/run_inputs_statistics.py b/src/morphobricks_preprocessing/run_inputs_statistics.py new file mode 100644 index 00000000..bc676160 --- /dev/null +++ b/src/morphobricks_preprocessing/run_inputs_statistics.py @@ -0,0 +1,251 @@ +"""Statistics of a run, refused for volumes: ``RunInputs.histograms``, ``image_qc`` (ADR 0010). + +Histograms, normalization and QC metrics are **not computed** for a volume (an image whose +confirmed ``Z`` has more than one slice; Spec ADR 0010 VZ2): it has no row in the histogram +table and none in the QC table, and its manifest entry records ``plane_statistics = +"not_computed_volume"``. A consumer that asks for them gets a coded refusal, never missing data +treated as absent, an empty result, zeros or the per-plane values of its slices +(:class:`VolumeStatisticsNotComputedError`, ``VOLUME_STATISTICS_NOT_COMPUTED``, built by +:func:`refuse_volume_statistics` only). The entry points (VC6), mixed into +:class:`.run_inputs.RunInputs`: + +- ``histograms(fovs=None)``: the rows of the named images (``Fov`` or image paths), in table + order, any volume among them refused; with no argument every row on a run with no volume, + refused on a run with any volume, naming every one; +- ``image_qc(fovs=None)``: the QC rows, with the same semantics; +- ``require_plane_statistics(fovs)``: the check alone, which a consumer calls **before** + fitting, loading, applying or reusing a normalization (any ADR 0011 scope, ``patch`` + included) and before computing, reading or reusing a QC metric. + +The arguments are an iterable of ``Fov`` or image paths, each an image of the run: empty or a +FOV named twice is ``ValueError``; an unknown one ``RunInputsError`` naming it. A run of +volumes only has no table: every call is refused (VC1). + +The rows are checked against the manifest when read (VC3): a plane image has exactly one row +per time point at ``z = 0`` (with its channels), a volume none, and no row names another image; +the QC rows cover each histogram row's channels and nothing else. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Sequence +from pathlib import Path +from typing import TYPE_CHECKING + +from morphobricks_normalization.records import PlaneRecord + +from .image_qc_table import ImageQcFormatError, QcRow, read_image_qc +from .manifest import FileEntry, RunManifest +from .run.generation import published_path +from .run_inputs_checks import check_sha +from .run_inputs_error import RunInputsError + +if TYPE_CHECKING: + from .run_inputs import Fov + +CODE = "VOLUME_STATISTICS_NOT_COMPUTED" +HISTOGRAMS = "histograms" +NORMALIZATION = "normalization" +QC = "qc" +WHAT = (HISTOGRAMS, NORMALIZATION, QC) +"""What a refusal is about (``VolumeStatisticsNotComputedError.what``).""" +SUBJECTS = { + HISTOGRAMS: ("Plane histograms are", "plane histograms"), + NORMALIZATION: ("Normalization is", "normalization"), + QC: ("QC metrics are", "QC metrics"), +} +"""How the refusal names what is not computed (owner answer of 2 December 2026, VZ33).""" +LISTED = 10 +"""Volumes named one per line in the refusal before ``... and m more``.""" + + +class VolumeStatisticsNotComputedError(RunInputsError): + """``VOLUME_STATISTICS_NOT_COMPUTED``: statistics of a volume were asked for (ADR 0010 VC6). + + Attributes + ---------- + what + ``"histograms"``, ``"normalization"`` or ``"qc"``. + volumes + Each volume concerned as ``(fov_key, path, z_count)``, sorted by FOV key then path. + """ + + code = CODE + + def __init__(self, message: str, what: str, volumes: tuple) -> None: + super().__init__(message) + self.what = what + self.volumes = volumes + + def __reduce__(self) -> tuple: + """Pickle with what and the volumes.""" + return (type(self), (str(self), self.what, self.volumes)) + + +def refuse_volume_statistics( + volumes: Iterable[tuple[tuple[str, str, str, str], str, int]], what: str +) -> VolumeStatisticsNotComputedError: + """Return the one ``VOLUME_STATISTICS_NOT_COMPUTED`` refusal: the only constructor. + + Parameters + ---------- + volumes + Each volume concerned as ``(fov_key, path, z_count)``. + what + ``"histograms"``, ``"normalization"`` or ``"qc"``. + """ + if what not in WHAT: + raise ValueError(f"what must be one of {WHAT}, not {what!r}") + found = tuple(sorted((tuple(key), path, count) for key, path, count in volumes)) + shown = "\n".join( + f" - {key!r}: {Path(path).name}, {count} Z planes" for key, path, count in found[:LISTED] + ) + more = f"\n ... and {len(found) - LISTED} more" if len(found) > LISTED else "" + subject, noun = SUBJECTS[what] + message = ( + f"{subject} not computed for volumes; this request names {len(found)} volume(s):\n" + f"{shown}{more}\nPer-volume statistics are not implemented yet (not computed: " + f"volume). Name plane images only, or analyse these volumes without {noun} ({CODE})." + ) + return VolumeStatisticsNotComputedError(message, what, found) + + +def check_rows(records: Sequence[PlaneRecord], manifest: RunManifest) -> None: + """Refuse histogram rows that do not cover exactly the planes of the plane images (VC3). + + Raises + ------ + RunInputsError + A row naming no plane image of the manifest (a volume, or no image), a plane image + without exactly one row per time point at ``z = 0``, or a duplicate row. + """ + entries = {e.relative_path: e for e in manifest.files} + seen: dict[str, list[tuple[int, int]]] = {} + for record in records: + entry = entries.get(record.source_relative_path) + if entry is None or entry.volume: + what = "a volume" if entry is not None else "no image of the run" + raise RunInputsError( + f"The histogram table has the row {record.plane_id} of " + f"{record.source_relative_path}, which is {what}: a volume has no row " + "(not computed: volume). Run preprocessing again." + ) + seen.setdefault(record.source_relative_path, []).append((record.t, record.z)) + for path, entry in entries.items(): + expected = [] if entry.volume else [(t, 0) for t in range(entry.t_count or 1)] + if sorted(seen.get(path, [])) != expected: + raise RunInputsError( + f"The histogram table's rows of {path} are not one per time point at z = 0 " + f"(t_count = {entry.t_count}): it is not the table of this run. Run " + "preprocessing again." + ) + + +def check_qc_rows(rows: Sequence[QcRow], records: Sequence[PlaneRecord]) -> None: + """Refuse QC rows that are not exactly one per channel of each histogram row (VC3, P90).""" + expected = sorted(QcRow.identity_of(r, c) for r in records for c in r.channels) + if sorted(row.identity for row in rows) != expected: + raise RunInputsError( + "The image QC table does not hold exactly one row per channel of each plane of the " + "plane images (a volume has none): it is not the QC table of this run. Run " + "preprocessing again." + ) + + +class StatisticsInputs: + """The statistics entry points of ``RunInputs`` (Spec ADR 0010 VC6).""" + + output_folder: Path + manifest: RunManifest + _records: tuple[PlaneRecord, ...] + + def fovs(self) -> tuple[Fov, ...]: # pragma: no cover - RunInputs provides it + """Return every position (``RunInputs``).""" + raise NotImplementedError + + def histograms(self, fovs: Iterable[Fov | str] | None = None) -> tuple[PlaneRecord, ...]: + """Return the histogram rows of plane images, in table order; volumes are refused. + + Parameters + ---------- + fovs + The images (``Fov`` or image paths) whose rows to return; None: every row, on a + run with no volume only. + + Raises + ------ + VolumeStatisticsNotComputedError + For any volume among ``fovs``, for ``fovs=None`` on a run with any volume (naming + every one), and for every call on a run of volumes only. + ValueError, RunInputsError + For ``fovs`` empty, naming an image twice, or naming one the run does not have. + """ + paths = self._statistics_paths(fovs, HISTOGRAMS) + return tuple(r for r in self._records if r.source_relative_path in paths) + + def image_qc(self, fovs: Iterable[Fov | str] | None = None) -> tuple[QcRow, ...]: + """Return the image QC rows of plane images, in table order (contract §19). + + The table is read and checked when called: its SHA-256 is the one the run recorded, + and it holds exactly one row per channel of each histogram row. Same arguments and + refusals as :meth:`histograms`, with ``what = "qc"``. + """ + paths = self._statistics_paths(fovs, QC) + recorded = self.manifest.image_qc or {} + table = published_path(self.output_folder, recorded["file"], recorded["sha256"]) + check_sha(table, recorded["sha256"]) + try: + rows = read_image_qc(table) + except ImageQcFormatError as exc: + raise RunInputsError(f"The image QC table cannot be used: {exc}") from exc + check_qc_rows(rows, self._records) + return tuple(row for row in rows if row.relative_path in paths) + + def require_plane_statistics(self, fovs: Iterable[Fov | str]) -> None: + """Refuse the statistics of any volume among ``fovs``; return None otherwise. + + A consumer calls it, with the FOVs of the selection concerned, before fitting + (from rows or from pixels, at every scope, ``patch`` included), loading, applying or + reusing a normalization, and before computing, reading or reusing a QC metric (VC6). + + Raises + ------ + VolumeStatisticsNotComputedError + ``what = "normalization"``, naming every volume among ``fovs``. + ValueError, RunInputsError + As :meth:`histograms`; ``fovs`` is required. + """ + if fovs is None: + raise ValueError("require_plane_statistics needs the FOVs of the selection concerned") + self._statistics_paths(fovs, NORMALIZATION) + + def _statistics_paths(self, fovs: Iterable[Fov | str] | None, what: str) -> set[str]: + """Return the image paths asked for, refusing volumes (and every call with no table).""" + entries = {e.relative_path: e for e in self.manifest.files} + if fovs is None: + chosen = list(entries) + else: + chosen = [f if isinstance(f, str) else f.relative_path for f in fovs] + _check_named(chosen, entries) + # A run of volumes only has no table (VC1): every call names only volumes, so is refused. + volumes = [entries[path] for path in chosen if entries[path].volume] + if volumes: + raise refuse_volume_statistics(_named(volumes), what) + return set(chosen) + + +def _check_named(chosen: list[str], entries: dict[str, FileEntry]) -> None: + """Refuse an empty list, an image named twice, or one the run does not have.""" + if not chosen: + raise ValueError("fovs is empty: name at least one image, or leave it unset (None)") + twice = sorted({path for path in chosen if chosen.count(path) > 1}) + if twice: + raise ValueError(f"fovs names {twice[0]!r} twice") + unknown = sorted(path for path in chosen if path not in entries) + if unknown: + raise RunInputsError(f"{unknown[0]} is not an image of this run.") + + +def _named(volumes: Iterable[FileEntry]) -> list[tuple[tuple[str, str, str, str], str, int]]: + """Return each volume as ``(fov_key, path, z_count)``.""" + return [((*v.labels, v.position_id or ""), v.relative_path, v.z_count or 1) for v in volumes] diff --git a/src/morphobricks_preprocessing/run_inputs_text.py b/src/morphobricks_preprocessing/run_inputs_text.py index f622b4e8..8d133dc2 100644 --- a/src/morphobricks_preprocessing/run_inputs_text.py +++ b/src/morphobricks_preprocessing/run_inputs_text.py @@ -44,3 +44,22 @@ def _labels_unreadable_text(exc: NgffError) -> str: "run; check the image's labels group, then run preprocessing again on the " "experiment as it is." ) + + +def _no_z_text(relative_path: str, z_count: int) -> str: + """Return the refusal of ``read_plane`` without ``z`` on a volume (Spec ADR 0010 B2).""" + return ( + f"{relative_path} is a volume ({z_count} Z planes) and read_plane was called without z: " + "no plane is chosen for you (never slice 0). Pass z, or request planes through " + "RunInputs.resolve_request with Request.z_indices." + ) + + +def _whole_volume_text(relative_path: str, z_count: int) -> str: + """Return the refusal of ``read_image`` on a volume without ``volume=True`` (B2).""" + return ( + f"{relative_path} is a volume ({z_count} Z planes): read_image reads it whole only when " + "the caller states it reads volumes (read_image(fov, volume=True)), which only a " + "consumer that declares volume_support = 'volumes' does. Read planes with " + "read_plane(fov, z=...) or request them with Request.z_indices." + ) diff --git a/src/morphobricks_preprocessing/run_inputs_volume.py b/src/morphobricks_preprocessing/run_inputs_volume.py new file mode 100644 index 00000000..70317a25 --- /dev/null +++ b/src/morphobricks_preprocessing/run_inputs_volume.py @@ -0,0 +1,193 @@ +"""The resolver's volume rules (resolver contract version 5, Spec ADR 0010 VZ11, VC13). + +A **volume** is an image whose confirmed ``Z`` role has more than one slice (``Fov.z_count > 1``); +any other image is a plane image. The resolver never chooses a plane of a volume for the +consumer, never expands Z into planes implicitly and never projects: + +- :func:`volume_refusals` builds every ``A_VOLUME_NOT_SUPPORTED`` refusal, in this order: + (a) a ``volume`` request without ``Capabilities.volume_support``; (b) a ``plane`` request + **without** ``z_indices`` covering a volume, one refusal per such position (sorted by path), + with or without ``volume_support``; (c) a ``binary_mask_policy`` on a volume, for a ``plane`` + request (with or without ``z_indices``) or a ``volume`` request (Spec ADR 0005 BM5, kept by + ADR 0010 VZ16); +- :func:`z_index_refusals` builds every ``A_Z_INDEX_NOT_IN_IMAGE`` refusal: a listed Z index a + covered position does not have, one per such position, sorted by path; never clipped, + wrapped or served for the positions that have it only; +- :func:`plane_selections` gives the planes to read of one position: for a ``plane`` request + with ``z_indices``, exactly ``(t, z)`` for every ``t`` and every listed ``z``. + +Only the positions a request covers (its ``fov_subset``) are given to these functions. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from .mask_requests import mask_uses +from .run_inputs_error import RunInputsError + +if TYPE_CHECKING: + from .run_inputs_request import Request + +PLANE = "plane" +VOLUME = "volume" + + +class VolumeNotSupportedError(RunInputsError): + """A Z-volume was requested without ``volume_support``, or a volume would be served as planes. + + The resolver contract's own code (Spec ADR 0002 AR3, ADR 0010): (a) a ``volume`` request + without ``volume_support``; (b) a ``plane`` request without ``z_indices`` on a volume, with + or without the capability (Z is never expanded into planes implicitly); (c) a + ``binary_mask_policy`` on a position with more than one Z plane, with or without the + capability (Spec ADR 0005 BM5): the labeller labels 2-D planes only. + """ + + code = "A_VOLUME_NOT_SUPPORTED" + + +class ZIndexNotInImageError(RunInputsError): + """``A_Z_INDEX_NOT_IN_IMAGE``: a requested Z index a covered image does not have (ADR 0010).""" + + code = "A_Z_INDEX_NOT_IN_IMAGE" + + +class FovNotInRunError(RunInputsError): + """``A_FOV_NOT_IN_RUN``: the request's ``fov_subset`` names a FOV the run does not have.""" + + code = "A_FOV_NOT_IN_RUN" + + +@dataclass(frozen=True) +class Refusal: + """One reason the request is refused, with its Spec code.""" + + code: str + subject: str + message: str + files: tuple[str, ...] = () + + +@dataclass(frozen=True) +class PlaneSelection: + """The planes of one read: time point ``t`` and the Z slices, one for a plane.""" + + t: int + z: tuple[int, ...] + + +def plane_selections( + t_count: int, z_count: int, kind: str, z_indices: tuple[int, ...] | None = None +) -> tuple[PlaneSelection, ...]: + """Return the planes to read of one position. + + A ``volume`` request: every Z of each ``t``. A ``plane`` request with ``z_indices``: exactly + ``(t, z)`` for every ``t`` and every listed ``z``. A ``plane`` request without: one plane per + ``t`` (a plane image; a volume is refused before, rule (b)). + """ + if kind == VOLUME: + return tuple(PlaneSelection(t, tuple(range(z_count))) for t in range(t_count)) + zs = tuple(range(z_count)) if z_indices is None else z_indices + return tuple(PlaneSelection(t, (z,)) for t in range(t_count) for z in zs) + + +def volume_refusals(request: Request, z_counts: Mapping[str, int]) -> tuple[Refusal, ...]: + """Return every ``A_VOLUME_NOT_SUPPORTED`` refusal of a request: the one place that builds it. + + Parameters + ---------- + request + The request (:class:`.run_inputs_request.Request`). + z_counts + Each covered position's image path to its number of Z planes (``Fov.z_count``). + + Returns + ------- + tuple of Refusal + (a), then (b) per volume sorted by path, then (c) per mask ID with a policy (in request + order) and per volume sorted by path. + """ + found = [] + if request.planes == VOLUME and not request.capabilities.volume_support: + found.append( + Refusal( + VolumeNotSupportedError.code, + VOLUME, + "A Z-volume selection was requested and this consumer does not declare " + "volume_support; ask for planes (A_VOLUME_NOT_SUPPORTED).", + ) + ) + stacks = sorted((path, count) for path, count in z_counts.items() if count > 1) + if request.planes == PLANE and request.z_indices is None: + found.extend( + Refusal( + VolumeNotSupportedError.code, + PLANE, + f"{path} is a volume ({count} Z planes) and the plane request names no Z " + "index: Z is never expanded into planes and no plane is chosen for the " + "consumer. Name the Z indices to read (Request.z_indices), or request whole " + "volumes with volume_support (A_VOLUME_NOT_SUPPORTED).", + (path,), + ) + for path, count in stacks + ) + for mask in mask_uses(request.masks): + if mask.binary_mask_policy is None: + continue + found.extend( + Refusal( + VolumeNotSupportedError.code, + mask.mask_id, + f"{mask.mask_id!r} would be converted by {mask.binary_mask_policy}, which labels " + f"2-D planes only; the images of {path} have {count} Z planes. Converting a " + "Z-stack is not supported (A_VOLUME_NOT_SUPPORTED).", + (path,), + ) + for path, count in stacks + ) + return tuple(found) + + +def z_index_refusals( + z_indices: tuple[int, ...] | None, z_counts: Mapping[str, int] +) -> tuple[Refusal, ...]: + """Return one ``A_Z_INDEX_NOT_IN_IMAGE`` per covered position lacking a requested Z index. + + Parameters + ---------- + z_indices + ``Request.z_indices``; None gives no refusal. + z_counts + Each covered position's image path to its number of Z planes. + + Returns + ------- + tuple of Refusal + Sorted by path, each with the message of ADR 0010 VC13. + """ + if z_indices is None: + return () + found = [] + for path, count in sorted(z_counts.items()): + missing = [z for z in z_indices if z >= count] + if not missing: + continue + found.append( + Refusal( + ZIndexNotInImageError.code, + "z_indices", + f"{path} has {count} Z plane(s) (0 to {count - 1}); the request names Z " + f"{_listed(missing)}, which it does not have. Nothing was selected or read. " + "Name Z indices every covered image has, or narrow the request with fov_subset " + "(A_Z_INDEX_NOT_IN_IMAGE).", + (path,), + ) + ) + return tuple(found) + + +def _listed(indices: Iterable[int]) -> str: + """Return the Z indices as text: ``"5"``, ``"5, 6"``.""" + return ", ".join(str(i) for i in indices) diff --git a/src/morphobricks_preprocessing/scaling_fit.py b/src/morphobricks_preprocessing/scaling_fit.py index 8f73fe78..3869c167 100644 --- a/src/morphobricks_preprocessing/scaling_fit.py +++ b/src/morphobricks_preprocessing/scaling_fit.py @@ -224,7 +224,7 @@ def _table_records(inputs: object, fovs: list, channels: Sequence[str]) -> list: raise run_folder_stale(sorted(changed), "content", at_read=True) rows: dict[tuple[str, int, int], list] = {} - for record in inputs.histograms(): + for record in inputs.histograms(fovs): rows.setdefault((record.source_relative_path, record.z, record.t), []).append(record) exact_needed = inputs.manifest.settings.histogram.histogram_range != "minmax" found = [] @@ -338,6 +338,8 @@ def fit_scaling( if not channels or len(set(channels)) != len(channels): raise ValueError("give the channel IDs to fit, each once") chosen = _selected(inputs, fovs) + # Before any row is read or pixel histogrammed: a volume is never normalized (ADR 0010 VC6). + inputs.require_plane_statistics(chosen) reader = _table_records if source == "plane_histograms" else _image_records records = reader(inputs, chosen, channels) groups = None diff --git a/src/morphobricks_preprocessing/size_checks.py b/src/morphobricks_preprocessing/size_checks.py index 9df26a24..9d737dc2 100644 --- a/src/morphobricks_preprocessing/size_checks.py +++ b/src/morphobricks_preprocessing/size_checks.py @@ -7,17 +7,17 @@ confirmed roles instead (issue #74): the header letters of a plain stack are only where its pages, rows and columns are stored, so they are never used for these warnings. -The error ``z_stack_not_supported`` (:func:`z_stack_issues`, owner decision of 5 November -2026) refuses every image with more than one depth slice, measured the same two ways: -MorphoBricks v1 analyses 2-D planes, and a projection is an explicit, recorded step -(``convert --project``), never made implicitly when an image is read. +An image with more than one depth slice is no longer refused here (Spec ADR 0010 VZ1; the +error ``z_stack_not_supported`` of the owner decision of 5 November 2026 is removed): it is a +volume, described and recorded as one, and the hand-off is the one Z gate. Projection stays an +explicit, recorded choice (``convert --project``), never made implicitly when an image is read. """ from __future__ import annotations from collections.abc import Callable, Hashable, Mapping, Sequence -from .validation import ValidationIssue, agree, error, plural, warning +from .validation import ValidationIssue, error, plural, warning _PLANE_NAMES = {"Z": "depth slices (Z)", "T": "time points"} """What the planes along each dimension are called in messages.""" @@ -43,48 +43,6 @@ def lettered_plane_counts(axes: str, shape: Sequence[int]) -> dict[str, int]: return counts -Z_STACK_CODE = "z_stack_not_supported" -"""The error of an image with more than one depth slice (owner decision of 5 November 2026).""" - - -def z_stack_issues(slices: Mapping[str, int]) -> list[ValidationIssue]: - """Refuse every image with more than one depth slice (Z): v1 analyses 2-D planes. - - A Z axis of one slice, or none, is accepted as it is. Nothing is projected or squeezed: - the user makes recorded 2-D projected copies first with ``convert --project`` (owner - decisions of 5 and 7 November 2026; contract §2, §17). - - Parameters - ---------- - slices - The depth slices of each image, by relative path (its header's named Z, or its - confirmed Z role; 1 without one). - - Returns - ------- - list of ValidationIssue - The error :data:`Z_STACK_CODE` naming every image with more than one slice, with - its number of slices, or nothing. - """ - stacks = sorted((path, n) for path, n in slices.items() if n > 1) - if not stacks: - return [] - listed = "; ".join(f"{path}: {n} slices" for path, n in stacks[:5]) - more = f"; and {len(stacks) - 5} more" if len(stacks) > 5 else "" - return [ - error( - Z_STACK_CODE, - f"{plural(len(stacks), 'image')} {agree(stacks, 'is a Z-stack', 'are Z-stacks')} " - f"(more than one depth slice, Z): {listed}{more}. MorphoBricks v1 analyses 2-D " - "planes, so Z-stacks are not analysed.", - [path for path, _ in stacks], - "Make 2-D projected copies first: convert EXPERIMENT --to FOLDER --axes ROLES " - "--project max|mean|sum (the originals are only read), then run on the copies; " - "or exclude these images.", - ) - ] - - def channel_count_issues(counts: Mapping[str, int]) -> list[ValidationIssue]: """Report images of one imaging unit with different numbers of channels. diff --git a/tests/older_manifests.py b/tests/older_manifests.py new file mode 100644 index 00000000..c7e34de8 --- /dev/null +++ b/tests/older_manifests.py @@ -0,0 +1,34 @@ +"""Rewrite run manifest data as an older version wrote it (before Spec ADR 0010, version 7).""" + +from __future__ import annotations + +VOLUME_KEYS = ( + "shape", + "z_count", + "t_count", + "c_count", + "image_kind", + "plane_statistics", + "statistics_rows", +) + + +def as_version_6(data: dict) -> dict: + """Return manifest data as version 6 records it: no volume fields, the older size codec. + + Each entry's ``plane_count`` becomes its rows in the table (version 6's meaning), its + ``pixel_sizes`` lose ``reason`` and write a null source for ``unknown``; ``checks`` and + ``statistics_artifacts`` are removed. + """ + data["manifest_version"] = "6" + for key in ("checks", "statistics_artifacts", "z_handling"): + data.pop(key, None) + for entry in data["files"]: + entry["plane_count"] = entry.get("statistics_rows", entry["plane_count"]) + for key in VOLUME_KEYS: + entry.pop(key, None) + for size in entry["pixel_sizes"]: + size.pop("reason", None) + if size["source"] == "unknown": + size["source"] = None + return data diff --git a/tests/spec_fixtures/PIN.toml b/tests/spec_fixtures/PIN.toml index 871877aa..312e2015 100644 --- a/tests/spec_fixtures/PIN.toml +++ b/tests/spec_fixtures/PIN.toml @@ -1,7 +1,7 @@ # The MorphoBricks-Spec commit these files are copied from (conformance plan section 1). # Updating the pin is a reviewed change: see README.md in this folder. repository = "https://github.com/CellMigrationLab/MorphoBricks-Spec" -commit = "232fb38880cc487510532d99dc71d46a27005f23" +commit = "5aad8d3ecf0088e9eb443ad79dafedab86977376" # `git rev-parse :fixtures`, the git tree-object ID of the fixtures/ folder. The # vendored folder must hash to it, so one changed, added or missing byte fails a test. @@ -9,6 +9,6 @@ fixtures_tree = "3951f9d8f2129103953ad2f1c7240c9a43e004ac" # `git rev-parse :`, the git blob ID of each other vendored file. [files] -"docs/experiment-v1.md" = "33cd157b1031efd47034abafa79e8ae8cc0f5c2e" +"docs/experiment-v1.md" = "17e0a99d2df535c571c9befd31af70f2d15f641b" "tools/audit/refval.py" = "f27e37cde1429c8c9db2a96610039ef833a54214" "tools/audit/refrecords.py" = "ef06a1ea59a93c695dbba21d2ee792667ad8e8eb" diff --git a/tests/spec_fixtures/docs/experiment-v1.md b/tests/spec_fixtures/docs/experiment-v1.md index 33cd157b..17e0a99d 100644 --- a/tests/spec_fixtures/docs/experiment-v1.md +++ b/tests/spec_fixtures/docs/experiment-v1.md @@ -1,6 +1,6 @@ # MorphoBricks experiment description, schema version 1 (normative) -- **Status:** Normative specification, Stage 0 (6 November 2026). No reader implements it yet. +- **Status:** Normative specification, Stage 0 (6 November 2026). Implemented by morphobricks-preprocessing, the reference reader (pins in [pins.md](pins.md)). The fixed-SHA audit of current consumers (roadmap S0.1) is done ([PR #5](https://github.com/CellMigrationLab/MorphoBricks-Spec/pull/5), audit [`s01-consumer-audit-2026-11-06.md`](audits/s01-consumer-audit-2026-11-06.md)); the owner answered @@ -46,10 +46,22 @@ fingerprints, calibration, exclusions, per-FOV statements, axes, brick names or requests, normalization, statistics, histogram or model settings. Those stay in `calibration.csv`, the run manifest, analysis requests and MorphoCoverage configuration. -v1 analyses 2-D planes only. A Z stack is projected by a recorded preprocessing step -(preprocessing #176) before it is described; the file has no Z, axes or shared-plane field. -Time-lapses (T > 1) are allowed: the file has no T field, and the homogeneity of an imaging unit -(§8, `R_UNIT_NOT_HOMOGENEOUS`) compares what each axis means, never the number of time points. +v1 describes 2-D images and Z-stacks (volumes). An included image is a **volume** when its confirmed +`Z` role has size > 1; otherwise it is a plane image. Whether an image is a volume is a fact of the +image and its confirmed roles, recorded in the run manifest; the file has no Z, axes, shared-plane +or projection field (§4.7). A volume's Z step, like every pixel size, comes from its header or is +stated in `calibration.csv`; it is never guessed. Any space axis of any image without a length is +recorded as unknown (or `pixels`) with the warning `W_AXIS_UNCALIBRATED` naming the axis (§8), which +blocks nothing in preprocessing; a consumer that declares it needs the axis refuses (consumer +manifest, ADR 0009). Projecting a Z-stack to 2-D is an explicit, recorded preprocessing choice, +never a default. Histograms, normalization (under every scope) and QC metrics are not computed for a +volume or for its planes, which the run records per image +(`plane_statistics = "not_computed_volume"`, ADR 0010). A whole volume is handed only to a consumer +that declares `volume_support = "volumes"`; planes of a volume are handed only for Z indices the +consumer names explicitly in its request, which is recorded, and never by an implicit expansion of Z +or a projection (ADR 0002 resolver contract). Time-lapses (T > 1) are allowed: the file has no T +field. The homogeneity of an imaging unit (§8, `R_UNIT_NOT_HOMOGENEOUS`) compares what each axis +means, never the number of time points or of depth slices. ## 2. File, encoding and parsing @@ -426,6 +438,13 @@ Repeat rules: Mask files, pairing, completeness and fingerprints stay in the run manifest. A declared mask with files for none, some or all FOVs is valid (progressive segmentation, 0/1000 → 1000/1000). +A mask of a volume has the volume's depth slices (a 2-D mask is never shared by the slices of an +image) and is paired with it by recorded identity, as a mask of a plane image is. Its +`representation` holds over the whole volume: an `instances` value is one 3-D object of that FOV, +mask and time point, never identified by its value alone; a `parent_labels` value is one group over +the volume; the `binary` rule is already over all planes. A per-request conversion (§4.5c) of a mask +with more than one depth slice is refused (`A_VOLUME_NOT_SUPPORTED`, ADR 0005 BM5). + **§4.5a When the representation is checked (AQ10).** `R_MASK_CONTRADICTS_REPRESENTATION` needs mask pixels. It is checked **in the preprocessing mask step** (the step that reads mask pixels), for every mask file as it is added: for a progressive mask, **for each new batch**, on the new @@ -663,7 +682,7 @@ folder `files`) cannot be used as the **ID** (the key) but **is** describable: i | Field | Belongs to | |---|---| -| `axes`, `shared`, `plane_scope`, `z`, `projection` | Image/manifest records; v1 is 2-D only (preprocessing #173, #176) | +| `axes`, `shared`, `plane_scope`, `z`, `projection` | Image/manifest records: Z, axes and projection are facts of the images and of preprocessing's recorded conversions, never of this file (preprocessing #173, #176; ADR 0010) | | `pixel_size`, `calibration` | `calibration.csv` | | `fovs`, `files`, `paths`, `overrides`, `exclude`, `fingerprints` | Run manifest / preprocessing inputs; no per-FOV statements | | `bricks`, `routes`, `features`, `normalization`, `statistics`, `contrasts` | Analysis requests / brick and MorphoCoverage configuration | @@ -831,6 +850,11 @@ validation: a reader MUST NOT try to interpret fields of a version it does not s description (FC1), never of readers, so no field changes meaning. Under ADR 0002 AR10 nothing is converted: a published strict file stays strict until the user adopts fast mode (§10), and strict per-unit is a mode the owner kept, not compatibility code. +- **Amendment of v1 (ADR 0010).** Volumes may be described (§1). No field, type or enumeration + changes, so every file valid before stays valid with the same meaning; a preprocessing release + pinned to an earlier Spec commit refuses Z-stacks before describing them, and every other reader (a + validator of `morphobricks.toml`, a consumer) is kept from a volume run by the run-manifest version, + which it does not accept. - A migration between versions MUST be an explicit, recorded operation that writes a new file and never changes canonical identities silently. - **Repeat, condition, technical repeat and channel IDs are immutable** (§4.6) and never reused @@ -874,7 +898,7 @@ Required preprocessing refusals (`R_*`): | `R_UNIT_NOT_FOUND` | A declared imaging unit has no included image | | `R_UNIT_NOT_DECLARED` | A discovered imaging unit is not in the file (reconciliation draft required) | | `R_CHANNEL_COUNT_MISMATCH` | An image's channel count differs from its unit's list length | -| `R_UNIT_NOT_HOMOGENEOUS` | FOVs of one unit differ in channel count, image type (the effective type after a valid header override, §4.4b), interpreted axes or header names at one C index; the message names FOV, path and C index | +| `R_UNIT_NOT_HOMOGENEOUS` | FOVs of one unit differ in channel count, image type (the effective type after a valid header override, §4.4b), interpreted axes or header names at one C index; the message names FOV, path and C index. The number of time points and of depth slices is never compared: an absent `T` or `Z` role reads as one, so a unit mixing plane images and volumes is not refused here (the warning `W_MIXED_PLANES_AND_VOLUMES`, below; ADR 0010) | | `R_HEADER_CONTRADICTION` | A header name at C*i* is not, after NFC of both sides and with no trimming (§4.3), in the confirmed `header_names` of the unit's channel at *i* | | `R_IMAGE_TYPE_CONTRADICTS_HEADER` | A unit's declared image type (`rgb` or absent, §4.4b) contradicts the image header metadata, in either direction, and is not an accepted `rgb_header_override` (RH1); pixels are never examined; for a unit declared `rgb` the message names `rgb_header_override` when its images have three interleaved samples | | `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` | A unit declares `rgb_header_override = true` and one of its images does not have exactly three interleaved samples per pixel (§4.4b, RH1); pixels are never examined | @@ -915,6 +939,24 @@ image with three interleaved samples whose header contradicts `rgb`, the message `rgb_header_override` for its unit. A unit with `channels_from = "unit"` is checked as in a strict file, with the codes and precedence above. +**Volumes: recorded, not refused (ADR 0010).** (1) A run whose included images are not all plane +images or all volumes, or any condition, biological repeat or imaging unit of which holds both +kinds, is not refused by preprocessing: it records the warning `W_MIXED_PLANES_AND_VOLUMES` in the +run manifest's `checks` and in the run report, with the counts of each kind, every image of each +kind (FOV key, path, and depth slices for a volume) and every condition, repeat and unit that holds +both, and the description can be published. `R_UNIT_NOT_HOMOGENEOUS` does not compare the number of +depth slices; an absent `Z` role reads as one slice. A consumer that needs one kind per run refuses +it itself. (2) A space axis (`x`, `y`, or `z` of a volume) of any included image whose size has no +source (none in the header or `calibration.csv`, or a unit that is not a supported length) or is +stated as `pixels` is recorded with the warning `W_AXIS_UNCALIBRATED` and the axis, per image (the +`reason` of its recorded pixel size) and once per run in the run manifest's `checks` and in the run +report, with the axes and how many images lack each, every such image (FOV key, path, depth slices) +and the fix (state the step in `calibration.csv` and run again). It blocks nothing in preprocessing: +not `describe`, the run or publication; the step is never guessed, and is never written as 0, 1 or +another axis's size. A chosen consumer whose manifest requires the axis refuses +(`R_CONSUMER_DIMENSIONS_NOT_ALLOWED`, kind `calibration`). The `z` of a plane image (one depth slice +or none) is never recorded with this warning. + Undetectable by any layer: identical-shape, unnamed images with physically swapped fluorophores. Representative previews and explicit confirmation are the guard; image-based checks are advisory. diff --git a/tests/test_absent_axis_sizes.py b/tests/test_absent_axis_sizes.py index 5466960e..af59a08c 100644 --- a/tests/test_absent_axis_sizes.py +++ b/tests/test_absent_axis_sizes.py @@ -19,6 +19,7 @@ prefill_mapping, read_manifest, ) +from older_manifests import as_version_6 HEADER = {"PhysicalSizeX": 0.5, "PhysicalSizeY": 0.5, "PhysicalSizeZ": 0.43, "TimeIncrement": 2.0} @@ -60,7 +61,7 @@ def test_a_projection_records_no_z_or_t_size_from_its_header(tmp_path): assert found["T"] == none("T") assert set(report(output)["images"]["ctrl/a.ome.tif"]["pixel_sizes"]) == {"X", "Y"} inputs = RunInputs.open(output) - assert inputs.pixel_sizes("ctrl/a.ome.tif")["Z"].source is None + assert inputs.pixel_sizes("ctrl/a.ome.tif")["Z"].source == "unknown" # ADR 0010 VC4 assert "calibration_axis_absent" not in {issue.code for issue in result.issues} @@ -119,7 +120,7 @@ def test_rows_recorded_with_a_z_size_from_an_earlier_version_are_reused(tmp_path table = (output / "plane_histograms.parquet").read_bytes() # The manifest as an earlier version wrote it: the unused z-step recorded. path = output / "run_manifest.json" - data = json.loads(path.read_text(encoding="utf-8")) + data = as_version_6(json.loads(path.read_text(encoding="utf-8"))) z_step = {"role": "Z", "value": 0.43, "unit": "micrometer", "source": "header"} data["files"][0]["pixel_sizes"][2] = z_step path.write_text(json.dumps(data), encoding="utf-8") diff --git a/tests/test_audit_run_inputs.py b/tests/test_audit_run_inputs.py index c3f44866..8ab27623 100644 --- a/tests/test_audit_run_inputs.py +++ b/tests/test_audit_run_inputs.py @@ -84,7 +84,7 @@ def test_a_header_size_in_an_unsupported_unit_is_not_recorded(tmp_path, unit): assert (recorded["X"].value, recorded["X"].unit, recorded["X"].source) == (None, None, None) result = run_described(tmp_path / "exp", prefill_mapping("YX")) sizes = RunInputs.open(result.output_folder).pixel_sizes("ctrl/a.ome.tif") - assert sizes["X"].value is None and sizes["Y"].source is None + assert sizes["X"].value is None and sizes["Y"].source == "unknown" # ADR 0010 VC4 assert f"X and Y in {unit!r}" in issue(result.issues, "unsupported_pixel_size_unit").message @@ -245,7 +245,7 @@ def test_an_ome_zarr_scale_without_a_unit_is_unknown_and_named(tmp_path): assert found.paths == ("c/a.ome.zarr",) assert "c/a.ome.zarr (X and Y without a unit)" in found.message sizes = RunInputs.open(result.output_folder).pixel_sizes("c/a.ome.zarr") - assert (sizes["X"].value, sizes["Y"].value, sizes["X"].source) == (None, None, None) + assert (sizes["X"].value, sizes["Y"].value, sizes["X"].source) == (None, None, "unknown") def test_a_time_step_without_a_unit_is_not_sent_to_calibration_csv(tmp_path): diff --git a/tests/test_brick_api_surface.py b/tests/test_brick_api_surface.py index 7beb473d..1252b93f 100644 --- a/tests/test_brick_api_surface.py +++ b/tests/test_brick_api_surface.py @@ -48,10 +48,10 @@ "fovs": "(self) -> 'tuple[Fov, ...]'", "pixel_sizes": "(self, fov: 'Fov | str') -> 'dict[str, RecordedSize]'", "read_plane": ( - "(self, fov: 'Fov | str', z: 'int' = 0, t: 'int' = 0, *, " + "(self, fov: 'Fov | str', z: 'int | None' = None, t: 'int' = 0, *, " "memory_limit: 'int' = 1073741824) -> 'np.ndarray'" ), - "read_image": "(self, fov: 'Fov | str') -> 'LazyImage'", + "read_image": "(self, fov: 'Fov | str', *, volume: 'bool' = False) -> 'LazyImage'", "plane_shape": "(self, fov: 'Fov | str') -> 'tuple[int, int]'", "read_window": ( "(self, fov: 'Fov | str', *, t: 'int', z: 'int', " @@ -81,7 +81,19 @@ "bounds: 'tuple[int, int, int, int]', level: 'int' = 0, " "memory_limit: 'int' = 1073741824) -> 'WindowPlan'" ), - "histograms": "(self) -> 'tuple[PlaneRecord, ...]'", + # Spec ADR 0010 VC6, VC9: statistics refused for volumes, the whole-volume mask read, and + # a consumer's declared Z and calibration rules (ADR 0009 O9, O10). + "histograms": "(self, fovs: 'Iterable[Fov | str] | None' = None) -> 'tuple[PlaneRecord, ...]'", + "image_qc": "(self, fovs: 'Iterable[Fov | str] | None' = None) -> 'tuple[QcRow, ...]'", + "require_plane_statistics": "(self, fovs: 'Iterable[Fov | str]') -> 'None'", + "read_mask_volume": ( + "(self, fov: 'Fov | str', mask_type: 'str', *, t: 'int | None' = None, " + "memory_limit: 'int' = 1073741824) -> 'np.ndarray'" + ), + "check_consumer": ( + "(self, consumer: 'str', *, volume_support: 'str', mixed_volume_support: 'bool', " + "requires_calibration: 'Sequence[str]') -> 'None'" + ), # Spec ADR 0005 BM15: the opt-in H&E tissue mask helper (imported lazily, he-mask extra). "he_tissue_mask": ( "(self, fov: 'Fov | str', *, output_mask_id: 'str', rule: 'str' = 'he_tissue_v1') " @@ -121,7 +133,7 @@ ("experiment_root", "Path"), ("masks_root", "Path | None"), ("manifest", "RunManifest"), - ("records", "tuple[PlaneRecord, ...]"), + ("_records", "tuple[PlaneRecord, ...]"), # internal (Spec ADR 0010 VC6) ("manifest_sha256", "str | None"), # review ar, B2: additive, last, defaults to None ], Fov: [ @@ -149,6 +161,8 @@ ("planes", "str"), ("capabilities", "Capabilities"), ("device", "str"), + ("fov_subset", "tuple[tuple[str, str, str, str], ...] | None"), + ("z_indices", "tuple[int, ...] | None"), ], MaskRequest: [("mask_id", "str"), ("role", "str"), ("binary_mask_policy", "str | None")], Capabilities: [ @@ -199,6 +213,7 @@ ("section_digests", "tuple[tuple[str, str], ...]"), ("request", "Request"), ("mask_conversions", "tuple[MaskConversion, ...]"), + ("fov_scope", "dict | None"), ], MaskConversion: [ ("mask_id", "str"), @@ -276,7 +291,8 @@ def test_test_run_helper_signatures_are_pinned(helper): def test_the_resolver_names_are_exported_and_versioned(): - assert package.RESOLVER_VERSION == 3 # 3: the conversion record (Spec ADR 0005) + # 5: volumes (Spec ADR 0010), with AR12's FOV subset in one wave (version 4 never released) + assert package.RESOLVER_VERSION == 5 assert package.PARENT_LABELS_AS_AREA == "parent_labels_as_area" assert COVERAGE == ("full", "partial", "unavailable") for cls in [*FIELDS, Fov]: @@ -364,6 +380,7 @@ def test_the_run_workers_are_a_run_mode_option(): ("checking", "Callable[[str, int, int, str], None] | None", None), ("memo", "ContentMemo | None", None), # one notebook press's SHA-256s (v0.9.1) ("expected", "ExpectedSources | None", None), # Register's segmented images (bc B2) + ("keep_z_stacks", "bool | None", None), # Spec ADR 0010 VZ32: the recorded choice ] assert package.RunMode is RunMode parameters = inspect.signature(run_experiment).parameters diff --git a/tests/test_cellpose_folders_open.py b/tests/test_cellpose_folders_open.py index ea864dd8..12dfcf05 100644 --- a/tests/test_cellpose_folders_open.py +++ b/tests/test_cellpose_folders_open.py @@ -123,8 +123,8 @@ def test_open_checked_tells_every_phase_in_order_and_opens_what_open_opens(app): assert checked.fovs() == plain.fovs() assert checked.manifest_sha256 == plain.manifest_sha256 assert checked.masks_root == plain.masks_root - assert [r.plane_id for r in checked.records] == [r.plane_id for r in plain.records] - for ours, theirs in zip(checked.records, plain.records, strict=True): + assert [r.plane_id for r in checked._records] == [r.plane_id for r in plain._records] + for ours, theirs in zip(checked._records, plain._records, strict=True): for a, b in zip(ours.histograms, theirs.histograms, strict=True): assert np.array_equal(a.counts, b.counts) phases = list(dict.fromkeys(phase for phase, *_ in told)) diff --git a/tests/test_check_metadata_allow_z.py b/tests/test_check_metadata_z.py similarity index 62% rename from tests/test_check_metadata_allow_z.py rename to tests/test_check_metadata_z.py index 2caf8cb8..a7f9de76 100644 --- a/tests/test_check_metadata_allow_z.py +++ b/tests/test_check_metadata_z.py @@ -1,4 +1,4 @@ -"""check_metadata(..., allow_z=True): header checks of Z-stacks for other tools (issue #438).""" +"""Header checks of Z-stacks: a Z-stack is a volume, never refused there (Spec ADR 0010, #438).""" import numpy as np import pytest @@ -51,41 +51,32 @@ def codes(issues): return [i.code for i in issues] -def test_default_still_refuses_a_z_stack(tmp_path): +def test_a_z_stack_is_not_refused_by_the_header_checks(tmp_path): path = write_imagej(tmp_path / "a.tif") - found = [i for i in check_metadata([inspect_image(path, "a.tif")]) if i.is_error] - assert codes(found) == ["z_stack_not_supported"] - assert found[0].paths == ("a.tif",) - assert codes(inspect_images(tmp_path, ["a.tif"]).issues) == ["z_stack_not_supported"] + assert check_metadata([inspect_image(path, "a.tif")]) == [] + assert inspect_images(tmp_path, ["a.tif"]).issues == () -def test_allow_z_reports_no_z_error_for_a_clean_stack(tmp_path): +def test_allow_z_is_gone(tmp_path): path = write_imagej(tmp_path / "a.tif") - files = [inspect_image(path, "a.tif")] - assert codes(check_metadata(files)) == ["z_stack_not_supported"] - assert check_metadata(files, allow_z=True) == [] - assert inspect_images(tmp_path, ["a.tif"], allow_z=True).issues == () + with pytest.raises(TypeError): + check_metadata([inspect_image(path, "a.tif")], allow_z=True) + with pytest.raises(TypeError): + inspect_images(tmp_path, ["a.tif"], allow_z=True) -def test_allow_z_keeps_every_other_check(tmp_path): +def test_every_other_header_check_runs_on_z_stacks(tmp_path): write_imagej(tmp_path / "a.tif") write_imagej(tmp_path / "b.tif", dtype=np.uint8) # another pixel type # Two channels where the others have none. write_imagej(tmp_path / "c.tif", shape=(4, 5, 2, 32, 32), axes="TZCYX") (tmp_path / "d.tif").write_bytes(b"garbage") # unreadable names = ["a.tif", "b.tif", "c.tif", "d.tif"] - files = [inspect_image(tmp_path / n, n) for n in names] - default = codes(check_metadata(files)) - allowed = codes(check_metadata(files, allow_z=True)) - # The Z error would be reported without the flag ... - assert "z_stack_not_supported" in default - # ... and is the only difference with it. - assert "z_stack_not_supported" not in allowed - assert [c for c in default if c != "z_stack_not_supported"] == allowed + found = codes(check_metadata([inspect_image(tmp_path / n, n) for n in names])) + assert "z_stack_not_supported" not in found for code in ("unreadable_tiff", "mixed_dtypes", "different_channel_counts"): - assert code in allowed - report = inspect_images(tmp_path, names, allow_z=True) - assert codes(report.issues) == allowed + assert code in found + assert codes(inspect_images(tmp_path, names).issues) == found @pytest.mark.parametrize("writer", [write_imagej, write_ome], ids=["imagej", "ome"]) diff --git a/tests/test_cli_projection.py b/tests/test_cli_projection.py index 9e549871..0492c808 100644 --- a/tests/test_cli_projection.py +++ b/tests/test_cli_projection.py @@ -25,12 +25,7 @@ def test_convert_project_makes_copies_the_run_accepts(tmp_path, capsys): """The regression: ``--project`` did not exist, and a Z-stack could only be refused.""" exp, copies = tmp_path / "exp", tmp_path / "copies" data = stack_experiment(exp) - assert convert(exp, copies) == 1 # without --project a Z-stack is still refused - refused = capsys.readouterr().out - assert "are Z-stacks" in refused or "is a Z-stack" in refused - assert "--project max|mean|sum" in refused - assert "Fiji" not in refused and not copies.exists() - + # Without --project a Z-stack is a volume (Spec ADR 0010): projection is a choice. assert convert(exp, copies, "--project", "max", "--z-range", "1:4") == 0 text = capsys.readouterr().out assert "max projections of slices 1:4, written as 2-D OME-TIFF: 2 images" in text @@ -51,13 +46,12 @@ def test_convert_project_makes_copies_the_run_accepts(tmp_path, capsys): assert (out / "plane_histograms.parquet").is_file() -def test_the_check_of_a_z_stack_names_the_command(tmp_path, capsys): +def test_the_check_of_a_z_stack_refuses_nothing(tmp_path, capsys): + # Spec ADR 0010 VZ1: a Z-stack is a volume; projection stays an explicit, recorded choice. exp = tmp_path / "exp" stack_experiment(exp, names=("a.tif",)) - main_described(["check", str(exp), "--output", str(tmp_path / "o")]) - text = capsys.readouterr().out - assert "Z-stack" in text - assert "convert EXPERIMENT --to FOLDER --axes ROLES --project max|mean|sum" in text + assert main_described(["check", str(exp), "--output", str(tmp_path / "o")]) == 0 + assert "z_stack_not_supported" not in capsys.readouterr().out @pytest.mark.parametrize("args", [["--project"], ["--project", "median"], ["--project", "MAX"]]) diff --git a/tests/test_content_hash_default.py b/tests/test_content_hash_default.py index fc5b8ec3..c080deec 100644 --- a/tests/test_content_hash_default.py +++ b/tests/test_content_hash_default.py @@ -29,7 +29,7 @@ def test_a_run_given_no_mode_hashes_every_source_and_records_it(experiment): root, out = experiment assert run_described(root, TYX, output_folder=out).written data = settings_of(out) - assert data["manifest_version"] == "6" and data["settings"]["verify_content"] is True + assert data["manifest_version"] == "7" and data["settings"]["verify_content"] is True assert all(entry["content_sha256"] for entry in data["files"]) assert read_manifest(out / "run_manifest.json").settings.verify_content @@ -46,7 +46,7 @@ def test_an_opt_out_is_recorded_as_false_and_the_rewrite_is_not_seen(experiment) root, out = experiment assert run_described(root, TYX, output_folder=out, mode=OFF).written data = settings_of(out) - assert data["manifest_version"] == "6" and data["settings"]["verify_content"] is False + assert data["manifest_version"] == "7" and data["settings"]["verify_content"] is False assert not any("content_sha256" in entry for entry in data["files"]) rewrite_keeping_metadata(root / IMAGES[0]) again = run_described(root, output_folder=out) # the earlier run's choice is kept diff --git a/tests/test_entry_record.py b/tests/test_entry_record.py index 9a6b9053..9151e024 100644 --- a/tests/test_entry_record.py +++ b/tests/test_entry_record.py @@ -21,7 +21,7 @@ from morphobricks_preprocessing import entry_record as entry from morphobricks_preprocessing.entry_errors import EntryError from morphobricks_preprocessing.entry_settings import read_declaration, resolve_settings -from morphobricks_preprocessing.run_inputs_request import Request +from morphobricks_preprocessing.run_inputs_request import RESOLVER_VERSION, Request from morphobricks_preprocessing.testing import make_described_run from spec_pin import fixtures @@ -81,11 +81,16 @@ def _compute(run, output, **changes): def test_a_first_run_publishes_then_an_identical_one_reuses(run): output = entry.check_output_place(entry.default_output(run.output, "demo"), run.output) assert output.name == "output__demo" - assert entry.reuse_or_refuse(output, _record(run), supported_resolver_versions=(3,)) is None + assert ( + entry.reuse_or_refuse(output, _record(run), supported_resolver_versions=(RESOLVER_VERSION,)) + is None + ) published, record = _compute(run, output) assert published and not list(output.parent.glob(".output__demo.staging-*")) before = {p: p.stat().st_mtime_ns for p in output.iterdir()} - result = entry.reuse_or_refuse(output, _record(run), supported_resolver_versions=(3,)) + result = entry.reuse_or_refuse( + output, _record(run), supported_resolver_versions=(RESOLVER_VERSION,) + ) assert result.reused and result.output == output assert result.record["identity"] == record["identity"] assert {p: p.stat().st_mtime_ns for p in output.iterdir()} == before # nothing written @@ -98,13 +103,17 @@ def test_a_changed_setting_is_output_exists_naming_it(run): output = entry.default_output(run.output, "demo") _compute(run, output) with pytest.raises(EntryError) as raised: - entry.reuse_or_refuse(output, _record(run, 64), supported_resolver_versions=(3,)) + entry.reuse_or_refuse( + output, _record(run, 64), supported_resolver_versions=(RESOLVER_VERSION,) + ) assert raised.value.code == "ENTRY_OUTPUT_EXISTS" assert "settings.common.patch_size" in raised.value.subjects library = copy.deepcopy(BRICK) library["libraries"]["numpy"]["record_sha256"] = "2" * 64 # same version, another RECORD with pytest.raises(EntryError, match="brick.libraries.numpy.record_sha256"): - entry.reuse_or_refuse(output, _record(run, brick=library), supported_resolver_versions=(3,)) + entry.reuse_or_refuse( + output, _record(run, brick=library), supported_resolver_versions=(RESOLVER_VERSION,) + ) def test_another_thread_setting_is_recorded_but_reused(run): @@ -116,7 +125,7 @@ def test_another_thread_setting_is_recorded_but_reused(run): again = _record(run, brick=threads) assert again["brick"]["threads"] == threads["threads"] # recorded assert again["identity"] == record["identity"] - result = entry.reuse_or_refuse(output, again, supported_resolver_versions=(3,)) + result = entry.reuse_or_refuse(output, again, supported_resolver_versions=(RESOLVER_VERSION,)) assert result.reused @@ -138,7 +147,7 @@ def test_a_damaged_output_is_incomplete_and_kept(run, damage): else: record.write_text(record.read_text(encoding="utf-8").replace("128", "64"), "utf-8") with pytest.raises(EntryError) as raised: - entry.reuse_or_refuse(output, _record(run), supported_resolver_versions=(3,)) + entry.reuse_or_refuse(output, _record(run), supported_resolver_versions=(RESOLVER_VERSION,)) assert raised.value.code == "ENTRY_OUTPUT_INCOMPLETE" assert output.exists() # never deleted @@ -149,14 +158,14 @@ def test_uncertain_identities_are_refused(run): editable = dict(BRICK, uncertain="demo: editable install") with pytest.raises(EntryError, match="Install a released demo") as raised: entry.reuse_or_refuse( - output, _record(run, brick=editable), supported_resolver_versions=(3,) + output, _record(run, brick=editable), supported_resolver_versions=(RESOLVER_VERSION,) ) assert raised.value.code == "ENTRY_IDENTITY_UNCERTAIN" data = json.loads((output / entry.ENTRY_FILENAME).read_text(encoding="utf-8")) data["entry_version"] = 9 (output / entry.ENTRY_FILENAME).write_text(json.dumps(data), encoding="utf-8") with pytest.raises(EntryError, match="entry version 9") as raised: - entry.reuse_or_refuse(output, _record(run), supported_resolver_versions=(3,)) + entry.reuse_or_refuse(output, _record(run), supported_resolver_versions=(RESOLVER_VERSION,)) assert raised.value.code == "ENTRY_IDENTITY_UNCERTAIN" @@ -166,7 +175,7 @@ def test_a_first_run_under_an_uncertain_identity_is_published_and_never_reused(r published, record = _compute(run, output, brick=editable) assert published and record["brick"]["uncertain"] == "demo: editable install" with pytest.raises(EntryError, match="computed under an uncertain identity"): - entry.reuse_or_refuse(output, _record(run), supported_resolver_versions=(3,)) + entry.reuse_or_refuse(output, _record(run), supported_resolver_versions=(RESOLVER_VERSION,)) def test_an_unsupported_resolver_version_is_refused(run): @@ -182,7 +191,7 @@ def test_a_moved_experiment_is_reused_only_when_content_verified(run, tmp_path, moved = run.experiment.rename(tmp_path / "elsewhere") # The run verified content: a moved folder with equal content is reused (E6). reused = entry.reuse_or_refuse( - output, _record(run, experiment=moved), supported_resolver_versions=(3,) + output, _record(run, experiment=moved), supported_resolver_versions=(RESOLVER_VERSION,) ) assert reused.reused # Known by fingerprint only: never reused from another location. @@ -195,7 +204,7 @@ def fingerprints(inputs, images, masks=()): monkeypatch.setattr(entry, "source_part", fingerprints) with pytest.raises(EntryError, match="was not content-verified") as raised: entry.reuse_or_refuse( - output, _record(run, experiment=moved), supported_resolver_versions=(3,) + output, _record(run, experiment=moved), supported_resolver_versions=(RESOLVER_VERSION,) ) assert raised.value.code == "ENTRY_IDENTITY_UNCERTAIN" @@ -206,7 +215,9 @@ def test_of_two_publications_exactly_one_wins(run): second, _ = _compute(run, output) assert (first, second) == (True, False) assert not list(output.parent.glob(".output__demo.staging-*")) # the loser's removed - assert entry.reuse_or_refuse(output, _record(run), supported_resolver_versions=(3,)).reused + assert entry.reuse_or_refuse( + output, _record(run), supported_resolver_versions=(RESOLVER_VERSION,) + ).reused def test_the_output_place_is_checked(run, tmp_path): diff --git a/tests/test_image_qc_run.py b/tests/test_image_qc_run.py index 90bb8580..c064df59 100644 --- a/tests/test_image_qc_run.py +++ b/tests/test_image_qc_run.py @@ -34,6 +34,7 @@ from morphobricks_preprocessing.planes import plane_layout from morphobricks_preprocessing.run import RunMode from morphobricks_preprocessing.run.staging import STAGING_FOLDER +from older_manifests import as_version_6 from qc_tree import ( CTYX, IMAGES, @@ -144,8 +145,8 @@ def test_rows_are_recomputed_when_the_earlier_table_cannot_be_reused( table.write_bytes(good.replace(b"measured", b"measured", 1) + b"\n") elif damage == "delete": table.unlink() - elif damage == "unrecorded": - del data["image_qc"] + elif damage == "unrecorded": # an older manifest (version 7 always records image_qc) + del as_version_6(data)["image_qc"] else: data["image_qc"]["qc_version"] = "0" manifest_path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") diff --git a/tests/test_manifest.py b/tests/test_manifest.py index db3661c1..304184a4 100644 --- a/tests/test_manifest.py +++ b/tests/test_manifest.py @@ -17,6 +17,7 @@ write_manifest, ) from morphobricks_preprocessing.image_names import position_id +from morphobricks_preprocessing.image_qc_record import image_qc_entry from morphobricks_preprocessing.manifest import ( file_entry_for, file_sha256, @@ -26,6 +27,8 @@ from morphobricks_preprocessing.recorded_sizes import SIZE_ROLES, RecordedSize from tiff_tree import write_tiff +IMAGE_QC = image_qc_entry("2" * 64) + def entry(path="cond/rep/a.tif", **kwargs): values = { @@ -34,14 +37,14 @@ def entry(path="cond/rep/a.tif", **kwargs): "mtime_ns": 1_700_000_000_123_456_789, "labels": ("cond", "rep", "single"), "axes": "ZYX", - "plane_count": 3, + "shape": (1, 6, 8), # a plane image with a one-slice Z (Spec ADR 0010) "roles": ("Z", "Y", "X"), "axes_from": "header", "position_id": position_id(path), "channel_ids": ("DNA",), "pixel_sizes": tuple(RecordedSize(role) for role in SIZE_ROLES), # one per role (#389) } - return FileEntry(**{**values, **kwargs}) + return FileEntry(**{**values, **kwargs}).with_acquisition() def manifest(**kwargs): @@ -60,6 +63,9 @@ def manifest(**kwargs): "versions": {"numpy": "2.0"}, "written_at": "2026-10-17T12:00:00+00:00", "experiment_description": description_entry(), + "image_qc": IMAGE_QC, + "checks": (), + "statistics_artifacts": {"state": "computed"}, } return RunManifest(**{**values, **kwargs}) @@ -79,7 +85,7 @@ def test_written_json_is_readable_and_stable(tmp_path): raw = path.read_bytes() assert b"\r\n" not in raw and raw.endswith(b"\n") data = json.loads(raw) - assert data["manifest_version"] == "6" and data["schema_version"] == "6" + assert data["manifest_version"] == "7" and data["schema_version"] == "6" assert "csv_sha256" not in data and data["histogram_table_content_sha256"] == "1" * 64 assert data["axis_mapping"] == {"axes": "ZYX", "roles": ["Z", "Y", "X"]} assert data["settings"]["exclude"] == ["a.tif", "b.tif"] @@ -165,7 +171,7 @@ def test_image_type_round_trips_and_is_none_when_absent(tmp_path): assert read_manifest(path) == original data = json.loads(path.read_bytes()) assert (data["image_type"], data["channels_from_rgb_samples"]) == ("rgb", True) - assert data["manifest_version"] == "6" + assert data["manifest_version"] == "7" del data["image_type"], data["channels_from_rgb_samples"] # written before P4 path.write_text(json.dumps(data), encoding="utf-8") read = read_manifest(path) diff --git a/tests/test_manifest_v2.py b/tests/test_manifest_v2.py index a0350d37..333553fc 100644 --- a/tests/test_manifest_v2.py +++ b/tests/test_manifest_v2.py @@ -67,13 +67,21 @@ def test_version_2_records_roles_their_source_and_pixel_sizes(tmp_path): mode=RunMode("restart", verify_content=False), ) data = json.loads(result.manifest_path.read_text(encoding="utf-8")) - assert data["manifest_version"] == MANIFEST_VERSION == "6" + assert data["manifest_version"] == MANIFEST_VERSION == "7" (entry,) = data["files"] assert entry["roles"] == ["T", "Y", "X"] and entry["axes_from"] == "header" sizes = {size["role"]: size for size in entry["pixel_sizes"]} - assert sizes["X"] == {"role": "X", "value": 0.5, "unit": "micrometer", "source": "header"} + x = {"role": "X", "value": 0.5, "unit": "micrometer", "source": "header", "reason": None} + assert sizes["X"] == x assert sizes["Y"]["value"] == 0.25 - assert sizes["Z"] == {"role": "Z", "value": None, "unit": None, "source": None} + # Version 7 (Spec ADR 0010 VC4): "unknown", and no reason for the Z of a plane image. + assert sizes["Z"] == { + "role": "Z", + "value": None, + "unit": None, + "source": "unknown", + "reason": None, + } assert data["conversion_record_sha256"] is None diff --git a/tests/test_manifest_version.py b/tests/test_manifest_version.py index ef593f70..185a5770 100644 --- a/tests/test_manifest_version.py +++ b/tests/test_manifest_version.py @@ -1,4 +1,4 @@ -"""Run manifest version "6" is written; "6" and "5" are read (Spec ADR 0008, owner decision 10). +"""Run manifest version "7" is written (Spec ADR 0010); "7", "6" and "5" are read (decision 10). Version 6 records the histogram table's two digests, ``histogram_table_sha256`` (file bytes) and ``histogram_table_content_sha256`` (content, PQ6), both mandatory, and never ``csv_sha256``. @@ -29,6 +29,7 @@ ) from morphobricks_preprocessing.manifest import ManifestFormatError, file_sha256 from morphobricks_preprocessing.manifest_versions import MANIFEST_VERSION, check_version +from older_manifests import as_version_6 from strict_tree import IMAGES, STRICT, TYX, write_experiment @@ -46,12 +47,12 @@ def _write(out, data): @pytest.mark.parametrize("verify_content", [True, False]) -def test_every_run_writes_version_6_with_its_description(experiment, verify_content): +def test_every_run_writes_version_7_with_its_description(experiment, verify_content): root, out = experiment mode = RunMode("restart", verify_content=verify_content) assert run_described(root, TYX, output_folder=out, mode=mode).written data = _data(out) - assert data["manifest_version"] == MANIFEST_VERSION == "6" + assert data["manifest_version"] == MANIFEST_VERSION == "7" assert data["schema_version"] == "6" and "csv_sha256" not in data table = out / "plane_histograms.parquet" assert data["histogram_table_sha256"] == file_sha256(table) @@ -60,7 +61,7 @@ def test_every_run_writes_version_6_with_its_description(experiment, verify_cont assert data["experiment_description"]["sha256"] assert data["settings"]["verify_content"] is verify_content assert all(bool(e.get("content_sha256")) is verify_content for e in data["files"]) - assert RunInputs.open(out).manifest.manifest_version == "6" + assert RunInputs.open(out).manifest.manifest_version == "7" def test_turning_content_verification_off_recomputes_every_row(experiment): @@ -71,10 +72,10 @@ def test_turning_content_verification_off_recomputes_every_row(experiment): off = run_described(root, output_folder=out, mode=RunMode("restart", verify_content=False)) assert off.written and off.read == tuple(IMAGES) assert off.rebuild_reason == "content verification (verify_content) was turned off" - assert _data(out)["manifest_version"] == "6" + assert _data(out)["manifest_version"] == "7" -@pytest.mark.parametrize("version", ["1", "2", "3", "4", "7"]) +@pytest.mark.parametrize("version", ["1", "2", "3", "4", "8"]) def test_any_other_version_is_refused_naming_the_fix(experiment, version): root, out = experiment assert run_described(root, TYX, output_folder=out).written @@ -89,6 +90,20 @@ def test_any_other_version_is_refused_naming_the_fix(experiment, version): assert raised.value.code == "RUN_FOLDER_VERSION" # Spec ADR 0007 +def test_a_version_6_run_is_read_for_its_inputs_and_refused_by_run_inputs(experiment): + # Spec ADR 0010: no reader takes a Z extent from rows again; a new run reuses the rows. + root, out = experiment + assert run_described(root, TYX, output_folder=out).written + _write(out, as_version_6(_data(out))) + assert read_manifest(out / "run_manifest.json").manifest_version == "6" + with pytest.raises(RunInputsError, match="run manifest version 6; this one reads 7") as raised: + RunInputs.open(out) + assert raised.value.code == "RUN_FOLDER_VERSION" + again = run_described(root, TYX, output_folder=out) + assert again.written and again.read == () # the rows of the version 6 run are reused + assert RunInputs.open(out).manifest.manifest_version == "7" + + def test_a_refused_older_manifest_is_replaced_by_the_next_run(experiment): root, out = experiment assert run_described(root, TYX, output_folder=out).written @@ -98,7 +113,7 @@ def test_a_refused_older_manifest_is_replaced_by_the_next_run(experiment): _write(out, data) again = run_described(root, TYX, output_folder=out) assert again.written and again.read == tuple(IMAGES) # nothing reused from it - assert _data(out)["manifest_version"] == "6" + assert _data(out)["manifest_version"] == "7" @pytest.mark.parametrize( @@ -126,7 +141,7 @@ def test_a_version_6_manifest_needs_both_digests_and_no_csv_sha256(experiment, c def as_version_5(out): """Rewrite a run folder as a version 5 run: its manifest and a plane_histograms.csv.""" - data = _data(out) + data = as_version_6(_data(out)) table = out / "plane_histograms.parquet" old = out / "plane_histograms.csv" old.write_bytes((DATA / "golden_float32.csv").read_bytes()) @@ -158,7 +173,7 @@ def test_a_version_5_run_is_read_and_refused_with_the_fix_then_recomputed(experi assert again.rebuild_reason == "the earlier table uses a different format version" assert not old.exists() and (out / "plane_histograms.parquet").exists() assert any(r.startswith("plane_histograms.csv") for r in again.replaced), again.replaced - assert RunInputs.open(out).manifest.manifest_version == "6" + assert RunInputs.open(out).manifest.manifest_version == "7" def test_a_version_5_manifest_is_never_written(experiment, tmp_path): @@ -166,7 +181,7 @@ def test_a_version_5_manifest_is_never_written(experiment, tmp_path): assert run_described(root, TYX, output_folder=out).written as_version_5(out) manifest = read_manifest(out / "run_manifest.json") - with pytest.raises(ValueError, match="only a version 6 manifest"): + with pytest.raises(ValueError, match="only a version 7 manifest"): write_manifest(manifest, tmp_path / "m.json") diff --git a/tests/test_masks.py b/tests/test_masks.py index c6c053dc..e8e87d85 100644 --- a/tests/test_masks.py +++ b/tests/test_masks.py @@ -370,7 +370,7 @@ def test_a_2d_mask_of_a_time_lapse_or_z_stack_is_refused(tmp_path): mismatch = next(i for i in result.issues if i.code == "mask_planes_mismatch") assert mismatch.paths == ("Cells/ctrl/a.tif",) assert "a 2-D mask fits only an image with one plane" in mismatch.message - assert not result.written and ("z_stack" in str(codes(result.issues))) == (roles == "ZYX") + assert not result.written and "z_stack_not_supported" not in codes(result.issues) def test_a_mask_with_the_images_time_points_is_accepted_and_recorded(tmp_path, no_pixel_reads): diff --git a/tests/test_notebook_cellpose.py b/tests/test_notebook_cellpose.py index c395d5c0..a2d2861e 100644 --- a/tests/test_notebook_cellpose.py +++ b/tests/test_notebook_cellpose.py @@ -495,7 +495,7 @@ def test_one_line_after_the_batch_says_what_comes_next_and_the_masks_pass_a_reru (run.out / "morphobricks.toml").write_bytes(run.data + MASKS_SECTION) again = run_described(run.experiment, MAPPING, output_folder=run.out, masks_folder=run.masks) assert again.written, [(i.code, i.message) for i in again.issues] - assert sorted(i.code for i in again.issues) == [] + assert sorted(i.code for i in again.issues) == ["W_AXIS_UNCALIBRATED"] # ADR 0010 reopened = RunInputs.open(check_masks(run.out)) assert reopened.mask_types() == ("Cells",) assert images_to_segment(reopened, "Cells", run.masks) == () diff --git a/tests/test_notebook_projection.py b/tests/test_notebook_projection.py index 6ea83ce0..f04fa9a6 100644 --- a/tests/test_notebook_projection.py +++ b/tests/test_notebook_projection.py @@ -1,10 +1,11 @@ """Z and T in the shipped notebook (owner, 11 November 2026). -A time-lapse goes through the steps as it is (one plane per time point). A Z-stack is refused -as before (``z_stack_not_supported``) and the Axes step offers the recorded way on: the user -chooses the projection (no default), one click writes the projected copies with their -conversion record into the output folder, and the later steps use the copies. The original -stacks are only read and stay recorded; the 3-D option is shown greyed with its reason. +A time-lapse goes through the steps as it is (one plane per time point). For a Z-stack the Axes +step asks for an explicit choice with no default (Spec ADR 0010 VZ1): keep the 3-D stacks (they +are described as volumes; histograms, normalization and QC are not computed for them), or choose +the projection, and one click writes the projected copies with their conversion record into the +output folder, and the later steps use the copies. The original stacks are only read and stay +recorded. """ import hashlib @@ -27,7 +28,7 @@ from morphobricks_preprocessing import notebook_style as ui # noqa: E402 from morphobricks_preprocessing.notebook_projection import ( # noqa: E402 KEEP_3D, - NOT_ENABLED, + NOT_COMPUTED, copies_folder, earlier_projections, projection_words, @@ -94,7 +95,7 @@ def test_a_time_lapse_goes_through_every_step_one_plane_per_time_point(tmp_path) def test_a_z_stack_offers_the_projection_and_chooses_nothing(tmp_path): nb, root, out, _ = started(tmp_path, "ZCYX", (5, 3, 16, 16)) - assert "z stack not supported" in _text(nb.axis_status.value) # the refusal is still shown + assert "z stack not supported" not in _text(nb.axis_status.value) # a volume (ADR 0010) assert ui.is_visible(nb.projection_card) and not ui.is_visible(nb.quick_card) assert nb.projection_method.value == "" # no default method assert (nb.projection_first.value, nb.projection_last.value) == (0, 4) @@ -102,8 +103,8 @@ def test_a_z_stack_offers_the_projection_and_chooses_nothing(tmp_path): said = _text(nb.projection_blocker.value) assert "no projection method is chosen" in said and "the example is not ticked" in said assert "choose a projection under Z-stacks below" in _text(nb.confirm_blocker.value) - keep = nb.projection_keep # 3-D kept compatible: shown, greyed, with its reason - assert keep.description == KEEP_3D and keep.disabled and not keep.value + keep = nb.projection_keep # keeping the stacks is the other choice (ADR 0010): no default + assert keep.description == KEEP_3D and not keep.disabled and not keep.value card = _text( " ".join( getattr(w, "value", "") or "" @@ -111,7 +112,7 @@ def test_a_z_stack_offers_the_projection_and_chooses_nothing(tmp_path): if isinstance(getattr(w, "value", None), str) ) ) - assert NOT_ENABLED in card and "never changed, moved or deleted" in card + assert NOT_COMPUTED in card and "never changed, moved or deleted" in card assert nb._write_projection() is None and not out.joinpath("projected_max").exists() nb.projection_method.value = "max" assert nb.projection_button.disabled # the roles are the user's: the example first @@ -124,6 +125,49 @@ def test_a_z_stack_offers_the_projection_and_chooses_nothing(tmp_path): assert not list(out.glob("projected_*")) and digests(root) # nothing written so far +def test_keeping_the_stacks_describes_them_as_volumes(tmp_path): + nb, _root, out, _ = started(tmp_path, "ZCYX", (5, 3, 16, 16)) + nb.preview_checked.button.click() + assert nb.confirm_button.disabled # neither choice made: no default + assert "tick Keep the 3-D stacks" in _text(nb.confirm_blocker.value) + nb.projection_keep.value = True + assert not nb.confirm_button.disabled and nb.projection_button.disabled + nb.confirm_button.click() + answer_all(nb) + assert nb.save_experiment() + assert "not computed: volume" in _text(nb.plan.value) + result = nb.run() + assert result.written and len(result.volumes) == len(FOLDERS) and result.plane_count == 0 + assert "not computed: volume" in _text(nb.run_status.value) + assert not (out / "plane_histograms.parquet").exists() + + +def test_a_mixed_experiment_is_said_at_the_choice_and_in_the_run_summary(tmp_path): + # VZ4, VZ19 (owner, 2 December 2026): checked and said where the user decides, never refused. + root, out = tmp_path / "exp", tmp_path / "out" + write_stacks(root, "ZCYX", (5, 3, 16, 16)) + plane = np.ones((3, 16, 16), np.uint16) + meta = {"axes": "CYX", "Channel": {"Name": NAMES}, "PhysicalSizeX": 0.3, "PhysicalSizeY": 0.3} + tifffile.imwrite(root / FOLDERS[0] / "a.tif", plane, ome=True, metadata=meta) + nb = PreprocessingNotebook(str(root), output_folder=str(out)) + nb.steps() + nb.scan_button.click() + nb.check_button.click() + nb.missing_as_singleton.button.click() + said = _text(nb.projection_mixed.value) + assert "mixes 1 plane image(s) and 3 volume(s)" in said and "condition ctrl" in said + assert "Split it into two experiments" in said and "mixes" in _text(nb.axis_status.value) + nb.preview_checked.button.click() + nb.projection_keep.value = True + nb.confirm_button.click() + answer_all(nb) + assert nb.save_experiment() + result = nb.run() + assert result.written # warned, never refused + assert "W_MIXED_PLANES_AND_VOLUMES" in {i.code for i in result.issues} + assert "mixes 1 plane image(s) and 3 volume(s)" in _text(nb.run_issues.value) + + def _all(widget): yield widget for child in getattr(widget, "children", ()): diff --git a/tests/test_notebook_tag_by_repeat_drafts.py b/tests/test_notebook_tag_by_repeat_drafts.py index d24839eb..e54c1131 100644 --- a/tests/test_notebook_tag_by_repeat_drafts.py +++ b/tests/test_notebook_tag_by_repeat_drafts.py @@ -18,7 +18,10 @@ from dataclasses import replace # noqa: E402 from morphobricks_preprocessing.description_file import DRAFT_FILENAME # noqa: E402 -from morphobricks_preprocessing.draft_format import answers_from_bytes, answers_to_bytes # noqa: E402 +from morphobricks_preprocessing.draft_format import ( # noqa: E402 + answers_from_bytes, + answers_to_bytes, +) from test_notebook_channels import set_labels # noqa: E402 from test_notebook_check_save import opened # noqa: E402 from test_notebook_tag_by_repeat import EXTRA # noqa: E402 diff --git a/tests/test_planes.py b/tests/test_planes.py index abbb2b85..265ee444 100644 --- a/tests/test_planes.py +++ b/tests/test_planes.py @@ -112,7 +112,7 @@ def test_planes_match_the_source(tmp_path, page_reads, shape, axes, kwargs, role if roles is not None: mapping = AxisMapping(info.axes, roles) review = review_axes([info], mapping) - found = [i.code for i in review.issues if i.code != "z_stack_not_supported"] # run's + found = [i.code for i in review.issues] # A plain stack is read with the confirmed roles, with the axes_not_named warning. assert found == (["axes_not_named"] if axes is None else []) @@ -186,7 +186,7 @@ def test_confirmed_missing_axis_gets_coordinate_zero(tmp_path): part = write_data(tmp_path / "b.tif", data, axes="ZYX") report = inspect_images(tmp_path, ["a.tif", "b.tif"]) review = review_axes(report, prefill_mapping("ZTYX"), missing_as_singleton=True) - assert {i.code for i in review.issues} == {"z_stack_not_supported"} + assert {i.code for i in review.issues} == set() # a volume (Spec ADR 0010), not an error planes = list(iter_planes(part, review.file_mappings["b.tif"])) assert [p.coordinates for p in planes] == [{"z": z, "c": None, "t": 0} for z in range(2)] diff --git a/tests/test_2d_planes_only.py b/tests/test_planes_and_volumes.py similarity index 76% rename from tests/test_2d_planes_only.py rename to tests/test_planes_and_volumes.py index 65b648cc..e05bddd1 100644 --- a/tests/test_2d_planes_only.py +++ b/tests/test_planes_and_volumes.py @@ -1,9 +1,9 @@ -"""MorphoBricks v1 is 2-D per plane (owner decision of 5 November 2026, tracker row 36). +"""Planes and volumes (Spec ADR 0010; before it, owner decision of 5 November 2026, row 36). -1. An image with more than one depth slice is refused (``z_stack_not_supported``) before - anything but the report is written, whatever route names its Z axis: an ImageJ - hyperstack, an OME-TIFF, tifffile's shaped metadata, an OME-Zarr image, or a plain - stack whose roles the user confirms. Every such image is named. Z = 1 is accepted. +1. An image with more than one depth slice is a volume: described and run without projection + (``z_stack_not_supported`` is removed, VZ1), whatever route names its Z axis: an ImageJ + hyperstack, an OME-TIFF, tifffile's shaped metadata, an OME-Zarr image, or a plain stack + whose roles the user confirms. Z = 1 is a plane image. 2. A time-lapse is accepted when its masks have its time points; a 2-D mask of a time-lapse is refused, saying the masks need the same T. The stated shared 2-D mask (``--mask-axes TYPE=YX``) is removed: refused with ``shared_mask_not_supported``. @@ -28,6 +28,7 @@ from morphobricks_preprocessing.run.recorded import recorded_mask_axes from morphobricks_preprocessing.run_inputs import RunInputs from tiff_tree import write_data, write_plain +from volume_tree import KEEP Z_STACK = "z_stack_not_supported" SHARED = "shared_mask_not_supported" @@ -61,7 +62,7 @@ def written_outputs(out): return sorted(p.name for p in out.iterdir()) if out.exists() else [] -# 1. Z > 1 is refused, by every route that names a Z axis ------------------------------- +# 1. Z > 1 is a volume, by every route that names a Z axis -------------------------------- def write_named(route, path, slices): @@ -74,100 +75,79 @@ def write_named(route, path, slices): write_data(path, data, "ZCYX") +def volume_kinds(out): + data = json.loads((out / "run_manifest.json").read_text(encoding="utf-8")) + return {e["relative_path"]: (e["image_kind"], e["z_count"]) for e in data["files"]} + + @pytest.mark.parametrize("route", ["imagej", "ome", "shaped"]) -def test_a_named_z_stack_is_refused_from_its_header(tmp_path, route): +def test_a_named_z_stack_is_described_and_run_as_a_volume(tmp_path, route): root, out = tmp_path / "exp", tmp_path / "out" write_named(route, root / "ctrl/r1/a.tif", 3) write_named(route, root / "ctrl/r1/b.tif", 4) - pre = preflight(root) - issue = one(pre.metadata.issues, Z_STACK) # before any role is confirmed - assert issue.is_error and issue.paths == ("ctrl/r1/a.tif", "ctrl/r1/b.tif") - assert "ctrl/r1/a.tif: 3 slices" in issue.message and "b.tif: 4 slices" in issue.message - assert "2-D planes" in issue.message and "project" in issue.action.lower() - result = run_described(root, AxisMapping("ZCYX", "ZCYX"), output_folder=out) - assert not result.written and Z_STACK in errors(result.issues) - # Nothing but the report: no table, no manifest. - assert "plane_histograms.parquet" not in written_outputs(out) - assert "run_manifest.json" not in written_outputs(out) - - -def test_every_z_stack_is_named_not_only_the_first(tmp_path): - root = tmp_path / "exp" - paths = [f"ctrl/r{i}/a.tif" for i in range(7)] - for path in paths: - write_named("shaped", root / path, 2) - issue = one(preflight(root).metadata.issues, Z_STACK) - assert issue.paths == tuple(paths) - assert "7 images are Z-stacks" in issue.message and "and 2 more" in issue.message + assert Z_STACK not in {i.code for i in preflight(root).issues} + result = run_described(root, AxisMapping("ZCYX", "ZCYX"), output_folder=out, mode=KEEP) + assert result.written, result.issues + assert result.volumes == ("ctrl/r1/a.tif", "ctrl/r1/b.tif") + assert volume_kinds(out) == {"ctrl/r1/a.tif": ("volume", 3), "ctrl/r1/b.tif": ("volume", 4)} + assert "plane_histograms.parquet" not in written_outputs(out) # volumes only: no table -def test_check_refuses_a_z_stack_and_writes_only_the_report(tmp_path, capsys): +def test_check_names_no_z_stack_error(tmp_path, capsys): root, out = tmp_path / "exp", tmp_path / "out" write_named("ome", root / "ctrl/r1/a.ome.tif", 3) - assert main_described(["check", str(root), "--output", str(out)]) == 1 - printed = capsys.readouterr().out - assert "1 image is a Z-stack" in printed and "--project max|mean|sum" in printed + assert main_described(["check", str(root), "--output", str(out)]) == 0 report = json.loads((out / "discovery_report.json").read_text(encoding="utf-8")) - assert Z_STACK in {i["code"] for i in report["issues"] if i["severity"] == "error"} - assert "plane_histograms.parquet" not in written_outputs(out) + assert Z_STACK not in {i["code"] for i in report["issues"]} -def test_a_plain_stack_confirmed_with_a_z_role_is_refused(tmp_path): +def test_a_plain_stack_confirmed_with_a_z_role_is_a_volume(tmp_path): root = tmp_path / "exp" write_plain(root / "ctrl/a.tif", np.zeros((3, 6, 8), np.uint8)) - assert Z_STACK not in {i.code for i in preflight(root).metadata.issues} # unnamed yet review = review_axes(preflight(root).metadata, AxisMapping("IYX", "ZYX")) - assert one(review.issues, Z_STACK).paths == ("ctrl/a.tif",) - result = run_described(root, AxisMapping("IYX", "ZYX")) - assert not result.written and Z_STACK in errors(result.issues) - # The same stack confirmed as time points is a time-lapse, and is analysed. - assert run_described(root, AxisMapping("IYX", "TYX")).written + assert review.ok + result = run_described(root, AxisMapping("IYX", "ZYX"), mode=KEEP) + assert result.written and result.volumes == ("ctrl/a.tif",) + # The same stack confirmed as time points is a time-lapse of plane images. + assert run_described(root, AxisMapping("IYX", "TYX")).volumes == () def test_a_header_z_confirmed_as_time_is_the_axis_error_that_convert_fixes(tmp_path): # An ImageJ stack of time points that tifffile reads as Z slices (likely_axis_cause): # confirmed as T it is never read under the contradicted header, and its named-axis - # copy (TYX) is a time-lapse the run accepts. A Z-stack error here would block the fix. + # copy (TYX) is a time-lapse the run accepts. root, out = tmp_path / "exp", tmp_path / "out" imagej(root / "ctrl/a.tif", np.zeros((3, 6, 8), np.uint8), "ZYX") pre = preflight(root) - assert Z_STACK in {i.code for i in pre.metadata.issues} # the header alone: a Z-stack review = review_axes(pre.metadata, AxisMapping("ZYX", "TYX")) combined = {i.code for i in review.combined_issues(pre.metadata) if i.is_error} assert combined == {"axes_contradict_header"} copies = tmp_path / "copies" assert main(["convert", str(root), "--to", str(copies), "--axes", "TYX"]) == 0 assert run_described(copies, AxisMapping("TYX", "TYX"), output_folder=out).written - # Confirmed as the depth its header names, it is a Z-stack. - refused = review_axes(pre.metadata, AxisMapping("ZYX", "ZYX")) - assert one(refused.issues, Z_STACK).paths == ("ctrl/a.tif",) + # Confirmed as the depth its header names, it is a volume. + assert review_axes(pre.metadata, AxisMapping("ZYX", "ZYX")).ok -def test_the_review_supersedes_the_header_error(tmp_path): - root = tmp_path / "exp" - write_named("shaped", root / "ctrl/a.tif", 3) - pre = preflight(root) - review = review_axes(pre.metadata, AxisMapping("ZCYX", "ZCYX")) - assert [i.code for i in review.combined_issues(pre.metadata)].count(Z_STACK) == 1 - - -def test_an_ome_zarr_z_stack_is_refused(tmp_path): +def test_an_ome_zarr_z_stack_is_a_volume(tmp_path): from zarr_tree import write_ngff root = tmp_path / "exp" write_ngff(root / "ctrl/a.ome.zarr", np.zeros((2, 3, 6, 8), np.uint16), "czyx") - assert one(preflight(root).metadata.issues, Z_STACK).paths == ("ctrl/a.ome.zarr",) - result = run_described(root, AxisMapping("CZYX", "CZYX")) - assert not result.written and Z_STACK in errors(result.issues) + assert Z_STACK not in {i.code for i in preflight(root).metadata.issues} + result = run_described(root, AxisMapping("CZYX", "CZYX"), mode=KEEP) + assert result.written and result.volumes == ("ctrl/a.ome.zarr",) + (fov,) = RunInputs.open(result.output_folder).fovs() + assert (fov.z_count, fov.c_count) == (3, 2) -def test_convert_refuses_a_z_stack_too(tmp_path, capsys): +def test_convert_makes_named_axis_copies_of_a_z_stack(tmp_path): root = tmp_path / "exp" - write_plain(root / "ctrl/a.tif", np.zeros((3, 6, 8), np.uint8)) + write_plain(root / "ctrl/a.tif", np.arange(3 * 6 * 8, dtype=np.uint8).reshape(3, 6, 8)) args = ["convert", str(root), "--to", str(tmp_path / "copies"), "--axes", "ZYX"] - assert main_described(args) == 1 - assert "1 image is a Z-stack" in capsys.readouterr().out - assert not (tmp_path / "copies/ctrl/a.tif").exists() + assert main_described(args) == 0 + with tifffile.TiffFile(tmp_path / "copies/ctrl/a.tif") as tif: + assert tif.series[0].axes == "ZYX" and tif.series[0].shape == (3, 6, 8) # Z = 1 stays allowed --------------------------------------------------------------------- diff --git a/tests/test_projection_convert.py b/tests/test_projection_convert.py index 16531f15..4512ddfc 100644 --- a/tests/test_projection_convert.py +++ b/tests/test_projection_convert.py @@ -63,11 +63,8 @@ def test_project_max_makes_a_z_stack_analysable(tmp_path): data = stack_experiment(exp) source = exp / NAMES[0] before = file_sha256(source) - # Without a projection the stack is still refused, by the check and by convert. - assert "z_stack_not_supported" in codes(preflight(exp, tmp_path / "o").metadata.issues) - refused = convert_experiment(exp, ZCYX, tmp_path / "plain") - assert not refused.written and "z_stack_not_supported" in codes(refused.issues) - assert not (tmp_path / "plain").exists() or not tree_files(tmp_path / "plain") + # Without a projection the stack is a volume (Spec ADR 0010): nothing refuses it. + assert "z_stack_not_supported" not in codes(preflight(exp, tmp_path / "o").metadata.issues) result = convert_experiment(exp, ZCYX, copies, projection=Projection("max")) @@ -186,9 +183,7 @@ def test_another_method_or_range_into_the_same_tree_is_refused(tmp_path): for other in (Projection("mean"), Projection("max", (0, 3)), None): result = convert_experiment(exp, ZCYX, copies, projection=other) assert not result.written, other - assert "copy_differs" in codes(result.issues) or "z_stack_not_supported" in codes( - result.issues - ) + assert "copy_differs" in codes(result.issues) result = convert_experiment(exp, ZCYX, copies, projection=Projection("mean")) assert "holds max projections of all slices" in result.issues[0].message assert "asked for mean projections" in result.issues[0].message diff --git a/tests/test_publication_removes.py b/tests/test_publication_removes.py index 29fa3c2c..4b636540 100644 --- a/tests/test_publication_removes.py +++ b/tests/test_publication_removes.py @@ -28,7 +28,7 @@ def committed(out, removes): "removes", [ ["../outside.txt"], - ["plane_histograms.parquet"], + ["design.csv"], # the tables are removable since Spec ADR 0010 VC1 (volumes only) [MANIFEST_FILENAME], [MASK_REPORT, "../outside.txt"], # one allowed entry does not excuse another ["sub/mask_relationships.json"], diff --git a/tests/test_read_arguments.py b/tests/test_read_arguments.py index 0ab2d284..0083184d 100644 --- a/tests/test_read_arguments.py +++ b/tests/test_read_arguments.py @@ -28,7 +28,8 @@ def stack(tmp_path_factory): @pytest.mark.parametrize("value", ["ctrl/rep1/a.ome.tif::z=0,t=0", "0", 0.0, 1.5, True, None]) def test_read_plane_refuses_a_z_or_t_that_is_not_an_integer(flat, value): fov = flat.fovs()[0] - for kwargs in ({"z": value}, {"t": value}): + # z=None is no z: z = 0 on a plane image, refused on a volume (Spec ADR 0010 B2). + for kwargs in ({"z": value}, {"t": value}) if value is not None else ({"t": value},): with pytest.raises(TypeError, match=r"read_plane\(fov, z, t\).*whole numbers"): flat.read_plane(fov, **kwargs) diff --git a/tests/test_recorded_sizes_strict.py b/tests/test_recorded_sizes_strict.py index aef00426..9cc8ebe4 100644 --- a/tests/test_recorded_sizes_strict.py +++ b/tests/test_recorded_sizes_strict.py @@ -112,7 +112,7 @@ def test_the_manifest_writer_refuses_what_the_reader_refuses(): with pytest.raises(ValueError, match="one size per role"): file_dict(replace(good, pixel_sizes=sizes)) nan = (RecordedSize("X", float("nan"), "micrometer", "stated"), *good.pixel_sizes[1:]) - with pytest.raises(ValueError, match="positive, finite"): + with pytest.raises(ValueError, match="positive finite"): # the version 7 codec (VC4) file_dict(replace(good, pixel_sizes=nan)) diff --git a/tests/test_run.py b/tests/test_run.py index a16f7d22..3428b240 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -93,7 +93,7 @@ def codes(issues): def other_codes(issues): - return [code for code in codes(issues) if code not in BALANCE_CODES] + return [c for c in codes(issues) if c not in {*BALANCE_CODES, "W_AXIS_UNCALIBRATED"}] def issue(issues, code): @@ -319,7 +319,7 @@ def test_every_row_has_its_position_id(experiment): rel: rel.rsplit("/", 1)[-1].removesuffix(".tif") for rel in IMAGES } data = json.loads(result.manifest_path.read_text(encoding="utf-8")) - assert data["manifest_version"] == "6" and data["schema_version"] == "6" + assert data["manifest_version"] == "7" and data["schema_version"] == "6" assert all("position_id" in f for f in data["files"]) @@ -527,14 +527,14 @@ def test_unreadable_manifest_is_rebuilt(experiment): def test_table_with_missing_rows_rereads_the_file(experiment, reads): first = run_described(experiment, TYX) manifest = read_manifest(first.manifest_path) - # Make the manifest claim more planes than the table holds for one file. + # More rows claimed than the table holds: refused in version 7 (ADR 0010 VC3), so no reuse. data = manifest.to_dict() - data["files"][0]["plane_count"] = 3 + data["files"][0]["statistics_rows"] = 3 first.manifest_path.write_text(json.dumps(data), encoding="utf-8") reads.clear() result = run_described(experiment, TYX) - assert result.changed == (sorted(IMAGES)[0],) - assert reads.relative(experiment) == [sorted(IMAGES)[0]] + assert result.written and result.reused == () + assert reads.relative(experiment) == sorted(IMAGES) # Blocking errors ---------------------------------------------------------------------- diff --git a/tests/test_run_folder_errors.py b/tests/test_run_folder_errors.py index 4754b635..82a44089 100644 --- a/tests/test_run_folder_errors.py +++ b/tests/test_run_folder_errors.py @@ -81,7 +81,7 @@ def test_a_manifest_of_another_version_is_run_folder_version(tmp_path): found = derive_state(run, "manifest_version") refusal = _refused(found.output) path = found.output.resolve() / MANIFEST_FILENAME - assert str(refusal) == str(family.run_folder_version(path, "run manifest", "4", "6")) + assert str(refusal) == str(family.run_folder_version(path, "run manifest", "4", "7")) assert refusal.reason == "run manifest version 4" diff --git a/tests/test_run_inputs.py b/tests/test_run_inputs.py index e14af2ae..6dac9074 100644 --- a/tests/test_run_inputs.py +++ b/tests/test_run_inputs.py @@ -54,7 +54,7 @@ def test_planes_and_images_are_the_stored_values(clean): def test_pixel_sizes_carry_their_unit_and_source(clean): sizes = RunInputs.open(clean.output).pixel_sizes("ctrl/rep1/a.ome.tif") assert (sizes["X"].value, sizes["X"].unit, sizes["X"].source) == (0.5, "micrometer", "header") - assert sizes["Z"].value is None and sizes["Z"].source is None + assert sizes["Z"].value is None and sizes["Z"].source == "unknown" # ADR 0010 VC4 def test_masks_by_the_recorded_pairing(clean): @@ -97,7 +97,7 @@ def test_an_older_manifest_version_is_refused(clean): for entry in data["files"]: del entry["content_sha256"] path.write_text(json.dumps(data), encoding="utf-8") - with pytest.raises(RunInputsError, match="run manifest version 1; this one reads 6") as raised: + with pytest.raises(RunInputsError, match="run manifest version 1; this one reads 7") as raised: RunInputs.open(clean.output) assert raised.value.code == "RUN_FOLDER_VERSION" # Spec ADR 0007 assert isinstance(raised.value.__cause__, ManifestFormatError) diff --git a/tests/test_run_page_labels.py b/tests/test_run_page_labels.py index f2849137..07879bc9 100644 --- a/tests/test_run_page_labels.py +++ b/tests/test_run_page_labels.py @@ -132,8 +132,16 @@ def test_replicates_within_a_condition_are_ordered_by_replicate_id(tmp_path, fig # --- 3. the no-problems icon ------------------------------------------------------------------- +def _calibrated(out): + """State X and Y, so no step is unknown (W_AXIS_UNCALIBRATED, Spec ADR 0010) and none warns.""" + (out / "calibration.csv").write_text( + "target,axis,size,unit\n.,X,0.5,um\n.,Y,0.5,um\n", encoding="utf-8" + ) + + def test_no_problems_found_has_no_warning_icon(tmp_path): - nb, _ = described(tmp_path) + nb, out = described(tmp_path) + _calibrated(out) result = nb.run() assert result.written and not result.issues assert "no problems found" in nb.run_tiles.value @@ -141,7 +149,8 @@ def test_no_problems_found_has_no_warning_icon(tmp_path): def test_problems_keep_the_warning_icon(tmp_path): - nb, _ = described(tmp_path) + nb, out = described(tmp_path) + _calibrated(out) result = nb.run() assert not result.issues and "\u2705 no problems found" in nb.run_tiles.value nb._show_run_tiles(replace(result, issues=(warning("odd", "Something to read."),))) diff --git a/tests/test_segmentation_cellpose.py b/tests/test_segmentation_cellpose.py index 347df629..31cd13de 100644 --- a/tests/test_segmentation_cellpose.py +++ b/tests/test_segmentation_cellpose.py @@ -545,7 +545,7 @@ def test_masks_of_the_batch_pass_preprocessings_own_mask_checks_on_a_rerun(run, (run.out / "morphobricks.toml").write_bytes(run.data + MASKS_SECTION) again = run_described(run.experiment, MAPPING, output_folder=run.out, masks_folder=run.masks) assert again.written, [(i.code, i.message) for i in again.issues] - assert sorted(i.code for i in again.issues) == [] + assert sorted(i.code for i in again.issues) == ["W_AXIS_UNCALIBRATED"] # ADR 0010 reopened = RunInputs.open(check_masks(run.out)) assert reopened.mask_types() == ("Cells",) mask = reopened.read_mask(fovs[0].relative_path, "Cells") diff --git a/tests/test_segmentation_handoff.py b/tests/test_segmentation_handoff.py index 2080469d..1fabeda8 100644 --- a/tests/test_segmentation_handoff.py +++ b/tests/test_segmentation_handoff.py @@ -43,7 +43,7 @@ ) MASKS_SECTION = b'\n[masks.Cells]\nsource_type = "Cells"\nrepresentation = "instances"\n' REPEAT_2 = "Biological_repeat_2" -EXPECTED_ROUND_TRIP_ISSUES = [] +EXPECTED_ROUND_TRIP_ISSUES = ["W_AXIS_UNCALIBRATED"] # no X, Y size (Spec ADR 0010) @pytest.fixture diff --git a/tests/test_spec_binary_masks.py b/tests/test_spec_binary_masks.py index c404ed3e..a7ea1f16 100644 --- a/tests/test_spec_binary_masks.py +++ b/tests/test_spec_binary_masks.py @@ -392,10 +392,10 @@ def _z_message(path): @pytest.mark.parametrize( "request_", [ - _objects(), + Request((), (OBJECTS_CC,), z_indices=(0,)), Request((), (OBJECTS_CC,), planes="volume", capabilities=Capabilities(volume_support=True)), ], - ids=["plane", "volume_with_support"], + ids=["explicit_planes", "volume_with_support"], ) def test_f09_a_conversion_on_a_z_stack_is_refused(tmp_path, monkeypatch, request_): out, _, _, _ = _v08(tmp_path, APART, images=2) @@ -431,9 +431,10 @@ def test_f09_a_region_on_a_z_stack_and_a_conversion_on_2d_planes_are_accepted( _, accepted = _resolve(out, _objects()) assert not accepted.refused # every position has one Z plane _z_stack(monkeypatch, out) - _, region = _resolve(out, Request((), (REGION,))) - assert not region.refused - assert len(region.selections[0].planes) == 2 # both slices, read raw + key = RunInputs.open(out).fovs()[0].key # the stack; an index the other image lacks + _, region = _resolve(out, Request((), (REGION,), fov_subset=(key,), z_indices=(0, 1))) + assert not region.refused # is A_Z_INDEX_NOT_IN_IMAGE (ADR 0010), so the stack is named + assert len(region.selections[0].planes) == 2 # both slices named explicitly, read raw # --- F10: strict binary at the mask step (BM11, experiment-v1 4.5) --------------------------- @@ -566,7 +567,7 @@ def test_f10_a_time_lapse_with_one_value_over_every_plane_is_checked(tmp_path): "(not a plain NumPy array)": "mask_rules.py", "is declared parent_labels: each non-zero value is one": "mask_rules.py", "so it has no object identity and cannot": "mask_rules.py", - "2-D planes only; the images of": "run_inputs_request.py", + "2-D planes only; the images of": "run_inputs_volume.py", "is requested as objects with two different conversions": "mask_requests.py", "older than the binary value rule": "mask_rules.py", } diff --git a/tests/test_spec_fast_layout.py b/tests/test_spec_fast_layout.py index bdbf8b85..62f256c9 100644 --- a/tests/test_spec_fast_layout.py +++ b/tests/test_spec_fast_layout.py @@ -408,12 +408,13 @@ def test_p39c_the_override_refusal_keeps_its_priority_and_is_not_listed_twice(tm assert [i.path for i in report.issues] == ["CTRL/rep1/FOV009.ome.tif"] -def test_fast_unit_axes_stay_a_homogeneity_rule(tmp_path): +def test_a_z_axis_in_a_fast_unit_is_not_a_homogeneity_difference(tmp_path): + # Spec ADR 0010 VC11: homogeneity leaves Z (and T) out, size and presence; a unit mixing + # plane images and volumes is the recorded warning W_MIXED_PLANES_AND_VOLUMES, not refused. root = _tree(tmp_path / "exp", V41) _ome(root / "CTRL/rep2/FOV009.ome.tif", MATCH, axes="CZYX") report = _check(root, V41) - assert "R_UNIT_NOT_HOMOGENEOUS" in report.codes - assert not report.codes - {"R_UNIT_NOT_HOMOGENEOUS", FAST} + assert "R_UNIT_NOT_HOMOGENEOUS" not in report.codes def test_the_run_manifest_records_fast_layout_images_per_fast_unit(tmp_path): diff --git a/tests/test_spec_parent_labels.py b/tests/test_spec_parent_labels.py index 30ac5801..a3ea8b13 100644 --- a/tests/test_spec_parent_labels.py +++ b/tests/test_spec_parent_labels.py @@ -46,7 +46,7 @@ VALID = {item.name.split("_")[0]: item for item in fixtures("valid")} INVALID = {item.name.split("_")[0]: item for item in fixtures("invalid")} -PINNED = "232fb38880cc487510532d99dc71d46a27005f23" # ADR 0006 accepted (Spec #53), after PL1 +PINNED = "5aad8d3ecf0088e9eb443ad79dafedab86977376" # ADR 0010 accepted (Spec #57), after PL1 EMPTY = DraftAnswers(ABSENT, SPEC_COMMIT) GROUPS = Capabilities(parent_labels_support=True) @@ -136,10 +136,10 @@ def test_a_parent_labels_file_the_mask_step_has_not_read_is_unchecked(tmp_path): # --- Resolver contract version 2 (ADR 0002) ------------------------------------------------- -def test_the_resolver_contract_is_version_3(): +def test_the_resolver_contract_is_version_5(): # 2 added parent-label masks; 3 (Spec ADR 0005) the conversion record, which records the - # marker of a parent_labels region too. - assert RESOLVER_VERSION == 3 + # marker of a parent_labels region too; 5 volumes (Spec ADR 0010, with AR12 in one wave). + assert RESOLVER_VERSION == 5 assert PARENT_LABELS_AS_AREA == "parent_labels_as_area" assert Capabilities().parent_labels_support is False @@ -184,7 +184,7 @@ def test_as_a_region_without_the_capability_it_is_an_area_with_the_marker(tmp_pa assert (mito.mask_id, mito.source_type, mito.role) == ("Mito", "mito", "region") assert mito.representation == "parent_labels" # the declaration is kept assert mito.conversion == PARENT_LABELS_AS_AREA - assert resolved.provenance.resolver_version == 3 + assert resolved.provenance.resolver_version == 5 # Spec ADR 0005: the marker is recorded once for the run, with null connectivity and # labeller; the instances object set has no record. assert [c.as_record() for c in resolved.provenance.mask_conversions] == [ diff --git a/tests/test_spec_resolve_request.py b/tests/test_spec_resolve_request.py index a676f793..a0d319b7 100644 --- a/tests/test_spec_resolve_request.py +++ b/tests/test_spec_resolve_request.py @@ -411,7 +411,7 @@ def test_provenance_is_the_manifests_record_and_the_request_with_its_device(tmp_ request = Request(("DNA",), device="cuda") resolved = inputs.resolve_request(request) recorded = read_manifest(run.output / "run_manifest.json").experiment_description - assert resolved.provenance.resolver_version == RESOLVER_VERSION == 3 + assert resolved.provenance.resolver_version == RESOLVER_VERSION == 5 assert resolved.provenance.description_sha256 == recorded["sha256"] assert dict(resolved.provenance.section_digests) == recorded["section_digests"] assert resolved.provenance.request == request and resolved.provenance.request.device == "cuda" diff --git a/tests/test_spec_run_aliases.py b/tests/test_spec_run_aliases.py index d00aced7..95997fef 100644 --- a/tests/test_spec_run_aliases.py +++ b/tests/test_spec_run_aliases.py @@ -184,7 +184,8 @@ def test_p06_two_unnamed_units_with_swapped_fluorophores_run_unrefused_on_the_co ): """P06: a documented limit, not a refusal; the record shows the units stand on confirmation.""" result, entry = _p06_run(tmp_path, swapped=True) - assert result.written and result.issues == () + # The images state no pixel size: W_AXIS_UNCALIBRATED x and y (Spec ADR 0010), nothing else. + assert result.written and {i.code for i in result.issues} <= {"W_AXIS_UNCALIBRATED"} _, unswapped = _p06_run(tmp_path, swapped=False) assert entry == unswapped # the described-run record cannot tell the two folders apart listed = { diff --git a/tests/test_stage3_channels.py b/tests/test_stage3_channels.py index a6732a67..28c9f90f 100644 --- a/tests/test_stage3_channels.py +++ b/tests/test_stage3_channels.py @@ -164,7 +164,7 @@ def test_the_extra_stain_is_blank_never_zero_where_it_was_not_acquired(extra_run def test_the_manifest_records_each_image_s_channels_and_the_coverage(extra_run): result, _, _ = extra_run manifest = json.loads(result.manifest_path.read_text(encoding="utf-8")) - assert manifest["manifest_version"] == "6" and manifest["schema_version"] == "6" + assert manifest["manifest_version"] == "7" and manifest["schema_version"] == "6" by_image = {entry["relative_path"]: entry["channel_ids"] for entry in manifest["files"]} assert by_image["Control/Biological_repeat_2/img0.tif"] == ["DNA", "ACTIN", "TUB", "EXTRA"] assert by_image["Treated/Biological_repeat_3/img1.tif"] == ["DNA", "ACTIN", "TUB"] diff --git a/tests/test_unnamed_header_images.py b/tests/test_unnamed_header_images.py index 86f503ea..9003a934 100644 --- a/tests/test_unnamed_header_images.py +++ b/tests/test_unnamed_header_images.py @@ -88,6 +88,10 @@ def test_the_run_lists_the_unnamed_and_the_partly_named_image_exactly(tmp_path): def test_the_report_text_and_json_show_them(tmp_path): root, out, by_unit = _run(tmp_path) + # X and Y stated, so W_AXIS_UNCALIBRATED (Spec ADR 0010) names no image in the report. + (out / "calibration.csv").write_text( + "target,axis,size,unit\n.,X,0.5,um\n.,Y,0.5,um\n", encoding="utf-8" + ) run_described(root, MAPPING, output_folder=out) text = (out / "discovery_report.txt").read_text(encoding="utf-8") assert "Images without header channel names: 2 images in 2 units" in text diff --git a/tests/test_volumes_handoff.py b/tests/test_volumes_handoff.py new file mode 100644 index 00000000..c082146e --- /dev/null +++ b/tests/test_volumes_handoff.py @@ -0,0 +1,303 @@ +"""Spec ADR 0010: the hand-off of volumes (P62-P65, P73, P75, P78-P83, P100, VC6, VC8, VC9). + +The hand-off is the one Z gate (VZ1). The resolver (contract version 5) never expands Z into +planes implicitly: a ``plane`` request without ``z_indices`` on a volume is +``A_VOLUME_NOT_SUPPORTED`` (rule (b)), explicit ``z_indices`` are served and recorded in +``fov_scope`` and its ``scope_digest``, an index an image lacks is ``A_Z_INDEX_NOT_IN_IMAGE``. +Statistics of a volume are ``VOLUME_STATISTICS_NOT_COMPUTED``; direct reads choose no plane; +``read_mask_volume`` is the one whole-volume mask read; ``read_objects`` stays in its selection. +""" + +from __future__ import annotations + +import numpy as np +import pytest + +from morphobricks_preprocessing.run_inputs import RunInputs, RunInputsError +from morphobricks_preprocessing.run_inputs_consumer import ( + ConsumerDimensionsNotAllowedError, + capabilities_for, +) +from morphobricks_preprocessing.run_inputs_request import ( + Capabilities, + MaskRequest, + Request, + z_index_refusals, +) +from morphobricks_preprocessing.run_inputs_statistics import ( + VolumeStatisticsNotComputedError, + refuse_volume_statistics, +) +from volume_tree import TZYX, published, stack, volumes, write_ome + +VOLUME_ON = Capabilities(volume_support=True) + + +@pytest.fixture(scope="module") +def volume_run(tmp_path_factory): + tmp = tmp_path_factory.mktemp("volumes") + root, out = tmp / "exp", tmp / "out" + volumes(root) + published(root, out) + return RunInputs.open(out) + + +@pytest.fixture(scope="module") +def mixed_run(tmp_path_factory): + tmp = tmp_path_factory.mktemp("mixed") + root, out = tmp / "exp", tmp / "out" + volumes(root, count=1) + write_ome(root / "drug/rep1/p0.ome.tif", stack(z=1, start=7)[0], "YX") + published(root, out, missing_as_singleton=True) + return RunInputs.open(out) + + +def _codes(resolved): + return [(r.code, r.subject, r.files) for r in resolved.refusals] + + +# P62: the resolver on a run of volumes --------------------------------------------------------- + + +@pytest.mark.parametrize("capabilities", [Capabilities(), VOLUME_ON], ids=["without", "with"]) +def test_p62ab_a_plane_request_without_z_indices_is_refused_per_volume(volume_run, capabilities): + resolved = volume_run.resolve_request(Request(capabilities=capabilities)) + assert _codes(resolved) == [ + ("A_VOLUME_NOT_SUPPORTED", "plane", ("ctrl/rep1/s0.ome.tif",)), + ("A_VOLUME_NOT_SUPPORTED", "plane", ("ctrl/rep1/s1.ome.tif",)), + ] + assert resolved.selections == () and "never expanded" in resolved.refusals[0].message + assert resolved.provenance.fov_scope["z_indices"] is None + + +def test_p62cd_a_volume_request_needs_volume_support(volume_run): + refused = volume_run.resolve_request(Request(planes="volume")) + assert _codes(refused) == [("A_VOLUME_NOT_SUPPORTED", "volume", ())] + served = volume_run.resolve_request(Request(planes="volume", capabilities=VOLUME_ON)) + assert [s.planes for s in served.selections][0][0].z == (0, 1, 2, 3, 4) + + +def test_p62e_explicit_z_indices_are_served_and_recorded(volume_run): + resolved = volume_run.resolve_request(Request(z_indices=(0, 2))) + assert not resolved.refused + assert [(p.t, p.z) for p in resolved.selections[0].planes] == [(0, (0,)), (0, (2,))] + scope = resolved.provenance.fov_scope + assert scope["z_indices"] == [0, 2] and list(scope)[-2:] == ["z_indices", "scope_digest"] + one = volume_run.resolve_request(Request(z_indices=(0,))).provenance.fov_scope + none = volume_run.resolve_request(Request()).provenance.fov_scope + assert len({scope["scope_digest"], one["scope_digest"], none["scope_digest"]}) == 3 # P100 + + +def test_p62f_an_index_the_image_lacks_is_refused_per_position(volume_run): + resolved = volume_run.resolve_request(Request(z_indices=(5,))) + assert [r.code for r in resolved.refusals] == ["A_Z_INDEX_NOT_IN_IMAGE"] * 2 + assert resolved.refusals[0].message == ( + "ctrl/rep1/s0.ome.tif has 5 Z plane(s) (0 to 4); the request names Z 5, which it does " + "not have. Nothing was selected or read. Name Z indices every covered image has, or " + "narrow the request with fov_subset (A_Z_INDEX_NOT_IN_IMAGE)." + ) + assert resolved.selections == () + assert z_index_refusals((5,), {"b": 3, "a": 7}) == z_index_refusals((5,), {"b": 3}) + + +@pytest.mark.parametrize( + "request_", + [ + lambda: Request(planes="volume", z_indices=(1,)), + lambda: Request(z_indices=()), + lambda: Request(z_indices=(2, 0)), + lambda: Request(z_indices=(True,)), # P79 + lambda: Request(z_indices=(1.0,)), + lambda: Request(z_indices=(-1,)), + lambda: Request(z_indices=(1, 1)), + lambda: Request(z_indices=[1]), + lambda: Request(z_indices=(np.int64(1),)), + ], +) +def test_p62g_p79_a_malformed_z_indices_is_a_value_error(volume_run, request_): + with pytest.raises(ValueError, match="z_indices"): + volume_run.resolve_request(request_()) + + +def test_p62h_direct_reads_choose_no_plane_of_a_volume(volume_run): + fov = volume_run.fovs()[0] + with pytest.raises(RunInputsError, match="5 Z planes"): + volume_run.read_plane(fov) + with pytest.raises(RunInputsError, match="volume=True"): + volume_run.read_image(fov) + np.testing.assert_array_equal(volume_run.read_plane(fov, z=2)[0], stack(z=5)[2]) + whole = volume_run.read_image(fov, volume=True) + assert whole.shape == (1, 5, 1, 6, 8) + + +def test_p80_an_unknown_fov_is_the_only_refusal(volume_run): + resolved = volume_run.resolve_request( + Request(fov_subset=(("x", "y", "z", "w"),), z_indices=(9,)) + ) + assert [r.code for r in resolved.refusals] == ["A_FOV_NOT_IN_RUN"] + assert resolved.provenance.fov_scope is None + + +def test_p78_a_subset_narrows_the_covered_positions(volume_run): + key = volume_run.fovs()[1].key + resolved = volume_run.resolve_request(Request(fov_subset=(key,), z_indices=(4,))) + assert not resolved.refused and [s.key for s in resolved.selections] == [key] + scope = resolved.provenance.fov_scope + assert (scope["fov_subset"], scope["selected"], scope["run_images"]) == ("explicit", 1, 2) + + +# P63: the resolver on a mixed run -------------------------------------------------------------- + + +def test_p63_a_mixed_run(mixed_run): + whole = mixed_run.resolve_request(Request(planes="volume", capabilities=VOLUME_ON)) + assert [len(s.planes[0].z) for s in whole.selections] == [5, 1] # ctrl volume, drug plane + assert _codes(mixed_run.resolve_request(Request())) == [ + ("A_VOLUME_NOT_SUPPORTED", "plane", ("ctrl/rep1/s0.ome.tif",)) + ] + zero = mixed_run.resolve_request(Request(z_indices=(0,))) + assert [[(p.t, p.z) for p in s.planes] for s in zero.selections] == [[(0, (0,))]] * 2 + three = mixed_run.resolve_request(Request(z_indices=(3,))) + assert _codes(three) == [("A_Z_INDEX_NOT_IN_IMAGE", "z_indices", ("drug/rep1/p0.ome.tif",))] + + +# P64, P73: statistics are refused for volumes --------------------------------------------------- + + +def test_p64_statistics_of_a_mixed_run(mixed_run): + plane, volume = sorted(mixed_run.fovs(), key=lambda f: f.z_count) + with pytest.raises(VolumeStatisticsNotComputedError) as refused: + mixed_run.histograms() + assert refused.value.code == "VOLUME_STATISTICS_NOT_COMPUTED" + assert refused.value.volumes == ((volume.key, volume.relative_path, 5),) + assert [r.source_relative_path for r in mixed_run.histograms([plane])] == [plane.relative_path] + assert len(mixed_run.histograms([plane.relative_path])) == 1 + with pytest.raises( + VolumeStatisticsNotComputedError, match="Plane histograms are not computed for volumes" + ): + mixed_run.histograms([volume]) + assert {row.relative_path for row in mixed_run.image_qc([plane])} == {plane.relative_path} + with pytest.raises( + VolumeStatisticsNotComputedError, match="QC metrics are not computed for volumes" + ): + mixed_run.image_qc() + mixed_run.require_plane_statistics([plane]) + with pytest.raises( + VolumeStatisticsNotComputedError, match="Normalization is not computed for volumes" + ): + mixed_run.require_plane_statistics([plane, volume]) + with pytest.raises(ValueError, match="empty"): + mixed_run.histograms([]) + with pytest.raises(ValueError, match="twice"): + mixed_run.histograms([plane, plane]) + with pytest.raises(RunInputsError, match="not an image of this run"): + mixed_run.histograms(["nowhere.tif"]) + assert not hasattr(mixed_run, "records") # internal (VC6) + + +def test_p73_every_statistics_call_on_a_run_of_volumes_is_refused(volume_run): + for call in ( + volume_run.histograms, + volume_run.image_qc, + lambda: volume_run.histograms(volume_run.fovs()), + lambda: volume_run.require_plane_statistics(volume_run.fovs()), + ): + with pytest.raises(VolumeStatisticsNotComputedError) as refused: + call() + assert len(refused.value.volumes) == 2 + + +def test_the_refusal_message_lists_at_most_ten_volumes(): + many = [(("c", "r", "t", f"p{i:02}"), f"c/p{i:02}.tif", 3) for i in range(12)] + error = refuse_volume_statistics(many, "histograms") + assert "... and 2 more" in str(error) and str(error).count("3 Z planes") == 10 + assert str(error).endswith("(VOLUME_STATISTICS_NOT_COMPUTED).") + + +# P75: a T x Z volume; P81: reads stay inside a selection ----------------------------------------- + + +@pytest.fixture(scope="module") +def tz_run(tmp_path_factory): + tmp = tmp_path_factory.mktemp("tz") + root, out, masks = tmp / "exp", tmp / "out", tmp / "masks" + write_ome(root / "ctrl/rep1/a.ome.tif", stack(z=5, t=3), "TZYX") + labels = (stack(z=5, t=3) % 7).astype(np.uint16) + write_ome(masks / "Nuclei/ctrl/rep1/a.ome.tif", labels, "TZYX") + published(root, out, TZYX, masks_folder=masks) + from described_tree import check_masks + + return RunInputs.open(check_masks(out)), labels + + +def test_p75_explicit_planes_of_a_time_lapse_volume(tz_run): + inputs, labels = tz_run + whole = inputs.resolve_request(Request(planes="volume", capabilities=VOLUME_ON)) + assert [p.z for p in whole.selections[0].planes] == [(0, 1, 2, 3, 4)] * 3 + resolved = inputs.resolve_request(Request(z_indices=(1, 3))) + planes = [(p.t, p.z[0]) for p in resolved.selections[0].planes] + assert planes == [(t, z) for t in range(3) for z in (1, 3)] + fov = inputs.fovs()[0] + for t, z in planes: + np.testing.assert_array_equal(inputs.read_plane(fov, z=z, t=t)[0], stack(z=5, t=3)[t, z]) + np.testing.assert_array_equal(inputs.read_mask(fov, "Nuclei", z=z, t=t), labels[t, z]) + + +def test_p82_the_whole_volume_mask_read(tz_run): + inputs, labels = tz_run + fov = inputs.fovs()[0] + np.testing.assert_array_equal(inputs.read_mask_volume(fov, "Nuclei", t=2), labels[2]) + with pytest.raises(RunInputsError, match="time points"): + inputs.read_mask_volume(fov, "Nuclei") # omitted t on a T > 1 mask + with pytest.raises(ValueError, match="say which one to read"): + inputs.read_mask(fov, "Nuclei", t=0) # read_mask keeps refusing an omitted z + from morphobricks_preprocessing.plane_errors import PlaneMemoryError + + with pytest.raises(PlaneMemoryError, match="limit"): + inputs.read_mask_volume(fov, "Nuclei", t=0, memory_limit=10) + + +def test_p81_read_objects_refuses_a_plane_outside_its_selection(tz_run): + inputs, labels = tz_run + resolved = inputs.resolve_request(Request(masks=(MaskRequest("Nuclei"),), z_indices=(1,))) + selection = resolved.require()[0] + np.testing.assert_array_equal(inputs.read_objects(selection, "Nuclei", t=0, z=1), labels[0, 1]) + with pytest.raises(RunInputsError, match=r"\(t=0, z=4\) is not a plane of the selection"): + inputs.read_objects(selection, "Nuclei", t=0, z=4) + + +def test_p65c_bm5_refuses_a_conversion_of_a_volume_for_explicit_planes_too(tz_run): + inputs, _ = tz_run + from morphobricks_preprocessing.run_inputs_volume import volume_refusals + + request = Request(masks=(MaskRequest("Nuclei", binary_mask_policy="connected_components"),)) + explicit = Request(request.channel_ids, request.masks, z_indices=(1,)) + found = volume_refusals(explicit, {inputs.fovs()[0].relative_path: 5}) + assert [(r.code, r.subject) for r in found] == [("A_VOLUME_NOT_SUPPORTED", "Nuclei")] + + +# The consumer's declared rules (Spec ADR 0009 O9, O10; the minimal hand-off part) --------------- + + +def test_volume_support_routes_to_the_resolvers_capability(): + assert capabilities_for("volumes").volume_support is True + assert capabilities_for("planes").volume_support is False + assert capabilities_for("none").volume_support is False + with pytest.raises(ValueError): + capabilities_for(True) + + +def test_a_consumer_check_lists_every_offending_image_and_kind(mixed_run, volume_run): + rules = {"volume_support": "none", "mixed_volume_support": False, "requires_calibration": []} + with pytest.raises(ConsumerDimensionsNotAllowedError, match="volume: Z = 5") as refused: + mixed_run.check_consumer("morphofeature", **rules) + assert refused.value.code == "R_CONSUMER_DIMENSIONS_NOT_ALLOWED" + planes = {**rules, "volume_support": "planes"} + with pytest.raises(ConsumerDimensionsNotAllowedError, match="mixed_volumes"): + mixed_run.check_consumer("t", **planes) + volume_run.check_consumer("t", **planes) # one kind: passes + needs_z = {**planes, "requires_calibration": ["z"]} + with pytest.raises(ConsumerDimensionsNotAllowedError, match="calibration: z step unknown"): + volume_run.check_consumer("t", **needs_z) + with pytest.raises(ValueError, match="admits no mix"): + volume_run.check_consumer("t", **{**rules, "mixed_volume_support": True}) diff --git a/tests/test_volumes_rows.py b/tests/test_volumes_rows.py new file mode 100644 index 00000000..4b989ce6 --- /dev/null +++ b/tests/test_volumes_rows.py @@ -0,0 +1,393 @@ +"""Spec ADR 0010: rows tested in preprocessing alone (P65, P76, P77, P83-P85, P90, P95, P98). + +The rows that need a consumer's own code (P92-P94, P96) or ADR 0009's early checks (P69, P70) +are not here; P95 uses a minimal test consumer whose guard is :meth:`RunInputs.check_consumer`. +""" + +from __future__ import annotations + +import numpy as np +import pytest + +from described_tree import check_masks, describe_tree, run_described +from morphobricks_preprocessing import AxisMapping +from morphobricks_preprocessing.run.mask_step import describe_masks, prepare_mask_step +from morphobricks_preprocessing.run_inputs import RunInputs, RunInputsError +from morphobricks_preprocessing.run_inputs_consumer import ConsumerDimensionsNotAllowedError +from morphobricks_preprocessing.run_inputs_request import MaskRequest, Request +from morphobricks_preprocessing.testing_spy import decoder_spy +from tiff_tree import write_plain +from volume_tree import ( + KEEP, + ZYX, + entry, + manifest_data, + published, + size, + stack, + state, + volumes, + write_ome, +) + +NONE_RULES = {"volume_support": "none", "mixed_volume_support": False, "requires_calibration": []} + + +def _errors(result): + return {i.code for i in result.issues if i.is_error} + + +# P65 (b): a 2-D mask of a volume is refused by the mask check --------------------------------- + + +def test_p65b_a_2d_mask_of_a_volume_is_refused(tmp_path): + root, out, masks = tmp_path / "exp", tmp_path / "out", tmp_path / "masks" + volumes(root, count=1) + write_ome(masks / "Nuclei/ctrl/rep1/s0.ome.tif", (stack(z=1)[0] % 5).astype(np.uint16), "YX") + result = run_described(root, ZYX, output_folder=out, masks_folder=masks, mode=KEEP) + assert not result.written + assert "mask_planes_mismatch" in _errors(result) + + +# P76: a stack whose pages could be Z or T is refused until its roles are confirmed ------------ + + +def test_p76_a_plain_stack_is_never_read_with_a_guessed_role(tmp_path): + root, out = tmp_path / "exp", tmp_path / "out" + write_plain(root / "ctrl/rep1/a.tif", stack(z=4)) + unconfirmed = run_described(root, AxisMapping("IYX", "-YX"), output_folder=out, mode=KEEP) + assert not unconfirmed.written + assert "unassigned_axis" in _errors(unconfirmed) + assert not (out / "run_manifest.json").exists() + as_z = run_described(root, AxisMapping("IYX", "ZYX"), output_folder=out, mode=KEEP) + assert as_z.written and entry(manifest_data(out), "ctrl/rep1/a.tif")["image_kind"] == "volume" + + +# P84: a binary volume mask holding two values is refused file-wide ---------------------------- + + +def test_p84_a_binary_volume_mask_with_two_values_is_refused_file_wide(tmp_path): + root, out, masks = tmp_path / "exp", tmp_path / "out", tmp_path / "masks" + volumes(root, count=1, z=2) + mask = np.zeros((2, 6, 8), np.uint8) + mask[0, 1:3, 1:3] = 3 # one value on each plane: each plane alone is a valid binary + mask[1, 2:4, 2:4] = 7 + write_ome(masks / "Region/ctrl/rep1/s0.ome.tif", mask, "ZYX") + describe_tree(root, out, ZYX, masks_folder=masks, representation="binary") + from morphobricks_preprocessing import run_experiment + + result = run_experiment(root, ZYX, output_folder=out, masks_folder=masks, mode=KEEP) + assert result.written, [(i.code, i.message) for i in result.issues if i.is_error] + step = describe_masks(prepare_mask_step(None, out)) + codes = {i.code for i in step.issues} + assert "R_MASK_CONTRADICTS_REPRESENTATION" in codes, [(i.code, i.message) for i in step.issues] + + +# P90: QC rows that do not cover the plane images are refused, never read as "no failure" ------ + + +@pytest.fixture +def mixed_run(tmp_path): + root, out = tmp_path / "exp", tmp_path / "out" + volumes(root, count=1) + write_ome(root / "drug/rep1/p0.ome.tif", stack(z=1, start=7)[0], "YX") + published(root, out, missing_as_singleton=True) + return out + + +def _qc_reader(monkeypatch, change): + from morphobricks_preprocessing import run_inputs_statistics + + real = run_inputs_statistics.read_image_qc + monkeypatch.setattr(run_inputs_statistics, "read_image_qc", lambda path: change(real(path))) + + +def test_p90_a_missing_qc_row_for_a_plane_image_is_refused(mixed_run, monkeypatch): + inputs = RunInputs.open(mixed_run) + plane = "drug/rep1/p0.ome.tif" + assert inputs.image_qc([f for f in inputs.fovs() if f.relative_path == plane]) + _qc_reader(monkeypatch, lambda rows: rows[1:]) + with pytest.raises(RunInputsError, match="one row per channel of each plane"): + inputs.image_qc([f for f in inputs.fovs() if f.relative_path == plane]) + + +def test_p90_a_qc_row_for_a_volume_is_refused(mixed_run, monkeypatch): + from dataclasses import replace + + from morphobricks_preprocessing.image_qc_table import IDENTITY + + inputs = RunInputs.open(mixed_run) + plane, volume = "drug/rep1/p0.ome.tif", "ctrl/rep1/s0.ome.tif" + values = { + "position_id": "s0", + "image_file": "s0.ome.tif", + "condition": "ctrl", + "source_relative_path": volume, + "plane_id": f"{volume}::z=0,t=0", + } + + def with_volume(rows): + identity = tuple( + values.get(name, old) for name, old in zip(IDENTITY, rows[0].identity, strict=True) + ) + return (*rows, replace(rows[0], identity=identity)) + + _qc_reader(monkeypatch, with_volume) + with pytest.raises(RunInputsError, match="one row per channel of each plane"): + inputs.image_qc([f for f in inputs.fovs() if f.relative_path == plane]) + + +# P95: a volume_support = "none" consumer's guard refuses every route before any pixel --------- + + +class _NoVolumeConsumer: + """A minimal consumer whose every route calls its own guard first (ADR 0009 B2, VC10).""" + + def __init__(self, inputs): + self.inputs = inputs + + def _guard(self): + self.inputs.check_consumer("test-consumer", **NONE_RULES) + + def request(self, z_indices): + self._guard() + return self.inputs.resolve_request(Request(z_indices=z_indices)) + + def plane(self, fov): + self._guard() + return self.inputs.read_plane(fov, z=0, t=0) + + def window(self, fov): + self._guard() + return self.inputs.read_window(fov, t=0, z=0, bounds=(0, 2, 0, 2), channels=fov.channel_ids) + + def mask(self, fov): + self._guard() + return self.inputs.read_mask(fov, "Nuclei", z=0, t=0) + + +@pytest.fixture +def masked_volume_run(tmp_path): + root, out, masks = tmp_path / "exp", tmp_path / "out", tmp_path / "masks" + write_ome(root / "ctrl/rep1/a.ome.tif", stack(z=5), "ZYX") + write_ome(masks / "Nuclei/ctrl/rep1/a.ome.tif", (stack(z=5) % 7).astype(np.uint16), "ZYX") + published(root, out, masks_folder=masks) + return RunInputs.open(check_masks(out)) + + +@pytest.mark.parametrize("route", ["request", "plane", "window", "mask"]) +def test_p95_a_none_consumer_refuses_every_route_before_any_read(masked_volume_run, route): + consumer = _NoVolumeConsumer(masked_volume_run) + fov = masked_volume_run.fovs()[0] + argument = (1,) if route == "request" else fov + with decoder_spy() as calls, pytest.raises(ConsumerDimensionsNotAllowedError, match="volume"): + getattr(consumer, route)(argument) + assert calls.total == 0, calls.counts + + +def test_p95_without_the_guard_the_routes_serve_explicit_planes(masked_volume_run): + # The guard is what refuses: the same routes serve a plane of the volume when asked for one. + fov = masked_volume_run.fovs()[0] + resolved = masked_volume_run.resolve_request( + Request(masks=(MaskRequest("Nuclei"),), z_indices=(0,)) + ) + assert resolved.selections and not resolved.refusals + np.testing.assert_array_equal(masked_volume_run.read_plane(fov, z=0, t=0)[0], stack(z=5)[0]) + window = masked_volume_run.read_window( + fov, t=0, z=0, bounds=(0, 2, 0, 2), channels=fov.channel_ids + ) + np.testing.assert_array_equal(np.asarray(window)[0], stack(z=5)[0, 0:2, 0:2]) + mask = masked_volume_run.read_mask(fov, "Nuclei", z=0, t=0) + np.testing.assert_array_equal(mask, stack(z=5)[0] % 7) + + +# P98: calibration changed after publication ------------------------------------------------- + + +def test_p98_a_calibration_added_after_publication_refuses_the_old_run_and_is_rerecorded( + tmp_path, +): + root, out = tmp_path / "exp", tmp_path / "out" + volumes(root, count=1) + published(root, out) + before = manifest_data(out) + assert size(entry(before, "ctrl/rep1/s0.ome.tif"), "Z")["source"] == "unknown" + assert before["checks"][0]["counts"] == {"x": 1, "y": 1, "z": 1} + state(out, ".,X,0.2,micrometer\n.,Y,0.2,micrometer\n.,Z,1.5,micrometer\n") + with pytest.raises(RunInputsError, match="RUN_FOLDER_STALE.*calibration.csv"): + RunInputs.open(out) + published(root, out) + after = manifest_data(out) + z = size(entry(after, "ctrl/rep1/s0.ome.tif"), "Z") + assert (z["source"], z["value"], z["reason"]) == ("stated", 1.5, None) + assert after["checks"] == [] + RunInputs.open(out) # the re-run is current + + +# P77: an OME-Zarr multiscale volume is described and read at level 0 only (VC14) ------------- + + +def _two_level_store(path, level0, level1, scale0, scale1): + from zarr_tree import _array, write_ngff, zarr_major + + write_ngff(path, level0, "zyx", scale=scale0, units=dict.fromkeys("zyx", "micrometer")) + import zarr + + group = ( + zarr.open_group(str(path), mode="a", zarr_format=2) + if zarr_major() >= 3 + else zarr.open_group(str(path), mode="a") + ) + _array(group, "1", level1, (1, *level1.shape[1:])) + attrs = dict(group.attrs) + multiscale = attrs["multiscales"][0] + multiscale["datasets"].append( + {"path": "1", "coordinateTransformations": [{"type": "scale", "scale": scale1}]} + ) + group.attrs.update(attrs) + + +def test_p77_a_multiscale_volume_is_described_and_read_at_level_0_only(tmp_path): + pytest.importorskip("zarr") + root, out = tmp_path / "exp", tmp_path / "out" + level0 = stack(z=20, y=8, x=8) + level1 = (level0[::4, ::2, ::2] + 1000).astype(np.uint16) # other values: never seen + _two_level_store(root / "ctrl/rep1/a.zarr", level0, level1, [0.7, 0.15, 0.1], [2.8, 0.3, 0.2]) + published(root, out) + data = manifest_data(out) + image = entry(data, "ctrl/rep1/a.zarr") + assert (image["z_count"], image["image_kind"]) == (20, "volume") + steps = {r: (size(image, r)["value"], size(image, r)["source"]) for r in "XYZ"} + assert steps == {"X": (0.1, "header"), "Y": (0.15, "header"), "Z": (0.7, "header")} + inputs = RunInputs.open(out) + fov = inputs.fovs()[0] + assert fov.z_count == 20 + resolved = inputs.resolve_request(Request(z_indices=(0, 19))) + assert [p.z for p in resolved.selections[0].planes] == [(0,), (19,)] + for z in (0, 19): + np.testing.assert_array_equal(inputs.read_plane(fov, z=z, t=0)[0], level0[z]) + + +# P83: one label value across Z planes, masks, FOVs and time points --------------------------- + + +@pytest.fixture +def labelled_run(tmp_path): + """Two FOVs, T = 2, Z = 4, two mask types; value 7 on z = 1-3 everywhere.""" + root, out, masks = tmp_path / "exp", tmp_path / "out", tmp_path / "masks" + label = np.zeros((2, 4, 6, 8), np.uint16) + label[:, 1:4, 2:4, 2:5] = 7 + for name in ("a", "b"): + write_ome(root / f"ctrl/rep1/{name}.ome.tif", stack(z=4, t=2), "TZYX") + for mask in ("Cells", "Nuclei"): + write_ome(masks / f"{mask}/ctrl/rep1/{name}.ome.tif", label, "TZYX") + from volume_tree import TZYX + + published(root, out, TZYX, masks_folder=masks) + return RunInputs.open(check_masks(out)), label + + +def test_p83_a_3d_object_is_keyed_by_fov_mask_and_time_point(labelled_run): + inputs, label = labelled_run + fovs = inputs.fovs() + assert len(fovs) == 2 + keys = set() + for fov in fovs: + for mask in ("Cells", "Nuclei"): + for t in (0, 1): + volume = inputs.read_mask_volume(fov, mask, t=t) + assert volume.shape == (4, 6, 8) # one 3-D array per (FOV, mask, t) + np.testing.assert_array_equal(volume, label[t]) + assert [z for z in range(4) if (volume[z] == 7).any()] == [1, 2, 3] + keys.add((fov.key, mask, t, 7)) + assert len(keys) == 8 # value 7 is eight distinct objects: never merged across the keys + + +def test_p83_per_plane_reads_are_keyed_with_z(labelled_run): + inputs, label = labelled_run + request = Request(masks=(MaskRequest("Nuclei"),), z_indices=(1, 2)) + for selection in inputs.resolve_request(request).require(): + keys = [(p.t, p.z) for p in selection.planes] + assert keys == [(0, (1,)), (0, (2,)), (1, (1,)), (1, (2,))] + for t, (z,) in keys: + plane = inputs.read_objects(selection, "Nuclei", t=t, z=z) + np.testing.assert_array_equal(plane, label[t, z]) + + +# P85 (RGB half): an anisotropic RGB volume keeps its steps and channels as declared ---------- + + +def test_p85_an_anisotropic_rgb_volume_keeps_its_steps_and_channels(tmp_path): + from volume_tree import CALIBRATED + + root, out = tmp_path / "exp", tmp_path / "out" + rgb = (np.arange(4 * 6 * 8 * 3).reshape(4, 6, 8, 3) % 251).astype(np.uint8) + path = root / "ctrl/rep1/a.ome.tif" + path.parent.mkdir(parents=True) + import tifffile + + tifffile.imwrite( + path, rgb, ome=True, photometric="rgb", metadata={"axes": "ZYXS", **CALIBRATED} + ) + result = published(root, out, AxisMapping("ZYXS", "ZYXC"), image_type="rgb") + assert result.written + image = entry(manifest_data(out), "ctrl/rep1/a.ome.tif") + assert (image["image_kind"], image["z_count"], image["c_count"]) == ("volume", 4, 3) + steps = {r: size(image, r)["value"] for r in "XYZ"} + assert steps == {"X": 0.1, "Y": 0.15, "Z": 0.7} # as recorded: no single scalar size + inputs = RunInputs.open(out) + fov = inputs.fovs()[0] + assert fov.channel_ids == ("R", "G", "B") + plane = inputs.read_plane(fov, z=2, t=0) + np.testing.assert_array_equal(np.moveaxis(np.asarray(plane), 0, -1), rgb[2]) + + +# P65 (d), (e): one value in two FOVs; a per-plane read of one object on two planes ----------- + + +@pytest.fixture +def nuclei_run(tmp_path): + """P59's stacks (ZYX, Z = 5) with Nuclei masks: value 7 in both FOVs, 9 on one plane.""" + root, out, masks = tmp_path / "exp", tmp_path / "out", tmp_path / "masks" + labels = {"a": np.zeros((5, 6, 8), np.uint16), "b": np.zeros((5, 6, 8), np.uint16)} + labels["a"][1:3, 1:3, 1:3] = 7 # one object on z = 1 and 2 + labels["a"][1, 4:6, 5:7] = 9 # an object on z = 1 only + labels["b"][3, 2:4, 2:4] = 7 # the same value, another FOV + for name, label in labels.items(): + write_ome(root / f"ctrl/rep1/{name}.ome.tif", stack(z=5), "ZYX") + write_ome(masks / f"Nuclei/ctrl/rep1/{name}.ome.tif", label, "ZYX") + published(root, out, masks_folder=masks) + return RunInputs.open(check_masks(out)), labels + + +def test_p65d_one_value_in_two_fovs_is_two_objects(nuclei_run): + inputs, labels = nuclei_run + found = {} + for fov in inputs.fovs(): + volume = inputs.read_mask_volume(fov, "Nuclei", t=0) + np.testing.assert_array_equal(volume, labels[fov.key[-1]]) + found[(fov.key, "Nuclei", 0, 7)] = tuple(np.flatnonzero((volume == 7).any(axis=(1, 2)))) + # Each read is one FOV's volume: value 7 is two objects, keyed apart, never joined. + assert sorted(found.values()) == [(1, 2), (3,)] and len(found) == 2 + + +def test_p65e_per_plane_reads_of_one_object_are_keyed_by_plane(nuclei_run): + inputs, labels = nuclei_run + request = Request(masks=(MaskRequest("Nuclei"),), z_indices=(1, 2)) + rows = {} + for selection in inputs.resolve_request(request).require(): + key = selection.key + for plane in selection.planes: + (z,) = plane.z + read = inputs.read_objects(selection, "Nuclei", t=plane.t, z=z) + np.testing.assert_array_equal(read, labels[key[-1]][z]) + for value in np.unique(read[read > 0]).tolist(): + row = (key, "Nuclei", plane.t, z, value) + assert row not in rows # no duplicate key + rows[row] = int((read == value).sum()) + a = next(k for k, *_ in rows if k[-1] == "a") + b = next((k for k, *_ in rows if k[-1] == "b"), None) + # Object 7 of FOV a: one row per plane; object 9: a row on z = 1 only, none on z = 2. + assert (a, "Nuclei", 0, 1, 7) in rows and (a, "Nuclei", 0, 2, 7) in rows + assert (a, "Nuclei", 0, 1, 9) in rows and (a, "Nuclei", 0, 2, 9) not in rows + assert b is None # FOV b's 7 is on z = 3, outside the selection: no row, never a zero diff --git a/tests/test_volumes_run.py b/tests/test_volumes_run.py new file mode 100644 index 00000000..937cad55 --- /dev/null +++ b/tests/test_volumes_run.py @@ -0,0 +1,395 @@ +"""Spec ADR 0010: Z-stacks are described, run and recorded as volumes (P59-P61, P67-P74, P86-P99). + +The description step no longer refuses a Z-stack (``z_stack_not_supported`` is removed, VZ1): it +is described and run without projection. The run records each image's acquisition sizes from its +shape and confirmed roles (VC2), ``image_kind``, ``plane_statistics`` (histograms, normalization +and QC are not computed for a volume, VZ2), the version 7 ``pixel_sizes`` (VC4), the derived +``checks`` (VC5) and ``statistics_artifacts`` (VC1); a run of volumes only writes no table. +""" + +from __future__ import annotations + +import numpy as np +import pytest + +from described_tree import main_described, run_described +from morphobricks_preprocessing import AxisMapping, preflight, read_manifest, review_axes +from morphobricks_preprocessing.manifest import ManifestFormatError +from morphobricks_preprocessing.run_inputs import RunInputs, RunInputsError +from tiff_tree import write_data, write_plain +from volume_tree import ( + CALIBRATED, + KEEP, + TZYX, + ZYX, + entry, + manifest_data, + published, + size, + stack, + state, + volumes, + write_manifest_data, + write_ome, +) + +NOT_COMPUTED = {"state": "not_computed", "reason": "all_volumes"} + + +def test_p59_a_calibrated_volume_run_is_published_without_projection(tmp_path): + root, out = tmp_path / "exp", tmp_path / "out" + paths = volumes(root, **CALIBRATED) + assert "z_stack_not_supported" not in {i.code for i in preflight(root).issues} + published(root, out) + data = manifest_data(out) + assert data["manifest_version"] == "7" + assert data["statistics_artifacts"] == NOT_COMPUTED + assert data["histogram_table_sha256"] is None and data["histogram_table_content_sha256"] is None + assert data["image_qc"] is None and data["checks"] == [] + assert not (out / "plane_histograms.parquet").exists() and not (out / "image_qc.csv").exists() + for path in paths: + found = entry(data, path) + assert found["shape"] == [5, 6, 8] + assert (found["z_count"], found["t_count"], found["c_count"]) == (5, 1, 1) + assert ( + found["image_kind"] == "volume" and found["plane_statistics"] == "not_computed_volume" + ) + assert (found["plane_count"], found["statistics_rows"]) == (5, 0) + assert size(found, "Z") == { + "role": "Z", + "value": 0.7, + "unit": "micrometer", + "source": "header", + "reason": None, + } + inputs = RunInputs.open(out) + assert [(f.z_count, f.t_count, f.plane_ids) for f in inputs.fovs()] == [(5, 1, ())] * 2 + + +@pytest.mark.parametrize( + ("statement", "source", "reason"), + [ + (None, "unknown", "W_AXIS_UNCALIBRATED"), # (a) no Z step anywhere + ("ctrl,Z,,pixels\n", "pixels", "W_AXIS_UNCALIBRATED"), # (b) stated as pixels + ("ctrl,Z,0.5,um\n", "stated", None), # (c) stated in calibration.csv + ], + ids=["unknown", "pixels", "stated"], +) +def test_p60_an_unknown_z_step_is_recorded_never_guessed(tmp_path, statement, source, reason): + root, out = tmp_path / "exp", tmp_path / "out" + xy = {k: v for k, v in CALIBRATED.items() if "Z" not in k} + volumes(root, **xy) + if statement is not None: + state(out, statement) + published(root, out) + data = manifest_data(out) + z = size(entry(data, "ctrl/rep1/s0.ome.tif"), "Z") + assert (z["source"], z["reason"]) == (source, reason) + assert z["value"] == (0.5 if source == "stated" else None) + if reason is None: + assert data["checks"] == [] # X and Y in the header + return + (check,) = data["checks"] # one run-level warning (owner answer, VZ30) + assert check["code"] == "W_AXIS_UNCALIBRATED" and check["axis"] is None + assert check["counts"] == {"z": 2} and check["places"] == [] + assert [(i["path"], i["z_count"], i["source"]) for i in check["images"]] == [ + ("ctrl/rep1/s0.ome.tif", 5, None), + ("ctrl/rep1/s1.ome.tif", 5, None), + ] + report = (out / "discovery_report.txt").read_text(encoding="utf-8") + assert "W_AXIS_UNCALIBRATED" in report and "calibration.csv" in report + assert RunInputs.open(out).pixel_sizes("ctrl/rep1/s0.ome.tif")["Z"].reason == reason + + +def test_p60e_no_x_or_y_step_is_the_same_code_on_planes_and_volumes(tmp_path): + root, out = tmp_path / "exp", tmp_path / "out" + write_ome(root / "ctrl/rep1/a.ome.tif", stack(z=1)[0], "YX") + published(root, out, missing_as_singleton=True) + data = manifest_data(out) + found = entry(data, "ctrl/rep1/a.ome.tif") + assert found["image_kind"] == "plane" + assert [size(found, r)["reason"] for r in "XYZT"] == ["W_AXIS_UNCALIBRATED"] * 2 + [None] * 2 + # One run-level warning; never z on a plane image (I3). + assert [c["counts"] for c in data["checks"]] == [{"x": 1, "y": 1}] + + +def _mixed(root, same_unit=False): + volumes(root, count=1) + folder = "ctrl/rep1" if same_unit else "drug/rep1" + write_ome(root / f"{folder}/p0.ome.tif", stack(z=1, start=7)[0], "YX") + + +@pytest.mark.parametrize("same_unit", [False, True], ids=["by_condition", "in_one_unit"]) +def test_p61_a_mixed_run_is_checked_early_warned_recorded_and_published(tmp_path, same_unit): + # VZ4, VZ8, VZ19, as clarified by the owner on 2 December 2026: check and inform, never refuse. + root, out = tmp_path / "exp", tmp_path / "out" + _mixed(root, same_unit) + pre = preflight(root) + early = review_axes(pre.metadata, ZYX, missing_as_singleton=True).issues + (warned,) = [i for i in early if i.code == "W_MIXED_PLANES_AND_VOLUMES"] + assert not warned.is_error and "1 plane image(s) and 1 volume(s)" in warned.message + assert "Split it into two experiments" in warned.action + result = published(root, out, missing_as_singleton=True) + data = manifest_data(out) + (mixed,) = [c for c in data["checks"] if c["code"] == "W_MIXED_PLANES_AND_VOLUMES"] + assert mixed["counts"] == {"planes": 1, "volumes": 1} and mixed["axis"] is None + assert [(i["path"], i["z_count"], i["source"]) for i in mixed["images"]] == sorted( + [("ctrl/rep1/s0.ome.tif", 5, None), (_plane_path(same_unit), 1, None)], + key=lambda i: i[0], + ) + levels = [p["level"] for p in mixed["places"]] + assert levels == ( + ["condition", "biological_repeat", "imaging_unit", "run"] + if same_unit + else ["biological_repeat", "run"] + ) + assert data["statistics_artifacts"] == {"state": "computed"} + mixed_issues = [i for i in result.issues if i.code == "W_MIXED_PLANES_AND_VOLUMES"] + assert len(mixed_issues) == 1 and not mixed_issues[0].is_error # the canonical one only + assert "R_UNIT_NOT_HOMOGENEOUS" not in {i.code for i in result.issues} + rows = read_manifest(out / "run_manifest.json") + assert {f.relative_path: f.statistics_rows for f in rows.files} == { + "ctrl/rep1/s0.ome.tif": 0, + _plane_path(same_unit): 1, + } + report = (out / "discovery_report.txt").read_text(encoding="utf-8") + assert "MorphoFeature refuses this run as it stands" in report + + +def test_the_command_line_check_prints_the_mixed_warning(tmp_path, capsys): + root, out = tmp_path / "exp", tmp_path / "out" + _mixed(root) + args = ["check", str(root), "--output", str(out), "--missing-as-singleton"] + assert main_described(args) == 0 + printed = capsys.readouterr().out + assert "W_MIXED_PLANES_AND_VOLUMES" in printed or "mixes 1 plane image(s)" in printed + + +def test_vz32_volumes_need_the_explicit_choice_and_it_is_recorded(tmp_path): + root, out = tmp_path / "exp", tmp_path / "out" + volumes(root) + refused = run_described(root, ZYX, output_folder=out) + assert not refused.written + assert "z_stacks_not_chosen" in {i.code for i in refused.issues if i.is_error} + published(root, out) + assert manifest_data(out)["z_handling"] == "kept" + again = run_described(root, ZYX, output_folder=out) # the recorded choice is kept + assert again.written and manifest_data(out)["z_handling"] == "kept" + + +def test_vc11_a_plain_stack_confirmed_zyx_joins_a_unit_of_plane_images(tmp_path): + # VC11 compares the confirmed roles without Z and T: no R_UNIT_NOT_HOMOGENEOUS for layout. + root, out = tmp_path / "exp", tmp_path / "out" + write_plain(root / "ctrl/rep1/a.tif", stack(z=3)) + write_plain(root / "ctrl/rep1/b.tif", stack(z=1)[0]) + mapping = AxisMapping("IYX", "ZYX") + result = run_described(root, mapping, output_folder=out, missing_as_singleton=True, mode=KEEP) + assert result.written, [(i.code, i.message) for i in result.issues if i.is_error] + assert "W_MIXED_PLANES_AND_VOLUMES" in {i.code for i in result.issues} + + +def _plane_path(same_unit): + return "ctrl/rep1/p0.ome.tif" if same_unit else "drug/rep1/p0.ome.tif" + + +def test_p67_a_time_lapse_and_a_one_slice_z_are_planes_without_z_reason(tmp_path): + root, out = tmp_path / "exp", tmp_path / "out" + write_ome(root / "ctrl/rep1/a.ome.tif", stack(z=1, t=10)[:, 0], "TYX") + published(root, out, TZYX, missing_as_singleton=True) + found = entry(manifest_data(out), "ctrl/rep1/a.ome.tif") + assert (found["z_count"], found["t_count"], found["statistics_rows"]) == (1, 10, 10) + assert size(found, "Z") == { + "role": "Z", + "value": None, + "unit": None, + "source": "unknown", + "reason": None, + } + assert len(RunInputs.open(out).histograms()) == 10 + + +def test_p74_an_unnamed_three_channel_volume_reads_its_channels(tmp_path): + root, out = tmp_path / "exp", tmp_path / "out" + write_data(root / "ctrl/rep1/a.tif", stack(z=5, c=3), "ZCYX") + published(root, out, AxisMapping("ZCYX", "ZCYX")) + (fov,) = RunInputs.open(out).fovs() + assert (fov.c_count, fov.z_count, fov.t_count) == (3, 5, 1) and len(fov.channel_ids) == 3 + plane = RunInputs.open(out).read_plane(fov, z=4) + np.testing.assert_array_equal(plane, stack(z=5, c=3)[4]) + + +def test_a_plain_stack_confirmed_with_a_z_role_is_a_volume(tmp_path): + root, out = tmp_path / "exp", tmp_path / "out" + write_plain(root / "ctrl/rep1/a.tif", stack(z=3)) + review = review_axes(preflight(root).metadata, AxisMapping("IYX", "ZYX")) + assert review.ok, review.issues + published(root, out, AxisMapping("IYX", "ZYX")) + (fov,) = RunInputs.open(out).fovs() + assert fov.z_count == 3 and fov.volume + + +def test_p99_a_rerun_whose_images_became_volumes_removes_the_tables(tmp_path): + root, out = tmp_path / "exp", tmp_path / "out" + write_plain(root / "ctrl/rep1/a.tif", stack(z=3)) + published(root, out, AxisMapping("IYX", "TYX")) # first read as a time-lapse: planes + assert (out / "plane_histograms.parquet").exists() and (out / "image_qc.csv").exists() + result = published(root, out, AxisMapping("IYX", "ZYX")) + assert not (out / "plane_histograms.parquet").exists() and not (out / "image_qc.csv").exists() + assert manifest_data(out)["statistics_artifacts"] == NOT_COMPUTED + assert {"plane_histograms.parquet", "image_qc.csv"} <= set(result.replaced) + RunInputs.open(out) # no stale table beside the run + + +def test_p73_a_stale_table_beside_a_run_of_volumes_is_refused(tmp_path): + root, out = tmp_path / "exp", tmp_path / "out" + volumes(root) + published(root, out) + (out / "plane_histograms.parquet").write_bytes(b"left by another run") + with pytest.raises(RunInputsError, match="plane_histograms.parquet"): + RunInputs.open(out) + + +# P68, P86-P91: the reader refuses a manifest that breaks a version 7 rule --------------------- + + +@pytest.fixture +def volume_run(tmp_path): + root, out = tmp_path / "exp", tmp_path / "out" + volumes(root) + published(root, out) + return out + + +@pytest.fixture +def plane_run(tmp_path): + root, out = tmp_path / "exp", tmp_path / "out" + write_ome(root / "drug/rep1/p0.ome.tif", stack(z=1, start=7)[0], "YX") + published(root, out, missing_as_singleton=True) + return out + + +def _refused(out, edit, match=None): + data = manifest_data(out) + edit(data) + write_manifest_data(out, data) + with pytest.raises((ManifestFormatError, RunInputsError), match=match): + RunInputs.open(out) + + +@pytest.mark.parametrize( + "edit", + [ + lambda d: d.pop("checks"), + lambda d: d.update(checks={}), + lambda d: d["checks"].append({"code": "W_AXIS_UNCALIBRATED", "axis": "x"}), + lambda d: d["checks"][0].update(extra=1), + lambda d: d.pop("statistics_artifacts"), + lambda d: d.pop("z_handling"), + lambda d: d.update(z_handling=None), + lambda d: d.update(z_handling={"projected": "max"}), + lambda d: d.update(statistics_artifacts={"state": "computed"}), + lambda d: d["files"][0]["pixel_sizes"][0].pop("reason"), + lambda d: d["files"][0]["pixel_sizes"][0].update(source=None), + lambda d: d["files"][0]["pixel_sizes"][2].update(unit="second"), # P86 + lambda d: d["files"][0]["pixel_sizes"][2].update(reason=None), + lambda d: d["files"][0].update(z_count=4), # P88 + lambda d: d["files"][0].update(t_count=0), + lambda d: d["files"][0].update(z_count=True), + lambda d: d["files"][0].update(image_kind="plane"), + lambda d: d["files"][0].update(plane_statistics="computed"), + lambda d: d["files"][0].update(statistics_rows=1), + lambda d: d["files"][0].update(shape=[5, 6]), + lambda d: d.update(histogram_table_sha256="0" * 64), + ], +) +def test_p68_p86_p88_a_manifest_breaking_a_rule_is_refused(volume_run, edit): + _refused(volume_run, edit) + + +def test_p68_a_z_reason_on_a_plane_image_is_refused(plane_run): + def edit(data): + size(entry(data, "drug/rep1/p0.ome.tif"), "Z").update(reason="W_AXIS_UNCALIBRATED") + + _refused(plane_run, edit, "reason") + + +@pytest.mark.parametrize( + "edit", + [ + lambda d: d.update(checks=[c for c in d["checks"] if c["code"] != "W_AXIS_UNCALIBRATED"]), + lambda d: d["checks"].append(d["checks"][-1]), + lambda d: d["checks"][-1]["counts"].update(x=2), + lambda d: d["checks"][-1]["images"].pop(0), + ], +) +def test_p91_checks_that_differ_from_the_entries_are_refused(plane_run, edit): + _refused(plane_run, edit, "checks") + + +@pytest.fixture +def mixed_run(tmp_path): + root, out = tmp_path / "exp", tmp_path / "out" + _mixed(root) + published(root, out, missing_as_singleton=True) + return out + + +def _mixed_check(data): + (check,) = [c for c in data["checks"] if c["code"] == "W_MIXED_PLANES_AND_VOLUMES"] + return check + + +@pytest.mark.parametrize( + "edit", + [ + lambda d: d.update(checks=[c for c in d["checks"] if c is not _mixed_check(d)]), + lambda d: _mixed_check(d)["counts"].update(planes=2), + lambda d: _mixed_check(d)["places"].pop(0), + lambda d: _mixed_check(d)["images"].pop(0), + lambda d: _mixed_check(d).update(axis="z"), + ], +) +def test_p91_a_mixed_check_that_differs_from_the_entries_is_refused(mixed_run, edit): + _refused(mixed_run, edit, "checks") + + +def test_p68_a_version_6_manifest_is_refused_with_the_fix(volume_run): + _refused(volume_run, lambda d: d.update(manifest_version="6")) + + +def test_p89_rows_that_do_not_cover_the_plane_images_are_refused(plane_run, monkeypatch): + from morphobricks_preprocessing import run_inputs_checks + + real = run_inputs_checks.read_records + + def doubled(table, manifest): + rows = real(table, manifest) + return (*rows, rows[0]) + + monkeypatch.setattr("morphobricks_preprocessing.run_inputs.read_records", doubled) + with pytest.raises(RunInputsError, match="one per time point"): + RunInputs.open(plane_run) + + +def test_p87_a_measured_step_of_exactly_one_micrometre_is_kept(tmp_path): + root, out = tmp_path / "exp", tmp_path / "out" + one = {**CALIBRATED, "PhysicalSizeZ": 1.0} + write_ome(root / "ctrl/rep1/a.ome.tif", stack(), "ZYX", **one) + write_ome(root / "ctrl/rep1/b.ome.tif", stack(), "ZYX") + published(root, out) + data = manifest_data(out) + assert size(entry(data, "ctrl/rep1/a.ome.tif"), "Z")["value"] == 1.0 + other = size(entry(data, "ctrl/rep1/b.ome.tif"), "Z") + assert (other["value"], other["source"], other["reason"]) == ( + None, + "unknown", + "W_AXIS_UNCALIBRATED", + ) + + +def test_a_czyx_volume_has_its_channels_and_planes(tmp_path): + root, out = tmp_path / "exp", tmp_path / "out" + write_ome(root / "ctrl/rep1/a.ome.tif", stack(z=4, c=2), "ZCYX") + published(root, out, AxisMapping("ZCYX", "ZCYX")) + found = entry(manifest_data(out), "ctrl/rep1/a.ome.tif") + assert (found["c_count"], found["z_count"], found["plane_count"]) == (2, 4, 4) diff --git a/tests/test_zarr_input.py b/tests/test_zarr_input.py index e121982b..881f8713 100644 --- a/tests/test_zarr_input.py +++ b/tests/test_zarr_input.py @@ -467,7 +467,7 @@ def test_review_of_a_mixed_experiment(): assert confirmed.file_mappings["c.ome.zarr"].singleton_roles == ("C",) # Read as one channel, c.ome.zarr differs from the two channels of the others (N43). assert issue(confirmed.issues, "different_channel_counts").paths == ("c.ome.zarr",) - assert sorted(codes(confirmed.issues)) == ["different_channel_counts", "z_stack_not_supported"] + assert sorted(codes(confirmed.issues)) == ["different_channel_counts"] # a volume (ADR 0010) # Reading planes ------------------------------------------------------------------------ diff --git a/tests/volume_tree.py b/tests/volume_tree.py new file mode 100644 index 00000000..7f12f689 --- /dev/null +++ b/tests/volume_tree.py @@ -0,0 +1,87 @@ +"""Small experiments of volumes (Z-stacks) and plane images for the Spec ADR 0010 tests.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import tifffile + +from described_tree import run_described +from morphobricks_preprocessing import AxisMapping, RunMode + +CALIBRATED = { + "PhysicalSizeX": 0.1, + "PhysicalSizeXUnit": "µm", + "PhysicalSizeY": 0.15, + "PhysicalSizeYUnit": "µm", + "PhysicalSizeZ": 0.7, + "PhysicalSizeZUnit": "µm", +} +"""Anisotropic X, Y and Z steps in the header (P59, P85).""" +ZYX = AxisMapping("ZYX", "ZYX") +TZYX = AxisMapping("TZYX", "TZYX") +CZYX = AxisMapping("CZYX", "CZYX") + + +def stack(z=5, t=None, c=None, y=6, x=8, start=0): + """Return a uint16 stack whose every (t, z, c) plane holds distinct values.""" + shape = tuple(n for n in (t, z, c) if n is not None) + (y, x) + return (np.arange(int(np.prod(shape))).reshape(shape) + start).astype(np.uint16) + + +def write_ome(path: Path, data: np.ndarray, axes: str, **metadata) -> Path: + """Write an OME-TIFF with its axes (and any physical sizes) in the header.""" + Path(path).parent.mkdir(parents=True, exist_ok=True) + header = {"axes": axes, **metadata} + tifffile.imwrite(path, data, ome=True, photometric="minisblack", metadata=header) + return Path(path) + + +def state(output: Path, text: str) -> Path: + """Write ``calibration.csv`` lines (``target,axis,size,unit``) into the output folder.""" + output.mkdir(parents=True, exist_ok=True) + path = output / "calibration.csv" + path.write_text("target,axis,size,unit\n" + text, encoding="utf-8") + return path + + +def volumes(root: Path, count=2, z=5, **metadata) -> list[str]: + """Write ``count`` ZYX volumes under ``ctrl/rep1``; return their paths.""" + paths = [f"ctrl/rep1/s{i}.ome.tif" for i in range(count)] + for i, rel in enumerate(paths): + write_ome(root / rel, stack(z=z, start=100 * i), "ZYX", **metadata) + return paths + + +KEEP = RunMode(keep_z_stacks=True) +"""The explicit choice to keep Z-stacks as volumes (owner answer of 2 December 2026).""" + + +def published(root: Path, output: Path, mapping=ZYX, **kwargs): + """Describe and run, keeping the Z-stacks as volumes; return the result, which is written.""" + kwargs.setdefault("mode", KEEP) + result = run_described(root, mapping, output_folder=output, **kwargs) + assert result.written, [(i.code, i.message) for i in result.issues if i.is_error] + return result + + +def manifest_data(output: Path) -> dict: + """Return the run manifest as JSON data.""" + return json.loads((output / "run_manifest.json").read_text(encoding="utf-8")) + + +def write_manifest_data(output: Path, data: dict) -> None: + """Write edited manifest data back (a hand-edited run folder).""" + (output / "run_manifest.json").write_text(json.dumps(data, indent=2), encoding="utf-8") + + +def entry(data: dict, path: str) -> dict: + """Return one file entry of manifest data.""" + return next(e for e in data["files"] if e["relative_path"] == path) + + +def size(data_entry: dict, role: str) -> dict: + """Return one ``pixel_sizes`` entry of a file entry.""" + return next(s for s in data_entry["pixel_sizes"] if s["role"] == role) diff --git a/tools/code_rules_baseline.json b/tools/code_rules_baseline.json index 24e2ca54..16f876b4 100644 --- a/tools/code_rules_baseline.json +++ b/tools/code_rules_baseline.json @@ -22,7 +22,7 @@ "src/morphobricks_preprocessing/masks/files.py _name_issues: private function of # lines without a docstring": 15, "src/morphobricks_preprocessing/metadata.py _check_channel_names: private function of # lines without a docstring": 32, "src/morphobricks_preprocessing/metadata.py check_metadata: # executable lines (max #)": 84, - "src/morphobricks_preprocessing/metadata.py: # lines (max #)": 622, + "src/morphobricks_preprocessing/metadata.py: # lines (max #)": 604, "src/morphobricks_preprocessing/planes.py _tiff_block_plane: private function of # lines without a docstring": 14, "src/morphobricks_preprocessing/planes.py _zarr_layout: private function of # lines without a docstring": 40, "src/morphobricks_preprocessing/planes.py: # lines (max #)": 1299,