diff --git a/AGENTS.md b/AGENTS.md index a8fdd76e..3f0a1ba7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -142,6 +142,14 @@ src/morphobricks_preprocessing/ image_type.py image type (P4): FLUORESCENCE/RGB, review_image_type (suggestion from TiffMetadata.rgb_samples and the confirmed roles, whether RGB is possible via the brick's check_rgb), image_type_issues (rgb_not_possible) + image_qc.py per-plane image QC metrics (contract §19), measured from the histogram pass's + blocks (run/rows.py _measure taps the first pass, no extra read): PlaneQc, + ImageQc (with the reason each blank metric is blank), qc_memory (the QC term of + the memory estimate), histogram_metrics (Otsu, separation, entropy); image_qc_sums.py + (BlockSums: one cache-blocked sweep of shifted dot products), image_qc_moments.py + (Moments/CoMoments, combined across blocks), image_qc_table.py (image_qc.csv, + strict reader: refuses inconsistent status/metric/reason combinations), + image_qc_record.py (the manifest's image_qc entry) intensity.py intensity checks (P5): check_intensities/check_table (the brick's image_summaries and intensity_checks, IntensityReport), repeat_boxes and repeat_distributions for the notebook's plots, intensity_text for the CLI @@ -214,7 +222,7 @@ src/morphobricks_preprocessing/ colour_composite (an RGB image as one colour picture, display only) planes.py plane-by-plane reader (iter_planes, read_plane, read_sample_plane), table rows as XYC planes whose channels are read one at a time (iter_xyc_planes, XycPlane), - memory estimate, + memory estimate (plane_binning.py Binning: the histogram and image QC terms), check_planes (preflight memory / layout errors); planes over the limit read in blocks of TIFF strips/tiles or zarr chunks (Plane.blocks, BlockReader), reduced previews; plane_errors.py PlaneReadError, PlaneMemoryError @@ -277,11 +285,13 @@ src/morphobricks_preprocessing/ mask_requests.py the resolver's mask uses (contract v3): MaskConversion, mask_uses, objects_conflict (re-exported by run_inputs_request) _io.py write_text_atomic (every file the brick writes) and free_space - manifest.py RunManifest / RunSettings / FileEntry, JSON read/write, SHA-256 of the CSV, + manifest.py RunManifest / RunSettings, JSON read/write, SHA-256 of the CSV (FileEntry and its + manifest data moved to manifest_files.py, re-exported here), check_sources (images against a run, for other bricks, contract §16) run/ the run (a package since PP-3; `morphobricks_preprocessing.run` re-exports its public names): preflight.py (Preflight, preflight, sample_planes), - pipeline.py (run_experiment, incremental), steps.py (header checks, + pipeline.py (run_experiment, incremental), state.py (RunOptions, RunState), + outputs.py (write_generation: the tables and the manifest; replaced_files), steps.py (header checks, rows, outcome), modes.py (restart/full, RunMode with verify_content), recorded.py (inputs reused from the earlier run, InputChange), lock.py (the output folder's O_EXCL lock, remove_stale_lock), output_guard.py (the output folder against the @@ -872,7 +882,7 @@ Technical details go to `logging` (shown in the notebook's "Technical details" p | Topic | Decision | |---|---| | Binning | Per-plane min–max, same bin count per experiment, pooled counts for groups (binning study) | -| Core dependencies | `numpy`, `tifffile`, `scipy` (the mask step's piece counts, Q32) and `morphobricks-normalization` (git dependency pinned to its release tag v0.7.1 (signed zero written as 0.0, NumPy per-bin work; v0.7.1), whose `regions` and `contracts` (Spec ADR 0005; v0.7.0) are not used here but pinned so that every consumer resolves one normalization, whose `stain` module (v0.6.0; `check_options` since v0.6.1), optical-density helpers and optional `histology` extra are used only by the opt-in H&E tissue mask helper (`he-mask` extra), whose reader takes the schema version 5 table (channels by canonical ID, ADR 0003; since v0.5.0), and whose CSV reader checks each row's stored `plane_id`, `image_file` and `bit_depth` (since v0.3.2), refuses a blank `position_id` and tables of schema versions 1 to 3 (v0.4.0), and whose `PlaneRecord` requires a keyword-only `position_id` and which refuses corrupt or ambiguous statistics and parameters (v0.3.3); `[tool.hatch.metadata] allow-direct-references`). `ipywidgets` and `matplotlib` in the `notebook` extra; `zarr` in the `zarr` extra; `pytest` and `ruff` in `dev` | +| Core dependencies | `numpy` (2.0 or later: the image QC sums use `numpy.vecdot`), `tifffile`, `scipy` (the mask step's piece counts, Q32) and `morphobricks-normalization` (git dependency pinned to its release tag v0.7.1 (signed zero written as 0.0, NumPy per-bin work; v0.7.1), whose `regions` and `contracts` (Spec ADR 0005; v0.7.0) are not used here but pinned so that every consumer resolves one normalization, whose `stain` module (v0.6.0; `check_options` since v0.6.1), optical-density helpers and optional `histology` extra are used only by the opt-in H&E tissue mask helper (`he-mask` extra), whose reader takes the schema version 5 table (channels by canonical ID, ADR 0003; since v0.5.0), and whose CSV reader checks each row's stored `plane_id`, `image_file` and `bit_depth` (since v0.3.2), refuses a blank `position_id` and tables of schema versions 1 to 3 (v0.4.0), and whose `PlaneRecord` requires a keyword-only `position_id` and which refuses corrupt or ambiguous statistics and parameters (v0.3.3); `[tool.hatch.metadata] allow-direct-references`). `ipywidgets` and `matplotlib` in the `notebook` extra; `zarr` in the `zarr` extra; `pytest` and `ruff` in `dev` | | OME-Zarr (Q12) | Input may be TIFF and/or OME-Zarr (folders ending in `.zarr`), mixed. OME-Zarr axes come from their metadata and are matched by role; level 0 of a single image only, several images per store is `multiple_series`. *Removed in v0.4.0 (plan Q46): TIFF images are always read directly; the following describes v0.3.* TIFF choice once per experiment (`convert_tiffs`): read directly (default) or convert to `/ome_zarr` (OME-NGFF 0.4) and compute rows from the copies; switching recomputes TIFF rows and removes unused copies. Reads OME-NGFF 0.4 and 0.5 (0.5 needs zarr 3). In the notebook: its own step-3 card "(Optional) Image conversion" after Settings (Q13): radio buttons (read directly = recommended), a disk-space warning (amber, red when the estimate exceeds free space, never blocking), and conversion settings (chunk size, compression + level, pyramid levels) shown only when converting. CLI `--convert-tiff` with `--chunk-size`, `--compression`, `--compression-level`, `--pyramid-levels`. No overlap setting: chunks never overlap | | System files (Q5) | Ignored silently; `single` check and sibling uniqueness are case-insensitive | | Too-deep folders (Q7) | Error | diff --git a/CHANGELOG.md b/CHANGELOG.md index c1b111d6..41ce39a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,28 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. in the manifest's new optional key `channel_identity`, beside `intensity_checks` (manifest version unchanged). +- **Image QC metrics per plane and channel, computed in the histogram pass** (MorphoFeature + design `image-qc-metrics-2026-11-21`, metrics 1-8): a new run-folder table `image_qc.csv`, one + row per plane and channel, with `foreground_fraction` (Otsu, with `otsu_threshold` and + `otsu_separation`), `entropy`, `normalized_variance`, `tenengrad`, `laplacian_variance`, + `correlation_1/4/16`, `local_focus_median/p10` and `tile_mean_cv`, scale-free and measured + from the blocks the histogram already reads (no extra read; `image_qc`, `image_qc_sums`, + `image_qc_moments`, `image_qc_table`, `image_qc_record`). The manifest gains the optional key + `image_qc` (file, SHA-256, `qc_version` and settings; manifest version stays 5). The table + follows the histogram step's reuse and resume rules: staging version 2 stages it with the + rows (a version 1 staged record is discarded and read again), and a run whose earlier + manifest has no `image_qc` entry recomputes every row once. `tools/benchmark_image_qc.py` + times the histogram step with and without the metrics on identical outputs. The + power-spectrum slope (PLLS) is not included (cost). Contract §19, user guide §6. Each blank + metric has a reason in the `blank_reasons` column (`constant_plane`, `no_pairs`, + `no_variance`, `non_positive_mean`, `plane_too_small`, `non_finite_pixels`, + `no_finite_pixels`), and the reader and writer refuse inconsistent status, metric and reason + combinations. The contract states what the metrics are not: scale-free only under pure + multiplication (an offset changes the ratio metrics), `otsu_separation` of noise is 2/pi (use + `correlation_1` for emptiness), `local_focus_p10` is content coverage, central-difference + Tenengrad (not Sobel), Pearson lag correlations (not Haralick), and the block tolerances are + observations, not guarantees. + - **Tag this repeat folder (all conditions)** on *Tag channels* (owner request of 20 November 2026): one row of tags per biological-repeat **folder name** and channel count; set once, it is saved for every condition's imaging units in that folder (technical repeats included), @@ -137,6 +159,19 @@ old pin are refused with `spec_commit_mismatch`, as at every re-pin. ### Changed +- **Another memory limit recomputes the rows when planes are read in blocks**: the image QC + neighbour metrics of a plane read in blocks depend on its blocks, so rows measured under + another limit were silently reused (and resumed). With the earlier run or this one reading any + plane in blocks, a changed `memory_limit` recomputes every row (reason in the report), and + staged rows of an image read in blocks are resumed only under their limit (`RowKey.block_limit`); + whole planes on both sides still keep their rows. The QC rows reused must also match the + histogram rows' full identity, not only plane ID and channel. The working memory of the QC sums + (`image_qc.qc_memory`) is part of the plane and block estimates (`plane_binning.Binning`), so + blocks are a little smaller; a float plane's sums are centred on its mean, not a rounded one. +- **NumPy 2.0 or later** (the image QC sums use `numpy.vecdot`), with the dependency floors + raised to releases that import with NumPy 2: SciPy 1.13, Matplotlib 3.8.4 (`notebook`) and + scikit-image 0.24 (`he-mask`). Checked on Python 3.11 with the lowest versions of every + dependency and on 3.13 with the newest. - **Draft file version 4** (`morphobricks.draft.json`): the keys `channel_layout` and `switch_mode`, and a unit's `channels_from`. A version 3 draft is refused (`unknown_version`; it was written under the old Spec pin anyway, `spec_commit_mismatch`). diff --git a/docs/contract.md b/docs/contract.md index 0c6e2b69..d13dc0a5 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -269,7 +269,7 @@ interpretation. | `settings` | `bin_count`, `memory_limit` (bytes), `missing_as_singleton`, `exclude` (sorted relative paths), `histogram` (`HistogramSettings.to_dict()` of the normalization brick: `library_version`, `histogram_range`, `robust_quantiles`, `min_central_bins`, §4; required), `verify_content` (JSON boolean, below: `true` when the run verified content, `false` when it opted out, so that an opt-out is on record (#159); required). Since v0.5.1 (SWEEP-PP) no key the writer always writes is defaulted when absent: such a manifest is refused. | | `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; information only; 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` | 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`). | | `csv_sha256` | SHA-256 of the table written with this manifest. | | `experiment_design_sha256` | SHA-256 of the `experiment_design.csv` the run derived from its description and wrote with the table (§12), so later bricks can check that the design they read is the one the run wrote. | | `masks` | The masks paired with the images (§15), when the run was given a masks folder or its OME-Zarr images have label images (always used): `folder` (absolute path of the masks folder, null when only OME-Zarr label images were used), `types` (sorted mask-type names) and `files` (one entry per image and mask type, sorted by image then type: `image`, `type`, `path`, `source` `folder` or `ome-zarr`, `axes` and `shape`: the mask's axes and lengths without its length-1 axes other than Y and X, `YX` for a 2D mask (`[1, 512]` for a mask one pixel high), with `Z` and/or `T` for a mask with depth slices or time points, e.g. `TYX` and `[50, 512, 512]`; §15). Absent when the run had no masks. Optional key: the table does not depend on the masks. `axes` and `shape` are absent in manifests written before them, whose masks are all 2D; a later brick must read `axes` before using a mask and never apply a 2D mask to several planes. **Version 2:** `axes` are the mask's axes as stored (its header's letters: `IYX` for a plain stack), and each mask entry also has `size` and `mtime_ns` (its fingerprint, the size and modification time `source_signature` gives: the mask file, or the label image's folder), `roles` (one per axis of `axes`, what each is read as: `TYX` for that plain stack stated `--mask-axes Cells=TYX`), `axes_from` (`header`, or `stated` when the axes were stated for its mask type). The release candidates up to v0.4.0rc6 also wrote `shared` (true for a 2-D mask stated `YX` for its type: one plane shared by every plane of its image); the option was removed by the owner decision of 5 November 2026, the key is no longer written, and `RunInputs.open` refuses a manifest that records `shared: true` (stated or not), naming the masks and asking for one mask plane per time point and a new run. A mask is read as stored, never reordered. | @@ -283,8 +283,9 @@ interpretation. | `experiment_description` | Always present (v0.5.1: every run is described, §0; experiment-v1 §4.5a, §4.6, §9.3). An object: `sha256` (of the exact bytes the run read: provenance, never a cache key), `schema_version`, `section_digests` (`conditions`, `channels`, `repeats`, `masks`), `units` (one object per declared unit: its repeat, condition and technical repeat IDs and `image_type_header_verified`, false for a format whose header states no colour interpretation and for a unit whose header was overridden; only for a unit declared `rgb` with `rgb_header_override = true` whose TIFF header does not say RGB and whose images all have three interleaved samples (Spec experiment-v1 §4.4b, amendment RH1), `image_type_header_overridden` (true) and `header_photometric` (the header's photometric interpretation, for example `minisblack`; distinct ones joined by `, `); for every unit declared `rgb`, `rgb_header_override`: the declared key (`true` or `false`, absent in the file is `false`; owner answers of 14 November 2026: declared and effective are recorded separately); for a unit that declares it `true`, `rgb_header_override_images`: a list sorted by `image` (relative path) of objects `image`, `override` (`used`: it lifted a header that does not say RGB; `unused`: it did not) and `header_photometric` (that image's own header colour interpretation, kept as evidence; null for a format that states none), an `unused` item adding `unused_reason` (`header_already_rgb`: header-verified; `no_colour_interpretation`, for example OME-Zarr: not header-verified). Homogeneity (`R_UNIT_NOT_HOMOGENEOUS`) compares the effective image type, so images of an overridden unit that differ only in colour interpretation are one layout; `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` is reported before it. These keys are additive (optional on read, checked when present): the manifest version stays 5; and, only for a unit that has such images, `images_without_header_channel_names`: a list sorted by `image` (relative path) of objects `image`, `header_names` (`none` when the header names no channel, `partial` when only some) and `channel_positions` (the zero-based C positions without a header name). Such an image passes the header checks, needs no evidence and the confirmed layout is used (§4.3); it is listed, not warned about, and the key is omitted for a unit whose images are all fully named; RGB units list nothing), `masks` (per declared mask ID: `source_type`, `representation`, `status`, `images_with_masks`, `images` and each file with its fingerprint and its own `status`) and `records` (the lines of `morphobricks.records.jsonl`, copied unchanged). A mask file is `checked` only when the mask step recorded it in `mask_representation.json` with the same fingerprint, representation and source type; otherwise `not yet checked`. Each unit record also lists its `channels` in source order; in a fast-mode description (Spec ADR 0006, `channel_layout`) every unit record adds `channels_from` (`experiment` or `unit`, as published) and a unit with `channels_from = "experiment"` adds `fast_layout_images`: one object per checked image, sorted by `path`, with `path`, `fov_key` (an object: `condition`, `biological_repeat`, `technical_repeat`, `position_id`), `header_verified` (true exactly when every channel's evidence is `header`) and `channels`, one object per index of the list: `c`, `channel`, `header_name` (as read, never normalised: `""` for a stated empty name, null when the format states none) and `evidence` (`header`, or `statement`: no name, accepted under the user's statement); additive keys, checked when present (the manifest version stays 5), and `channel_coverage` (manifest version 5, Stage 3 S3.3) classifies every biological repeat for every declared channel ID: `status` `full` (every unit of the repeat lists it), `partial` (some do; also the warning `partial_channel_coverage`) or `unavailable`, with `units_with`, `units` and the units `lacking` it (`condition/technical repeat` IDs). A run refuses units of different image types (`R_HETEROGENEOUS_LAYOUT_NOT_ENABLED`); units with different channel lists are accepted. | | `projection` | Only for a run on a tree of Z-projected copies (the key is left out otherwise, so a run without projection is byte for byte as before; issue #176, run side). An object with exactly `method` (`max`, `mean` or `sum`), `z_range` (`[start, stop]` requested for the experiment, or null for every slice), `conversion_record` (`{file, sha256}`: the record these facts come from, the same SHA-256 as `conversion_record_sha256`), `source_root`, `images` (one per analysed image, by path: `relative_path`, `source_relative_path`, `source_content_sha256`, `source_z_size`, `z_range` (the slices used), `source_dtype`, `output_dtype`, `dtype_rule`, `rounding`, `significant_bits_dropped`), `masks_paired` (the masks paired with projected images, sorted) and `warnings` (`["masks_on_projected_images"]` exactly when `masks_paired` is not empty). A reader that knows nothing of the key ignores it, but it also refuses the conversion record the run names (version 3 or later), so projected copies are never read by it as plain images; `manifest_version` is not changed. | | `lab_links` | Only for a run given lab-tool links (v0.5.1, PP-2; Spec experiment-v1 §9.3; owner decision of 9 November 2026); the key is left out otherwise, so a run without links is byte for byte as before. An object with exactly the keys the user gave, recorded verbatim: `repository_url`, `commit` and `experiment_path` (each non-empty text with no outer whitespace or control character; `commit` a full lowercase hexadecimal SHA of 40 or 64 characters) and, when given, `repeat_codes` (each lab-tool repeat code to a canonical biological repeat ID, written sorted by code). Input: `run --lab-links FILE` (a UTF-8 JSON object; any other key, a value of another type, an empty value or a key given twice in one object is refused before anything is read, `lab_links_invalid`), or `run_experiment(mode=RunMode(lab_links=LabLinks(...)))` (`read_lab_links`, `LabLinks`, `LabLinksError`). Nothing is trimmed, guessed or filled in. A `repository_url` holding a credential (a password, `user:password@`, in any form; a user name before `@` in a URL whose scheme is not `ssh`, `git+ssh` or `ssh+git`, because `https://TOKEN@host/...` carries a token there), a query string or a fragment (`?` or `#`) is refused (`lab_links_invalid`), and the refusal does not repeat the URL: a credential is never written to the manifest. An SSH remote's login name (`git@host:lab/db.git`, `ssh://git@host/...`) is kept. `repeat_codes` are used only when the user confirmed them for this run (`--confirm-repeat-codes`, `LabLinks(repeat_codes_confirmed=True)`, `read_lab_links(confirmed=True)`; never read from the file): equal strings are not evidence. They must name every biological repeat of the published description exactly once and no other ID (compared exactly: a source folder or display name is not an ID). Each refusal is a run error reported together, before any pixel is read: `lab_links_repeat_codes_not_confirmed`, `lab_links_repeat_unknown`, `lab_links_repeat_twice`, `lab_links_repeat_missing`. **Provenance only:** the links are never written to `morphobricks.toml` (`labchronicle`, `provenance` and `source_database` stay `E_FORBIDDEN_FIELD`, `i99`), and they are in no section digest, description SHA-256, row key, staging key, mask-step check, design, table or report: a run with, without or with changed links publishes the same files apart from this key, and so the manifest's own SHA-256 (which the report records, and which later bricks that pin the manifest see change). Not a recorded input (§9.2): a run not given links records none. The reader checks the entry as the input is checked; a malformed one makes the manifest malformed. | +| `image_qc` | The image QC table written with the run (§19): an object with exactly `file` (`"image_qc.csv"`), `sha256` (of the table), `qc_version` (`"1"`) and `settings` (`qc_version`, `correlation_lags` `[1, 4, 16]`, `tile_grid` `[8, 8]`, `entropy_bins` `64`). Written by every run of this version; absent in manifests written before it (optional on read, checked when present: anything else makes the manifest malformed; the manifest version stays 5). The next run reuses earlier rows only when the table has this SHA-256, the same `qc_version` and settings, and a row for each channel of each histogram row; otherwise every row is recomputed, with the reason (§19). `RunInputs` does not read or check the table. | | Older versions | Refused (v0.5.1, see `manifest_version`): no row of an older run is reused and nothing is taken from it; the next run reads every image again. | -| Row reuse | A file's rows are reused only when its row key is the earlier run's (`fingerprint.RowKey`, one rule for "the same file, read the same way", audit D5): its fingerprint (`fingerprint.Fingerprint`: size and modification time, and for an OME-Zarr image the inventory digest), labels, axes, roles, `singleton_roles`, `axes_from` and the path it is read from (so moving or converting the experiment recomputes it), and the settings that change rows (bins, histogram range, robust quantiles, range-check limit). **The identity rule is the fingerprint, which is metadata** (design v0.4 §1): its known blind spot is a file rewritten with the same size whose modification time (for an OME-Zarr image, every changed file's) is set back to its earlier value; its earlier rows are then reused, its staged rows resumed, and `RunInputs` accepts it. | +| Row reuse | A file's rows are reused only when its row key is the earlier run's (`fingerprint.RowKey`, one rule for "the same file, read the same way", audit D5): its fingerprint (`fingerprint.Fingerprint`: size and modification time, and for an OME-Zarr image the inventory digest), labels, axes, roles, `singleton_roles`, `axes_from` and the path it is read from (so moving or converting the experiment recomputes it), and the settings that change rows (bins, histogram range, robust quantiles, range-check limit; and, for an image whose planes are read in blocks, the memory limit, which sets the blocks the image QC metrics depend on, §19). **The identity rule is the fingerprint, which is metadata** (design v0.4 §1): its known blind spot is a file rewritten with the same size whose modification time (for an OME-Zarr image, every changed file's) is set back to its earlier value; its earlier rows are then reused, its staged rows resumed, and `RunInputs` accepts it. | | Content verification (on by default, owner 7 November 2026, #159; opt-in before) | Every run does it unless it opts out with `RunMode(name, verify_content=False)` (`run_experiment(mode=...)`, CLI `--no-verify-content`, the notebook's "Verify each image's content" box unticked); the opt-out is recorded as `settings.verify_content: false`. It closes that blind spot: each analysed image's `content_sha256` is taken after its fingerprint and recorded; it is part of the row key, so an earlier or staged row is reused only for the same content; an image read must still have it after its pixels are read (else `source_changed_during_run`); every recorded image (reused, resumed or read; an OME-Zarr image by the same store digest) is hashed once more as the last step before the commit, after the generation is staged, flushed and recorded and right before the manifest's rename (`staged_generation(before_commit=...)`, review of rc5), and a mismatch is `source_changed_during_run`: the publication folder is discarded and the earlier generation is intact, as for a fingerprint change; an image that cannot be hashed is `unreadable_planes`; and `RunInputs.open` of such a run checks every image's content SHA-256 once (reads after `open` check the fingerprint). It is a recorded input (`settings.verify_content`): a run given none keeps the recorded choice (true without one: a first run, or a version 1 manifest); turning it on or off recomputes every row ("content verification (verify_content) was turned on/off"), is reported as the change `verify_content`, and discards staged rows of the other mode with that reason. It reads every analysed image whole twice more per run (when its entry is made and before the commit), once more for each image read, and once for each `RunInputs.open`; the cost is in the pull request that made it the default (about 3 seconds per 1.5 GB read, measured at 1 GB/s of SHA-256). A run that verifies writes manifest version 3. Masks are hashed too (issue #160): each mask's content SHA-256 is taken once the header checks pass and again as the last step before the commit, and a mismatch (or a mask that cannot be hashed) is `mask_changed_during_run`; it is not recorded in the manifest (no mask has rows to reuse), so the manifest's mask entries are unchanged. Not covered: a change between the header read and the first hashing with its metadata kept (the rows are of the hashed content, the header may be of the earlier one); and a change in the moment between the last hashing and the rename, or after the commit (`RunInputs.open` hashes again). | | Removed keys | `settings.convert_tiffs`, `settings.conversion` and `files[].ome_zarr_path` were written by v0.3 runs that converted TIFF images to OME-Zarr in the output folder (removed in v0.4.0, §10); a manifest that holds them is still read, and they are ignored. The copies such a run left in `/ome_zarr` are not touched. | | Flags | `missing_as_singleton`, `verify_content`, `read_in_blocks`, `channel_names_trimmed` and `channels_from_rgb_samples` are JSON booleans (`true`/`false`); any other value (`"false"`, `0`) makes the manifest malformed, never read as true or false, and `write_manifest` refuses to write one (`ValueError`), so a written manifest always reads back. | @@ -785,11 +786,11 @@ any of them changes that test, this section and the CHANGELOG together. | Topic | Rule | |---|---| -| Staging | As soon as a run has read one image, that image's rows are staged in the output folder's `.staging` folder: a `.csv` with its rows (the normalization brick's writer, the table's format) and then `.json` (staging version 1) naming the image, its staging key and the rows file's SHA-256. The staging key is the image's row key (§9: fingerprint, labels, axes, roles, `singleton_roles`, `axes_from`, read path, bins and histogram settings) with the pixel type, the table's schema version and the versions of `morphobricks-preprocessing` and `morphobricks-normalization`. A rows file without its record (killed between the two) was never staged. | +| Staging | As soon as a run has read one image, that image's rows are staged in the output folder's `.staging` folder: a `.csv` with its rows (the normalization brick's writer, the table's format), a `.qc.csv` with its image QC rows (§19) and then `.json` (staging version 2; a version 1 record is discarded and its image read again) naming the image, its staging key and the SHA-256 of both rows files. The staging key is the image's row key (§9: fingerprint, labels, axes, roles, `singleton_roles`, `axes_from`, read path, bins and histogram settings) with the pixel type, the table's schema version, the image QC `qc_version` and the versions of `morphobricks-preprocessing` and `morphobricks-normalization`. A rows file without its record (killed between the two) was never staged. | | Resume | A run killed part-way (a crash, a kill, a lost Colab session) is resumed by the next run: each image that needs new rows whose staged key is the key it would have now (and whose fingerprint is still that; with content verification, whose content SHA-256, part of the key, too) takes its staged rows without its pixels being read (`RunResult.resumed`, report `resumed`). Any other staged rows are discarded and reported with the reason (report `staged_discarded`): the image changed since its rows were staged; its roles, labels, folder or row settings changed; the experiment's pixel type changed; another version staged them; they could not be read (reported under the image the record names, else the record's file name); the table already holds its rows; the image is no longer analysed; a `full` run (which reuses no staged row). Nothing is reused when identity is uncertain. A run that stops keeps `.staging`, so the next run resumes; a run that publishes removes it after the commit. Every check still runs over the whole experiment (design v0.4 §1). A resumed table is byte-identical to an uninterrupted run's. | | Source changes during a run (issue #90) | Each image's header is read between two fingerprints that must agree (`preflight(bind_headers=True)`), and that fingerprint is the one its manifest entry records; the image must still have it just after its pixels are read (only then are its rows staged); and every analysed image (reused, resumed or read) is fingerprinted again just before the commit (in a `verify_content` run also hashed again, as the last step before the manifest's rename, above). An image that changed or went missing at any of these points is the error `source_changed_during_run` naming it: no scientific outputs are published and sources are untouched; the discovery report is written; the earlier generation is kept, and the rows staged so far stay staged (the changed image's own rows are not staged, or are discarded by the next run). Masks are bound the same way (issue #160): each mask's header is read between two fingerprints that must agree (`find_masks(bind=True)`, `MaskFile.bound`; else `mask_changed_during_check`), that fingerprint is the one its manifest entry records (before #160 the fingerprint was taken when the manifest was written), and every mask must still have it right before the commit; a mask that changed or went missing is the error `mask_changed_during_run` naming it, with what changed, and nothing is published (`mask_binding`). Source masks are checked as late as practicable (right before the manifest's `os.replace`, in `before_commit`), and ordinary concurrent edits are detected. The source files are not locked and not snapshotted (owner decision of 8 November 2026, issue #222), so a change in the instant between that final check and the manifest replace is not detected: the manifest binds the masks' bytes as they were at that final check. | | Workers (issue #107) | `RunMode(workers=..., max_ram=...)` (`run_experiment(mode=...)`, CLI `run --workers N\|auto`, `--max-ram SIZE`): how many images are read at once, each whole (every plane and channel) in its own worker thread. A worker only reads its image with the run's reader and checks it after the read (fingerprint; with content verification, SHA-256), and returns its rows or `failed` / `changed`; the calling thread alone resumes staged rows (before any worker starts), stages each image's rows as soon as its worker returns, aggregates them in the sorted order of the images, runs the dataset-wide checks, publishes and calls `progress`. `1` (default): one image after the other in the calling thread, as before. A whole number `N`: `N` threads (at most one per image to read). `"auto"`: `min(images to read, CPUs this process may use)` and, with `max_ram` (bytes; only with `"auto"`), at most `(max_ram - 256 MiB) // largest`, where `largest` is the largest image's working-memory estimate from its header (`planes.plane_layout` under the run's memory limit: one plane, or one block when its planes are read in blocks, plus `8 × bins` per 2-D plane for its rows; never the size on disk; 256 MiB are kept for the run itself). Every image is counted as the largest (conservative); an image whose estimate alone is over that budget stops the run before any pixel is read: the error `image_over_max_ram` naming those images. The memory limit itself is never changed. The outputs are byte for byte those of the serial run with any value (every file, the manifest included: `written_at` is the only field excluded from byte identity, see §9); the number of workers is in no row key, staging key, manifest or table (`RunResult.workers` only: the size of the thread pool the images were read with, `min(workers planned, images to read)`, which is the most images read at once and the most distinct threads that read them, not a count of the threads used, since a pool starts a thread only when no idle one is waiting; 1 when they were read in the calling thread or none was read). Failures are the serial ones: `unreadable_planes`, `source_changed_during_run` (never staged), and an unexpected exception in a worker is raised by `run_experiment`, with a note naming the image, once the images not yet started are cancelled and those being read have finished; nothing is published, and what was staged is resumed by the next run. No serial fallback, no process backend, no plane- or channel-level parallelism. The notebook's **Images read at once** (step 3) defaults to `"auto"` with `max_ram` half of `run.workers.available_memory()` at its start (Linux `MemAvailable` lowered to the control group's remaining limit; Windows `GlobalMemoryStatusEx`; elsewhere the physical memory), rounded down to 0.1 GiB, and to 1 when that is unknown or below 0.5 GiB (owner decision of 16 November 2026); the CLI and `RunMode` keep 1. Once the axis roles give every analysed image's layout, and while the user has changed neither the workers nor the cap, the notebook starts at 1 when that default cap is below what the largest image needs (`run.workers.max_ram_needed`: its working-memory estimate, as above, plus the 256 MiB, so exactly when `"auto"` would refuse with `image_over_max_ram`) and says so ("Images read at once: 1, because the default memory cap (X GiB) is smaller than the largest image (Y GiB); outputs are identical for any number", Y rounded up to 0.1 GiB); values the user set are kept, with their refusal (D4b). Where the figure is the physical memory (`run.workers.memory_is_physical`: macOS), the cap's line says "physical memory". | -| Generation | The run's published files: `plane_histograms.csv`, `experiment_design.csv` (with a design), `run_manifest.json` and the report files, and the files the generation removes (`mask_relationships.json`, §9.2). | +| Generation | The run's published files: `plane_histograms.csv`, `image_qc.csv` (§19), `experiment_design.csv` (with a design), `run_manifest.json` and the report files, and the files the generation removes (`mask_relationships.json`, §9.2). | | Publication | (1) The whole new generation is written into `.publish` in the output folder and flushed to disk, then `.publish/publication.json` (publication version 1: each file's SHA-256 and the files removed). (2) **Commit, the one atomic step:** `os.replace` of the new `run_manifest.json` over the old one, then the output folder is flushed (`fsync` of the folder, POSIX), so the commit is on the disk when it returns and a power cut after it keeps the new generation. Nothing in the output folder changes before it. (3) The other files are moved into place (`os.replace` each), the removed files removed, `.publish` deleted, then `.staging`. | | Interrupted publication | Whatever next takes the output folder's lock (`run`, `check`, `masks`, `design`, `calibrate`, the notebook's writes) first finishes a committed publication or deletes an uncommitted `.publish`, record first (the earlier generation is then untouched) (`run.generation.finish_publication`). **Committed** means the staged manifest was moved: the record is there, `.publish/run_manifest.json` is not, and the manifest in place is the record's; the remaining moves and removals are then done. Anything else is not committed, also when the manifest in place is byte-identical to the staged one (an identical rerun refused before its commit); a `.publish` whose record cannot be removed is left whole (its staged manifest keeps it uncommitted) for the next holder of the lock. A failure to move a file after the commit (for example a table held open on Windows) raises `PublicationIncompleteError`: the new generation is current, and the next holder of the lock finishes the moves. | | What readers see | **Through the manifest** (`RunInputs`): exactly one generation, the old or the new one, never a mix: each file the manifest names is read by its SHA-256 from the output folder or, while a publication is unfinished, from `.publish` (`run.generation.published_path`), and the read is repeated if the manifest changed meanwhile (`read_stable`). **A plain reader of `plane_histograms.csv` alone** always reads one whole table of one generation (each move is one rename): the old one until it is moved. A reader that opens several output files without the manifest can pair files of two generations while a publication's step 3 runs or after a kill in it, until the next holder of the lock finishes it: read several files through `RunInputs`, or check `csv_sha256` and `experiment_design_sha256`. | @@ -1382,3 +1383,123 @@ Rules. - **Resume** (`load_draft`): the file's `spec_commit` must equal the pinned `SPEC_COMMIT`, else `DraftFileError` with code `spec_commit_mismatch` (owner decision, 2026-11-08): the confirmations in the file were given under other rules, so none is carried forward. The message names both commits, says the published `morphobricks.toml` is untouched and says to start a fresh draft from the folders. Library code never rewrites the stored commit and never deletes or replaces the stale draft; the caller derives a fresh draft and saves it, which replaces the file. `publish_draft` resumes first, so it refuses the same way and writes nothing. Then the file's `base_sha256` must equal the SHA-256 of the file published now (or `absent` if there is none), else `R_PUBLISHED_FILE_CHANGED` (`PublicationRefused`); the draft is never merged with the new file, it is derived again from it. An answer keyed by a folder or repeat the draft no longer has is `DraftError` (`unknown_key`), never moved to another folder. In the notebook's described run, a repeat's `confirmed_on` read from the draft file is kept only when every unit the repeat has now has its whole saved channel list and image type and no unit with a saved answer has left it (experiment-v1 §10: a new or removed unit or member reopens the confirmation); otherwise it is dropped and the repeat is asked again, and the card names it. The same holds for an answer given in the draft with no published file: a change of a unit's declared channel list, image type or grouping after the confirmation drops it. - **Draft to description** (`description_from_draft(draft, answers, *, channel_counts=None)`, pure): refuses with `DraftIncomplete`, listing **every** missing confirmation once (`id_pending`, `repeat_not_confirmed`, `confirmed_on_missing`, `unit_channels_missing` for a unit with no channel list, `unit_image_type_unanswered` for a unit whose image type is not answered `channels` or `rgb` (an old draft without one reopens with the question asked, never as `channels`), `unit_channel_untagged` for a position still `null`, `channel_undeclared` for a channel a unit names that is not declared; with `channel_counts`, the channel count of each unit's image now read through the confirmed axis roles, also `unit_channels_stale` for tags saved for another count and `unit_channel_count_unknown` for a unit without a count), otherwise returns the `Description`. A unit tagging one label at two positions is refused by `apply_answers` before anything is saved (`E_DUPLICATE_CHANNEL_IN_UNIT`). Nothing is confirmed for the user. `used_ids` is the draft's retired IDs plus every ID confirmed now. The description is then validated by the strict reader at publication; the function does not repeat the reader's rules. - **Publication** (`publish_draft(..., channel_counts=...)`, the counts required): under one hold of the lock the draft is resumed, the description built with the counts, published with all the checks of `publish_description` (symbolic link, base, transition, strict reader on the exact bytes), and then the draft file is deleted. Any refusal writes nothing: the draft and the published file stay byte for byte as they were. If the draft cannot be deleted after a successful publication, the error is raised and the publication stands; the leftover draft records a base that no longer matches and is refused on resume. + +## 19. Image QC metrics (`image_qc.csv`, `qc_version` 1) + +Per-plane image QC metrics, measured in the histogram pass from the pixels it already reads (no +extra read; MorphoFeature design `docs/restart/designs/image-qc-metrics-2026-11-21.md`, branch +`claude/restart-doc`). They describe how a plane looks, not how bright it is: they are flags for +review (a rare phenotype can look like a QC outlier), never a reason to exclude an image, and +nothing in this brick acts on them. Nothing is normalised before measuring; the raw +intensities, the extrema and the saturation stay in `plane_histograms.csv`. + +**The table.** UTF-8 CSV, LF line endings, one row for each channel of each row of +`plane_histograms.csv` (the channels the plane's unit lists), sorted by `source_relative_path`, +`z`, `t` and `channel`. Columns: `position_id`, `image_file`, `z`, `t`, `condition`, +`biological_repeat`, `technical_repeat`, `source_relative_path`, `plane_id` (the histogram +table's values), `channel` (the canonical channel ID), `read_in_blocks` (`true`/`false`), +`qc_status`, the metrics below, `blank_reasons`, `qc_version`. A metric that is undefined for a +plane is **blank, never zero**; floats are written with `repr`. `qc_status` is `measured`, +`non_finite_pixels` (a float plane with NaN or infinite pixels: the pixel metrics are blank, the +histogram metrics use its finite pixels) or `no_finite_pixels` (every metric blank). + +**Why a metric is blank (`blank_reasons`).** One cell per row: `metric=reason` for every blank +metric, in column order, separated by `;` (empty when no metric is blank). The reasons: +`no_finite_pixels` and `non_finite_pixels` (the two statuses above), `constant_plane` (the Otsu +metrics of a plane of one value), `no_pairs` (a correlation whose lag is not shorter than the +plane's height or width, or than a block's: no pixel pair that far apart), `no_variance` (a +correlation whose pairs are all one value), `non_positive_mean` (a ratio metric of a plane whose +mean `m <= 0`) and `plane_too_small` (a side under 3 pixels for `tenengrad` and +`laplacian_variance`, under 16 for the tile metrics). The reader (`read_image_qc`) and the writer +are strict: another header, status, version, flag, reason, or a value that is not a finite number +refuses the table, and so does a combination no measurement makes: a status with metrics it +blanks (`no_finite_pixels` with a value, `non_finite_pixels` with a pixel metric, `measured` +without an `entropy`), a blank metric without a reason or a reason for a metric that has a value, +the three Otsu metrics not blank together, and a value outside its range (`foreground_fraction` +and `otsu_separation` in 0 to 1, `entropy` in 0 to 6, correlations in -1 to 1, the ratio metrics +and `tile_mean_cv` not negative). `blank_reasons` was added before the first release, so +`qc_version` stays 1; a table written without it is not read and its rows are recomputed. + +**The metrics** (`m` is the plane's mean over all its pixels; every ratio metric is divided by +`m` or `m²`, so multiplying the intensities by a constant, or an 8-bit, 16-bit or float copy of +one image, gives the same value; the ratio metrics are blank when `m <= 0`). **Scale-free only +under pure multiplication.** A pedestal or background offset (`I -> a * I + b`, a camera offset, +an uneven background that was not subtracted) changes `m` to `a * m + b` and leaves the variance +and the differences at `a²` times theirs, so it changes `normalized_variance`, `tenengrad`, +`laplacian_variance`, `local_focus_median`, `local_focus_p10` and `tile_mean_cv` (all divided +by `m²` or by a mean): the same sample with more background reads as less sharp and less +uneven. The correlations, `otsu_fraction`-type shares (`foreground_fraction`, `otsu_separation`) +and `entropy` do not change under an offset. Nothing is subtracted before measuring (the raw +intensities are in `plane_histograms.csv`), so compare these metrics between images that +share an offset (same camera and settings), or read them next to the histogram table's minimum +and median. **Related metrics:** `tenengrad` is, up to the pixels at the plane's edge, +`normalized_variance * (1 - ρ₂)`, where `ρ₂` is the Pearson correlation of pixels two apart +(the mean of the two directions): the mean squared central difference is `σ²(1 - ρ₂)` +(tested), so Tenengrad is the variance seen at the finest scale and adds the structure scale +that `correlation_1` and `correlation_4` give; they are not independent evidence of focus. + +| Column | Definition | +|---|---| +| `otsu_threshold` | Two-class Otsu threshold on the plane's histogram (each bin at its representative value, a robust-range tail at its mean; exact for integer histograms with one bin per value, the default for 8- and 16-bit images): the value of the highest bin of the lower class. Blank for a plane of one value. | +| `otsu_separation` | Otsu's separability: between-class variance at the threshold over the total variance (0 to 1). Two-class Otsu always splits. **Baseline:** on unimodal noise it splits the noise at its middle, giving `foreground_fraction` about 0.5 and a separation of `2/π ≈ 0.637` for Gaussian noise (0.635 to 0.66 for the Poisson and Gaussian noise tested). A sparse field of bright cells reads about 0.93, but a dense field with a unimodal histogram (smoothed noise, tested) reads 0.64 as well, so **`otsu_separation` does not tell an empty field from dense content** (it measures how two-class the histogram is, not how much is in the field); use `correlation_1` for that. | +| `foreground_fraction` | Share of the finite pixels above `otsu_threshold`. | +| `entropy` | Shannon entropy in bits of the histogram regrouped into 64 equal bins from the plane's minimum to its maximum (relative to the plane's own range; 0 for a plane of one value). | +| `normalized_variance` | `var / m²` (population variance; the squared coefficient of variation). CellProfiler's FocusScore is `var / m`, which changes with the intensity scale; divided by `m²` it is scale-free (design principle). | +| `tenengrad` | `(mean(gx²) + mean(gy²)) / m²` with central differences `gx = (I[y, x+1] - I[y, x-1]) / 2` over every pixel that has both neighbours in X (and `gy` likewise in Y). This is a central-difference Tenengrad, **not** the classical Tenengrad of the 3 x 3 Sobel operator (Krotkov): values are not comparable with Sobel-based ones. See the relation to `normalized_variance` above. | +| `laplacian_variance` | Variance of `I[y-1,x] + I[y+1,x] + I[y,x-1] + I[y,x+1] - 4 I[y,x]` over the pixels with all four neighbours, `/ m²`. | +| `correlation_1`, `correlation_4`, `correlation_16` | Pearson correlation of every pixel with its neighbour `k` pixels to the right, and (separately) `k` pixels below, over every such pair; the mean of the two. Blank when either direction has no pair (a plane not wider and taller than `k`, or read in blocks no more than `k` rows or columns across) or a constant side. These are Pearson correlations of pixel pairs at a distance, **not** CellProfiler's `MeasureTexture` "Correlation", which is a Haralick feature of a grey-level co-occurrence matrix of quantised intensities. **The emptiness marker:** `correlation_1` is about 0 (under 0.05 in absolute value, tested on Gaussian and Poisson noise) for an empty field of camera noise, where neighbouring pixels are independent, and 0.86 to 0.88 on the sparse small-cell test fields and at least 0.9 on fields with extended or blurred structure (tested); the Otsu metrics cannot show this. Optics and sensor binning can correlate noise, so read it as a flag, not a verdict. | +| `local_focus_median`, `local_focus_p10` | Each tile of a fixed 8 x 8 grid (tile edges at `floor(i * side / 8)`): its population variance `/ m²` (the plane's mean, so a dark tile is not inflated); the median and the 10th percentile over the 64 tiles (NumPy's default linear interpolation). Blank when a side is under 16 pixels. **`local_focus_p10` is content coverage, not focus:** when more than about 6 of the 64 tiles hold only background, the 10th percentile is the variance of that background (over `m²`), so it falls with the share of the field that is empty, not with blur (a sparse field of cells reads low at any sharpness). Read focus from `local_focus_median` on dense fields and from `tenengrad` and `laplacian_variance`. | +| `tile_mean_cv` | Population standard deviation of the 64 tile means over their mean: uneven content or illumination (never interpreted as illumination alone). | + +**Planes read in blocks** (`read_in_blocks` true). Every metric is a combination of sums that add +up exactly across blocks (counts, means and centred sums of squares and products, combined +pairwise), and the histogram metrics come from the histogram, so the histogram, mean, variance +and tile metrics equal the whole plane's (to float64 rounding). The neighbour metrics +(`tenengrad`, `laplacian_variance`, the correlations) leave out the pairs that cross a block +edge: a small difference for full-width bands of many rows, larger for long lags in narrow +blocks (tested: within 5 % for Tenengrad and the Laplacian and 0.05 for the correlations on +cell-like test fields in blocks down to 17 x 33 pixels). **These tolerances are observations on +those fields, not guarantees.** An image whose strongest change lies on a block edge (a stitching +seam, a saturated band, a hard crop) can differ much more: a step exactly at a band edge drops +`tenengrad` and `laplacian_variance` to a fraction of the whole plane's (tested), and the blocks +are set by the memory limit and the file's strips or tiles, not by the image. A lag that no pair +spans (a correlation at lag `k` in blocks of at most `k` rows or columns) is blank with the reason +`no_pairs`, never zero (tested with blocks of 16 rows and lag 16). Compare these metrics only +between planes read the same way (`read_in_blocks`, and the same memory limit). Planes under the +memory limit are read whole. + +**Numerics.** For an integer image every sum is a whole number held exactly in float64 on planes +of the usual sizes (below `2**53`), so the result does not depend on the summation order. For a +float image the sums are centred on the block's mean (an integer image on its rounded mean, which +keeps the sums whole) and taken in a fixed order: the same machine gives the same bytes; another +processor may change the last digits. Workers do not change the table. The sums use +`numpy.vecdot`, so the dependency floor is NumPy 2.0 (`pyproject.toml`; the other floors were +raised with it to releases that import with NumPy 2: SciPy 1.13, Matplotlib 3.8.4 and, for the +`he-mask` extra, scikit-image 0.24). + +**Memory.** The working memory of the QC sums is part of the estimate of a whole plane and of a +block (`image_qc.qc_memory`, added by `plane_binning.Binning`, so a plane is read in blocks when +the histogram and the QC sums together do not fit the limit; it also enters the workers' per-image +estimate): the float64 band buffer of `min(64, block height) + 16` rows of the block's width, the +column sums, the thin strips of the window sums, NumPy's casting buffers and, for a float block, +the one-byte-per-pixel mask of the finite scan. It is an upper bound, checked against the measured +peak (`tracemalloc`) over blocks of different shapes and types. + +**Reuse and resume.** The table is an output of the histogram step and follows its rules (§9, +§9.4): reused rows keep their QC rows; staged rows are staged with theirs; an earlier table that is +missing, changed (SHA-256), of another `qc_version` or settings, or not holding exactly one row for +each channel of each histogram row, with that row's full identity (position, image, Z, T, labels, +path, plane ID and channel, not only plane ID and channel), recomputes every row, with the reason +in the report. Changing the metric definitions changes `qc_version`. **The memory limit** changes +no histogram row but sets the blocks, and so the neighbour metrics of planes read in blocks: when +the earlier run or this one reads any plane in blocks, another `memory_limit` recomputes every row +(`rebuild_reason`: "the memory limit changed from X to Y ..."); with whole planes on both sides it +changes nothing. Staged rows record the limit in their key for an image read in blocks +(`RowKey.block_limit`) and are resumed only under it (reason in `staged_discarded`). The limit is +compared, not the resulting partition: a change that leaves the blocks as they were still +recomputes. + +**Not in version 1:** the power-spectrum slope (PLLS: one FFT per plane, measured at 29-62 ms for +a 2048 x 2048 plane against a histogram step of about 74 ms per channel plane, over the design's ++50 % limit), background noise or SNR, stripes, bright artefacts, near-duplicates, time-lapse and +Z profiles. The channel-identity check does not use the metrics yet. diff --git a/docs/development.md b/docs/development.md index f65c3846..92694bbc 100644 --- a/docs/development.md +++ b/docs/development.md @@ -111,6 +111,9 @@ recorded with its seed), the speed-up paired by round with its spread, the peak distribution, CPUs pinned with `--cpus` (`taskset`) where available, the load average recorded in the report quoted with the numbers, and identical output digests in every run (the tool exits 1 otherwise). `--phases` times the calling thread's steps of a run. +`tools/benchmark_image_qc.py` times the histogram step with and without the image QC metrics +(contract §19) against a checkout without them (`--baseline-src`), whole and in blocks, and +exits 1 unless every run writes the same `plane_histograms.csv`. ## Spec conformance tests diff --git a/docs/user_guide.md b/docs/user_guide.md index fc4ecbb8..0ef5bcb4 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -1032,6 +1032,23 @@ The default output folder is next to the experiment folder: the image does not have is blank; each channel also has its underflow and overflow, zero unless the robust range is used). A table written by an earlier version is recomputed on the next run; later bricks ask you to run this brick again on it. +- **`image_qc.csv`:** one row per plane and channel with image QC metrics measured while the + histograms are computed (no extra read): the share of the plane above its Otsu threshold + (`foreground_fraction`; `otsu_separation` is about 0.64 for noise and for any dense field + with one broad histogram peak, so it does not tell an empty field from content), the + histogram's `entropy`, focus (`normalized_variance`, `tenengrad`, `laplacian_variance`, + `local_focus_median`; `local_focus_p10` shows how much of the field holds content, not focus), + the correlation of each pixel with its neighbours 1, 4 and 16 pixels away (structure size; + `correlation_1` is about 0 for an empty field of camera noise and high when there is + structure) and how uneven the field is (`tile_mean_cv`). They do not change when all + intensities are multiplied by a constant (an 8-bit and a 16-bit copy give the same values), + but a background offset does change the focus and unevenness values, so compare images that + share their camera settings. They are for review only: nothing is excluded because of them. A + blank value means the metric is not defined for that plane, never zero; the `blank_reasons` + column says why for each (for example a plane of one value, or no pixel pair that far apart). + Planes read in blocks are marked `read_in_blocks`; their neighbour metrics leave out the pixel + pairs across block edges, which can matter for an image with a seam on a block edge, and + another memory limit recomputes them. Definitions in [contract.md](contract.md) §19. - **`experiment_design.csv`:** one row per biological-repeat folder of each condition: its repeat group, whether its condition is a control, its image and technical-repeat counts, and whether and when the repeat group was confirmed. Derived from the saved description and diff --git a/pyproject.toml b/pyproject.toml index ea196ecb..f1486e8d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,10 +20,13 @@ classifiers = [ "Topic :: Scientific/Engineering :: Image Processing", ] dependencies = [ - "numpy>=1.24", + # 2.0: the image QC sums use numpy.vecdot (contract §19). The suite passes with the lowest + # floors of every dependency below on Python 3.11 and numpy 2.0.0 (matplotlib 3.7 and + # scikit-image 0.22 do not import with NumPy 2, hence their floors). + "numpy>=2.0", "tifffile>=2023.7.10", # Counting the connected pieces of each mask label in the optional mask step. - "scipy>=1.10", + "scipy>=1.13", # The measured decoders of every compressed TIFF the bounded readers read (#356; owner # decision of 18 November 2026): deflate, LZMA, LZW and JPEG (libjpeg-turbo 3), checked at # run time by codec_bounds.decoder_unmeasured. @@ -36,7 +39,7 @@ dependencies = [ [project.optional-dependencies] notebook = [ "ipywidgets>=7.7,<9", - "matplotlib>=3.7", + "matplotlib>=3.8.4", ] zarr = [ "zarr>=2.18", @@ -46,6 +49,9 @@ zarr = [ # requirement's URL (pip refuses two direct URLs for one package). he-mask = [ "morphobricks-normalization[histology] @ git+https://github.com/CellMigrationLab/morphobricks-normalization.git@v0.7.1", + # Normalization's histology extra allows scikit-image 0.22, which does not import with + # NumPy 2 (checked); 0.24 is the first release that does. + "scikit-image>=0.24", ] dev = [ "pytest>=7.4", @@ -132,6 +138,12 @@ baseline = "tools/code_rules_baseline.json" # pure: no I/O, no UI; io: reads or writes files; ui: notebook and command line, no # computing; orchestration: ties the others together. "morphobricks_preprocessing" = "orchestration" +"morphobricks_preprocessing.image_qc" = "pure" +"morphobricks_preprocessing.image_qc_moments" = "pure" +"morphobricks_preprocessing.image_qc_record" = "pure" +"morphobricks_preprocessing.image_qc_sums" = "pure" +"morphobricks_preprocessing.image_qc_table" = "io" +"morphobricks_preprocessing.plane_binning" = "pure" "morphobricks_preprocessing.__main__" = "ui" "morphobricks_preprocessing._io" = "io" "morphobricks_preprocessing.axes" = "pure" @@ -320,6 +332,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.intensity" = "io" "morphobricks_preprocessing.manifest" = "io" "morphobricks_preprocessing.manifest_fields" = "pure" +"morphobricks_preprocessing.manifest_files" = "io" "morphobricks_preprocessing.lab_links" = "pure" "morphobricks_preprocessing.lab_links_file" = "io" "morphobricks_preprocessing.manifest_versions" = "pure" @@ -413,6 +426,8 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.run.result" = "pure" "morphobricks_preprocessing.run.reuse" = "io" "morphobricks_preprocessing.run.output_guard" = "io" +"morphobricks_preprocessing.run.outputs" = "io" +"morphobricks_preprocessing.run.state" = "orchestration" "morphobricks_preprocessing.run.rows" = "io" "morphobricks_preprocessing.run.workers" = "io" "morphobricks_preprocessing.run.arguments" = "orchestration" diff --git a/src/morphobricks_preprocessing/fingerprint.py b/src/morphobricks_preprocessing/fingerprint.py index aadc7d1f..bd7bfcae 100644 --- a/src/morphobricks_preprocessing/fingerprint.py +++ b/src/morphobricks_preprocessing/fingerprint.py @@ -123,6 +123,11 @@ class RowKey: channel_ids The image's canonical channel IDs in source order (its unit's confirmed list, Stage 3): rows recorded under other IDs are recomputed, never relabelled. + block_limit + The memory limit, for an image whose planes are read in blocks; None for one read + whole. The limit sets the blocks, and the image QC metrics of a plane read in blocks + leave out the neighbour pairs across a block edge (contract §19), so staged rows are + resumed only under the limit they were measured with. """ relative_path: str @@ -137,6 +142,7 @@ class RowKey: histogram: tuple content_sha256: str | None = None channel_ids: tuple[str, ...] = () + block_limit: int | None = None @classmethod def of(cls, entry: FileEntry, settings: RunSettings, experiment_root: str) -> RowKey: @@ -164,6 +170,7 @@ def of(cls, entry: FileEntry, settings: RunSettings, experiment_root: str) -> Ro histogram=tuple(sorted(_frozen(settings.histogram.to_dict()).items())), content_sha256=entry.content_sha256, channel_ids=tuple(entry.channel_ids), + block_limit=settings.memory_limit if entry.read_in_blocks else None, ) diff --git a/src/morphobricks_preprocessing/image_qc.py b/src/morphobricks_preprocessing/image_qc.py new file mode 100644 index 00000000..d98b619d --- /dev/null +++ b/src/morphobricks_preprocessing/image_qc.py @@ -0,0 +1,408 @@ +"""Image QC metrics of one channel of one plane, measured in the histogram pass (contract §19). + +The metrics describe how a plane looks, not how bright it is: the share of the plane above +its Otsu threshold, the histogram's entropy, focus (normalized variance, Tenengrad, +Laplacian variance, local focus on a grid of tiles), the correlation of each pixel with its +neighbours 1, 4 and 16 pixels away, and how much the tile means vary. Every ratio metric is +divided by the plane's mean or its square, so it does not change when the intensities are +multiplied by a constant (an 8-bit, 16-bit or float copy of one image gives the same value); +the raw intensities stay in the histogram table. Nothing is normalised before measuring. + +Scale-free only under pure multiplication: a pedestal or background offset ``I -> a*I + b`` +changes the mean, so it changes every metric divided by it (``normalized_variance``, +``tenengrad``, ``laplacian_variance``, ``local_focus_*``, ``tile_mean_cv``); the correlations, +the Otsu shares and the entropy are unchanged by it. ``tenengrad`` is, up to the plane's edge +pixels, ``normalized_variance * (1 - rho_2)`` with ``rho_2`` the lag-2 Pearson correlation, so +it adds no independent evidence of focus. ``otsu_separation`` of unimodal noise is ``2/pi``, +so it does not tell an empty field from dense content; ``correlation_1`` (about 0 on camera +noise, high with structure) does. ``local_focus_p10`` is content coverage in a sparse field, +not focus. ``tenengrad`` uses central differences (not the Sobel operator) and the correlations +are Pearson correlations of pixel pairs (not CellProfiler's Haralick correlation). Contract §19. + +:class:`PlaneQc` takes the plane's blocks as the histogram reads them (no extra read) and +:meth:`PlaneQc.finish` adds the histogram metrics once the histogram is known. Every metric +is built from sums that combine across blocks (:mod:`.image_qc_moments`), so a plane read in +blocks gives the whole plane's values, except that neighbour pairs crossing a block edge are +left out of the neighbour metrics (gradients, Laplacian, correlations). A plane held whole is +one block. The metrics are flags for review, never a reason to exclude an image. +""" + +from __future__ import annotations + +from dataclasses import dataclass, fields + +import numpy as np +from morphobricks_normalization.histogram import PlaneHistogram + +from .image_qc_moments import CoMoments, Moments +from .image_qc_sums import BAND_ROWS, BlockSums, Window, valid_window + +QC_VERSION = "1" +"""Version of the metric definitions; a change recomputes every row (contract §19).""" +LAGS = (1, 4, 16) +"""Neighbour distances (pixels) of the ``correlation_`` metrics.""" +TILE_GRID = 8 +"""The tiles of the local focus and tile mean metrics: an 8 x 8 grid over the plane.""" +ENTROPY_BINS = 64 +"""Equal bins over the plane's own range for the entropy.""" +OFFSETS = ( + *((0, lag) for lag in sorted({1, 2, *LAGS})), + *((lag, 0) for lag in sorted({1, 2, *LAGS})), + (1, 1), + (1, -1), +) +"""Every neighbour offset ``(dy, dx)`` a pair sum is taken at (correlations, gradients and +the Laplacian).""" +REACH = max(dy + (dx > 0) for dy, dx in OFFSETS) +"""Rows below a band of the sweep that the offsets reach (:mod:`.image_qc_sums`).""" +MEASURED, NON_FINITE, NO_FINITE = "measured", "non_finite_pixels", "no_finite_pixels" +"""The values of ``qc_status``.""" +CONSTANT, NO_PAIRS, NO_VARIANCE = "constant_plane", "no_pairs", "no_variance" +NON_POSITIVE_MEAN, TOO_SMALL = "non_positive_mean", "plane_too_small" +REASONS = frozenset( + {NO_FINITE, NON_FINITE, CONSTANT, NO_PAIRS, NO_VARIANCE, NON_POSITIVE_MEAN, TOO_SMALL} +) +"""Why a metric is blank (``blank_reasons``): the status's two blanking causes, a plane of one +value (no Otsu split), no pixel pair at the lag, a constant side of the pairs, a mean that is +not positive (the ratio metrics) and a plane too small for the metric (a side under 3 pixels +for the gradient and the Laplacian, under 16 for the tile metrics).""" + + +OVERHEAD = 16 * 2**10 +"""Python objects of one block's sums (dictionaries, windows, moments), whatever its size.""" + + +def qc_memory(rows: int, cols: int, floating: bool) -> int: + """Return an upper bound of the working memory the QC sums of one block hold, in bytes. + + Besides the block itself (counted with the pixels): a fixed ``OVERHEAD`` of Python objects, + the sweep's float64 band buffer of ``min(BAND_ROWS, rows) + REACH`` rows, the column sums of + each band and their temporaries, the float64 copies of the thin strips and wrapped columns of + the window and pair sums (two operands, at most ``REACH`` rows or columns wide), NumPy's + casting buffers (two operands of up to 8192 float64: ``numpy.getbufsize``, never more than the + block) and, for a float block, the boolean mask of the finite scan (one byte per pixel). The + terms are added, though some are freed + before others are made (measured with ``tracemalloc``, ``tests/test_image_qc_memory.py``). + + Parameters + ---------- + rows, cols + The block's (Y, X) shape. + floating + Whether its pixel type is a float type (the finite scan runs). + """ + band = (min(BAND_ROWS, rows) + REACH) * cols * 8 + columns = 4 * cols * 8 + strips = 2 * 8 * REACH * (rows + cols) + casting = 2 * 8 * min(np.getbufsize(), rows * cols) + return OVERHEAD + band + columns + strips + casting + (rows * cols if floating else 0) + + +def qc_settings() -> dict: + """Return the fixed settings of the metrics, as the manifest records them.""" + return { + "qc_version": QC_VERSION, + "correlation_lags": list(LAGS), + "tile_grid": [TILE_GRID, TILE_GRID], + "entropy_bins": ENTROPY_BINS, + } + + +@dataclass(frozen=True) +class ImageQc: + """The QC metrics of one channel of one plane; None where a metric is undefined. + + Attributes + ---------- + status + ``measured``; ``non_finite_pixels`` (a float plane with NaN or infinite pixels: the + pixel metrics are left blank, the histogram metrics use the finite pixels); or + ``no_finite_pixels`` (every metric blank). + reasons + ``(metric, reason)`` for every blank metric, in table order; the reasons are those + of :data:`REASONS`. + """ + + status: str + reasons: tuple[tuple[str, str], ...] = () + otsu_threshold: float | None = None + otsu_separation: float | None = None + foreground_fraction: float | None = None + entropy: float | None = None + normalized_variance: float | None = None + tenengrad: float | None = None + laplacian_variance: float | None = None + correlation_1: float | None = None + correlation_4: float | None = None + correlation_16: float | None = None + local_focus_median: float | None = None + local_focus_p10: float | None = None + tile_mean_cv: float | None = None + + +METRICS = tuple(f.name for f in fields(ImageQc) if f.name not in ("status", "reasons")) +"""The metric columns, in table order.""" +HISTOGRAM_METRICS = ("otsu_threshold", "otsu_separation", "foreground_fraction", "entropy") +"""The metrics of the histogram; the others are measured from the pixels.""" +PIXEL_METRICS = tuple(name for name in METRICS if name not in HISTOGRAM_METRICS) +RATIO_METRICS = tuple(name for name in PIXEL_METRICS if not name.startswith("correlation")) +"""The pixel metrics divided by the mean or its square: blank when the mean is not positive.""" + + +class PlaneQc: + """Accumulates the QC sums of one plane, block by block. + + Parameters + ---------- + shape + (Y, X) shape of the whole plane. + dtype + Its pixel type. + """ + + def __init__(self, shape: tuple[int, int], dtype: np.dtype) -> None: + self.shape = (int(shape[0]), int(shape[1])) + self.floating = np.dtype(dtype).kind == "f" + self.non_finite = False + self.seen = 0 + self.pixels = Moments() + self.laplacian = Moments() + self.gradient = [0.0, 0, 0.0, 0] # sum and count of x, then y, squared differences + self.pairs = {(lag, axis): CoMoments() for lag in LAGS for axis in (0, 1)} + self.tiles = [[Moments()] * TILE_GRID for _ in range(TILE_GRID)] + self.edges = tuple( + tuple((i * side) // TILE_GRID for i in range(TILE_GRID + 1)) for side in self.shape + ) + + def add(self, y: int, x: int, pixels: np.ndarray) -> None: + """Add one block whose first pixel is at plane row ``y`` and column ``x``.""" + self.seen += pixels.size + if self.non_finite or pixels.size == 0: + return + if self.floating and not np.isfinite(pixels).all(): + self.non_finite = True # the pixel metrics stay blank (contract §19) + return + # A constant near the mean keeps the sums small (well conditioned); any value works. + sample = pixels[:: max(1, pixels.shape[0] // 16), :: max(1, pixels.shape[1] // 16)] + bands = self._tile_rows(y, pixels.shape[0]) + mean = float(sample.mean()) + # Whole numbers keep the integer sums exact; a float plane is centred on its mean, which + # a rounded one would miss for data in [0, 1). + offset = mean if self.floating else float(round(mean)) + sums = BlockSums(pixels, offset, OFFSETS, [top for _, top in bands]) + self.pixels = self.pixels.merged( + Moments.of_sums(pixels.size, sums.offset, sums.total, sums.total_sq) + ) + for (lag, axis), found in self.pairs.items(): + dy, dx = (lag, 0) if axis else (0, lag) + n, pair = _pair_sums(sums, dy, dx) + self.pairs[lag, axis] = found.merged(CoMoments.of_sums(n, sums.offset, pair)) + for axis in (0, 1): + n, (_, _, saa, sbb, sab) = _pair_sums(sums, *((2, 0) if axis else (0, 2))) + self.gradient[2 * axis] += saa + sbb - 2.0 * sab + self.gradient[2 * axis + 1] += n + self.laplacian = self.laplacian.merged(_laplacian(sums)) + self._add_tiles([i for i, _ in bands], x, sums) + + def _tile_rows(self, y: int, height: int) -> list[tuple[int, int]]: + """Return each tile row a block of ``height`` rows at ``y`` meets, with its top in it.""" + rows = self.edges[0] + return [ + (i, max(rows[i], y) - y) + for i in range(TILE_GRID) + if max(rows[i], y) < min(rows[i + 1], y + height) + ] + + def _add_tiles(self, tile_rows: list[int], x: int, sums: BlockSums) -> None: + """Add the block's part of each tile of the grid, from the column sums of its bands.""" + width, cols = sums.shape[1], self.edges[1] + for i, (top, bottom, column, column_sq) in zip(tile_rows, sums.bands, strict=True): + for j in range(TILE_GRID): + left, right = max(cols[j], x), min(cols[j + 1], x + width) + if left >= right: + continue + part = slice(left - x, right - x) + found = Moments.of_sums( + (bottom - top) * (right - left), + sums.offset, + float(column[part].sum()), + float(column_sq[part].sum()), + ) + self.tiles[i][j] = self.tiles[i][j].merged(found) + + def finish(self, histogram: PlaneHistogram) -> ImageQc: + """Return the metrics, with those of the plane's ``histogram`` (its finite pixels). + + Parameters + ---------- + histogram + The channel plane's histogram from the same pass. + + Returns + ------- + ImageQc + + Raises + ------ + ValueError + If the blocks added do not hold every pixel of the plane once. + """ + if self.seen != self.shape[0] * self.shape[1]: + raise ValueError(f"the QC pass saw {self.seen} pixels of a {self.shape} plane") + if histogram.is_empty: + return ImageQc(NO_FINITE, reasons=tuple((name, NO_FINITE) for name in METRICS)) + found = histogram_metrics(histogram) + why = {name: CONSTANT for name in HISTOGRAM_METRICS if found[name] is None} + if self.non_finite: + why.update(dict.fromkeys(PIXEL_METRICS, NON_FINITE)) + return ImageQc(NON_FINITE, **found, reasons=_in_order(why)) + pixel, blank = self._pixel_metrics() + return ImageQc(MEASURED, **found, **pixel, reasons=_in_order({**why, **blank})) + + def _pixel_metrics(self) -> tuple[dict[str, float | None], dict[str, str]]: + """Return the metrics of the pixel pass, and why each undefined one is.""" + mean = self.pixels.mean + found: dict[str, float | None] = {name: None for name in PIXEL_METRICS} + why: dict[str, str] = {} + for lag in LAGS: + pairs = [self.pairs[lag, axis] for axis in (0, 1)] + name = f"correlation_{lag}" + found[name] = _mean_of(pairs[0].correlation, pairs[1].correlation) + if found[name] is None: + why[name] = NO_PAIRS if min(p.n for p in pairs) == 0 else NO_VARIANCE + if self.pixels.n == 0 or mean <= 0.0: # the ratio metrics need a positive mean + why.update(dict.fromkeys(RATIO_METRICS, NON_POSITIVE_MEAN)) + return found, why + square = mean * mean + sx, nx, sy, ny = self.gradient + found["normalized_variance"] = self.pixels.variance / square + if nx and ny: + found["tenengrad"] = (sx / (4.0 * nx) + sy / (4.0 * ny)) / square + if self.laplacian.n: + found["laplacian_variance"] = self.laplacian.variance / square + if min(self.shape) >= 2 * TILE_GRID: + tiles = [tile for row in self.tiles for tile in row] + focus = np.array([tile.variance for tile in tiles]) / square + found["local_focus_median"] = float(np.quantile(focus, 0.5)) + found["local_focus_p10"] = float(np.quantile(focus, 0.1)) + means = np.array([tile.mean for tile in tiles]) + if means.mean() > 0.0: + found["tile_mean_cv"] = float(means.std() / means.mean()) + small = min(self.shape) < 2 * TILE_GRID + for name in RATIO_METRICS: + if found[name] is None: # only tile_mean_cv has another cause: a tile mean of 0 + why[name] = TOO_SMALL if small or name != "tile_mean_cv" else NON_POSITIVE_MEAN + return found, why + + +def _in_order(why: dict[str, str]) -> tuple[tuple[str, str], ...]: + """Return the reasons as ``(metric, reason)`` pairs in table order.""" + return tuple((name, why[name]) for name in METRICS if name in why) + + +def _mean_of(a: float | None, b: float | None) -> float | None: + """Return the mean of the two directions' values, or None when either is undefined.""" + return None if a is None or b is None else (a + b) / 2.0 + + +def _pair_sums(sums: BlockSums, dy: int, dx: int) -> tuple[int, tuple[float, ...]]: + """Return the number of pairs at ``(dy, dx)`` and the sums of a, b, a², b² and ab.""" + window = valid_window(sums.shape, dy, dx) + if window.size == 0: + return 0, (0.0,) * 5 + partner = window.shifted(dy, dx) + return window.size, ( + sums.window_sum(window), + sums.window_sum(partner), + sums.window_sum(window, squared=True), + sums.window_sum(partner, squared=True), + sums.pair_sum(window, dy, dx), + ) + + +def _laplacian(sums: BlockSums) -> Moments: + """Return the moments of the 4-neighbour Laplacian over the block's inner pixels. + + ``L = up + down + left + right - 4 centre``, expanded into window sums and pair sums + (its coefficients add up to 0, so the block's offset cancels). + """ + height, width = sums.shape + centre = Window(1, height - 1, 1, width - 1) + if centre.size == 0: + return Moments() + up, down = centre.shifted(-1, 0), centre.shifted(1, 0) + left, right = centre.shifted(0, -1), centre.shifted(0, 1) + side = [up, down, left, right] + total = sum(sums.window_sum(w) for w in side) - 4.0 * sums.window_sum(centre) + square = sum(sums.window_sum(w, squared=True) for w in side) + square += 16.0 * sums.window_sum(centre, squared=True) + neighbours = ( + (up, 2, 0), # up x down + (left, 0, 2), # left x right + (up, 1, -1), # up x left + (up, 1, 1), # up x right + (left, 1, 1), # left x down + (right, 1, -1), # right x down + ) + square += 2.0 * sum(sums.pair_sum(w, dy, dx) for w, dy, dx in neighbours) + with_centre = ((up, 1, 0), (centre, 1, 0), (left, 0, 1), (centre, 0, 1)) + square -= 8.0 * sum(sums.pair_sum(w, dy, dx) for w, dy, dx in with_centre) + return Moments.of_sums(centre.size, 0.0, total, square) + + +def histogram_metrics(histogram: PlaneHistogram) -> dict[str, float | None]: + """Return the Otsu threshold, its separation, the foreground fraction and the entropy. + + From the bins of a histogram with finite pixels: each bin stands for its pixels at its + representative value, and each tail of a robust-range histogram for its pixels at the + tail's mean (exact for integer histograms with one bin per value, the default for 8- and + 16-bit images). + + Parameters + ---------- + histogram + A plane's histogram with at least one finite pixel. + + Returns + ------- + dict + ``otsu_threshold`` (the value of the highest bin of the lower class), + ``otsu_separation`` (between-class variance over total variance, 0 to 1), + ``foreground_fraction`` (pixels above the threshold over finite pixels; the three + are None for a plane of one value) and ``entropy`` (bits, over + :data:`ENTROPY_BINS` equal bins from the plane's minimum to its maximum). + """ + values = np.concatenate( + ([histogram.underflow.mean], histogram.representatives, [histogram.overflow.mean]) + ) + counts = np.concatenate( + ([histogram.underflow.count], histogram.counts, [histogram.overflow.count]) + ).astype(np.float64) + keep = counts > 0 + values, counts = values[keep], counts[keep] + total = counts.sum() + found = dict.fromkeys(("otsu_threshold", "otsu_separation", "foreground_fraction")) + found["entropy"] = _entropy(values, counts, histogram) + if len(values) < 2: + return found + centred = values - float(np.dot(counts, values)) / total + weight = np.cumsum(counts)[:-1] / total + moment = np.cumsum(counts * centred)[:-1] / total + between = moment * moment / (weight * (1.0 - weight)) + best = int(np.argmax(between)) + variance = float(np.dot(counts, centred * centred)) / total + found["otsu_threshold"] = float(values[best]) + found["otsu_separation"] = min(1.0, float(between[best]) / variance) + found["foreground_fraction"] = float(1.0 - weight[best]) + return found + + +def _entropy(values: np.ndarray, counts: np.ndarray, histogram: PlaneHistogram) -> float: + """Return the Shannon entropy (bits) of the counts in equal bins over the plane's range.""" + low, high = float(histogram.pixel_min), float(histogram.pixel_max) + if high <= low: + return 0.0 + index = np.floor((values - low) / (high - low) * ENTROPY_BINS).astype(np.int64) + coarse = np.bincount(np.clip(index, 0, ENTROPY_BINS - 1), counts, ENTROPY_BINS) + share = coarse[coarse > 0] / coarse.sum() + return float(-np.sum(share * np.log2(share))) + 0.0 diff --git a/src/morphobricks_preprocessing/image_qc_moments.py b/src/morphobricks_preprocessing/image_qc_moments.py new file mode 100644 index 00000000..41f6fff3 --- /dev/null +++ b/src/morphobricks_preprocessing/image_qc_moments.py @@ -0,0 +1,102 @@ +"""Combinable statistics of the image QC metrics: moments and co-moments (contract §19). + +Each block of a plane gives a count, means and centred sums of squares and products; two +such results combine exactly into the result of the union (Chan, Golub and LeVeque's +pairwise update), so a plane read in blocks gives the whole plane's statistics, up to the +neighbour pairs that cross a block edge (:mod:`.image_qc`). +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass + + +@dataclass(frozen=True) +class Moments: + """Count, mean and centred sum of squares (``M2``) of a set of values.""" + + n: int = 0 + mean: float = 0.0 + m2: float = 0.0 + + @classmethod + def of_sums(cls, n: int, offset: float, total: float, total_sq: float) -> Moments: + """Return the moments of ``n`` values given the sums of ``value - offset`` and squares.""" + if n == 0: + return cls() + shift = total / n + return cls(n, offset + shift, max(0.0, total_sq - total * shift)) + + def merged(self, other: Moments) -> Moments: + """Return the moments of both sets together.""" + if other.n == 0: + return self + if self.n == 0: + return other + n = self.n + other.n + delta = other.mean - self.mean + mean = self.mean + delta * other.n / n + return Moments(n, mean, self.m2 + other.m2 + delta * delta * self.n * other.n / n) + + @property + def variance(self) -> float | None: + """Population variance, or None for no values.""" + return None if self.n == 0 else self.m2 / self.n + + +@dataclass(frozen=True) +class CoMoments: + """Count, means and centred sums of squares and products of paired values ``(a, b)``.""" + + n: int = 0 + mean_a: float = 0.0 + mean_b: float = 0.0 + caa: float = 0.0 + cbb: float = 0.0 + cab: float = 0.0 + + @classmethod + def of_sums( + cls, n: int, offset: float, sums: tuple[float, float, float, float, float] + ) -> CoMoments: + """Return the co-moments from the sums of ``a``, ``b``, ``a²``, ``b²`` and ``ab``. + + The values are offset by ``offset`` (the same constant for ``a`` and ``b``). + """ + if n == 0: + return cls() + sa, sb, saa, sbb, sab = sums + return cls( + n, + offset + sa / n, + offset + sb / n, + max(0.0, saa - sa * sa / n), + max(0.0, sbb - sb * sb / n), + sab - sa * sb / n, + ) + + def merged(self, other: CoMoments) -> CoMoments: + """Return the co-moments of both sets of pairs together.""" + if other.n == 0: + return self + if self.n == 0: + return other + n = self.n + other.n + weight = self.n * other.n / n + da, db = other.mean_a - self.mean_a, other.mean_b - self.mean_b + return CoMoments( + n, + self.mean_a + da * other.n / n, + self.mean_b + db * other.n / n, + self.caa + other.caa + da * da * weight, + self.cbb + other.cbb + db * db * weight, + self.cab + other.cab + da * db * weight, + ) + + @property + def correlation(self) -> float | None: + """Pearson correlation of ``a`` and ``b``; None without pairs or when either is constant.""" + if self.n == 0 or self.caa <= 0.0 or self.cbb <= 0.0: + return None + return max(-1.0, min(1.0, self.cab / math.sqrt(self.caa * self.cbb))) diff --git a/src/morphobricks_preprocessing/image_qc_record.py b/src/morphobricks_preprocessing/image_qc_record.py new file mode 100644 index 00000000..64395368 --- /dev/null +++ b/src/morphobricks_preprocessing/image_qc_record.py @@ -0,0 +1,83 @@ +"""The run manifest's ``image_qc`` entry: which image QC table the run wrote (contract §19). + +The entry names the table (``image_qc.csv``), its SHA-256, the metrics' version and their +fixed settings, so the next run reuses the earlier rows only with the same table and the same +metric definitions. It is read strictly: anything other than these four keys, with these +types, makes the manifest malformed. +""" + +from __future__ import annotations + +import re + +from .image_qc import QC_VERSION, qc_settings + +KEY = "image_qc" +"""The manifest's key; absent in manifests written before the image QC table.""" +IMAGE_QC_FILENAME = "image_qc.csv" +"""The image QC table in the output folder.""" + +_SHA256 = re.compile(r"[0-9a-f]{64}") +_KEYS = frozenset({"file", "sha256", "qc_version", "settings"}) + + +def image_qc_entry(sha256: str) -> dict: + """Return the manifest entry of an image QC table written by this version. + + Parameters + ---------- + sha256 + The table's SHA-256. + + Returns + ------- + dict + """ + return { + "file": IMAGE_QC_FILENAME, + "sha256": sha256, + "qc_version": QC_VERSION, + "settings": qc_settings(), + } + + +def recorded_image_qc(data: object) -> dict | None: + """Return a recorded ``image_qc`` entry checked, or None when the manifest has none. + + Parameters + ---------- + data + The manifest's value for :data:`KEY`. + + Returns + ------- + dict or None + + Raises + ------ + ValueError + If the entry is not an object with exactly ``file`` (``image_qc.csv``), ``sha256`` + (64 lowercase hexadecimal digits), ``qc_version`` (text) and ``settings`` (an + object). + """ + if data is None: + return None + if not isinstance(data, dict) or set(data) != _KEYS: + raise ValueError(f"the {KEY} entry must have exactly the keys {sorted(_KEYS)}") + sha256, version = data["sha256"], data["qc_version"] + if data["file"] != IMAGE_QC_FILENAME: + raise ValueError(f"the {KEY} entry must name {IMAGE_QC_FILENAME}") + if not isinstance(sha256, str) or _SHA256.fullmatch(sha256) is None: + raise ValueError(f"the {KEY} entry's sha256 is not a SHA-256") + if not isinstance(version, str) or not isinstance(data["settings"], dict): + raise ValueError(f"the {KEY} entry's qc_version must be text and settings an object") + return dict(data) + + +def same_metrics(entry: dict | None) -> bool: + """Return True when a recorded entry's metrics are this version's (version and settings).""" + return ( + entry is not None + and entry["qc_version"] == QC_VERSION + and entry["settings"] == qc_settings() + ) diff --git a/src/morphobricks_preprocessing/image_qc_sums.py b/src/morphobricks_preprocessing/image_qc_sums.py new file mode 100644 index 00000000..232fc798 --- /dev/null +++ b/src/morphobricks_preprocessing/image_qc_sums.py @@ -0,0 +1,209 @@ +"""Sums over one block of pixels that the image QC metrics are built from (contract §19). + +Every metric of :mod:`.image_qc` is a ratio of sums: of the pixels, of their squares and of +products of each pixel with a neighbour at a fixed offset (a *pair sum*). This module +computes those sums for one block, offset by a constant near its mean so that they are well +conditioned, and :mod:`.image_qc` combines the blocks of a plane. + +A pair sum over a whole block is one dot product of the flattened block with itself shifted +by ``dy * width + dx`` places, minus the products that wrapped from the end of one row to the +next (a strip of ``|dx|`` columns). A pair sum over a smaller window subtracts the thin strips +between the window and the valid region. The dot products of every offset are taken in one +sweep over the block, a band of rows at a time (with the rows below it that the offsets +reach), so each band is converted to float64 once and stays in the processor's cache while +all the products are summed. + +For an integer image every product and every partial sum is a whole number below ``2**53`` +on planes of the usual sizes, so float64 holds them exactly and the result does not depend on +the order of summation. For a float image the sums are taken in a fixed order, so the same +machine gives the same bytes (another processor's vector width may change the last digits). +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass + +import numpy as np + +BAND_ROWS = 64 +"""Rows of a band of the sweep (a 2048-pixel-wide band of float64 is 1 MiB).""" +DOT_LENGTH = 8192 +"""Products summed per row of :func:`_dot` (short rows: no threads, the band stays cached).""" + + +def _dot(a: np.ndarray, b: np.ndarray) -> float: + """Return the dot product of two contiguous 1-D float64 arrays of one length. + + Summed as rows of :data:`DOT_LENGTH` (``numpy.vecdot``), then the rows in order: a fixed + order, and no BLAS threads started for each call (measured: thread start-up cost more + than the products on a loaded machine). + """ + whole = a.size - a.size % DOT_LENGTH + found = 0.0 + if whole: + rows = np.vecdot(a[:whole].reshape(-1, DOT_LENGTH), b[:whole].reshape(-1, DOT_LENGTH)) + found = float(rows.sum()) + return found + float(np.einsum("i,i->", a[whole:], b[whole:])) + + +@dataclass(frozen=True) +class Window: + """A rectangle of base pixels: rows ``y0`` to ``y1 - 1``, columns ``x0`` to ``x1 - 1``.""" + + y0: int + y1: int + x0: int + x1: int + + @property + def size(self) -> int: + """Number of pixels in the window (0 when it is empty).""" + return max(0, self.y1 - self.y0) * max(0, self.x1 - self.x0) + + def shifted(self, dy: int, dx: int) -> Window: + """Return the window moved by ``dy`` rows and ``dx`` columns.""" + return Window(self.y0 + dy, self.y1 + dy, self.x0 + dx, self.x1 + dx) + + +def valid_window(shape: tuple[int, int], dy: int, dx: int) -> Window: + """Return the base pixels whose neighbour at ``(dy, dx)`` lies inside a block of ``shape``. + + Parameters + ---------- + shape + The block's (rows, columns). + dy, dx + The offset; ``dy`` is never negative. + + Returns + ------- + Window + """ + height, width = shape + return Window(0, max(0, height - dy), max(0, -dx), max(0, width - max(0, dx))) + + +class BlockSums: + """The sums of one block, offset by ``offset`` (its pixels minus a constant). + + Parameters + ---------- + pixels + The block, finite values only, as a 2-D array. + offset + A constant near the block's mean, subtracted before any sum is taken. + offsets + The ``(dy, dx)`` offsets whose pair sums will be asked for (``dy >= 0``, and + ``dx > 0`` when ``dy == 0``). + row_edges + Rows of the block where a band of tiles starts (0 first); the column sums of each + band are kept (:attr:`bands`: first row, end row, column sums, column sums of squares). + """ + + def __init__( + self, + pixels: np.ndarray, + offset: float, + offsets: Sequence[tuple[int, int]], + row_edges: Sequence[int] = (0,), + ) -> None: + self.pixels = pixels + self.offset = float(offset) + self.shape = (int(pixels.shape[0]), int(pixels.shape[1])) + self._flat = dict.fromkeys(offsets, 0.0) + self._pairs: dict[tuple[int, int], float] = {} + self.bands = self._sweep(list(row_edges)) + self.total = float(sum(band[2].sum() for band in self.bands)) + self.total_sq = float(sum(band[3].sum() for band in self.bands)) + + def _sweep(self, row_edges: list[int]) -> list[tuple[int, int, np.ndarray, np.ndarray]]: + """Take every offset's flat dot product and each band's column sums in one sweep.""" + height, width = self.shape + reach = max((dy + (dx > 0) for dy, dx in self._flat), default=0) + steps = {key: key[0] * width + key[1] for key in self._flat} + buffer = np.empty((min(BAND_ROWS, height) + reach) * width) # as qc_memory counts it + edges = sorted({*row_edges, height}) + bands = [] + for start, stop in zip(edges[:-1], edges[1:], strict=True): + column, column_sq = np.zeros(width), np.zeros(width) + for top in range(start, stop, BAND_ROWS): + base = min(BAND_ROWS, stop - top) + rows = min(height, top + base + reach) - top + chunk = buffer[: rows * width] + np.subtract(self.pixels[top : top + rows].reshape(-1), self.offset, out=chunk) + own = chunk[: base * width].reshape(base, width) + column += own.sum(axis=0) + column_sq += np.einsum("ij,ij->j", own, own) + for key, step in steps.items(): + count = min(base * width, chunk.size - step) + if count > 0: + self._flat[key] += _dot(chunk[:count], chunk[step : step + count]) + bands.append((start, stop, column, column_sq)) + return bands + + def window_sum(self, window: Window, squared: bool = False) -> float: + """Return the sum of the offset pixels (or their squares) over ``window``. + + The total of the block minus the strips around the window, which are thin for the + windows the metrics use. + """ + total = self.total_sq if squared else self.total + height, width = self.shape + strips = ( + Window(0, window.y0, 0, width), + Window(window.y1, height, 0, width), + Window(window.y0, window.y1, 0, window.x0), + Window(window.y0, window.y1, window.x1, width), + ) + return total - sum(self._direct_sum(strip, squared) for strip in strips) + + def pair_sum(self, window: Window, dy: int, dx: int) -> float: + """Return the sum of ``d[y, x] * d[y + dy, x + dx]`` over the base pixels of ``window``. + + ``window`` must lie inside :func:`valid_window` for the offset, which must be one of + the block's ``offsets``. + """ + valid = valid_window(self.shape, dy, dx) + total = self._valid_pair_sum(dy, dx) + strips = ( + Window(valid.y0, window.y0, valid.x0, valid.x1), + Window(window.y1, valid.y1, valid.x0, valid.x1), + Window(window.y0, window.y1, valid.x0, window.x0), + Window(window.y0, window.y1, window.x1, valid.x1), + ) + return total - sum(self._direct_pairs(strip, dy, dx) for strip in strips) + + def _valid_pair_sum(self, dy: int, dx: int) -> float: + """Return the pair sum over every valid base pixel (the flat dot, wraps taken out).""" + key = (dy, dx) + if key not in self._pairs: + height, width = self.shape + found = self._flat[key] + # The flat dot also pairs pixels across a row end: take those products back out. + if dx > 0: + wrapped = Window(0, height - dy - 1, width - dx, width) + found -= self._direct_pairs(wrapped, dy + 1, dx - width) + elif dx < 0: + wrapped = Window(0, height - dy + 1, 0, -dx) + found -= self._direct_pairs(wrapped, dy - 1, dx + width) + self._pairs[key] = found + return self._pairs[key] + + def _part(self, window: Window) -> np.ndarray: + """Return the offset pixels of a small window as float64.""" + part = self.pixels[window.y0 : window.y1, window.x0 : window.x1] + return np.subtract(part, self.offset, dtype=np.float64) + + def _direct_sum(self, window: Window, squared: bool) -> float: + """Return the sum of the offset pixels (or their squares) of a small window directly.""" + if window.size == 0: + return 0.0 + part = self._part(window) + return float(np.einsum("ij,ij->", part, part)) if squared else float(part.sum()) + + def _direct_pairs(self, window: Window, dy: int, dx: int) -> float: + """Return a pair sum over a small window directly (its partners must be in the block).""" + if window.size == 0: + return 0.0 + return float(np.einsum("ij,ij->", self._part(window), self._part(window.shifted(dy, dx)))) diff --git a/src/morphobricks_preprocessing/image_qc_table.py b/src/morphobricks_preprocessing/image_qc_table.py new file mode 100644 index 00000000..8931cc2b --- /dev/null +++ b/src/morphobricks_preprocessing/image_qc_table.py @@ -0,0 +1,258 @@ +"""The image QC table ``image_qc.csv``: one row per plane and channel (contract §19). + +One row for each channel of each row of ``plane_histograms.csv``: the plane's identity (the +same columns and values as the histogram table), the canonical channel ID, whether the plane +was read in blocks, ``qc_status``, the metrics of :mod:`.image_qc` (blank where undefined, +never zero), ``blank_reasons`` (why each blank metric is blank) and ``qc_version``. Rows are +sorted by image, Z, T and channel ID; floats are written with ``repr``, so they read back +exactly. The reader is strict: another header, an unknown status or version, a value that is +not a number, or a combination no writer makes (:func:`_consistent`: a status with metrics it +blanks, a blank metric without a reason, a value out of its range) refuses the whole table. +""" + +from __future__ import annotations + +import csv +import io +import math +import os +from collections.abc import Iterable +from dataclasses import dataclass +from pathlib import Path + +from morphobricks_normalization.records import PlaneRecord + +from ._io import write_text_atomic +from .image_qc import ( + ENTROPY_BINS, + HISTOGRAM_METRICS, + MEASURED, + METRICS, + NO_FINITE, + NON_FINITE, + PIXEL_METRICS, + QC_VERSION, + RATIO_METRICS, + REASONS, + ImageQc, +) + +IDENTITY = ( + "position_id", + "image_file", + "z", + "t", + "condition", + "biological_repeat", + "technical_repeat", + "source_relative_path", + "plane_id", + "channel", +) +"""The identity columns of a row (the histogram table's, with the channel ID).""" +COLUMNS = (*IDENTITY, "read_in_blocks", "qc_status", *METRICS, "blank_reasons", "qc_version") +"""Every column, in order.""" +_STATUSES = frozenset({MEASURED, NON_FINITE, NO_FINITE}) +_RANGES = { + "otsu_separation": (0.0, 1.0), + "foreground_fraction": (0.0, 1.0), + "entropy": (0.0, math.log2(ENTROPY_BINS)), + "correlation_1": (-1.0, 1.0), + "correlation_4": (-1.0, 1.0), + "correlation_16": (-1.0, 1.0), +} +"""The closed range of each bounded metric; the ratio metrics are only never negative.""" +_FLAGS = {"true": True, "false": False} + + +class ImageQcFormatError(ValueError): + """Raised when a file is not an image QC table this version reads.""" + + +@dataclass(frozen=True) +class QcRow: + """One row of the table: one channel of one plane. + + Attributes + ---------- + identity + The values of :data:`IDENTITY`, as text (``z`` and ``t`` as decimal numbers). + read_in_blocks + True when the plane was read in blocks (neighbour pairs crossing a block edge are + left out of the neighbour metrics). + qc + The metrics. + """ + + identity: tuple[str, ...] + read_in_blocks: bool + qc: ImageQc + + @classmethod + def of(cls, record: PlaneRecord, channel: str, in_blocks: bool, qc: ImageQc) -> QcRow: + """Return the row of ``channel`` of the histogram table's row ``record``.""" + return cls(cls.identity_of(record, channel), in_blocks, qc) + + @staticmethod + def identity_of(record: PlaneRecord, channel: str) -> tuple[str, ...]: + """Return the values of :data:`IDENTITY` of ``channel`` of the histogram row ``record``.""" + return ( + record.position_id, + record.image_file, + str(record.z), + str(record.t), + record.condition, + record.biological_repeat, + record.technical_repeat, + record.source_relative_path, + record.plane_id, + channel, + ) + + @property + def relative_path(self) -> str: + """The image, relative to the experiment folder.""" + return self.identity[IDENTITY.index("source_relative_path")] + + @property + def key(self) -> tuple[str, str]: + """``(plane_id, channel)``: the row's key.""" + return self.identity[-2], self.identity[-1] + + def order(self) -> tuple: + """Return the sort key: image, Z, T, channel ID.""" + z, t = (int(self.identity[IDENTITY.index(name)]) for name in ("z", "t")) + return self.relative_path, z, t, self.identity[-1] + + +def table_text(rows: Iterable[QcRow]) -> str: + """Return the table of ``rows`` as CSV text (sorted, LF line endings).""" + stream = io.StringIO() + writer = csv.writer(stream, lineterminator="\n") + writer.writerow(COLUMNS) + for row in sorted(rows, key=QcRow.order): + if problem := _consistent(row.qc): # the writer refuses what the reader refuses + raise ValueError(f"the QC row of {row.identity[-2]!r}, {row.identity[-1]!r}: {problem}") + values = [getattr(row.qc, name) for name in METRICS] + writer.writerow( + [ + *row.identity, + "true" if row.read_in_blocks else "false", + row.qc.status, + *("" if value is None else repr(float(value)) for value in values), + ";".join(f"{name}={reason}" for name, reason in row.qc.reasons), + QC_VERSION, + ] + ) + return stream.getvalue() + + +def write_image_qc(rows: Iterable[QcRow], path: str | os.PathLike) -> Path: + """Write the table atomically. + + Parameters + ---------- + rows + Its rows, in any order. + path + Where to write. + + Returns + ------- + Path + """ + return write_text_atomic(path, table_text(rows)) + + +def read_image_qc(path: str | os.PathLike) -> list[QcRow]: + """Read a table written by :func:`write_image_qc`. + + Raises + ------ + ImageQcFormatError + If the file is not such a table (its header, a status, a flag, a number or the + version). + """ + try: + text = Path(path).read_text(encoding="utf-8") + except UnicodeDecodeError as exc: + raise ImageQcFormatError(f"{path} is not UTF-8 text: {exc}") from exc + lines = list(csv.reader(io.StringIO(text, newline=""))) + if not lines or tuple(lines[0]) != COLUMNS: + raise ImageQcFormatError(f"{path} does not have the image QC table's columns.") + return [_row(values, number, path) for number, values in enumerate(lines[1:], start=2)] + + +def _row(values: list[str], line: int, path: str | os.PathLike) -> QcRow: + """Read one line of the table.""" + if len(values) != len(COLUMNS): + raise ImageQcFormatError(f"{path}, line {line}: {len(values)} values, not {len(COLUMNS)}.") + data = dict(zip(COLUMNS, values, strict=True)) + if data["qc_version"] != QC_VERSION or data["qc_status"] not in _STATUSES: + raise ImageQcFormatError(f"{path}, line {line}: unknown qc_version or qc_status.") + if data["read_in_blocks"] not in _FLAGS or not all(data[name].isdigit() for name in ("z", "t")): + raise ImageQcFormatError(f"{path}, line {line}: read_in_blocks, z or t is malformed.") + metrics = {name: _number(data[name], name, line, path) for name in METRICS} + qc = ImageQc(data["qc_status"], **metrics, reasons=_reasons(data["blank_reasons"], line, path)) + if problem := _consistent(qc): + raise ImageQcFormatError(f"{path}, line {line}: {problem}.") + return QcRow(tuple(data[name] for name in IDENTITY), _FLAGS[data["read_in_blocks"]], qc) + + +def _number(text: str, name: str, line: int, path: str | os.PathLike) -> float | None: + """Return a metric's value: blank is None; anything but a finite number is refused.""" + if text == "": + return None + try: + value = float(text) + except ValueError: + value = math.nan + if not math.isfinite(value): + raise ImageQcFormatError(f"{path}, line {line}: {name} is not a finite number.") + return value + + +def _reasons(text: str, line: int, path: str | os.PathLike) -> tuple[tuple[str, str], ...]: + """Return the ``metric=reason`` pairs of a ``blank_reasons`` cell, as written.""" + pairs = [] + for item in text.split(";") if text else (): + name, _, reason = item.partition("=") + if name not in METRICS or reason not in REASONS: + raise ImageQcFormatError(f"{path}, line {line}: blank_reasons has {item!r}.") + pairs.append((name, reason)) + return tuple(pairs) + + +def _consistent(qc: ImageQc) -> str | None: + """Return what is wrong with a row's status, metrics and reasons together, or None. + + The combinations the writer never makes: a metric without a value and without a reason + (or the reverse), reasons out of table order or repeated, a status that does not match + what it blanks (``no_finite_pixels``: every metric, each with that reason; + ``non_finite_pixels``: exactly the pixel metrics, each with that reason, and the + histogram metrics of the finite pixels; ``measured``: the entropy at least, and no + status reason), the three Otsu metrics not blank together, and a value outside its range. + """ + values = {name: getattr(qc, name) for name in METRICS} + blank = [name for name in METRICS if values[name] is None] + why = dict(qc.reasons) + if [name for name, _ in qc.reasons] != blank: + return "the blank metrics and blank_reasons do not name the same metrics, in table order" + if qc.status == NO_FINITE: + if blank != list(METRICS) or set(why.values()) != {NO_FINITE}: + return "qc_status no_finite_pixels with a metric present or another reason" + return None + if values["entropy"] is None: + return f"qc_status {qc.status} without an entropy" + if qc.status == NON_FINITE: + if not set(PIXEL_METRICS) <= set(blank) or any(why[n] != NON_FINITE for n in PIXEL_METRICS): + return "qc_status non_finite_pixels with a pixel metric present or another reason" + elif {NON_FINITE, NO_FINITE} & set(why.values()): + return "qc_status measured with a metric blank for pixels that are not finite" + if len({values[n] is None for n in HISTOGRAM_METRICS[:3]}) != 1: + return "the Otsu metrics are not blank together" + for name, value in values.items(): + low, high = _RANGES.get(name, (0.0 if name in RATIO_METRICS else -math.inf, math.inf)) + if value is not None and not low <= value <= high: + return f"{name} is outside its range" + return None diff --git a/src/morphobricks_preprocessing/log_target.py b/src/morphobricks_preprocessing/log_target.py index cd42678d..ac93d961 100644 --- a/src/morphobricks_preprocessing/log_target.py +++ b/src/morphobricks_preprocessing/log_target.py @@ -34,6 +34,7 @@ from .conversion_record import RECORD_FILENAME from .design import DESIGN_FILENAME from .discovery_report import REPORT_FILENAME, REPORT_TEXT_FILENAME +from .image_qc_record import IMAGE_QC_FILENAME from .manifest import MANIFEST_FILENAME from .mask_scan import MASK_REPORT_FILENAME from .run.generation import PUBLISH_FOLDER @@ -46,6 +47,7 @@ PROTECTED_OUTPUTS = frozenset( { OUTPUT_FILENAME, + IMAGE_QC_FILENAME, MANIFEST_FILENAME, REPORT_FILENAME, REPORT_TEXT_FILENAME, diff --git a/src/morphobricks_preprocessing/manifest.py b/src/morphobricks_preprocessing/manifest.py index ac376159..7ebbabf4 100644 --- a/src/morphobricks_preprocessing/manifest.py +++ b/src/morphobricks_preprocessing/manifest.py @@ -34,39 +34,45 @@ from .channel_identity_model import ChannelIdentitySettings, recorded_settings, settings_entry from .description_record import KEY as DESCRIPTION_KEY from .description_record import recorded_description -from .image_names import position_id -from .inventory import INVENTORY_KEY, source_signature +from .image_qc_record import KEY as IMAGE_QC_KEY +from .image_qc_record import recorded_image_qc from .lab_links import KEY as LAB_LINKS_KEY from .lab_links import recorded_lab_links from .manifest_fields import ( - CHANNEL_IDS_KEY, - RAW_NAMES_KEY, optional_text, - recorded_channel_ids, recorded_flag, recorded_masks, - recorded_position_id, - recorded_raw_names, - recorded_roles, ) +from .manifest_files import ( + AXES_FROM as AXES_FROM, # re-exported (moved) +) +from .manifest_files import ( + FileEntry as FileEntry, # re-exported (moved) +) +from .manifest_files import ( + file_dict, + file_from_data, +) +from .manifest_files import ( + file_entry_for as file_entry_for, # re-exported (moved) +) +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 ( - CONTENT_KEY, RERUN, UnsupportedVersionError, check_version, recorded_version, ) -from .manifest_versions import MANIFEST_VERSION as MANIFEST_VERSION from .narrow_ranges import NarrowRange from .projection_run import KEY as PROJECTION_KEY from .projection_run import recorded_projection -from .recorded_sizes import RecordedSize, sizes_from_data, sizes_to_data from .versions import package_versions as package_versions # re-exported (moved) MANIFEST_FILENAME = "run_manifest.json" -AXES_FROM = ("header", "confirmed") _LABEL_KEYS = ("folder", "condition", "biological_repeat", "technical_repeat") -"""Where a file's roles come from (:attr:`FileEntry.axes_from`).""" class ManifestFormatError(ValueError): @@ -82,7 +88,9 @@ class RunSettings: bin_count Number of bins of every plane. memory_limit - Working-memory limit per plane, in bytes. It does not change any row. + Working-memory limit per plane, in bytes. It changes no histogram row, but it sets the + blocks of planes read in blocks, which the image QC metrics depend on (contract §19): + another limit recomputes the rows when planes are read in blocks (``run.reuse``). missing_as_singleton Whether the user confirmed that files lacking axes have one plane along them. @@ -108,105 +116,6 @@ def __post_init__(self) -> None: object.__setattr__(self, "exclude", tuple(sorted(set(self.exclude)))) -@dataclass(frozen=True) -class FileEntry: - """One analysed source file. - - Attributes - ---------- - relative_path - Path relative to the experiment root, with ``/`` separators. - size - File size in bytes when it was read; for an OME-Zarr folder, the total - size of its files. - mtime_ns - Modification time in nanoseconds when it was read; for an OME-Zarr - folder, the time of its most recently modified file. - labels - ``(condition, biological_repeat, technical_repeat)``. - axes - The file's axis labels. - 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. - channel_names - Channel names from metadata; empty when not given. - significant_bits - Significant bits from metadata; None when not given. - channel_names_trimmed - True when whitespace was removed around the channel names (names are recorded trimmed). - read_in_blocks - True when the planes are too large for the memory limit and are read in blocks. - For information only: the rows are the same either way. - position_id - The image's position identifier, its name without the extension - (:func:`~morphobricks_preprocessing.image_names.position_id`). Required when written - and read, and equal to that rule (round-2 audit A-m5); None only before the entry is - complete. - roles - The role of each of the file's axes (``"X"``, ``"Y"``, ``"Z"``, ``"C"``, ``"T"`` or - None), from its own mapping: for an OME-Zarr image whose declared order differs from - the experiment mapping's, these are its roles, not the experiment's. Required when - written and read. - axes_from - Where the roles come from: ``"header"`` (the metadata names every axis and - the roles agree) or ``"confirmed"`` (a plain stack: the user confirmed them). - Required when written and read. - pixel_sizes - The size of one step along X, Y, Z and T, each with its unit and source - (:class:`.recorded_sizes.RecordedSize`); always written. - inventory_sha256 - For an OME-Zarr folder, the SHA-256 of its inventory (each file's relative path, - size and modification time, :func:`.inventory.source_signature`); None for a - TIFF file, and in manifests written before it was recorded (such an OME-Zarr - image counts as changed: its fingerprint is not known to be complete). - content_sha256 - The SHA-256 of the file's content (an OME-Zarr folder: of its files' paths and SHA-256s, - :func:`.source_content.source_content_sha256`) in a ``verify_content`` run; else None. - raw_channel_names - Header channel names, untrimmed; written only when not empty; not in :meth:`same_source`. - channel_ids - The image's canonical channel IDs in source order: its imaging unit's confirmed - ``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. - """ - - relative_path: str - size: int - mtime_ns: int - labels: tuple[str, str, str] - axes: str - singleton_roles: tuple[str, ...] = () - plane_count: int = 0 - channel_names: tuple[str | None, ...] = () - significant_bits: int | None = None - read_in_blocks: bool = False - position_id: str | None = None - channel_names_trimmed: bool = False - roles: tuple[str | None, ...] | None = None - axes_from: str | None = None - pixel_sizes: tuple[RecordedSize, ...] = () - inventory_sha256: str | None = None - content_sha256: str | None = None - raw_channel_names: tuple[str | None, ...] = () - channel_ids: tuple[str, ...] = () - - def same_source(self, other: FileEntry) -> bool: - """Return True if ``other`` describes the same unchanged file, read the same way.""" - return ( - self.relative_path == other.relative_path - and self.size == other.size - and self.mtime_ns == other.mtime_ns - and self.inventory_sha256 == other.inventory_sha256 - and self.content_sha256 == other.content_sha256 - and self.labels == other.labels - and self.axes == other.axes - and self.singleton_roles == other.singleton_roles - ) - - @dataclass(frozen=True) class RunManifest: """Everything a run records about its inputs and output. @@ -267,6 +176,9 @@ class RunManifest: lab_links The lab-tool links the user gave the run (:mod:`.lab_links`), provenance only; None (key left out) if none. + 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. schema_version Version of the CSV format. manifest_version @@ -294,6 +206,7 @@ class RunManifest: experiment_description: dict | None = None projection: dict | None = None lab_links: dict | None = None + image_qc: dict | None = None schema_version: str = SCHEMA_VERSION manifest_version: str = MANIFEST_VERSION @@ -346,7 +259,7 @@ def to_dict(self) -> dict: dict(zip(_LABEL_KEYS, (folder, *labels), strict=True)) for folder, labels in self.leaves.items() ], - "files": [_file_dict(f) for f in self.files], + "files": [file_dict(f) for f in self.files], "csv_sha256": self.csv_sha256, "experiment_design_sha256": self.experiment_design_sha256, "image_type": self.image_type, @@ -367,6 +280,7 @@ 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}) return data @@ -395,7 +309,7 @@ def from_dict(cls, data: dict) -> RunManifest: verify_content=recorded_flag(settings["verify_content"], "verify_content"), ), mapping=AxisMapping(str(mapping["axes"]), tuple(mapping["roles"])), - files=tuple(_file_entry(f) for f in data["files"]), + files=tuple(file_from_data(f) for f in data["files"]), csv_sha256=str(data["csv_sha256"]), versions={str(k): str(v) for k, v in data.get("versions", {}).items()}, written_at=str(data.get("written_at", "")), @@ -422,6 +336,7 @@ def from_dict(cls, data: dict) -> RunManifest: 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), ) @@ -438,64 +353,6 @@ def from_dict(cls, data: dict) -> RunManifest: raise ManifestFormatError(f"The manifest is incomplete or malformed: {exc}") from exc -def file_entry_for( # noqa: PLR0913 - root: str | os.PathLike, - relative_path: str, - labels: tuple[str, str, str], - mapping: AxisMapping, - *, - plane_count: int = 0, - channel_names: tuple[str | None, ...] = (), - significant_bits: int | None = None, - read_in_blocks: bool = False, - channel_names_trimmed: bool = False, -) -> FileEntry: - """Describe a source image as it is on disk now, with its position identifier.""" - return file_entry_with( - source_signature(Path(root) / relative_path), - relative_path, - labels, - mapping, - plane_count=plane_count, - channel_names=tuple(channel_names), - significant_bits=significant_bits, - read_in_blocks=read_in_blocks, - channel_names_trimmed=channel_names_trimmed, - ) - - -def file_entry_with( - signature: tuple[int, int, str | None], - relative_path: str, - labels: tuple[str, str, str], - mapping: AxisMapping, - **header: object, -) -> FileEntry: - """Describe a source image with a fingerprint already taken, as :func:`file_entry_for`. - - ``signature`` is ``(size, mtime_ns, inventory)`` (:func:`.inventory.source_signature`), for - example the one taken when the header was read; ``relative_path``, ``labels``, ``mapping`` - and the ``header`` keywords (channel names, bits, ...) are those of :func:`file_entry_for`. - - Returns - ------- - FileEntry - """ - size, mtime_ns, inventory = signature - return FileEntry( - relative_path=relative_path, - size=size, - mtime_ns=mtime_ns, - labels=tuple(labels), - axes=mapping.axes, - singleton_roles=mapping.singleton_roles, - position_id=position_id(relative_path), - roles=tuple(mapping.roles), - inventory_sha256=inventory, - **header, - ) - - def write_manifest(manifest: RunManifest, path: str | os.PathLike) -> Path: """Write a manifest as JSON, replacing the file only once writing succeeded.""" text = json.dumps(manifest.to_dict(), indent=2, ensure_ascii=False) + "\n" @@ -519,82 +376,5 @@ def read_manifest(path: str | os.PathLike) -> RunManifest: return RunManifest.from_dict(data) -def _file_dict(entry: FileEntry) -> dict: - """Return a file entry as manifest data; its roles, their source and position are required. - - The writer refuses what the reader would refuse, so a written manifest always reads back. - """ - 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) - data = { - "relative_path": entry.relative_path, - "size": entry.size, - "mtime_ns": entry.mtime_ns, - "condition": entry.labels[0], - "biological_repeat": entry.labels[1], - "technical_repeat": entry.labels[2], - "axes": entry.axes, - "singleton_roles": list(entry.singleton_roles), - "plane_count": entry.plane_count, - "channel_names": list(entry.channel_names), - "significant_bits": entry.significant_bits, - "read_in_blocks": recorded_flag(entry.read_in_blocks, "read_in_blocks"), - "position_id": entry.position_id, - "channel_names_trimmed": recorded_flag( - entry.channel_names_trimmed, "channel_names_trimmed" - ), - "roles": None if entry.roles is None else list(entry.roles), - "axes_from": entry.axes_from, - "pixel_sizes": sizes_to_data(entry.pixel_sizes), - } - if entry.inventory_sha256 is not None: - data[INVENTORY_KEY] = entry.inventory_sha256 - if entry.content_sha256 is not None: - data[CONTENT_KEY] = entry.content_sha256 - if entry.raw_channel_names: - data[RAW_NAMES_KEY] = list(entry.raw_channel_names) - data[CHANNEL_IDS_KEY] = list(recorded_channel_ids(entry.channel_ids, entry.relative_path)) - return data - - -def _file_entry(data: dict) -> 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. - """ - 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") - return FileEntry( - relative_path=path, - size=int(data["size"]), - mtime_ns=int(data["mtime_ns"]), - labels=( - str(data["condition"]), - str(data["biological_repeat"]), - str(data["technical_repeat"]), - ), - axes=str(data["axes"]), - singleton_roles=tuple(str(r) for r in data["singleton_roles"]), - plane_count=int(data["plane_count"]), - channel_names=tuple(None if n is None else str(n) for n in data["channel_names"]), - significant_bits=None if bits is None else int(bits), - read_in_blocks=recorded_flag(data["read_in_blocks"], "read_in_blocks"), - position_id=recorded_position_id(data.get("position_id"), path), - 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"]), - 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), - channel_ids=recorded_channel_ids(data.get(CHANNEL_IDS_KEY), path), - ) - - def _parent(relative_path: str) -> str: return relative_path.rsplit("/", 1)[0] if "/" in relative_path else "." diff --git a/src/morphobricks_preprocessing/manifest_files.py b/src/morphobricks_preprocessing/manifest_files.py new file mode 100644 index 00000000..d2307656 --- /dev/null +++ b/src/morphobricks_preprocessing/manifest_files.py @@ -0,0 +1,269 @@ +"""One analysed source file of a run manifest, and its manifest data (contract §9). + +:class:`FileEntry` describes a source image as the run read it: fingerprint, labels, axes, +roles and where they come from, pixel sizes, channel names and IDs. :func:`file_entry_for` and +:func:`file_entry_with` describe a file as it is on disk now; :func:`file_dict` and +:func:`file_from_data` write and read an entry as manifest data, refusing what the other would +refuse, so a written manifest always reads back. :mod:`.manifest` holds the manifest around the +entries and re-exports these names. +""" + +from __future__ import annotations + +import os +from dataclasses import dataclass +from pathlib import Path + +from .axes import AxisMapping +from .image_names import position_id +from .inventory import INVENTORY_KEY, source_signature +from .manifest_fields import ( + CHANNEL_IDS_KEY, + RAW_NAMES_KEY, + optional_text, + recorded_channel_ids, + recorded_flag, + recorded_position_id, + recorded_raw_names, + recorded_roles, +) +from .manifest_versions import CONTENT_KEY +from .recorded_sizes import RecordedSize, sizes_from_data, sizes_to_data + +AXES_FROM = ("header", "confirmed") +"""Where a file's roles come from (:attr:`FileEntry.axes_from`).""" + + +@dataclass(frozen=True) +class FileEntry: + """One analysed source file. + + Attributes + ---------- + relative_path + Path relative to the experiment root, with ``/`` separators. + size + File size in bytes when it was read; for an OME-Zarr folder, the total + size of its files. + mtime_ns + Modification time in nanoseconds when it was read; for an OME-Zarr + folder, the time of its most recently modified file. + labels + ``(condition, biological_repeat, technical_repeat)``. + axes + The file's axis labels. + 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. + channel_names + Channel names from metadata; empty when not given. + significant_bits + Significant bits from metadata; None when not given. + channel_names_trimmed + True when whitespace was removed around the channel names (names are recorded trimmed). + read_in_blocks + True when the planes are too large for the memory limit and are read in blocks. The + histogram rows are the same either way; the neighbour metrics of the image QC rows are + not (contract §19), so the row key holds the memory limit for such an image. + position_id + The image's position identifier, its name without the extension + (:func:`~morphobricks_preprocessing.image_names.position_id`). Required when written + and read, and equal to that rule (round-2 audit A-m5); None only before the entry is + complete. + roles + The role of each of the file's axes (``"X"``, ``"Y"``, ``"Z"``, ``"C"``, ``"T"`` or + None), from its own mapping: for an OME-Zarr image whose declared order differs from + the experiment mapping's, these are its roles, not the experiment's. Required when + written and read. + axes_from + Where the roles come from: ``"header"`` (the metadata names every axis and + the roles agree) or ``"confirmed"`` (a plain stack: the user confirmed them). + Required when written and read. + pixel_sizes + The size of one step along X, Y, Z and T, each with its unit and source + (:class:`.recorded_sizes.RecordedSize`); always written. + inventory_sha256 + For an OME-Zarr folder, the SHA-256 of its inventory (each file's relative path, + size and modification time, :func:`.inventory.source_signature`); None for a + TIFF file, and in manifests written before it was recorded (such an OME-Zarr + image counts as changed: its fingerprint is not known to be complete). + content_sha256 + The SHA-256 of the file's content (an OME-Zarr folder: of its files' paths and SHA-256s, + :func:`.source_content.source_content_sha256`) in a ``verify_content`` run; else None. + raw_channel_names + Header channel names, untrimmed; written only when not empty; not in :meth:`same_source`. + channel_ids + The image's canonical channel IDs in source order: its imaging unit's confirmed + ``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. + """ + + relative_path: str + size: int + mtime_ns: int + labels: tuple[str, str, str] + axes: str + singleton_roles: tuple[str, ...] = () + plane_count: int = 0 + channel_names: tuple[str | None, ...] = () + significant_bits: int | None = None + read_in_blocks: bool = False + position_id: str | None = None + channel_names_trimmed: bool = False + roles: tuple[str | None, ...] | None = None + axes_from: str | None = None + pixel_sizes: tuple[RecordedSize, ...] = () + inventory_sha256: str | None = None + content_sha256: str | None = None + raw_channel_names: tuple[str | None, ...] = () + channel_ids: tuple[str, ...] = () + + def same_source(self, other: FileEntry) -> bool: + """Return True if ``other`` describes the same unchanged file, read the same way.""" + return ( + self.relative_path == other.relative_path + and self.size == other.size + and self.mtime_ns == other.mtime_ns + and self.inventory_sha256 == other.inventory_sha256 + and self.content_sha256 == other.content_sha256 + and self.labels == other.labels + and self.axes == other.axes + and self.singleton_roles == other.singleton_roles + ) + + +def file_entry_for( # noqa: PLR0913 + root: str | os.PathLike, + relative_path: str, + labels: tuple[str, str, str], + mapping: AxisMapping, + *, + plane_count: int = 0, + channel_names: tuple[str | None, ...] = (), + significant_bits: int | None = None, + read_in_blocks: bool = False, + channel_names_trimmed: bool = False, +) -> FileEntry: + """Describe a source image as it is on disk now, with its position identifier.""" + return file_entry_with( + source_signature(Path(root) / relative_path), + relative_path, + labels, + mapping, + plane_count=plane_count, + channel_names=tuple(channel_names), + significant_bits=significant_bits, + read_in_blocks=read_in_blocks, + channel_names_trimmed=channel_names_trimmed, + ) + + +def file_entry_with( + signature: tuple[int, int, str | None], + relative_path: str, + labels: tuple[str, str, str], + mapping: AxisMapping, + **header: object, +) -> FileEntry: + """Describe a source image with a fingerprint already taken, as :func:`file_entry_for`. + + ``signature`` is ``(size, mtime_ns, inventory)`` (:func:`.inventory.source_signature`), for + example the one taken when the header was read; ``relative_path``, ``labels``, ``mapping`` + and the ``header`` keywords (channel names, bits, ...) are those of :func:`file_entry_for`. + + Returns + ------- + FileEntry + """ + size, mtime_ns, inventory = signature + return FileEntry( + relative_path=relative_path, + size=size, + mtime_ns=mtime_ns, + labels=tuple(labels), + axes=mapping.axes, + singleton_roles=mapping.singleton_roles, + position_id=position_id(relative_path), + roles=tuple(mapping.roles), + inventory_sha256=inventory, + **header, + ) + + +def file_dict(entry: FileEntry) -> dict: + """Return a file entry as manifest data; its roles, their source and position are required. + + The writer refuses what the reader would refuse, so a written manifest always reads back. + """ + 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) + data = { + "relative_path": entry.relative_path, + "size": entry.size, + "mtime_ns": entry.mtime_ns, + "condition": entry.labels[0], + "biological_repeat": entry.labels[1], + "technical_repeat": entry.labels[2], + "axes": entry.axes, + "singleton_roles": list(entry.singleton_roles), + "plane_count": entry.plane_count, + "channel_names": list(entry.channel_names), + "significant_bits": entry.significant_bits, + "read_in_blocks": recorded_flag(entry.read_in_blocks, "read_in_blocks"), + "position_id": entry.position_id, + "channel_names_trimmed": recorded_flag( + entry.channel_names_trimmed, "channel_names_trimmed" + ), + "roles": None if entry.roles is None else list(entry.roles), + "axes_from": entry.axes_from, + "pixel_sizes": sizes_to_data(entry.pixel_sizes), + } + if entry.inventory_sha256 is not None: + data[INVENTORY_KEY] = entry.inventory_sha256 + if entry.content_sha256 is not None: + data[CONTENT_KEY] = entry.content_sha256 + if entry.raw_channel_names: + data[RAW_NAMES_KEY] = list(entry.raw_channel_names) + data[CHANNEL_IDS_KEY] = list(recorded_channel_ids(entry.channel_ids, entry.relative_path)) + return data + + +def file_from_data(data: dict) -> 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. + """ + 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") + return FileEntry( + relative_path=path, + size=int(data["size"]), + mtime_ns=int(data["mtime_ns"]), + labels=( + str(data["condition"]), + str(data["biological_repeat"]), + str(data["technical_repeat"]), + ), + axes=str(data["axes"]), + singleton_roles=tuple(str(r) for r in data["singleton_roles"]), + plane_count=int(data["plane_count"]), + channel_names=tuple(None if n is None else str(n) for n in data["channel_names"]), + significant_bits=None if bits is None else int(bits), + read_in_blocks=recorded_flag(data["read_in_blocks"], "read_in_blocks"), + position_id=recorded_position_id(data.get("position_id"), path), + 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"]), + 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), + channel_ids=recorded_channel_ids(data.get(CHANNEL_IDS_KEY), path), + ) diff --git a/src/morphobricks_preprocessing/plane_binning.py b/src/morphobricks_preprocessing/plane_binning.py new file mode 100644 index 00000000..5752e8fa --- /dev/null +++ b/src/morphobricks_preprocessing/plane_binning.py @@ -0,0 +1,69 @@ +"""What measuring a plane costs in working memory beyond its pixels (audit I2, contract §19). + +The histogram's temporary arrays, the finished histograms of the plane's channels and the +image QC sums (:func:`.image_qc.qc_memory`) of the same pass. The layouts of :mod:`.planes` add +it to the memory estimate of a whole plane and of a block, so a plane is read in blocks +exactly when the whole measurement would not fit the memory limit. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np +from morphobricks_normalization.dtypes import default_bin_count +from morphobricks_normalization.histogram import estimate_histogram_memory +from morphobricks_normalization.ranges import HistogramSettings + +from .image_qc import qc_memory + + +@dataclass(frozen=True) +class Binning: + """What a plane's histogram and QC metrics cost in memory (nothing when only read). + + Attributes + ---------- + bin_count + Histogram bins; the pixel type's default if None. + settings + The histogram range of the run. + histogram + False when the plane is only read (a mask, a preview): no histogram, no QC. + """ + + bin_count: int | None = None + settings: HistogramSettings | None = None + histogram: bool = True + + def memory(self, rows: int, cols: int, dtype: np.dtype, transposed: bool = False) -> int: + """Temporary memory of measuring ``rows`` x ``cols`` pixels (none when only read). + + Parameters + ---------- + rows, cols + The part measured, as stored; the QC sums work on it as (Y, X). + dtype + Its pixel type. + transposed + True when the stored rows are the plane's X (the part is turned before it is + measured, so the QC band runs along the stored columns). + """ + if not self.histogram: + return 0 + qc = qc_memory(*((cols, rows) if transposed else (rows, cols)), dtype.kind == "f") + histogram = estimate_histogram_memory( + rows * cols, dtype, self.bin_count, settings=self.settings, range_check=True + ) + return histogram + qc + + def finished(self, dtype: np.dtype, channels: int) -> int: + """Memory of the finished histograms of an XYC plane's channels. + + The bin counts of every channel, kept until the plane's row is made. + """ + if not self.histogram: + return 0 + return ( + channels * 8 * (default_bin_count(dtype) if self.bin_count is None else self.bin_count) + ) diff --git a/src/morphobricks_preprocessing/plane_channels.py b/src/morphobricks_preprocessing/plane_channels.py index e64f2374..8883525a 100644 --- a/src/morphobricks_preprocessing/plane_channels.py +++ b/src/morphobricks_preprocessing/plane_channels.py @@ -46,11 +46,11 @@ from . import window_memory from .axes import AxisMapping from .codec_bounds import check_tiff_codec +from .plane_binning import Binning from .planes import ( DEFAULT_MEMORY_LIMIT, PlaneLayout, PlaneMemoryError, - _Binning, _layout, _open, _open_zarr, @@ -93,12 +93,12 @@ def xyc_plane_memory( """ if is_zarr_store(path): layout = _zarr_layout( - _open_zarr(path), mapping, path, _Binning(histogram=False), memory_limit + _open_zarr(path), mapping, path, Binning(histogram=False), memory_limit ) return _zarr_memory(layout, _count(layout, channel_count)) with _open(path) as tif: series = tif.series[0] - layout = _layout(series, mapping, path, _Binning(histogram=False), memory_limit) + layout = _layout(series, mapping, path, Binning(histogram=False), memory_limit) count = _checked(layout, channel_count, path) pages = _page_indices(layout, mapping, {"Z": z, "T": t}, count) return _tiff_memory(series, layout, pages, count, path) @@ -132,13 +132,13 @@ def read_xyc_plane( wanted = {"Z": z, "T": t} if is_zarr_store(path): image = _open_zarr(path) - layout = _zarr_layout(image, mapping, path, _Binning(histogram=False), memory_limit) + layout = _zarr_layout(image, mapping, path, Binning(histogram=False), memory_limit) count = _checked(layout, channel_count, path) _refuse_over(_zarr_memory(layout, count), layout, count, path) return _read_zarr(image, layout, mapping, path, wanted, count) with _open(path) as tif: series = tif.series[0] - layout = _layout(series, mapping, path, _Binning(histogram=False), memory_limit) + layout = _layout(series, mapping, path, Binning(histogram=False), memory_limit) count = _checked(layout, channel_count, path) pages = _page_indices(layout, mapping, wanted, count) _refuse_over(_tiff_memory(series, layout, pages, count, path), layout, count, path) diff --git a/src/morphobricks_preprocessing/planes.py b/src/morphobricks_preprocessing/planes.py index ed9b5c18..dc976fce 100644 --- a/src/morphobricks_preprocessing/planes.py +++ b/src/morphobricks_preprocessing/planes.py @@ -53,17 +53,16 @@ import numpy as np import tifffile -from morphobricks_normalization.dtypes import default_bin_count from morphobricks_normalization.histogram import ( PlaneHistogram, compute_block_histogram, - estimate_histogram_memory, histogram_with_range_check, ) from morphobricks_normalization.ranges import HistogramSettings, RangeCheck from .axes import PLANE_ROLES, AxisMapping, AxisReview from .codec_bounds import FIX, READ, refusal_text, unbounded +from .plane_binning import Binning from .plane_errors import CompressionNotBoundedError, PlaneMemoryError, PlaneReadError from .tiff_pieces import _Blocking, _largest_piece, _read_tiff_box, _tiff_blocking, page_array from .validation import ValidationIssue, error, plural, warning @@ -384,11 +383,11 @@ def plane_layout( """ if is_zarr_store(path): return _zarr_layout( - _open_zarr(path), mapping, path, _Binning(bin_count, histogram_settings), memory_limit + _open_zarr(path), mapping, path, Binning(bin_count, histogram_settings), memory_limit ) with _open(path) as tif: return _layout( - tif.series[0], mapping, path, _Binning(bin_count, histogram_settings), memory_limit + tif.series[0], mapping, path, Binning(bin_count, histogram_settings), memory_limit ) @@ -436,7 +435,7 @@ def iter_planes( if is_zarr_store(path): image = _open_zarr(path) layout = _zarr_layout( - image, mapping, path, _Binning(bin_count, histogram_settings), memory_limit + image, mapping, path, Binning(bin_count, histogram_settings), memory_limit ) _check_limit(layout, path) for position in _positions(layout, mapping): @@ -445,7 +444,7 @@ def iter_planes( with _open(path) as tif: series = tif.series[0] layout = _layout( - series, mapping, path, _Binning(bin_count, histogram_settings), memory_limit + series, mapping, path, Binning(bin_count, histogram_settings), memory_limit ) _check_limit(layout, path) read = _tiff_reader(series, layout, mapping, path) @@ -496,7 +495,7 @@ def iter_xyc_planes( if is_zarr_store(path): image = _open_zarr(path) layout = _zarr_layout( - image, mapping, path, _Binning(bin_count, histogram_settings), memory_limit + image, mapping, path, Binning(bin_count, histogram_settings), memory_limit ) _check_limit(layout, path) yield from _xyc_planes( @@ -508,7 +507,7 @@ def iter_xyc_planes( with _open(path) as tif: series = tif.series[0] layout = _layout( - series, mapping, path, _Binning(bin_count, histogram_settings), memory_limit + series, mapping, path, Binning(bin_count, histogram_settings), memory_limit ) _check_limit(layout, path) yield from _xyc_planes(layout, mapping, _tiff_reader(series, layout, mapping, path)) @@ -548,13 +547,13 @@ def read_plane( wanted = {"Z": z, "C": c, "T": t} if is_zarr_store(path): image = _open_zarr(path) - layout = _zarr_layout(image, mapping, path, _Binning(histogram=False), memory_limit) + layout = _zarr_layout(image, mapping, path, Binning(histogram=False), memory_limit) layout = _whole_or_preview(layout, path, preview, _zarr_reblock(image, mapping, path)) position = _position(layout, mapping, wanted) return _whole_or_reduced(_zarr_plane(image, layout, mapping, position, path), layout) with _open(path) as tif: series = tif.series[0] - layout = _layout(series, mapping, path, _Binning(histogram=False), memory_limit) + layout = _layout(series, mapping, path, Binning(histogram=False), memory_limit) layout = _whole_or_preview(layout, path, preview, _tiff_reblock(series, mapping, path)) return _whole_or_reduced(_read_one(series, layout, mapping, path, wanted), layout) @@ -576,7 +575,7 @@ def read_sample_plane( return read_plane(path, mapping, z=z, memory_limit=memory_limit, preview=True) with _open(path) as tif: series = tif.series[0] - layout = _layout(series, mapping, path, _Binning(histogram=False), memory_limit) + layout = _layout(series, mapping, path, Binning(histogram=False), memory_limit) layout = _whole_or_preview(layout, path, True, _tiff_reblock(series, mapping, path)) dim = mapping.index_of("Z") z = None if dim is None else layout.shape[dim] // 2 @@ -754,7 +753,7 @@ def _layout( series: tifffile.TiffPageSeries, mapping: AxisMapping, path, # noqa: ANN001 - binning: _Binning, + binning: Binning, memory_limit: int = DEFAULT_MEMORY_LIMIT, ) -> PlaneLayout: """Work out from a TIFF series' header how its planes are read: whole, or in blocks.""" @@ -789,7 +788,7 @@ def _layout( page_nbytes + encoded_nbytes + plane_pixels * dtype.itemsize - + binning.memory(plane_pixels, dtype) + + binning.memory(shape[y], shape[x], dtype) + binning.finished(dtype, channels) ) layout = PlaneLayout( @@ -819,30 +818,6 @@ def _channel_count(shape: tuple[int, ...], mapping: AxisMapping) -> int: return 1 if c is None else shape[c] -@dataclass(frozen=True) -class _Binning: - """What a plane's histogram costs in memory (nothing when only read, audit I2).""" - - bin_count: int | None = None - settings: HistogramSettings | None = None - histogram: bool = True - - def memory(self, pixels: int, dtype: np.dtype) -> int: - """Temporary memory of binning ``pixels`` pixels (none when only read: bool masks).""" - return self.histogram and estimate_histogram_memory( - pixels, dtype, self.bin_count, settings=self.settings, range_check=True - ) - - def finished(self, dtype: np.dtype, channels: int) -> int: - """Memory of the finished histograms of an XYC plane's channels.""" - return self.histogram and _finished_histograms_nbytes(dtype, self.bin_count, channels) - - -def _finished_histograms_nbytes(dtype: np.dtype, bin_count: int | None, channels: int) -> int: - """Memory of the bin counts of every channel of an XYC plane, kept until its row is made.""" - return channels * 8 * (default_bin_count(dtype) if bin_count is None else bin_count) - - def _check_limit(layout: PlaneLayout, path) -> None: # noqa: ANN001 _refuse_codec(layout, path) if not layout.fits: @@ -1011,7 +986,7 @@ def _coordinates(mapping: AxisMapping, position: Mapping[int, int]) -> dict[str, # Blocks -------------------------------------------------------------------------------- -def _with_blocks(layout: PlaneLayout, blocking: _Blocking | None, binning: _Binning) -> PlaneLayout: +def _with_blocks(layout: PlaneLayout, blocking: _Blocking | None, binning: Binning) -> PlaneLayout: """Add the block size that fits the memory limit to a layout over the limit.""" if blocking is None: return layout @@ -1076,13 +1051,13 @@ def largest(count: int, size: Callable[[int], tuple[int, int]]) -> int: def _block_memory( - layout: PlaneLayout, blocking: _Blocking, rows: int, cols: int, binning: _Binning + layout: PlaneLayout, blocking: _Blocking, rows: int, cols: int, binning: Binning ) -> int: """Estimated working memory to read one block and add it to the histogram.""" pixels = rows * cols memory = ( pixels * layout.dtype.itemsize - + binning.memory(pixels, layout.dtype) + + binning.memory(rows, cols, layout.dtype, not blocking.rows_are_y) + binning.finished(layout.dtype, layout.channel_count) ) unit_rows, unit_cols = blocking.unit @@ -1205,7 +1180,7 @@ def _whole_or_reduced(plane: Plane, layout: PlaneLayout) -> Plane: def _tiff_reblock(series, mapping: AxisMapping, path) -> Callable[[int], PlaneLayout]: # noqa: ANN001 - return lambda limit: _layout(series, mapping, path, _Binning(histogram=False), limit) + return lambda limit: _layout(series, mapping, path, Binning(histogram=False), limit) def _tiff_block_plane( @@ -1248,7 +1223,7 @@ def _zarr_layout( image: NgffImage, mapping: AxisMapping, path, # noqa: ANN001 - binning: _Binning, + binning: Binning, memory_limit: int = DEFAULT_MEMORY_LIMIT, ) -> PlaneLayout: shape = image.shape @@ -1264,7 +1239,7 @@ def _zarr_layout( memory = ( page_nbytes + plane_pixels * dtype.itemsize - + binning.memory(plane_pixels, dtype) + + binning.memory(shape[y], shape[x], dtype) + binning.finished(dtype, channels) ) layout = PlaneLayout( @@ -1295,7 +1270,7 @@ def _zarr_layout( def _zarr_reblock(image: NgffImage, mapping: AxisMapping, path) -> Callable[[int], PlaneLayout]: # noqa: ANN001 - return lambda limit: _zarr_layout(image, mapping, path, _Binning(histogram=False), limit) + return lambda limit: _zarr_layout(image, mapping, path, Binning(histogram=False), limit) def _zarr_plane( diff --git a/src/morphobricks_preprocessing/run/generation.py b/src/morphobricks_preprocessing/run/generation.py index 7add10a2..cc7f8be3 100644 --- a/src/morphobricks_preprocessing/run/generation.py +++ b/src/morphobricks_preprocessing/run/generation.py @@ -1,8 +1,8 @@ """Publish a run's outputs as one generation, made current in one atomic step (contract §9). -A run's published outputs (``plane_histograms.csv``, ``experiment_design.csv``, -``run_manifest.json`` and the report files) are one **generation**. Publication is -crash-consistent (owner decision of 2 November 2026, PP-12): +A run's published outputs (``plane_histograms.csv``, ``image_qc.csv``, +``experiment_design.csv``, ``run_manifest.json`` and the report files) are one +**generation**. Publication is crash-consistent (owner decision of 2 November 2026, PP-12): 1. The whole new generation is written into the publication folder ``.publish`` in the output folder, each file flushed to disk, and then the **publication record** @@ -50,6 +50,7 @@ from .._io import give_output_mode, write_text_atomic from ..design import DESIGN_FILENAME from ..discovery_report import REPORT_FILENAME, REPORT_TEXT_FILENAME +from ..image_qc_record import IMAGE_QC_FILENAME from ..manifest import MANIFEST_FILENAME, file_sha256 logger = logging.getLogger(__name__) @@ -61,7 +62,13 @@ PUBLICATION_RECORD = "publication.json" """The record of a generation being published, written last into :data:`PUBLISH_FOLDER`.""" PUBLICATION_VERSION = "1" -MOVED_IN_ORDER = (OUTPUT_FILENAME, DESIGN_FILENAME, REPORT_TEXT_FILENAME, REPORT_FILENAME) +MOVED_IN_ORDER = ( + OUTPUT_FILENAME, + IMAGE_QC_FILENAME, + DESIGN_FILENAME, + REPORT_TEXT_FILENAME, + REPORT_FILENAME, +) """The files moved into place after the commit, in this order (the manifest is the commit).""" diff --git a/src/morphobricks_preprocessing/run/outputs.py b/src/morphobricks_preprocessing/run/outputs.py new file mode 100644 index 00000000..d1f70df9 --- /dev/null +++ b/src/morphobricks_preprocessing/run/outputs.py @@ -0,0 +1,134 @@ +"""What a run writes into its publication folder: the tables and the manifest (contract §9). + +:func:`write_generation` writes the histogram table, the image QC table, the experiment design +and the manifest, and returns the manifest's SHA-256; :func:`replaced_files` names the earlier +outputs the run replaces or removes. Moved from :mod:`.pipeline`. +""" + +from __future__ import annotations + +from collections import Counter +from dataclasses import replace +from datetime import UTC, datetime +from pathlib import Path + +from morphobricks_normalization.csv_io import OUTPUT_FILENAME, write_plane_histograms + +from ..channel_identity import ChannelIdentityReport +from ..design import DESIGN_FILENAME, write_experiment_design +from ..discovery_report import REPORT_FILENAME, REPORT_TEXT_FILENAME +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, + RunManifest, + RunSettings, + file_sha256, + package_versions, + write_manifest, +) +from ..manifest_versions import MANIFEST_VERSION +from ..mask_scan import MASK_REPORT_FILENAME +from .description_run import manifest_entry +from .modes import FULL +from .preflight import Preflight +from .recorded import usable +from .state import RunState +from .steps import Rows + + +def write_generation( + run: RunState, + rows: Rows, + settings: RunSettings, + records: list, + checks: tuple[dict | None, IntensityReport, ChannelIdentityReport], + staged: Path, +) -> str: + """Write the table, design and manifest into the publication folder. + + ``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). + """ + pre, design, ids = run.pre, run.checked.design, run.checked.channel_ids + masks, intensity, identity = checks + described = run.description + per_file = Counter(record.source_relative_path for record in records) + csv_path = write_plane_histograms(records, staged / OUTPUT_FILENAME, channel_ids=ids) + qc_sha256 = 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)) + manifest = RunManifest( + experiment_root=pre.discovery.root.as_posix(), + 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()) + ), + csv_sha256=file_sha256(csv_path), + versions=package_versions(), + written_at=datetime.now(UTC).isoformat(timespec="seconds"), + experiment_design_sha256=design_sha256, + masks=masks, + image_type=run.inputs.image_type, + channels_from_rgb_samples=run.checked.type_review.channels_from_rgb_samples, + intensity_checks=intensity.settings, + channel_identity=identity.settings, + narrow_ranges=tuple(rows.narrow), + calibration_sha256=pre.calibration.sha256, + conversion_record_sha256=None if pre.conversion is None else pre.conversion.sha256, + 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), + manifest_version=MANIFEST_VERSION, + ) + manifest = _kept_time(manifest, run.previous[0]) + return file_sha256(write_manifest(manifest, staged / MANIFEST_FILENAME)) + + +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 + return None if found is None else found.to_dict() + + +def _kept_time(manifest: RunManifest, earlier: RunManifest | None) -> RunManifest: + """Return the manifest with the earlier run's ``written_at`` when nothing else changed. + + Later bricks pin the manifest's SHA-256 (CellPatcher, MorphoFeature): a rerun that + changes nothing must leave its bytes as they were (cross-brick test F10). The report + still records the rerun. + """ + if earlier is None: + return manifest + 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]: + """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. + """ + names = [ + OUTPUT_FILENAME, + IMAGE_QC_FILENAME, + MANIFEST_FILENAME, + REPORT_FILENAME, + REPORT_TEXT_FILENAME, + ] + if run.checked.design is not None: + names.append(DESIGN_FILENAME) + replaced = {name: "replaced" for name in names if name in run.found} + if MASK_REPORT_FILENAME in run.found: + before = usable(run.previous[0]) + if run.mode == FULL: + replaced[MASK_REPORT_FILENAME] = "removed: a full run recomputes every check" + elif before is None or before.masks != masks: + replaced[MASK_REPORT_FILENAME] = "removed: the masks changed since it was written" + return replaced diff --git a/src/morphobricks_preprocessing/run/pipeline.py b/src/morphobricks_preprocessing/run/pipeline.py index 902d0a7b..b92630fa 100644 --- a/src/morphobricks_preprocessing/run/pipeline.py +++ b/src/morphobricks_preprocessing/run/pipeline.py @@ -11,42 +11,29 @@ import logging import os -from collections import Counter from collections.abc import Callable, Iterable, Mapping -from dataclasses import dataclass, field, replace -from datetime import UTC, datetime +from dataclasses import replace from functools import partial from pathlib import Path from typing import Literal from morphobricks_normalization.checks import IntensityCheckSettings -from morphobricks_normalization.csv_io import OUTPUT_FILENAME, write_plane_histograms from morphobricks_normalization.ranges import HistogramSettings from ..axes import AxisMapping from ..axis_check import ConfirmedAxes from ..channel_identity import ChannelIdentityReport, check_channel_identity -from ..design import DESIGN_FILENAME, write_experiment_design from ..discovery import check_output_folder, default_output_folder from ..discovery_report import ( - REPORT_FILENAME, - REPORT_TEXT_FILENAME, WRITTEN, DiscoveryReport, RunOutcome, build_report, ) from ..intensity import IntensityReport, check_intensities -from ..lab_links import LabLinks from ..manifest import ( - MANIFEST_FILENAME, - RunManifest, RunSettings, - file_sha256, - package_versions, - write_manifest, ) -from ..manifest_versions import MANIFEST_VERSION from ..mask_binding import ( changed_masks, content_changed_masks, @@ -62,21 +49,19 @@ from .arguments import check_arguments as _check_arguments from .arguments import masks_argument as _masks_argument from .description_run import ( - RunDescription, load_description, - manifest_entry, run_checks, unit_entries, ) from .generation import staged_generation from .lock import OutputLockedError, lock_issue, output_lock -from .modes import FULL, RESTART, RunMode, run_mode +from .modes import RESTART, RunMode, run_mode from .output_guard import output_masks_issues -from .preflight import Preflight, fit_calibration, preflight +from .outputs import replaced_files, write_generation +from .preflight import fit_calibration, preflight from .publish import write_report from .recorded import ( GivenInputs, - ResolvedInputs, calibration_change, resolve_inputs, usable, @@ -86,7 +71,8 @@ from .reuse import read_previous, recorded_experiment_root from .rows import _pixel_issues, _range_issues, _row_order from .staging import clear_staging -from .steps import Checked, Rows, compute_rows, counts, header_checks, outcome_of, unreadable_issue +from .state import RunOptions, RunState +from .steps import Rows, compute_rows, counts, header_checks, outcome_of, unreadable_issue from .workers import Workers logger = logging.getLogger(__name__) @@ -222,43 +208,13 @@ def run_experiment( # noqa: PLR0913 try: with output_lock(output): reading = Workers(chosen.workers, chosen.max_ram) - options = _Options(mode, memory_limit, progress, chosen.lab_links, reading) + options = RunOptions(mode, memory_limit, progress, chosen.lab_links, reading) return _locked_run(given, output, options) except OutputLockedError as exc: return RunResult(output, False, (lock_issue(exc),), mode=mode) -@dataclass(frozen=True) -class _Options: - """The run's options that are not recorded inputs.""" - - mode: str - memory_limit: int - progress: Callable[[int, int, str], None] | None - lab_links: LabLinks | None = None - workers: Workers = field(default_factory=Workers) - - -@dataclass(frozen=True) -class _Run: - """What one run works with once its header checks are done.""" - - output: Path - pre: Preflight - inputs: ResolvedInputs - mode: str - checked: Checked - previous: tuple[RunManifest | None, str | None] - found: frozenset[str] - """The names in the output folder before the run wrote anything.""" - mask_content: Mapping[str, str | None] = field(default_factory=dict) - """In a ``verify_content`` run, each mask's content SHA-256 taken after the header checks.""" - description: RunDescription | None = None - """The published experiment description the run works with; None when it was refused.""" - lab_links: LabLinks | None = None - - -def _locked_run(given: GivenInputs, output: Path, options: _Options) -> RunResult: +def _locked_run(given: GivenInputs, output: Path, options: RunOptions) -> RunResult: """Run every step while holding the output folder's lock.""" found = frozenset(path.name for path in output.iterdir()) previous = read_previous(output) @@ -282,7 +238,9 @@ def _locked_run(given: GivenInputs, output: Path, options: _Options) -> RunResul checked.issues.extend(absent) calibrated = calibration_change(usable(previous[0]), pre.calibration) inputs = replace(inputs, changes=(*inputs.changes, *calibrated)) - run = _Run(output, pre, inputs, options.mode, checked, previous, found, {}, described, links) + run = RunState( + output, pre, inputs, options.mode, checked, previous, found, {}, described, links + ) recorded = usable(previous[0]) base = RunOutcome( step="run", @@ -330,7 +288,7 @@ def _read_issues(rows: Rows, settings: RunSettings) -> list[ValidationIssue]: return issues -def _with_mask_content(run: _Run) -> _Run: +def _with_mask_content(run: RunState) -> RunState: """Return the run with each mask's content SHA-256 (``verify_content``, issue #160). Taken once the header checks pass, of the masks as fingerprinted with their headers: a @@ -346,7 +304,7 @@ def _with_mask_content(run: _Run) -> _Run: return run -def _report(run: _Run, outcome: RunOutcome, checks: _Checks | None = None) -> DiscoveryReport: +def _report(run: RunState, outcome: RunOutcome, checks: _Checks | None = None) -> DiscoveryReport: """Build the run's report, with the intensity and channel checks once the table is checked.""" found = [] if checks is not None: @@ -368,7 +326,7 @@ def _as_warning(issue: object) -> ValidationIssue: return warning(issue.code, issue.message, issue.items, issue.action) -def _stop(run: _Run, base: RunOutcome, rows: Rows | None) -> RunResult: +def _stop(run: RunState, base: RunOutcome, rows: Rows | None) -> RunResult: """Write the stopped run's report and return its result; no scientific output is published.""" write_report(_report(run, outcome_of(rows, base)), run.output) return RunResult( @@ -383,7 +341,7 @@ def _stop(run: _Run, base: RunOutcome, rows: Rows | None) -> RunResult: ) -def _publish(run: _Run, base: RunOutcome, rows: Rows, settings: RunSettings) -> RunResult: +def _publish(run: RunState, base: RunOutcome, rows: Rows, settings: RunSettings) -> RunResult: """Publish the table, design, manifest and report as one generation; return the result. Every image is fingerprinted again just before the commit (issue #90), and in a strict @@ -397,12 +355,12 @@ def _publish(run: _Run, base: RunOutcome, rows: Rows, settings: RunSettings) -> 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(run, masks)) + outcome = replace(outcome_of(rows, base), replaced=replaced_files(run, masks)) removes = [name for name in (MASK_REPORT_FILENAME,) if name in outcome.replaced] final_check = _final_content_check(run, rows, settings) try: with staged_generation(output, removes, final_check) as staged: - sha256 = _write_generation( + sha256 = write_generation( run, rows, settings, records, (masks, intensity, identity), staged ) changed = changed_since(rows.entries, pre.discovery.root) @@ -443,7 +401,9 @@ def _publish(run: _Run, base: RunOutcome, rows: Rows, settings: RunSettings) -> ) -def _final_content_check(run: _Run, rows: Rows, settings: RunSettings) -> Callable[[], None] | None: +def _final_content_check( + run: RunState, rows: Rows, settings: RunSettings +) -> Callable[[], None] | None: """Return a run's last check before its commit, or None when there is nothing to check. Every run fingerprints each mask once more after its generation is staged, right before @@ -491,94 +451,6 @@ def __init__( self.masks = masks -def _write_generation( - run: _Run, - rows: Rows, - settings: RunSettings, - records: list, - checks: tuple[dict | None, IntensityReport, ChannelIdentityReport], - staged: Path, -) -> str: - """Write the table, design and manifest into the publication folder. - - ``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). - """ - pre, design, ids = run.pre, run.checked.design, run.checked.channel_ids - masks, intensity, identity = checks - described = run.description - per_file = Counter(record.source_relative_path for record in records) - csv_path = write_plane_histograms(records, staged / OUTPUT_FILENAME, channel_ids=ids) - design_sha256 = None - if design is not None: - design_sha256 = file_sha256(write_experiment_design(design, staged / DESIGN_FILENAME)) - manifest = RunManifest( - experiment_root=pre.discovery.root.as_posix(), - 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()) - ), - csv_sha256=file_sha256(csv_path), - versions=package_versions(), - written_at=datetime.now(UTC).isoformat(timespec="seconds"), - experiment_design_sha256=design_sha256, - masks=masks, - image_type=run.inputs.image_type, - channels_from_rgb_samples=run.checked.type_review.channels_from_rgb_samples, - intensity_checks=intensity.settings, - channel_identity=identity.settings, - narrow_ranges=tuple(rows.narrow), - calibration_sha256=pre.calibration.sha256, - conversion_record_sha256=None if pre.conversion is None else pre.conversion.sha256, - 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(), - manifest_version=MANIFEST_VERSION, - ) - manifest = _kept_time(manifest, run.previous[0]) - return file_sha256(write_manifest(manifest, staged / MANIFEST_FILENAME)) - - -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 - return None if found is None else found.to_dict() - - -def _kept_time(manifest: RunManifest, earlier: RunManifest | None) -> RunManifest: - """Return the manifest with the earlier run's ``written_at`` when nothing else changed. - - Later bricks pin the manifest's SHA-256 (CellPatcher, MorphoFeature): a rerun that - changes nothing must leave its bytes as they were (cross-brick test F10). The report - still records the rerun. - """ - if earlier is None: - return manifest - same = replace(manifest, written_at=earlier.written_at) - return same if same.to_dict() == earlier.to_dict() else manifest - - -def _replaced(run: _Run, masks: dict | None) -> 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. - """ - names = [OUTPUT_FILENAME, MANIFEST_FILENAME, REPORT_FILENAME, REPORT_TEXT_FILENAME] - if run.checked.design is not None: - names.append(DESIGN_FILENAME) - replaced = {name: "replaced" for name in names if name in run.found} - if MASK_REPORT_FILENAME in run.found: - before = usable(run.previous[0]) - if run.mode == FULL: - replaced[MASK_REPORT_FILENAME] = "removed: a full run recomputes every check" - elif before is None or before.masks != masks: - replaced[MASK_REPORT_FILENAME] = "removed: the masks changed since it was written" - return replaced - - def _folders( experiment_root: str | os.PathLike | None, output_folder: str | os.PathLike | None ) -> tuple[Path, Path]: diff --git a/src/morphobricks_preprocessing/run/resume.py b/src/morphobricks_preprocessing/run/resume.py index 4b626f49..d1ab2222 100644 --- a/src/morphobricks_preprocessing/run/resume.py +++ b/src/morphobricks_preprocessing/run/resume.py @@ -28,6 +28,7 @@ from ..axes import AxisReview from ..fingerprint import Fingerprint, RowKey, current_fingerprint +from ..image_qc_table import QcRow from ..manifest import FileEntry, NarrowRange, RunSettings from ..planes import PlaneReadError from ..source_content import current_content @@ -50,6 +51,8 @@ class NewRows: ---------- records, narrow Their rows and narrow-range checks. + qc + The image QC rows of their channel planes (contract §19). read The files whose pixels were read. resumed @@ -73,6 +76,7 @@ class NewRows: records: list[PlaneRecord] = field(default_factory=list) narrow: list[NarrowRange] = field(default_factory=list) + qc: list[QcRow] = field(default_factory=list) read: list[str] = field(default_factory=list) resumed: list[str] = field(default_factory=list) failed: list[str] = field(default_factory=list) @@ -202,6 +206,7 @@ def _resumed(job: FileJob, rel: str, key: dict, earlier: StagedFile | None, foun if not job.full and earlier.key == key and unchanged: found.records.extend(earlier.records) found.narrow.extend(earlier.narrow) + found.qc.extend(earlier.qc) found.resumed.append(rel) return True found.discarded[rel] = _why_discarded(earlier.key, key, job.full, unchanged) @@ -248,7 +253,9 @@ def _read_in_workers( for future in as_completed(futures): result = future.result() # a worker's exception is raised here, in this thread if result.status == READ: - stage_file(job.output, keys[result.relative_path], result.rows, result.ranges) + stage_file( + job.output, keys[result.relative_path], result.rows, result.ranges, result.qc + ) results[result.relative_path] = result if progress is not None: progress(done, total, result.relative_path) @@ -274,8 +281,8 @@ class FileRead: status ``"read"``, ``"failed"`` (its pixels could not be read) or ``"changed"`` (it changed while it was read: never staged or published). - rows, ranges - Its rows and narrow-range checks; empty unless read. + rows, ranges, qc + Its rows, narrow-range checks and image QC rows; empty unless read. failures When failed: each plane and channel that could not be measured, with the cause, or the file and the cause when it could not be read plane by plane. @@ -286,6 +293,7 @@ class FileRead: rows: tuple[PlaneRecord, ...] = () ranges: tuple[NarrowRange, ...] = () failures: tuple[str, ...] = () + qc: tuple[QcRow, ...] = () def _read_checked(job: FileJob, rel: str) -> FileRead: @@ -309,7 +317,7 @@ def _read_between_fingerprints(job: FileJob, rel: str) -> FileRead: expected = Fingerprint.recorded(job.entries[rel]) labels = job.entries[rel].labels try: - rows, ranges = _read_file( + rows, ranges, qc = _read_file( root / rel, rel, labels, @@ -329,13 +337,13 @@ def _read_between_fingerprints(job: FileJob, rel: str) -> FileRead: and current_content(root / rel) != job.entries[rel].content_sha256 ): return FileRead(rel, CHANGED) - return FileRead(rel, READ, tuple(rows), tuple(ranges)) + return FileRead(rel, READ, tuple(rows), tuple(ranges), qc=tuple(qc)) def _take(job: FileJob, key: dict, result: FileRead, found: NewRows) -> None: """Stage a file's rows when it was read, and add what happened to ``found``.""" if result.status == READ: - stage_file(job.output, key, list(result.rows), list(result.ranges)) + stage_file(job.output, key, result.rows, result.ranges, result.qc) _add(result, found) @@ -350,6 +358,7 @@ def _add(result: FileRead, found: NewRows) -> None: else: found.records.extend(result.rows) found.narrow.extend(result.ranges) + found.qc.extend(result.qc) found.read.append(rel) @@ -398,6 +407,9 @@ def _why_discarded(staged: dict, now: dict, full: bool, unchanged: bool) -> str: return "its rows were staged by another version" if staged.get("dtype") != now["dtype"]: return "the experiment's pixel type changed since its rows were staged" + limits = (staged.get("row_key", {}).get("block_limit"), now["row_key"].get("block_limit")) + if limits[0] != limits[1]: + return "its planes' block layout (the memory limit) changed since its rows were staged" return "its axis roles, labels, folder or row settings changed since its rows were staged" diff --git a/src/morphobricks_preprocessing/run/reuse.py b/src/morphobricks_preprocessing/run/reuse.py index 866ed47b..9905bf9a 100644 --- a/src/morphobricks_preprocessing/run/reuse.py +++ b/src/morphobricks_preprocessing/run/reuse.py @@ -20,6 +20,8 @@ from ..axes import ( AxisMapping, ) +from ..image_qc_record import IMAGE_QC_FILENAME, same_metrics +from ..image_qc_table import ImageQcFormatError, QcRow, read_image_qc from ..manifest import ( MANIFEST_FILENAME, ManifestFormatError, @@ -28,6 +30,7 @@ file_sha256, read_manifest, ) +from ..planes import format_bytes from ..validation import ValidationIssue, error from .modes import FULL @@ -100,10 +103,12 @@ def _load_previous( mapping: AxisMapping, dtype: str, mode: str, + blocks_now: bool = False, ) -> tuple[dict[str, list[PlaneRecord]], str | None]: """Load the earlier run's rows by file, and say why they cannot be reused. ``previous`` is :func:`read_previous`'s answer. In ``full`` mode no row is reused. + ``blocks_now``: whether this run reads any plane in blocks (see :func:`_settings_changed`). """ manifest, missing = previous csv_path = output / OUTPUT_FILENAME @@ -115,7 +120,8 @@ def _load_previous( return {}, "the earlier table uses a different format version" if manifest.dtype != dtype: return {}, f"the pixel type changed from {manifest.dtype} to {dtype}" - changed = _settings_changed(manifest.settings, settings) + blocked = blocks_now or any(f.read_in_blocks for f in manifest.files) + changed = _settings_changed(manifest.settings, settings, blocked) if changed is not None: return {}, changed if (manifest.mapping.axes, manifest.mapping.roles) != (mapping.axes, mapping.roles): @@ -133,11 +139,51 @@ def _load_previous( return by_file, None -def _settings_changed(before: RunSettings, now: RunSettings) -> str | None: +def _load_previous_qc( + output: Path, manifest: RunManifest, earlier: dict[str, list[PlaneRecord]] +) -> tuple[dict[str, list[QcRow]], str | None]: + """Load the earlier run's image QC rows by file, and say why they cannot be reused. + + They follow the histogram table's reuse rule (contract §19): the earlier rows are reused + only with the image QC table the manifest names (its SHA-256), measured by the same + metric definitions (version and settings), and holding one row for each channel of each + earlier histogram row, with that row's full identity (position, image, Z, T, labels, path, + plane ID and channel, not only plane ID and channel); otherwise every row is recomputed, + with the reason. + """ + entry, path = manifest.image_qc, output / IMAGE_QC_FILENAME + if entry is None: + return {}, "the earlier run has no image QC table (image_qc.csv)" + if not same_metrics(entry): + return {}, "the image QC metrics changed since the earlier run" + if not path.exists() or file_sha256(path) != entry["sha256"]: + return {}, "the image QC table was changed or replaced after the earlier run" + try: + rows = read_image_qc(path) + except ImageQcFormatError: + logger.warning("Cannot read %s", path, exc_info=True) + return {}, "the earlier image QC table could not be read" + expected = [ + QcRow.identity_of(r, c) for records in earlier.values() for r in records for c in r.channels + ] + if sorted(row.identity for row in rows) != sorted(expected): + return {}, "the earlier image QC table does not match the histogram table" + by_file: dict[str, list[QcRow]] = {} + for row in rows: + by_file.setdefault(row.relative_path, []).append(row) + return by_file, None + + +def _settings_changed(before: RunSettings, now: RunSettings, blocked: bool = False) -> str | None: """Say which setting that changes every row (or how rows are reused) changed, or None. Turning content verification on or off recomputes every row: rows recorded without a content SHA-256 cannot be verified, and reuse never changes its rule silently. + + The memory limit changes no histogram row, but it sets the blocks a plane is read in, and + the neighbour metrics of the image QC table leave out the pairs across a block edge + (contract §19): another limit recomputes every row when ``blocked`` (the earlier run or + this one reads a plane in blocks). With only whole planes on both sides it changes no row. """ if before.bin_count != now.bin_count: return f"the bin count changed from {before.bin_count:,} to {now.bin_count:,}" @@ -149,6 +195,12 @@ def _settings_changed(before: RunSettings, now: RunSettings) -> str | None: if before.verify_content != now.verify_content: state = "turned on" if now.verify_content else "turned off" return f"content verification (verify_content) was {state}" + if blocked and before.memory_limit != now.memory_limit: + return ( + f"the memory limit changed from {format_bytes(before.memory_limit)} to " + f"{format_bytes(now.memory_limit)} (the image QC metrics of planes read in blocks " + "depend on the block layout)" + ) return None diff --git a/src/morphobricks_preprocessing/run/rows.py b/src/morphobricks_preprocessing/run/rows.py index 8de267e3..495c8532 100644 --- a/src/morphobricks_preprocessing/run/rows.py +++ b/src/morphobricks_preprocessing/run/rows.py @@ -5,22 +5,28 @@ from __future__ import annotations +from collections.abc import Iterator from dataclasses import dataclass from pathlib import Path +import numpy as np from morphobricks_normalization.dtypes import default_bin_count, validate_bin_count -from morphobricks_normalization.ranges import range_check_issues +from morphobricks_normalization.histogram import PlaneHistogram, histogram_with_range_check +from morphobricks_normalization.ranges import RangeCheck, range_check_issues from morphobricks_normalization.records import PlaneRecord from ..axes import ( AxisMapping, ) +from ..image_qc import ImageQc, PlaneQc +from ..image_qc_table import QcRow from ..manifest import ( NarrowRange, RunSettings, ) from ..plane_errors import PlaneReadError from ..planes import ( + Plane, iter_xyc_planes, ) from ..validation import ValidationIssue, error, plural, warning @@ -71,18 +77,19 @@ def _read_file( settings: RunSettings, position: str, channels: tuple[str, ...], -) -> tuple[list[PlaneRecord], list[NarrowRange]]: +) -> tuple[list[PlaneRecord], list[NarrowRange], list[QcRow]]: """Histogram every XYC plane of ``path``, recording the rows under the source ``rel``. One row per plane holds the histograms of all its channels (schema version 5), named by ``channels``, the canonical IDs of its unit's confirmed list (entry ``i`` is source channel ``C``), binned with the run's histogram range. Also returns the channel planes - whose range check found the central range too narrow, by channel ID. + whose range check found the central range too narrow, by channel ID, and the image QC + row of every channel plane, measured in the same pass (contract §19). A channel that cannot be measured fails the image (Spec ADR 0003 HV3); the other planes are measured still, so that :class:`ChannelReadError` names every failed one. """ - records, narrow, failed = [], [], [] + records, narrow, failed, qc = [], [], [], [] for plane in iter_xyc_planes( path, mapping, @@ -90,12 +97,12 @@ def _read_file( bin_count=settings.bin_count, histogram_settings=settings.histogram, ): - measured = [] + measured, in_blocks = [], [] for c in range(plane.channel_count): try: - measured.append( - plane.channel(c).histogram_with_check(settings.bin_count, settings.histogram) - ) + channel_plane = plane.channel(c) + in_blocks.append(channel_plane.in_blocks) + measured.append(_measure(channel_plane, settings)) except PlaneReadError as exc: # Measure on, so that the error names every failed plane (HV3); none of # this image's rows is used. @@ -106,7 +113,7 @@ def _read_file( record = PlaneRecord( rel, *labels, - histograms=tuple(histogram for histogram, _ in measured), + histograms=tuple(histogram for histogram, _, _ in measured), z=plane.z, t=plane.t, position_id=position, @@ -115,12 +122,42 @@ def _read_file( records.append(record) narrow.extend( NarrowRange(rel, record.plane_id, channel, check) - for channel, (_, check) in zip(channels, measured, strict=True) + for channel, (_, check, _) in zip(channels, measured, strict=True) if check is not None and check.narrow ) + qc.extend( + QcRow.of(record, channel, blocks, found) + for channel, blocks, (_, _, found) in zip(channels, in_blocks, measured, strict=True) + ) if failed: raise ChannelReadError(tuple(failed)) - return records, narrow + return records, narrow, qc + + +def _measure( + plane: Plane, settings: RunSettings +) -> tuple[PlaneHistogram, RangeCheck | None, ImageQc]: + """Return a channel plane's histogram, range check and QC metrics, from the same reads. + + The QC sums are taken from the blocks of the histogram's first pass over the plane, so + no pixel is read again for them (contract §19). + """ + qc = PlaneQc(plane.shape, plane.dtype) + passes = [] + + def blocks() -> Iterator[np.ndarray]: + """Yield the plane's blocks; the first pass also adds them to the QC sums.""" + tap = not passes + passes.append(tap) + for block in plane.blocks(): + if tap: + qc.add(block.y, block.x, block.pixels) + yield block.pixels + + histogram, check = histogram_with_range_check( + blocks, plane.dtype, settings.bin_count, settings=settings.histogram + ) + return histogram, check, qc.finish(histogram) def _bin_count(dtype, bin_count: int | None) -> tuple[int | None, list[ValidationIssue]]: # noqa: ANN001 diff --git a/src/morphobricks_preprocessing/run/staging.py b/src/morphobricks_preprocessing/run/staging.py index 7d7e6345..9e486e29 100644 --- a/src/morphobricks_preprocessing/run/staging.py +++ b/src/morphobricks_preprocessing/run/staging.py @@ -3,11 +3,13 @@ As soon as a run has read one file, its rows are staged in the output folder's staging folder ``.staging``: the rows as a small ``plane_histograms.csv`` written with the normalization brick's writer (the same writer and reader as the table, so a resumed row is -the row the run would compute), then a JSON record naming the file, its row key +the row the run would compute) and its image QC rows as a small ``image_qc.csv`` (contract +§19), then a JSON record naming the file, its row key (:class:`.fingerprint.RowKey`: fingerprint, labels, axes, roles, ``axes_from``, read path, bins and histogram settings, and in a ``verify_content`` run the content SHA-256), the pixel type, the table's schema version, the versions of the two packages that compute -rows, the planes whose range check failed, and the SHA-256 of the rows file. The record is +rows and the version of the QC metrics, the planes whose range check failed, and the SHA-256 +of the two rows files. The record is written last, so a staged entry without one is incomplete and never used. The next run (after a crash, a kill or a lost Colab session) reuses a staged file's rows @@ -23,6 +25,7 @@ import json import logging import shutil +from collections.abc import Sequence from dataclasses import asdict, dataclass from functools import lru_cache from pathlib import Path @@ -37,13 +40,16 @@ from .._io import write_text_atomic from ..fingerprint import RowKey +from ..image_qc import QC_VERSION +from ..image_qc_table import QcRow, read_image_qc, write_image_qc from ..manifest import NarrowRange, file_sha256, package_versions logger = logging.getLogger(__name__) STAGING_FOLDER = ".staging" """The staging folder in the output folder (removed once a run publishes).""" -STAGING_VERSION = "1" +STAGING_VERSION = "2" +"""Version 2 adds the image QC rows; a version 1 record is discarded (rows read again).""" _ROW_PACKAGES = ("morphobricks-preprocessing", "morphobricks-normalization") """The packages whose versions a staged file's rows depend on.""" @@ -62,12 +68,15 @@ class StagedFile: Its rows, one per XYC plane. narrow Its channel planes whose range check found the central range too narrow. + qc + Its image QC rows (contract §19). """ relative_path: str key: dict records: tuple[PlaneRecord, ...] narrow: tuple[NarrowRange, ...] + qc: tuple[QcRow, ...] = () def staging_key(key: RowKey, dtype: str) -> dict: @@ -84,16 +93,18 @@ def staging_key(key: RowKey, dtype: str) -> dict: ------- dict The row key (with the content SHA-256 only in a ``verify_content`` run), the pixel - type, the table's schema version and the versions of the packages that compute - rows, normalised through JSON so it compares with a record. + type, the table's schema version, the version of the QC metrics and the versions of + the packages that compute rows, normalised through JSON so it compares with a record. """ row = asdict(key) - if row["content_sha256"] is None: # not a verify_content run: the key as before - del row["content_sha256"] + for name in ("content_sha256", "block_limit"): + if row[name] is None: # not a verify_content run, or read whole: the key as before + del row[name] data = { "row_key": row, "dtype": dtype, "schema_version": SCHEMA_VERSION, + "qc_version": QC_VERSION, "versions": dict(_row_versions()), } return json.loads(json.dumps(data, sort_keys=True)) @@ -102,10 +113,11 @@ def staging_key(key: RowKey, dtype: str) -> dict: def stage_file( output: Path, key: dict, - records: list[PlaneRecord], - narrow: list[NarrowRange], + records: Sequence[PlaneRecord], + narrow: Sequence[NarrowRange], + qc: Sequence[QcRow], ) -> None: - """Stage one file's rows: its rows file first, then the record naming them. + """Stage one file's rows: its rows files first, then the record naming them. Parameters ---------- @@ -113,8 +125,8 @@ def stage_file( The output folder (its lock held). key :func:`staging_key` of the file as it was read. - records, narrow - Its rows and its narrow-range checks. + records, narrow, qc + Its rows, its narrow-range checks and its image QC rows. """ folder = output / STAGING_FOLDER folder.mkdir(exist_ok=True) @@ -122,12 +134,14 @@ def stage_file( stem = _stem(relative) # The file's own channel IDs: a staged file is read back on its own, never merged as bytes. ids = sorted({channel for record in records for channel in record.channels}) - rows = write_plane_histograms(records, folder / f"{stem}.csv", channel_ids=ids) + rows = write_plane_histograms(list(records), folder / f"{stem}.csv", channel_ids=ids) + qc_rows = write_image_qc(qc, folder / f"{stem}.qc.csv") record = { "staging_version": STAGING_VERSION, "relative_path": relative, "key": key, "rows_sha256": file_sha256(rows), + "qc_sha256": file_sha256(qc_rows), "narrow_histogram_ranges": [entry.to_dict() for entry in narrow], } write_text_atomic(folder / f"{stem}.json", json.dumps(record, sort_keys=True) + "\n") @@ -166,8 +180,9 @@ def load_staged(output: Path) -> tuple[dict[str, StagedFile], dict[str, str]]: staged[found.relative_path] = found named = {_stem(rel) for rel in staged} for rows in folder.glob("*.csv"): - if rows.stem not in named: - _remove(rows.with_suffix(".json")) + stem = rows.name.split(".", 1)[0] # .csv and .qc.csv + if stem not in named: + _remove(folder / f"{stem}.json") return staged, discarded @@ -184,6 +199,7 @@ def discard_staged(output: Path, relative_path: str) -> None: stem = output / STAGING_FOLDER / _stem(relative_path) stem.with_suffix(".json").unlink(missing_ok=True) stem.with_suffix(".csv").unlink(missing_ok=True) + stem.with_suffix(".qc.csv").unlink(missing_ok=True) def clear_staging(output: Path) -> None: @@ -223,8 +239,15 @@ def _read_staged(path: Path) -> StagedFile: records = tuple(read_plane_histograms(rows)) if not records or any(r.source_relative_path != relative for r in records): raise ValueError("its rows are not the file's") + qc_rows = path.with_suffix(".qc.csv") + if file_sha256(qc_rows) != data["qc_sha256"]: + raise ValueError("its image QC rows file is not the one it names") + qc = tuple(read_image_qc(qc_rows)) + keys = {(r.plane_id, channel) for r in records for channel in r.channels} + if sorted(row.key for row in qc) != sorted(keys): + raise ValueError("its image QC rows are not its rows'") narrow = tuple(NarrowRange.from_dict(e) for e in data["narrow_histogram_ranges"]) - return StagedFile(relative, dict(data["key"]), records, narrow) + return StagedFile(relative, dict(data["key"]), records, narrow, qc) def _staged_name(record: Path) -> str: @@ -242,6 +265,7 @@ def _remove(record: Path) -> None: """Remove a staged record and its rows file.""" record.unlink(missing_ok=True) record.with_suffix(".csv").unlink(missing_ok=True) + record.with_suffix(".qc.csv").unlink(missing_ok=True) def _stem(relative_path: str) -> str: diff --git a/src/morphobricks_preprocessing/run/state.py b/src/morphobricks_preprocessing/run/state.py new file mode 100644 index 00000000..ce6fdbab --- /dev/null +++ b/src/morphobricks_preprocessing/run/state.py @@ -0,0 +1,49 @@ +"""What one run works with: its options and, once its header checks are done, its state. + +Moved from :mod:`.pipeline`, which holds the run's steps; :mod:`.outputs` writes what the state +describes. +""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +from dataclasses import dataclass, field +from pathlib import Path + +from ..lab_links import LabLinks +from ..manifest import RunManifest +from .description_run import RunDescription +from .preflight import Preflight +from .recorded import ResolvedInputs +from .steps import Checked +from .workers import Workers + + +@dataclass(frozen=True) +class RunOptions: + """The run's options that are not recorded inputs.""" + + mode: str + memory_limit: int + progress: Callable[[int, int, str], None] | None + lab_links: LabLinks | None = None + workers: Workers = field(default_factory=Workers) + + +@dataclass(frozen=True) +class RunState: + """What one run works with once its header checks are done.""" + + output: Path + pre: Preflight + inputs: ResolvedInputs + mode: str + checked: Checked + previous: tuple[RunManifest | None, str | None] + found: frozenset[str] + """The names in the output folder before the run wrote anything.""" + mask_content: Mapping[str, str | None] = field(default_factory=dict) + """In a ``verify_content`` run, each mask's content SHA-256 taken after the header checks.""" + description: RunDescription | None = None + """The published experiment description the run works with; None when it was refused.""" + lab_links: LabLinks | None = None diff --git a/src/morphobricks_preprocessing/run/steps.py b/src/morphobricks_preprocessing/run/steps.py index 74957a1f..4cbef558 100644 --- a/src/morphobricks_preprocessing/run/steps.py +++ b/src/morphobricks_preprocessing/run/steps.py @@ -20,6 +20,7 @@ from ..design import DesignTable, design_issues, reconcile_design from ..discovery_report import RunOutcome from ..fingerprint import unchanged_confirmation +from ..image_qc_table import QcRow from ..image_type import ImageTypeReview, image_type_issues, review_image_type from ..manifest import FileEntry, NarrowRange, RunManifest, RunSettings from ..mask_checks import mask_issues @@ -31,7 +32,7 @@ from .preflight import Preflight from .recorded import ResolvedInputs from .resume import FileJob, changed_during_check, new_rows -from .reuse import _load_previous +from .reuse import _load_previous, _load_previous_qc from .rows import _bin_count from .workers import Workers @@ -174,6 +175,8 @@ class Rows: ---------- records, narrow The table's rows and the channel planes whose range check failed. + qc + The image QC row of every channel of every row (contract §19). found The files compared with the earlier run's. read @@ -212,6 +215,7 @@ class Rows: discarded: Mapping[str, str] = field(default_factory=dict) workers: int = 1 refused: ValidationIssue | None = None + qc: list[QcRow] = field(default_factory=list) def compute_rows( @@ -251,16 +255,23 @@ def compute_rows( """ review, root = checked.review, pre.discovery.root dtype = pre.metadata.dtype.name - earlier, reason = _load_previous(output, previous, settings, review.mapping, dtype, mode) in_blocks = {p for i in checked.issues if i.code == "planes_read_in_blocks" for p in i.paths} + earlier, reason = _load_previous( + output, previous, settings, review.mapping, dtype, mode, bool(in_blocks) + ) + earlier_qc: dict[str, list[QcRow]] = {} + if reason is None: # the image QC table follows the histogram table's reuse rule + earlier_qc, reason = _load_previous_qc(output, previous[0], earlier) entries = file_entries(pre, review, root, in_blocks, checked.channels) # Strict reuse: each image's content SHA-256 joins its row key; an unreadable one fails. entries, unhashed = with_content(entries, root) if settings.verify_content else (entries, []) found = compare_with_previous(entries, previous[0], earlier, reason is not None, settings, root) records: list[PlaneRecord] = [] narrow: list[NarrowRange] = [] + qc: list[QcRow] = [] for rel in found.unchanged if not reason else (): records.extend(earlier[rel]) + qc.extend(earlier_qc.get(rel, ())) # Kept rows keep the range checks they were written with. narrow.extend(entry for entry in previous[0].narrow_ranges if entry.relative_path == rel) job = FileJob(pre, review, settings, entries, output, mode == FULL) @@ -289,6 +300,7 @@ def compute_rows( discarded=dict(sorted(new.discarded.items())), workers=new.workers, refused=new.refused, + qc=[*qc, *new.qc], ) diff --git a/src/morphobricks_preprocessing/window_tiff.py b/src/morphobricks_preprocessing/window_tiff.py index 943f3ff4..5ad62a7a 100644 --- a/src/morphobricks_preprocessing/window_tiff.py +++ b/src/morphobricks_preprocessing/window_tiff.py @@ -18,10 +18,10 @@ from . import window_memory from .axes import AxisMapping from .codec_bounds import check_tiff_codec +from .plane_binning import Binning from .planes import ( PlaneLayout, PlaneReadError, - _Binning, _largest_piece, _layout, _page_index, @@ -112,7 +112,7 @@ def _tiff_layout( memory_limit: int, ) -> PlaneLayout: """Return a TIFF series' layout with how its pages are stored, or refuse it.""" - layout = _layout(series, mapping, path, _Binning(histogram=False), memory_limit) + layout = _layout(series, mapping, path, Binning(histogram=False), memory_limit) # Only codecs with a measured bound are read in windows, refused before any pixel (#356). check_tiff_codec([series.keyframe], path, "in windows", WindowCompressionError) y, x = mapping.index_of("Y"), mapping.index_of("X") diff --git a/src/morphobricks_preprocessing/windows.py b/src/morphobricks_preprocessing/windows.py index 38c5241e..2909473f 100644 --- a/src/morphobricks_preprocessing/windows.py +++ b/src/morphobricks_preprocessing/windows.py @@ -55,11 +55,11 @@ from . import window_memory from .axes import AxisMapping +from .plane_binning import Binning from .planes import ( DEFAULT_MEMORY_LIMIT, PlaneLayout, PlaneMemoryError, - _Binning, _Blocking, _open, _open_zarr, @@ -355,7 +355,7 @@ def _zarr_source( With ``cached``, the window is read chunk by chunk, each chunk from the cache. """ - layout = _zarr_layout(image, mapping, path, _Binning(histogram=False), memory_limit) + layout = _zarr_layout(image, mapping, path, Binning(histogram=False), memory_limit) y, x = mapping.index_of("Y"), mapping.index_of("X") rows, cols = sorted((y, x)) blocking = _Blocking( diff --git a/tests/memory_limits.py b/tests/memory_limits.py new file mode 100644 index 00000000..bc7a5884 --- /dev/null +++ b/tests/memory_limits.py @@ -0,0 +1,15 @@ +"""Memory limits for tests that read a large plane in blocks beside a small plane read whole.""" + +from morphobricks_preprocessing.image_qc import qc_memory + +__all__ = ["block_limit", "qc_memory"] + + +def block_limit(small_estimate: int, small_shape: tuple[int, int], cols: int) -> int: + """Return the limit that fits the small plane whole and one row of ``cols`` pixels in blocks. + + The small plane's whole estimate, with the QC working memory of its (Y, X) shape swapped + for that of the one-row block (the histogram and pixel terms of both are those of the same + number of pixels), so the large plane is read in blocks of one row and not refused. + """ + return small_estimate - qc_memory(*small_shape, False) + qc_memory(1, cols, False) diff --git a/tests/qc_tree.py b/tests/qc_tree.py new file mode 100644 index 00000000..985f2e55 --- /dev/null +++ b/tests/qc_tree.py @@ -0,0 +1,61 @@ +"""A small experiment for the image QC tests: three images of two time points and channels.""" + +import hashlib + +import numpy as np + +from described_tree import run_described +from morphobricks_preprocessing import prefill_mapping +from tiff_tree import write_data + +CTYX = prefill_mapping("TCYX") +IMAGES = ["ctrl/r1/a.tif", "ctrl/r1/b.tif", "drug/r1/a.tif"] + + +def stack(seed): + """Two time points of two channels: smooth structure plus noise, never constant.""" + rng = np.random.default_rng(seed) + y, x = np.mgrid[:40, :48] + base = (np.sin(y / (3 + seed)) * np.cos(x / 5) * 60 + 120).astype(np.uint8) + data = np.empty((2, 2, 40, 48), dtype=np.uint8) + for t in range(2): + for c in range(2): + data[t, c] = base // (c + 1) + rng.integers(0, 30, (40, 48), dtype=np.uint8) + return data + + +def make_experiment(tmp_path): + """Write the experiment under ``tmp_path / "exp"`` and return its folder.""" + root = tmp_path / "exp" + for seed, rel in enumerate(IMAGES): + write_data(root / rel, stack(seed), "TCYX") + return root + + +def run(root, out, **kwargs): + result = run_described(root, CTYX, output_folder=out, **kwargs) + assert result.written, [issue.message for issue in result.issues if issue.is_error] + return result + + +def sha256(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def interrupt_at_second_file(monkeypatch): + """Make the run raise ``RuntimeError("stopped")`` when it reads its second image. + + Returns the real reader, to put back (``run.resume._read_file``) before the next run. + """ + from morphobricks_preprocessing import run as run_module + + read, calls = run_module.resume._read_file, [] + + def stop_at_second(*args): + calls.append(args[1]) + if len(calls) == 2: + raise RuntimeError("stopped") + return read(*args) + + monkeypatch.setattr(run_module.resume, "_read_file", stop_at_second) + return read diff --git a/tests/test_codec_bounds.py b/tests/test_codec_bounds.py index bdf83436..87ce6212 100644 --- a/tests/test_codec_bounds.py +++ b/tests/test_codec_bounds.py @@ -233,14 +233,14 @@ def test_the_allowed_codecs_read_bitwise_through_every_bounded_reader(tmp_path, with WindowReader(path, mapping, cache_bytes=2**20) as reader: np.testing.assert_array_equal(reader.read_window(bounds=bounds, channels=[1, 0]), window) np.testing.assert_array_equal(read_xyc_plane(path, mapping), data) - for c, plane in enumerate(iter_planes(path, mapping, memory_limit=2**16)): + for c, plane in enumerate(iter_planes(path, mapping, memory_limit=2**18)): assert plane.in_blocks # each plane read while the file is open whole = np.empty((H, W), dtype=np.uint8) for block in plane.blocks(): rows, cols = block.pixels.shape whole[block.y : block.y + rows, block.x : block.x + cols] = block.pixels np.testing.assert_array_equal(whole, data[c]) - assert [i.code for i in check_planes(tmp_path, {"a.tif": mapping}, memory_limit=2**16)] == [ + assert [i.code for i in check_planes(tmp_path, {"a.tif": mapping}, memory_limit=2**18)] == [ "planes_read_in_blocks" ] diff --git a/tests/test_image_qc.py b/tests/test_image_qc.py new file mode 100644 index 00000000..76c449b4 --- /dev/null +++ b/tests/test_image_qc.py @@ -0,0 +1,377 @@ +"""The image QC metrics of one plane (contract §19): formulas, invariances, blocks. + +Known values are worked out by hand on tiny planes; the synthetic tests check the direction +each metric moves under a known distortion (blur, brightness, emptiness, uneven +illumination), and that a plane read in blocks gives the whole plane's values up to the +documented edge effect. +""" + +import math + +import numpy as np +import pytest +from morphobricks_normalization.histogram import compute_plane_histogram +from scipy.ndimage import gaussian_filter + +from morphobricks_preprocessing.image_qc import ( + MEASURED, + METRICS, + NO_FINITE, + NON_FINITE, + OFFSETS, + PlaneQc, +) +from morphobricks_preprocessing.image_qc_sums import BlockSums, Window, valid_window + +HISTOGRAM_METRICS = ("otsu_threshold", "otsu_separation", "foreground_fraction", "entropy") +SHAPE = ( + "normalized_variance", + "tenengrad", + "laplacian_variance", + "correlation_1", + "correlation_4", + "correlation_16", + "local_focus_median", + "local_focus_p10", + "tile_mean_cv", +) +NEIGHBOUR = ("tenengrad", "laplacian_variance", "correlation_1", "correlation_4", "correlation_16") +"""The metrics of neighbour pairs: a block edge leaves some pairs out.""" + + +def measure(pixels, block=None): + """Measure a plane whole, or in blocks of ``block`` (rows, columns).""" + qc = PlaneQc(pixels.shape, pixels.dtype) + rows, cols = block or pixels.shape + for y in range(0, pixels.shape[0], rows): + for x in range(0, pixels.shape[1], cols): + qc.add(y, x, pixels[y : y + rows, x : x + cols]) + return qc.finish(compute_plane_histogram(pixels)) + + +def cells(seed=0, side=256, count=40, noise=20.0): + """A field of bright round cells on a dark noisy background, as uint16.""" + rng = np.random.default_rng(seed) + y, x = np.mgrid[:side, :side] + image = np.full((side, side), 200.0) + for cy, cx, r in zip( + *rng.integers(8, side - 8, (2, count)), rng.integers(3, 9, count), strict=True + ): + image[(y - cy) ** 2 + (x - cx) ** 2 <= r * r] += 1500.0 + image += rng.normal(0.0, noise, image.shape) + return np.clip(image, 0, 65535).astype(np.uint16) + + +def reference(pixels): + """The pixel metrics computed directly from their definitions (independent code).""" + p = pixels.astype(np.float64) + mean = p.mean() + gx, gy = (p[:, 2:] - p[:, :-2]) / 2, (p[2:] - p[:-2]) / 2 + lap = p[:-2, 1:-1] + p[2:, 1:-1] + p[1:-1, :-2] + p[1:-1, 2:] - 4 * p[1:-1, 1:-1] + found = { + "normalized_variance": p.var() / mean**2, + "tenengrad": ((gx**2).mean() + (gy**2).mean()) / mean**2, + "laplacian_variance": lap.var() / mean**2, + } + for k in (1, 4, 16): + cx = np.corrcoef(p[:, :-k].ravel(), p[:, k:].ravel())[0, 1] + cy = np.corrcoef(p[:-k].ravel(), p[k:].ravel())[0, 1] + found[f"correlation_{k}"] = (cx + cy) / 2 + rows = [(i * p.shape[0]) // 8 for i in range(9)] + cols = [(j * p.shape[1]) // 8 for j in range(9)] + tiles = [p[rows[i] : rows[i + 1], cols[j] : cols[j + 1]] for i in range(8) for j in range(8)] + focus = np.array([t.var() for t in tiles]) / mean**2 + means = np.array([t.mean() for t in tiles]) + found["local_focus_median"] = np.median(focus) + found["local_focus_p10"] = np.quantile(focus, 0.1) + found["tile_mean_cv"] = means.std() / means.mean() + return found + + +# Sums --------------------------------------------------------------------------------------- + + +def test_pair_and_window_sums_equal_brute_force_for_every_offset_and_window(): + rng = np.random.default_rng(1) + offsets = [(0, 1), (0, 2), (1, 0), (2, 0), (1, 1), (1, -1), (0, 4), (4, 0), (3, -2)] + for _ in range(150): + height, width = (int(v) for v in rng.integers(1, 14, 2)) + pixels = rng.normal(size=(height, width)) + edges = sorted({0, *(int(v) for v in rng.integers(0, height, 2))}) + sums = BlockSums(pixels, 0.3, offsets, edges) + d = pixels - 0.3 + assert math.isclose(sums.total, d.sum(), abs_tol=1e-9) + for dy, dx in offsets: + valid = valid_window((height, width), dy, dx) + if valid.size == 0: + continue + y0 = int(rng.integers(valid.y0, valid.y1)) + x0 = int(rng.integers(valid.x0, valid.x1)) + window = Window( + y0, + int(rng.integers(y0 + 1, valid.y1 + 1)), + x0, + int(rng.integers(x0 + 1, valid.x1 + 1)), + ) + part = d[window.y0 : window.y1, window.x0 : window.x1] + moved = window.shifted(dy, dx) + partner = d[moved.y0 : moved.y1, moved.x0 : moved.x1] + assert math.isclose(sums.pair_sum(window, dy, dx), (part * partner).sum(), abs_tol=1e-9) + assert math.isclose(sums.window_sum(window), part.sum(), abs_tol=1e-9) + assert math.isclose( + sums.window_sum(window, squared=True), (part**2).sum(), abs_tol=1e-9 + ) + + +def test_every_metric_equals_its_definition_on_a_whole_plane(): + pixels = cells(seed=3, side=203)[:, :187] + found, expected = measure(pixels), reference(pixels) + assert found.status == MEASURED + for name, value in expected.items(): + assert getattr(found, name) == pytest.approx(value, rel=1e-9), name + + +# Known values on tiny planes ---------------------------------------------------------------- + + +def test_normalized_variance_is_the_variance_over_the_mean_squared(): + found = measure(np.array([[1, 3], [1, 3]], dtype=np.uint8)) + assert found.normalized_variance == pytest.approx(1 / 4) # mean 2, variance 1 + + +def test_tenengrad_is_the_mean_squared_central_difference_over_the_mean_squared(): + found = measure(np.array([[1, 2, 3]] * 3, dtype=np.uint8)) + # x: (3 - 1) / 2 = 1 at each of 3 pixels; y: 0; mean 2. + assert found.tenengrad == pytest.approx((1.0 + 0.0) / 4) + + +def test_laplacian_variance_is_the_variance_of_the_four_neighbour_laplacian(): + pixels = np.array([[1, 1, 1], [1, 5, 1], [1, 1, 1], [1, 1, 1]], dtype=np.uint8) + # Inner pixels: 4 - 20 = -16 and (5 + 1 + 1 + 1) - 4 = 4; variance 100; mean 16 / 12. + assert measure(pixels).laplacian_variance == pytest.approx(100 / (16 / 12) ** 2) + + +def test_correlations_of_a_checkerboard_and_lags_longer_than_the_plane(): + pixels = (np.indices((4, 4)).sum(axis=0) % 2 + 1).astype(np.uint8) + found = measure(pixels) + assert found.correlation_1 == pytest.approx(-1.0) + assert found.correlation_4 is None and found.correlation_16 is None # no pairs that far + + +def test_otsu_threshold_fraction_separation_and_entropy_of_two_values(): + found = measure(np.array([[10, 10], [10, 20]], dtype=np.uint8)) + assert found.otsu_threshold == 10.0 + assert found.foreground_fraction == pytest.approx(0.25) + assert found.otsu_separation == pytest.approx(1.0) # two values: all variance is between + # 10 falls in the first of 64 bins over 10-20 and 20 in the last. + assert found.entropy == pytest.approx(-(0.75 * math.log2(0.75) + 0.25 * math.log2(0.25))) + + +def test_tile_metrics_of_two_halves(): + pixels = np.ones((16, 16), dtype=np.uint8) + pixels[:, 8:] = 3 + found = measure(pixels) + assert found.tile_mean_cv == pytest.approx(0.5) # tile means 1 and 3: mean 2, std 1 + assert found.local_focus_median == 0.0 and found.local_focus_p10 == 0.0 + assert measure(pixels[:15]).tile_mean_cv is None # under 2 pixels per tile side + + +def test_a_constant_plane_has_no_otsu_split_and_no_correlation(): + found = measure(np.full((32, 32), 7, dtype=np.uint16)) + assert found.status == MEASURED + assert found.otsu_threshold is found.foreground_fraction is found.otsu_separation is None + assert found.entropy == 0.0 and found.normalized_variance == 0.0 + assert found.correlation_1 is None + + +# Synthetic distortions ---------------------------------------------------------------------- + + +def test_blur_lowers_focus_metrics_and_raises_the_short_lag_correlation(): + sharp = cells(seed=4, noise=5.0).astype(np.float64) + series = [measure(gaussian_filter(sharp, sigma)) for sigma in (0.5, 1.0, 2.0, 4.0)] + for name in ("tenengrad", "laplacian_variance", "local_focus_median", "local_focus_p10"): + values = [getattr(found, name) for found in series] + assert values == sorted(values, reverse=True) and len(set(values)) == 4, name + values = [found.correlation_1 for found in series] + assert values == sorted(values) and len(set(values)) == 4 + + +@pytest.mark.parametrize("scale", [0.5, 2.0]) +def test_brightness_scaling_leaves_every_shape_metric_unchanged(scale): + pixels = cells(seed=5) + base, scaled = measure(pixels), measure(pixels.astype(np.float64) * scale) + for name in SHAPE: + assert getattr(scaled, name) == pytest.approx(getattr(base, name), rel=1e-9), name + + +def test_uint16_and_float_copies_give_the_same_metrics(): + pixels = cells(seed=6) + whole, copy = measure(pixels), measure(pixels.astype(np.float32) / np.float32(65535)) + for name in SHAPE: + assert getattr(copy, name) == pytest.approx(getattr(whole, name), rel=1e-5), name + # The histogram metrics depend on the binning (float: 10,000 equal bins), not the scale. + assert copy.foreground_fraction == pytest.approx(whole.foreground_fraction, abs=0.01) + assert copy.entropy == pytest.approx(whole.entropy, abs=0.05) + + +def test_doubling_an_integer_image_leaves_the_histogram_metrics_unchanged(): + pixels = cells(seed=7) + base, doubled = measure(pixels), measure(pixels * np.uint16(2)) + assert doubled.otsu_threshold == 2 * base.otsu_threshold + for name in ("foreground_fraction", "otsu_separation", "entropy"): + assert getattr(doubled, name) == pytest.approx(getattr(base, name), rel=1e-12), name + + +def test_a_near_empty_field_has_almost_no_foreground(): + empty = cells(seed=8, count=0) + empty[100:102, 100:102] = 3000 # one speck of debris + assert measure(empty).foreground_fraction < 0.01 + assert measure(cells(seed=8)).foreground_fraction > 0.03 + + +@pytest.mark.parametrize("sigma", [50.0, 400.0]) +def test_otsu_separation_of_pure_noise_is_two_over_pi_so_it_does_not_mark_emptiness(sigma): + # The baseline (contract §19): two-class Otsu splits Gaussian noise at its mean, and the + # between-class share of the variance of a normal distribution there is 2 / pi. + noise = np.random.default_rng(1).normal(5000.0, sigma, (512, 512)) + found = measure(np.clip(noise, 0, 65535).astype(np.uint16)) + assert found.otsu_separation == pytest.approx(2 / math.pi, abs=0.01) + assert found.foreground_fraction == pytest.approx(0.5, abs=0.02) + # A sparse field of bright cells separates far above that baseline. + assert measure(cells(seed=9)).otsu_separation > 0.85 + + +def test_dense_smooth_content_has_the_noise_baseline_separation_but_a_high_correlation(): + # Smoothed noise: unimodal like camera noise (Otsu separation near 2 / pi), yet full of + # structure (correlation_1 near 1). Only the correlation tells it from an empty field. + rng = np.random.default_rng(3) + field = gaussian_filter(rng.normal(0.0, 1.0, (512, 512)), 3.0) + found = measure(np.clip(5000 + field / field.std() * 400, 0, 65535).astype(np.uint16)) + assert found.otsu_separation == pytest.approx(2 / math.pi, abs=0.02) + assert found.correlation_1 > 0.9 + + +@pytest.mark.parametrize("seed", [3, 21]) +def test_tenengrad_is_the_normalized_variance_times_one_minus_the_lag_2_correlation(seed): + pixels = cells(seed=seed) + p = pixels.astype(np.float64) + + def lag_2(): + x = np.corrcoef(p[:, :-2].ravel(), p[:, 2:].ravel())[0, 1] + y = np.corrcoef(p[:-2].ravel(), p[2:].ravel())[0, 1] + return (x + y) / 2 + + found = measure(pixels) + assert found.tenengrad == pytest.approx(found.normalized_variance * (1 - lag_2()), rel=0.02) + + +def test_an_offset_changes_the_ratio_metrics_but_not_the_correlations_or_the_histogram_shape(): + pixels = cells(seed=22) + base, lifted = measure(pixels), measure(pixels + np.uint16(3000)) # a background pedestal + for name in ("normalized_variance", "tenengrad", "laplacian_variance", "local_focus_median"): + assert getattr(lifted, name) < 0.5 * getattr(base, name), name + assert lifted.tile_mean_cv < 0.5 * base.tile_mean_cv + for name in ("correlation_1", "correlation_4", "correlation_16", "otsu_separation"): + assert getattr(lifted, name) == pytest.approx(getattr(base, name), rel=1e-9), name + assert lifted.foreground_fraction == base.foreground_fraction + + +def test_correlation_1_marks_an_empty_field_from_one_with_structure(): + noise = measure(cells(seed=9, count=0)) + assert abs(noise.correlation_1) < 0.05 and abs(noise.correlation_4) < 0.05 + structured = measure(gaussian_filter(cells(seed=9).astype(np.float64), 1.5)) + assert structured.correlation_1 >= 0.9 + ramp = np.tile(np.arange(256, dtype=np.float64), (256, 1)) + 500.0 + assert measure(ramp).correlation_1 >= 0.9 + + +def test_a_left_right_illumination_ramp_raises_tile_mean_cv(): + flat = np.random.default_rng(10).normal(1000.0, 50.0, (256, 256)) + ramp = flat * np.linspace(0.3, 1.0, flat.shape[1])[None, :] + assert measure(flat).tile_mean_cv < 0.01 < 0.2 < measure(ramp).tile_mean_cv + + +# Blocks --------------------------------------------------------------------------------------- + + +@pytest.mark.parametrize("block", [(64, 256), (50, 64), (256, 40), (17, 33)]) +def test_blocks_give_the_whole_plane_values_up_to_the_edge_effect(block): + pixels = cells(seed=11) + whole, blocks = measure(pixels), measure(pixels, block) + for name in SHAPE: + if name.startswith("correlation"): # pairs at the lag that cross an edge are left out + expected = pytest.approx(getattr(whole, name), abs=0.05) + else: + expected = pytest.approx(getattr(whole, name), rel=0.05 if name in NEIGHBOUR else 1e-9) + assert getattr(blocks, name) == expected, name + for name in HISTOGRAM_METRICS: + assert getattr(blocks, name) == getattr(whole, name) + + +def test_full_width_bands_give_the_whole_plane_values_except_pairs_across_band_edges(): + pixels = cells(seed=12) + whole, bands = measure(pixels), measure(pixels, (128, 256)) + assert bands.correlation_1 != whole.correlation_1 # vertical pairs across the edge are out + assert bands.correlation_1 == pytest.approx(whole.correlation_1, rel=1e-3) + + +def test_finish_refuses_when_the_blocks_do_not_cover_the_plane(): + pixels = cells(seed=13, side=32) + qc = PlaneQc(pixels.shape, pixels.dtype) + qc.add(0, 0, pixels[:16]) + with pytest.raises(ValueError, match="pixels"): + qc.finish(compute_plane_histogram(pixels)) + + +# Special planes ------------------------------------------------------------------------------- + + +def test_non_finite_pixels_blank_the_pixel_metrics_and_keep_the_histogram_ones(): + pixels = cells(seed=14).astype(np.float32) + pixels[3, 3] = np.nan + found = measure(pixels, (64, 64)) + assert found.status == NON_FINITE + assert all(getattr(found, name) is None for name in SHAPE) + assert found.foreground_fraction is not None and found.entropy is not None + + +def test_a_plane_without_finite_pixels_has_no_metric(): + found = measure(np.full((8, 8), np.nan, dtype=np.float32)) + assert found.status == NO_FINITE + assert all(getattr(found, name) is None for name in METRICS) + + +def test_a_plane_whose_mean_is_not_positive_has_no_ratio_metric(): + pixels = (cells(seed=15).astype(np.int32) - 5000).astype(np.int16) + found = measure(pixels) + for name in SHAPE: + assert (getattr(found, name) is None) == (not name.startswith("correlation")), name + + +def test_a_float_plane_in_the_unit_range_is_centred_on_its_mean_not_a_rounded_one(): + # A mean of 0.4 rounds to 0: uncentred sums lose a spread of 1e-8 to cancellation (the + # metrics are about 1e-16 here, so they are compared as ratios, not by pytest's absolute + # tolerance). + rng = np.random.default_rng(16) + pixels = 0.4 + 1e-8 * rng.standard_normal((64, 64)) + expected = reference(pixels) + whole, blocks = measure(pixels), measure(pixels, (16, 64)) + for found, names in ((whole, ("normalized_variance", "tenengrad")), (blocks, SHAPE[:1])): + for name in names: + assert getattr(found, name) / expected[name] == pytest.approx(1.0, rel=1e-6), name + + +def test_the_offsets_cover_every_metric(): + assert { + (0, 1), + (0, 2), + (0, 4), + (0, 16), + (1, 0), + (2, 0), + (4, 0), + (16, 0), + (1, 1), + (1, -1), + } == set(OFFSETS) diff --git a/tests/test_image_qc_blocks.py b/tests/test_image_qc_blocks.py new file mode 100644 index 00000000..70ef90b9 --- /dev/null +++ b/tests/test_image_qc_blocks.py @@ -0,0 +1,76 @@ +"""QC metrics of planes read in blocks: the edge effect is an observation, not a bound (§19). + +The neighbour metrics leave out the pairs across a block edge. How much that matters depends on +the image: ``test_image_qc.py`` observes small differences on cell-like fields, and the first +test here a large one for an image whose strongest change lies exactly on a block edge. The +second runs the real blocked reader with blocks of at most 16 rows. +""" + +import numpy as np +import pytest + +from morphobricks_preprocessing.image_qc_record import IMAGE_QC_FILENAME +from morphobricks_preprocessing.image_qc_table import read_image_qc +from morphobricks_preprocessing.planes import iter_xyc_planes, plane_layout +from qc_tree import CTYX, IMAGES, make_experiment, run +from test_image_qc import measure + + +@pytest.fixture +def experiment(tmp_path): + return make_experiment(tmp_path) + + +def test_a_step_exactly_at_a_block_edge_is_missed_by_the_neighbour_metrics(): + rng = np.random.default_rng(0) + pixels = rng.integers(95, 105, (64, 64)).astype(np.uint16) + pixels[16:] += 900 # the step lies between row 15 and row 16: a band edge + whole, bands = measure(pixels), measure(pixels, (16, 64)) + # The histogram, mean, variance and tile metrics are the whole plane's... + for name in ("normalized_variance", "tile_mean_cv", "otsu_separation", "entropy"): + assert getattr(bands, name) == pytest.approx(getattr(whole, name), rel=1e-9), name + # ...but the vertical differences across the edge are the plane's strongest, and are left + # out: Tenengrad drops to a fraction of the whole plane's. The 5 % and 0.05 seen on + # cell-like fields are observations (contract §19), not guarantees. + assert bands.tenengrad < 0.5 * whole.tenengrad + assert bands.laplacian_variance < 0.5 * whole.laplacian_variance + assert abs(bands.correlation_1 - whole.correlation_1) > 0.002 + assert whole.correlation_16 is not None and bands.correlation_16 is None # blank, not zero + + +def rows_limit(path, mapping, rows): + """Return the smallest memory limit at which the plane's blocks are ``rows`` rows high.""" + low, high = plane_layout(path, mapping, memory_limit=1).block_memory_estimate, 2**30 + while low < high: # the blocks grow with the limit until the plane fits whole + middle = (low + high) // 2 + layout = plane_layout(path, mapping, memory_limit=middle) + if not layout.in_blocks or layout.block_shape[0] >= rows: + high = middle + else: + low = middle + 1 + assert plane_layout(path, mapping, memory_limit=low).block_shape[0] == rows + return low + + +def test_blocks_of_sixteen_rows_leave_lag_16_blank_and_never_zero(tmp_path, experiment): + path = experiment / IMAGES[0] + limit = rows_limit(path, CTYX, 16) + heights = { + block.pixels.shape[0] + for plane in iter_xyc_planes(path, CTYX, memory_limit=limit) + for block in plane.channel(0).blocks() + } + assert heights == {16, 8} # 40 rows: two bands of 16 and one of 8 + whole, blocked = tmp_path / "whole", tmp_path / "blocked" + run(experiment, whole) + run(experiment, blocked, memory_limit=limit) + text = (blocked / IMAGE_QC_FILENAME).read_text(encoding="utf-8") + assert text.count("correlation_16=no_pairs") == len(IMAGES) * 4 + rows = read_image_qc(blocked / IMAGE_QC_FILENAME) + assert len(rows) == len(IMAGES) * 4 and all(row.read_in_blocks for row in rows) + for row in rows: + assert row.qc.correlation_16 is None # no vertical pair 16 rows apart in a 16-row band + assert row.qc.correlation_1 is not None and row.qc.correlation_4 is not None + assert ("correlation_16", "no_pairs") in row.qc.reasons + for row in read_image_qc(whole / IMAGE_QC_FILENAME): + assert not row.read_in_blocks and row.qc.correlation_16 is not None diff --git a/tests/test_image_qc_memory.py b/tests/test_image_qc_memory.py new file mode 100644 index 00000000..4d26a0c0 --- /dev/null +++ b/tests/test_image_qc_memory.py @@ -0,0 +1,92 @@ +"""The working memory of the image QC sums is counted in the block and plane estimates. + +The band buffer is sized from the block (``min(64, rows) + reach`` rows, not always the full +band), the finite scan of a float block holds a mask, and ``planes.plane_layout`` adds the QC +term to the estimate of a whole plane and of a block (contract §19). +""" + +import tracemalloc + +import numpy as np +import pytest +import tifffile +from morphobricks_normalization.histogram import estimate_histogram_memory + +from morphobricks_preprocessing import plane_binning, prefill_mapping +from morphobricks_preprocessing.image_qc import PlaneQc, qc_memory +from morphobricks_preprocessing.plane_binning import Binning +from morphobricks_preprocessing.planes import plane_layout + +SHAPES = [ + (8, 4096, np.uint16), + (64, 2048, np.uint16), + (200, 300, np.float32), + (16, 1000, np.float64), + (3000, 20, np.uint16), + (5, 7, np.uint8), + (1, 1, np.uint8), + (300, 2048, np.uint16), + (17, 33, np.uint16), + (40, 5, np.float32), +] + + +def peak_of_add(pixels): + """Return the peak of extra memory (bytes) while one block is added to the QC sums.""" + qc = PlaneQc(pixels.shape, pixels.dtype) + tracemalloc.start() + try: + before = tracemalloc.get_traced_memory()[0] + tracemalloc.reset_peak() + qc.add(0, 0, pixels) + return tracemalloc.get_traced_memory()[1] - before + finally: + tracemalloc.stop() + + +@pytest.mark.parametrize(("rows", "cols", "dtype"), SHAPES) +def test_the_qc_estimate_bounds_the_measured_peak_of_a_block(rows, cols, dtype): + pixels = (np.random.default_rng(0).random((rows, cols)) * 1000).astype(dtype) + floating = np.dtype(dtype).kind == "f" + assert peak_of_add(pixels) <= qc_memory(rows, cols, floating) + + +def test_a_short_block_does_not_allocate_the_full_band(): + # 8 rows of 4096: the buffer holds 8 + 16 rows, not 64 + 16. + pixels = np.random.default_rng(1).integers(0, 1000, (8, 4096)).astype(np.uint16) + assert peak_of_add(pixels) < 80 * 4096 * 8 + + +def test_the_estimate_counts_the_finite_mask_of_float_blocks_only(): + assert qc_memory(512, 512, True) - qc_memory(512, 512, False) == 512 * 512 + + +def test_a_block_over_the_band_height_adds_only_its_strips(): + # The band buffer is full at 64 + 16 rows; taller blocks add the strips, not more band. + assert qc_memory(10_000, 1000, False) - qc_memory(64, 1000, False) == 2 * 8 * 16 * (10_000 - 64) + + +def test_binning_adds_the_qc_term_to_the_histogram_memory_unless_the_plane_is_only_read(): + dtype = np.dtype(np.uint16) + histogram = estimate_histogram_memory(300 * 200, dtype, range_check=True) + assert Binning().memory(300, 200, dtype) == histogram + qc_memory(300, 200, False) + assert Binning().memory(200, 300, dtype, transposed=True) == Binning().memory(300, 200, dtype) + assert Binning(histogram=False).memory(300, 200, dtype) == 0 + + +@pytest.mark.parametrize("dtype", [np.uint16, np.float32]) +def test_the_plane_and_block_estimates_include_the_qc_term(tmp_path, dtype, monkeypatch): + path = tmp_path / "plane.tif" + tifffile.imwrite(path, np.zeros((600, 800), dtype), photometric="minisblack") + mapping = prefill_mapping("YX") + floating = np.dtype(dtype).kind == "f" + with_qc = [plane_layout(path, mapping, memory_limit=limit) for limit in (2**30, 20_000_000)] + monkeypatch.setattr(plane_binning, "qc_memory", lambda rows, cols, floating: 0) + without = [plane_layout(path, mapping, memory_limit=limit) for limit in (2**30, 20_000_000)] + whole, blocks = with_qc + assert not whole.in_blocks and blocks.in_blocks and blocks.block_shape is not None + assert whole.memory_estimate - without[0].memory_estimate == qc_memory(600, 800, floating) + # The QC term takes memory from the block: it is shorter than without the term, and fits. + assert blocks.block_shape[0] < without[1].block_shape[0] + assert blocks.block_memory_estimate <= 20_000_000 + assert blocks.block_memory_estimate >= qc_memory(*blocks.block_shape, floating) diff --git a/tests/test_image_qc_reasons.py b/tests/test_image_qc_reasons.py new file mode 100644 index 00000000..8dbd2210 --- /dev/null +++ b/tests/test_image_qc_reasons.py @@ -0,0 +1,178 @@ +"""Why a QC metric is blank, and which row combinations the table refuses (contract §19). + +Every blank metric has a reason in the ``blank_reasons`` column, besides the row's +``qc_status``. The reader (and the writer) refuse the combinations no measurement makes: a +status with metrics it blanks, a blank metric without a reason, a value outside its range. +""" + +import csv +import io + +import numpy as np +import pytest +from morphobricks_normalization.histogram import compute_plane_histogram + +from morphobricks_preprocessing.image_qc import METRICS, PlaneQc +from morphobricks_preprocessing.image_qc_table import ( + COLUMNS, + ImageQcFormatError, + QcRow, + read_image_qc, + table_text, + write_image_qc, +) + +IDENTITY = ("a", "a.tif", "0", "1", "c", "b", "t", "x/a.tif", "x/a.tif::z=0,t=1", "GFP") + + +def measure(pixels): + qc = PlaneQc(pixels.shape, pixels.dtype) + qc.add(0, 0, pixels) + return qc.finish(compute_plane_histogram(pixels)) + + +def reasons(pixels): + return dict(measure(pixels).reasons) + + +def noisy(shape=(40, 48), dtype=np.uint16): + return np.random.default_rng(0).integers(100, 1000, shape).astype(dtype) + + +def test_a_plane_with_every_metric_has_no_reason(): + found = measure(noisy()) + assert found.reasons == () and all(getattr(found, name) is not None for name in METRICS) + + +def test_a_constant_plane_has_no_otsu_split_and_no_correlation_variance(): + assert reasons(np.full((32, 32), 7, dtype=np.uint16)) == { + "otsu_threshold": "constant_plane", + "otsu_separation": "constant_plane", + "foreground_fraction": "constant_plane", + "correlation_1": "no_variance", + "correlation_4": "no_variance", + "correlation_16": "no_variance", + } + + +def test_a_plane_not_wider_and_taller_than_the_lag_has_no_pairs_at_it(): + assert reasons(noisy((10, 10))) == { + "correlation_16": "no_pairs", + "local_focus_median": "plane_too_small", + "local_focus_p10": "plane_too_small", + "tile_mean_cv": "plane_too_small", + } + + +def test_a_plane_under_three_rows_has_no_gradient_or_laplacian(): + found = reasons(noisy((2, 64))) + assert found["tenengrad"] == found["laplacian_variance"] == "plane_too_small" + assert found["correlation_4"] == "no_pairs" and "normalized_variance" not in found + + +def test_a_plane_with_a_mean_that_is_not_positive_has_no_ratio_metric(): + pixels = (noisy().astype(np.int32) - 5000).astype(np.int16) + found = reasons(pixels) + assert set(found) == { + "normalized_variance", + "tenengrad", + "laplacian_variance", + "local_focus_median", + "local_focus_p10", + "tile_mean_cv", + } + assert set(found.values()) == {"non_positive_mean"} + + +def test_non_finite_pixels_blank_every_pixel_metric_with_that_reason(): + pixels = noisy().astype(np.float32) + pixels[3, 3] = np.nan + found = reasons(pixels) + assert len(found) == 9 and set(found.values()) == {"non_finite_pixels"} + assert "entropy" not in found and "otsu_threshold" not in found + + +def test_a_plane_without_finite_pixels_has_every_metric_blank_for_that_reason(): + found = reasons(np.full((8, 8), np.nan, dtype=np.float32)) + assert list(found) == list(METRICS) and set(found.values()) == {"no_finite_pixels"} + + +def test_the_reasons_are_in_the_table_and_read_back(tmp_path): + rows = [QcRow(IDENTITY, False, measure(np.full((32, 32), 7, dtype=np.uint16)))] + path = write_image_qc(rows, tmp_path / "t.csv") + cell = list(csv.DictReader(path.read_text(encoding="utf-8").splitlines()))[0]["blank_reasons"] + assert cell.startswith("otsu_threshold=constant_plane;") and cell.endswith( + "correlation_16=no_variance" + ) + assert read_image_qc(path) == rows + + +# Refused combinations ----------------------------------------------------------------------------- + + +def table_with(pixels, **cells): + """Return the table text of one real row with the named cells replaced.""" + text = table_text([QcRow(IDENTITY, False, measure(pixels))]) + header, row = list(csv.reader(io.StringIO(text))) + for name, value in cells.items(): + if name in COLUMNS: + row[COLUMNS.index(name)] = value + out = io.StringIO() + csv.writer(out, lineterminator="\n").writerows([header, row]) + return out.getvalue() + + +def refused(tmp_path, text): + (tmp_path / "t.csv").write_text(text, encoding="utf-8") + with pytest.raises(ImageQcFormatError): + read_image_qc(tmp_path / "t.csv") + + +def test_the_real_rows_used_below_are_accepted(tmp_path): + (tmp_path / "t.csv").write_text(table_with(noisy()), encoding="utf-8") + assert read_image_qc(tmp_path / "t.csv")[0].qc == measure(noisy()) + + +@pytest.mark.parametrize( + "cells", + [ + {"qc_status": "no_finite_pixels"}, # every metric is still there + {"qc_status": "non_finite_pixels"}, # the pixel metrics are still there + {"qc_status": "measured", "entropy": ""}, # a measured plane has an entropy + {"foreground_fraction": "1.5"}, + {"otsu_separation": "-0.1"}, + {"correlation_1": "1.2"}, + {"correlation_16": "-1.01"}, + {"entropy": "6.5"}, + {"tenengrad": "-0.5"}, + {"tile_mean_cv": "-1e-9"}, + {"otsu_threshold": "", "otsu_separation": ""}, # the Otsu metrics are blank together + {"correlation_4": "", "blank_reasons": ""}, # a blank metric without a reason + {"blank_reasons": "entropy=no_pairs"}, # a reason for a metric that has a value + {"blank_reasons": "correlation_1=weather"}, # an unknown reason + {"blank_reasons": "mean=no_pairs"}, # an unknown metric + {"correlation_4": "", "blank_reasons": "correlation_4=non_finite_pixels"}, + ], +) +def test_the_reader_refuses_a_row_no_measurement_makes(tmp_path, cells): + refused(tmp_path, table_with(noisy(), **cells)) + + +def test_the_reader_refuses_a_non_finite_row_that_has_a_pixel_metric(tmp_path): + pixels = noisy().astype(np.float32) + pixels[0, 0] = np.nan + text = table_with(pixels, normalized_variance="0.5", blank_reasons="") + refused(tmp_path, text) + + +def test_the_reader_refuses_a_no_finite_row_that_has_a_metric(tmp_path): + text = table_with(np.full((8, 8), np.nan, dtype=np.float32), entropy="1.0") + refused(tmp_path, text) + + +def test_the_writer_refuses_what_the_reader_refuses(tmp_path): + from dataclasses import replace + + bad = replace(measure(noisy()), status="no_finite_pixels") + with pytest.raises(ValueError, match="no_finite_pixels"): + write_image_qc([QcRow(IDENTITY, False, bad)], tmp_path / "t.csv") diff --git a/tests/test_image_qc_reuse.py b/tests/test_image_qc_reuse.py new file mode 100644 index 00000000..bcb3383f --- /dev/null +++ b/tests/test_image_qc_reuse.py @@ -0,0 +1,118 @@ +"""Image QC rows are reused only under the block layout they were measured with (contract §19). + +The memory limit changes no histogram row, but the neighbour metrics of a plane read in blocks +leave out the pairs across a block edge, so a row measured under another limit is not the row +a fresh run would write. Reuse and resume compare the limit (when planes are read in blocks) +and the full identity of each row. +""" + +import json + +import pytest + +from described_tree import run_described +from morphobricks_preprocessing import run as run_module +from morphobricks_preprocessing.discovery_report import REPORT_FILENAME +from morphobricks_preprocessing.image_qc_record import IMAGE_QC_FILENAME +from morphobricks_preprocessing.image_qc_table import QcRow, read_image_qc, write_image_qc +from morphobricks_preprocessing.planes import plane_layout +from morphobricks_preprocessing.run.staging import STAGING_FOLDER +from qc_tree import CTYX, IMAGES, interrupt_at_second_file, make_experiment, run, sha256 + + +@pytest.fixture +def experiment(tmp_path): + return make_experiment(tmp_path) + + +@pytest.fixture +def small_limit(experiment): + """A memory limit that reads every plane of the experiment in blocks.""" + return plane_layout(experiment / IMAGES[0], CTYX, memory_limit=1).block_memory_estimate + + +def fresh_table(tmp_path, experiment, name, **kwargs): + """Return the table a fresh run writes into a new folder with ``kwargs``.""" + out = tmp_path / name + run(experiment, out, **kwargs) + return (out / IMAGE_QC_FILENAME).read_bytes() + + +def test_one_folder_whole_then_blocked_then_whole_equals_fresh_runs( + tmp_path, + experiment, + small_limit, +): + whole = fresh_table(tmp_path, experiment, "fresh_whole") + blocked = fresh_table(tmp_path, experiment, "fresh_blocked", memory_limit=small_limit) + assert whole != blocked # the block edges are visible in the neighbour metrics + out = tmp_path / "out" + run(experiment, out) + assert (out / IMAGE_QC_FILENAME).read_bytes() == whole + result = run(experiment, out, memory_limit=small_limit) + assert "memory limit changed" in result.rebuild_reason + assert sorted(result.read) == sorted(IMAGES) + assert (out / IMAGE_QC_FILENAME).read_bytes() == blocked + result = run(experiment, out) + assert "memory limit changed" in result.rebuild_reason + assert (out / IMAGE_QC_FILENAME).read_bytes() == whole + + +def test_a_limit_that_leaves_every_plane_whole_still_keeps_the_rows(tmp_path, experiment): + out = tmp_path / "out" + run(experiment, out) + result = run(experiment, out, memory_limit=2**29) + assert result.rebuild_reason is None and result.read == () + + +def test_the_same_blocked_limit_reuses_the_rows(tmp_path, experiment, small_limit): + out = tmp_path / "out" + run(experiment, out, memory_limit=small_limit) + result = run(experiment, out, memory_limit=small_limit) + assert result.rebuild_reason is None and result.read == () + + +@pytest.mark.parametrize("first_blocked", [True, False]) +def test_staged_rows_are_not_resumed_under_another_limit( + tmp_path, + experiment, + small_limit, + monkeypatch, + first_blocked, +): + limits = (small_limit, None) if first_blocked else (None, small_limit) + extra = [{} if limit is None else {"memory_limit": limit} for limit in limits] + expected = fresh_table(tmp_path, experiment, "fresh", **extra[1]) + out, read = tmp_path / "out", interrupt_at_second_file(monkeypatch) + with pytest.raises(RuntimeError, match="stopped"): + run_described(experiment, CTYX, output_folder=out, **extra[0]) + assert any(p.name.endswith(".qc.csv") for p in (out / STAGING_FOLDER).iterdir()) + monkeypatch.setattr(run_module.resume, "_read_file", read) + result = run(experiment, out, **extra[1]) + assert result.resumed == () + report = json.loads((out / REPORT_FILENAME).read_text(encoding="utf-8")) + assert "block layout" in report["staged_discarded"][IMAGES[0]] + assert (out / IMAGE_QC_FILENAME).read_bytes() == expected + + +def test_a_table_whose_rows_name_other_planes_than_the_histogram_table_is_not_reused( + tmp_path, + experiment, +): + out = tmp_path / "out" + run(experiment, out) + table, manifest_path = out / IMAGE_QC_FILENAME, out / "run_manifest.json" + good = table.read_bytes() + rows = read_image_qc(table) + # Same plane ID and channel in every row, another position identifier in one. + first = rows[0] + identity = ("elsewhere", *first.identity[1:]) + rows[0] = QcRow(identity, first.read_in_blocks, first.qc) + write_image_qc(rows, table) + data = json.loads(manifest_path.read_text(encoding="utf-8")) + data["image_qc"]["sha256"] = sha256(table) + manifest_path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + assert read_image_qc(table)[0].key == QcRow(identity, False, first.qc).key + result = run(experiment, out) + assert result.rebuild_reason == "the earlier image QC table does not match the histogram table" + assert table.read_bytes() == good diff --git a/tests/test_image_qc_run.py b/tests/test_image_qc_run.py new file mode 100644 index 00000000..a125ea09 --- /dev/null +++ b/tests/test_image_qc_run.py @@ -0,0 +1,240 @@ +"""The run's image QC table ``image_qc.csv`` and its manifest entry (contract §19). + +The table is written with the histogram table, one row per plane and channel, named in the +manifest by its SHA-256, and follows the histogram step's reuse and resume rules. The table +format and the manifest entry are read strictly. +""" + +import csv +import json + +import pytest +import tifffile +from morphobricks_normalization.csv_io import read_plane_histograms +from morphobricks_normalization.histogram import compute_plane_histogram + +from described_tree import run_described +from morphobricks_preprocessing import read_manifest +from morphobricks_preprocessing import run as run_module +from morphobricks_preprocessing.image_qc import METRICS, QC_VERSION, ImageQc, PlaneQc +from morphobricks_preprocessing.image_qc_record import ( + IMAGE_QC_FILENAME, + image_qc_entry, + recorded_image_qc, +) +from morphobricks_preprocessing.image_qc_table import ( + COLUMNS, + ImageQcFormatError, + QcRow, + read_image_qc, + table_text, + write_image_qc, +) +from morphobricks_preprocessing.log_target import PROTECTED_OUTPUTS +from morphobricks_preprocessing.planes import plane_layout +from morphobricks_preprocessing.run import RunMode +from morphobricks_preprocessing.run.staging import STAGING_FOLDER +from qc_tree import ( + CTYX, + IMAGES, + interrupt_at_second_file, + make_experiment, + run, + sha256, + stack, +) +from tiff_tree import write_data + + +@pytest.fixture +def experiment(tmp_path): + return make_experiment(tmp_path) + + +def test_the_table_and_its_manifest_entry_match_the_histogram_table(tmp_path, experiment): + out = tmp_path / "out" + run(experiment, out) + rows = read_image_qc(out / IMAGE_QC_FILENAME) + manifest = read_manifest(out / "run_manifest.json") + assert manifest.image_qc == image_qc_entry(sha256(out / IMAGE_QC_FILENAME)) + raw = json.loads((out / "run_manifest.json").read_text(encoding="utf-8")) + assert raw["image_qc"]["settings"]["correlation_lags"] == [1, 4, 16] + records = read_plane_histograms(out / "plane_histograms.csv") + expected = [ + QcRow.of(r, channel, False, None).identity for r in records for channel in r.channels + ] + assert sorted(row.identity for row in rows) == sorted(expected) + assert len(rows) == len(IMAGES) * 2 * 2 and not any(row.read_in_blocks for row in rows) + assert (out / IMAGE_QC_FILENAME).read_text(encoding="utf-8").splitlines()[0] == ",".join( + COLUMNS + ) + + +def test_each_row_holds_the_metrics_of_its_channel_plane(tmp_path, experiment): + out = tmp_path / "out" + run(experiment, out) + data = tifffile.imread(experiment / "drug/r1/a.tif") + plane_id = "drug/r1/a.tif::z=0,t=1" + found = {row.key: row for row in read_image_qc(out / IMAGE_QC_FILENAME)} + for c, channel in enumerate(sorted({key[1] for key in found})): + pixels = data[1, c] + qc = PlaneQc(pixels.shape, pixels.dtype) + qc.add(0, 0, pixels) + assert found[plane_id, channel].qc == qc.finish(compute_plane_histogram(pixels)) + + +def test_planes_read_in_blocks_are_marked_and_keep_their_histograms(tmp_path, experiment): + whole, blocks = tmp_path / "whole", tmp_path / "blocks" + run(experiment, whole) + limit = plane_layout(experiment / IMAGES[0], CTYX, memory_limit=1).block_memory_estimate + run(experiment, blocks, memory_limit=limit) + assert (whole / "plane_histograms.csv").read_bytes() == ( + blocks / "plane_histograms.csv" + ).read_bytes() + found = {row.key: row for row in read_image_qc(blocks / IMAGE_QC_FILENAME)} + for row in read_image_qc(whole / IMAGE_QC_FILENAME): + other = found[row.key] + assert other.read_in_blocks and not row.read_in_blocks + assert other.qc.normalized_variance == pytest.approx(row.qc.normalized_variance, rel=1e-9) + assert other.qc.entropy == row.qc.entropy + + +def test_a_rerun_reuses_the_rows_and_leaves_the_outputs_as_they_were( + tmp_path, experiment, monkeypatch +): + out = tmp_path / "out" + run(experiment, out) + before = {name: (out / name).read_bytes() for name in (IMAGE_QC_FILENAME, "run_manifest.json")} + reads = [] + read = run_module.resume._read_file + monkeypatch.setattr(run_module.resume, "_read_file", lambda *a: reads.append(a[1]) or read(*a)) + result = run(experiment, out) + assert reads == [] and result.rebuild_reason is None + assert {name: (out / name).read_bytes() for name in before} == before + + +def test_a_changed_image_replaces_only_its_rows(tmp_path, experiment): + out, reference = tmp_path / "out", tmp_path / "reference" + run(experiment, out) + write_data(experiment / "ctrl/r1/b.tif", stack(9), "TCYX") + result = run(experiment, out) + assert result.read == ("ctrl/r1/b.tif",) + run(experiment, reference, mode="full") + assert (out / IMAGE_QC_FILENAME).read_bytes() == (reference / IMAGE_QC_FILENAME).read_bytes() + + +@pytest.mark.parametrize( + ("damage", "reason"), + [ + ("edit", "the image QC table was changed or replaced after the earlier run"), + ("delete", "the image QC table was changed or replaced after the earlier run"), + ("unrecorded", "the earlier run has no image QC table (image_qc.csv)"), + ("version", "the image QC metrics changed since the earlier run"), + ], +) +def test_rows_are_recomputed_when_the_earlier_table_cannot_be_reused( + tmp_path, experiment, damage, reason +): + out = tmp_path / "out" + run(experiment, out) + table, manifest_path = out / IMAGE_QC_FILENAME, out / "run_manifest.json" + good = table.read_bytes() + data = json.loads(manifest_path.read_text(encoding="utf-8")) + if damage == "edit": + table.write_bytes(good.replace(b"measured", b"measured", 1) + b"\n") + elif damage == "delete": + table.unlink() + elif damage == "unrecorded": + del data["image_qc"] + else: + data["image_qc"]["qc_version"] = "0" + manifest_path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + result = run(experiment, out) + assert result.rebuild_reason == reason and sorted(result.read) == sorted(IMAGES) + assert table.read_bytes() == good + + +def test_an_interrupted_run_resumes_the_staged_rows(tmp_path, experiment, monkeypatch): + out, reference = tmp_path / "out", tmp_path / "reference" + run(experiment, reference) + read = interrupt_at_second_file(monkeypatch) + with pytest.raises(RuntimeError, match="stopped"): + run_described(experiment, CTYX, output_folder=out) + staged = sorted(p.name for p in (out / STAGING_FOLDER).iterdir()) + assert len(staged) == 3 and sum(name.endswith(".qc.csv") for name in staged) == 1 + monkeypatch.setattr(run_module.resume, "_read_file", read) + result = run(experiment, out) + assert result.resumed == (IMAGES[0],) + assert (out / IMAGE_QC_FILENAME).read_bytes() == (reference / IMAGE_QC_FILENAME).read_bytes() + + +def test_workers_write_the_same_table(tmp_path, experiment): + serial, parallel = tmp_path / "serial", tmp_path / "parallel" + run(experiment, serial) + run(experiment, parallel, mode=RunMode("restart", workers=2)) + assert (serial / IMAGE_QC_FILENAME).read_bytes() == (parallel / IMAGE_QC_FILENAME).read_bytes() + + +def test_a_log_may_not_be_written_over_the_table(): + assert IMAGE_QC_FILENAME in PROTECTED_OUTPUTS + + +# The table format ------------------------------------------------------------------------------- + + +def row(**metrics): + identity = ("a", "a.tif", "0", "1", "c", "b", "t", "x/a.tif", "x/a.tif::z=0,t=1", "GFP") + blank = tuple((name, "plane_too_small") for name in METRICS if name not in metrics) + return QcRow(identity, True, ImageQc("measured", **metrics, reasons=blank)) + + +def test_the_table_reads_back_exactly(tmp_path): + rows = [row(entropy=1 / 3, correlation_1=-0.1), row(entropy=1.0, tenengrad=1e-300)] + path = write_image_qc(rows, tmp_path / IMAGE_QC_FILENAME) + assert read_image_qc(path) == sorted(rows, key=QcRow.order) + line = list(csv.reader(path.read_text(encoding="utf-8").splitlines()))[1] + assert line[COLUMNS.index("foreground_fraction")] == "" # blank, never zero + assert line[-1] == QC_VERSION and line[COLUMNS.index("read_in_blocks")] == "true" + + +@pytest.mark.parametrize( + ("old", "new"), + [ + ("qc_status", "status"), + ("measured", "fine"), + (",true,", ",yes,"), + (f",{QC_VERSION}\n", ",9\n"), + ], +) +def test_the_reader_refuses_a_malformed_table(tmp_path, old, new): + text = table_text([row(entropy=1.0)]).replace(old, new, 1) + (tmp_path / "t.csv").write_text(text, encoding="utf-8") + with pytest.raises(ImageQcFormatError): + read_image_qc(tmp_path / "t.csv") + + +@pytest.mark.parametrize("value", ["nan", "inf", "x"]) +def test_the_reader_refuses_a_value_that_is_not_a_finite_number(tmp_path, value): + text = table_text([row(entropy=1.5)]).replace("1.5", value) + (tmp_path / "t.csv").write_text(text, encoding="utf-8") + with pytest.raises(ImageQcFormatError, match="entropy"): + read_image_qc(tmp_path / "t.csv") + + +def test_the_manifest_entry_is_read_strictly(): + entry = image_qc_entry("0" * 64) + assert recorded_image_qc(entry) == entry and recorded_image_qc(None) is None + for broken in ( + {**entry, "extra": 1}, + {**entry, "file": "other.csv"}, + {**entry, "sha256": "abc"}, + {**entry, "qc_version": 1}, + {**entry, "settings": []}, + [], + ): + with pytest.raises(ValueError): + recorded_image_qc(broken) + + +def test_the_metric_columns_are_the_metrics(): + assert COLUMNS[COLUMNS.index("qc_status") + 1 : -2] == METRICS diff --git a/tests/test_modes_lock_report.py b/tests/test_modes_lock_report.py index 9dea5fa8..47a70210 100644 --- a/tests/test_modes_lock_report.py +++ b/tests/test_modes_lock_report.py @@ -256,7 +256,7 @@ def test_the_lock_is_released_when_a_run_fails(experiment, monkeypatch): def broken(*args, **kwargs): raise OSError("simulated") - monkeypatch.setattr(run_module.pipeline, "write_plane_histograms", broken) + monkeypatch.setattr(run_module.outputs, "write_plane_histograms", broken) with pytest.raises(OSError, match="simulated"): run_described(experiment, TYX) assert read_lock(default_output_folder(experiment)) is None diff --git a/tests/test_notebook_debt.py b/tests/test_notebook_debt.py index b3e5b22c..1ddaf949 100644 --- a/tests/test_notebook_debt.py +++ b/tests/test_notebook_debt.py @@ -8,6 +8,7 @@ import numpy as np import pytest +from memory_limits import block_limit from morphobricks_preprocessing import prefill_mapping from morphobricks_preprocessing.axes import AxisMapping from morphobricks_preprocessing.notebook_values import plane_counts, value_range @@ -41,7 +42,9 @@ def test_plane_layouts_and_memory_plan(tmp_path): mapping = prefill_mapping("ZYX") small = plane_layout(root / "small.tif", mapping, bin_count=65_536).memory_estimate files = {"big.tif": mapping, "small.tif": mapping, "broken.tif": mapping} - layouts = plane_layouts(root, files, memory_limit=small, bin_count=65_536) + layouts = plane_layouts( + root, files, memory_limit=block_limit(small, (8, 8), 64), bin_count=65_536 + ) assert list(layouts) == ["big.tif", "small.tif"] # an unreadable layout is left out plan = memory_plan(layouts) assert plan.blocked == ("big.tif",) and plan.over == () and plan.need == 0 diff --git a/tests/test_notebook_ui.py b/tests/test_notebook_ui.py index 9f32b546..00fe5cac 100644 --- a/tests/test_notebook_ui.py +++ b/tests/test_notebook_ui.py @@ -11,6 +11,7 @@ from morphobricks_normalization.csv_io import read_plane_histograms from described_tree import describe_tree # noqa: E402 +from memory_limits import block_limit # noqa: E402 from morphobricks_preprocessing import Plane, notebook_ui, read_manifest from morphobricks_preprocessing import notebook_style as ui # noqa: E402 from morphobricks_preprocessing.axes import AxisMapping # noqa: E402 @@ -459,8 +460,7 @@ def test_intensity_checks_follow_a_successful_run(tmp_path): assert not ui.is_visible(nb.run_checks.card) nb.run() assert sorted(p.name for p in out.iterdir() if "report" not in p.name) == [ - "experiment_design.csv", - "morphobricks.toml", + *("experiment_design.csv", "image_qc.csv", "morphobricks.toml"), "plane_histograms.csv", "run_manifest.json", ] @@ -739,9 +739,8 @@ def small_estimate(root): def test_plan_names_images_read_in_blocks(tmp_path, monkeypatch): root = large_planes_experiment(tmp_path) nb = checked(root) - set_memory_limit(nb, small_estimate(root)) - # Before the axis roles are confirmed the planes are not known yet. - assert "read in blocks" not in nb.plan.value + set_memory_limit(nb, block_limit(small_estimate(root), (8, 8), 64)) + assert "read in blocks" not in nb.plan.value # planes not known before the axis roles def fail(*args, **kwargs): raise AssertionError("pixel data was read") diff --git a/tests/test_numpy_floor.py b/tests/test_numpy_floor.py new file mode 100644 index 00000000..08650193 --- /dev/null +++ b/tests/test_numpy_floor.py @@ -0,0 +1,36 @@ +"""The declared NumPy floor covers the NumPy functions the code uses (contract §19, B1). + +The image QC sums use ``numpy.vecdot``, new in NumPy 2.0, so ``pyproject.toml`` must not +allow an older NumPy. +""" + +import tomllib +from pathlib import Path + +from packaging.requirements import Requirement +from packaging.version import Version + +ROOT = Path(__file__).resolve().parents[1] +SINCE = {"np.vecdot": "2.0", "numpy.vecdot": "2.0"} +"""NumPy functions used under ``src`` and the first NumPy release that has each.""" + + +def numpy_floor(): + """Return the lowest NumPy version the project's dependencies allow.""" + data = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8")) + (spec,) = ( + Requirement(text) + for text in data["project"]["dependencies"] + if Requirement(text).name == "numpy" + ) + return min(Version(s.version) for s in spec.specifier if s.operator in (">=", "==")) + + +def test_the_numpy_floor_is_a_release_that_has_every_function_the_code_uses(): + used = { + name: since + for path in (ROOT / "src").rglob("*.py") + for name, since in SINCE.items() + if name in path.read_text(encoding="utf-8") + } + assert numpy_floor() >= max((Version(since) for since in used.values()), default=Version("0")) diff --git a/tests/test_plane_channels.py b/tests/test_plane_channels.py index 2e0c0374..bb7cc37f 100644 --- a/tests/test_plane_channels.py +++ b/tests/test_plane_channels.py @@ -13,10 +13,10 @@ from described_tree import run_described from morphobricks_preprocessing import plane_channels as channels_module from morphobricks_preprocessing import prefill_mapping +from morphobricks_preprocessing.plane_binning import Binning from morphobricks_preprocessing.plane_channels import read_xyc_plane, xyc_plane_memory from morphobricks_preprocessing.planes import ( PlaneMemoryError, - _Binning, _layout, read_plane, ) @@ -382,7 +382,7 @@ def test_a_plane_just_over_the_limit_is_refused_before_any_read(rgb_run, monkeyp mapping = prefill_mapping("YXS") estimate = xyc_plane_memory(path, mapping) with tifffile.TiffFile(path) as tif: - single = _layout(tif.series[0], mapping, path, _Binning(histogram=False)).memory_estimate + single = _layout(tif.series[0], mapping, path, Binning(histogram=False)).memory_estimate # One channel's read alone fits the limit: the per-channel check let this read through. assert single < estimate - 1 calls = count_decodes(monkeypatch) diff --git a/tests/test_planes.py b/tests/test_planes.py index 481a9b34..abbb2b85 100644 --- a/tests/test_planes.py +++ b/tests/test_planes.py @@ -6,6 +6,7 @@ import tifffile from morphobricks_normalization.histogram import compute_plane_histogram, estimate_histogram_memory +from memory_limits import block_limit, qc_memory from morphobricks_preprocessing import ( DEFAULT_MEMORY_LIMIT, AxisMapping, @@ -322,10 +323,9 @@ def test_memory_estimate_covers_page_plane_and_histogram(tmp_path): assert layout.page_shape == (60, 70, 3) assert layout.page_nbytes == 60 * 70 * 3 histogram = estimate_histogram_memory(60 * 70, np.dtype("uint8")) - # The finished bin counts of the plane's three channels are kept for its row. assert layout.channel_count == 3 - finished = 3 * 8 * 256 - assert layout.memory_estimate == ( + finished = 3 * 8 * 256 # the finished bin counts of the plane's three channels, for its row + assert layout.memory_estimate - qc_memory(60, 70, False) == ( layout.page_nbytes + layout.encoded_nbytes + 60 * 70 + histogram + finished ) @@ -433,7 +433,7 @@ def fail(*args, **kwargs): for cls in (tifffile.TiffFile, tifffile.TiffPage, tifffile.TiffFrame, tifffile.TiffPageSeries): monkeypatch.setattr(cls, "asarray", fail) monkeypatch.setattr(tiff_pieces, "_read_segment", fail) - (found,) = check_planes(tmp_path, review, memory_limit=small) + (found,) = check_planes(tmp_path, review, memory_limit=block_limit(small, (8, 8), 64)) assert found.code == "planes_read_in_blocks" assert found.severity is Severity.WARNING assert found.paths == ("c/big.tif",) diff --git a/tests/test_publication.py b/tests/test_publication.py index 123c1e2b..b20c8ba0 100644 --- a/tests/test_publication.py +++ b/tests/test_publication.py @@ -105,9 +105,9 @@ def broken_hash(path): with monkeypatch.context() as patch: target = { - "csv": (run_module.pipeline, "write_plane_histograms", broken), + "csv": (run_module.outputs, "write_plane_histograms", broken), "hash": (generation, "file_sha256", broken_hash), - "manifest": (run_module.pipeline, "write_manifest", broken), + "manifest": (run_module.outputs, "write_manifest", broken), "record": (generation, "write_text_atomic", broken), "commit": (os, "replace", broken_commit), }[failure] diff --git a/tests/test_resume.py b/tests/test_resume.py index 4a5f8680..4ff4a9b0 100644 --- a/tests/test_resume.py +++ b/tests/test_resume.py @@ -364,7 +364,7 @@ class Clock: def now(tz=None): return __import__("datetime").datetime.fromisoformat(next(times)) - monkeypatch.setattr(run_module.pipeline, "datetime", Clock) + monkeypatch.setattr(run_module.outputs, "datetime", Clock) first = run_described(root, TYX) before = first.manifest_path.read_bytes() again = run_described(root, TYX) diff --git a/tests/test_run.py b/tests/test_run.py index 2f716956..5428c1ed 100644 --- a/tests/test_run.py +++ b/tests/test_run.py @@ -585,7 +585,7 @@ def test_plane_over_memory_limit_blocks(experiment, reads): assert not result.written and reads == [] -def test_planes_over_the_memory_limit_are_read_in_blocks(experiment, tmp_path, reads): +def test_planes_over_the_memory_limit_are_read_in_blocks(experiment, tmp_path): whole = run_described(experiment, TYX, output_folder=tmp_path / "whole") limit = plane_layout(experiment / IMAGES[0], TYX, memory_limit=1).block_memory_estimate blocks = run_described(experiment, TYX, output_folder=tmp_path / "blocks", memory_limit=limit) @@ -595,10 +595,10 @@ def test_planes_over_the_memory_limit_are_read_in_blocks(experiment, tmp_path, r assert csv_bytes(blocks) == csv_bytes(whole) assert all(f.read_in_blocks for f in read_manifest(blocks.manifest_path).files) assert not any(f.read_in_blocks for f in read_manifest(whole.manifest_path).files) - # Changing only the limit reads nothing again; the manifest records the new way. - reads.clear() + # Only the limit changed: the same table, but the images are read again (image QC, §19). again = run_described(experiment, TYX, output_folder=tmp_path / "blocks") - assert again.read == () and reads == [] and csv_bytes(again) == csv_bytes(whole) + assert "memory limit changed" in again.rebuild_reason and sorted(again.read) == sorted(IMAGES) + assert csv_bytes(again) == csv_bytes(whole) assert not any(f.read_in_blocks for f in read_manifest(again.manifest_path).files) diff --git a/tests/worker_bytes.py b/tests/worker_bytes.py index 630b567c..8e60812a 100644 --- a/tests/worker_bytes.py +++ b/tests/worker_bytes.py @@ -14,7 +14,7 @@ from described_tree import run_described from morphobricks_preprocessing.run import RunMode -from morphobricks_preprocessing.run import pipeline as pipeline_module +from morphobricks_preprocessing.run import outputs as outputs_module from morphobricks_preprocessing.run import workers as workers_module WRITTEN_AT = "2026-11-16T12:00:00+00:00" @@ -34,7 +34,7 @@ def now(cls, tz=None): @pytest.fixture(autouse=True) def fixed_clock(monkeypatch): """Every run writes ``written_at`` = :data:`WRITTEN_AT`; set ``fixed_clock.at`` to move it.""" - monkeypatch.setattr(pipeline_module, "datetime", FixedClock) + monkeypatch.setattr(outputs_module, "datetime", FixedClock) monkeypatch.setattr(FixedClock, "at", datetime.fromisoformat(WRITTEN_AT)) return FixedClock diff --git a/tools/benchmark_image_qc.py b/tools/benchmark_image_qc.py new file mode 100644 index 00000000..b82c30db --- /dev/null +++ b/tools/benchmark_image_qc.py @@ -0,0 +1,229 @@ +"""Benchmark the histogram step with and without the image QC metrics (``image_qc.csv``). + +Usage:: + + python tools/benchmark_image_qc.py --baseline-src DIR [--folder DIR] [--repeats 10] + [--images 10] [--side 2048] [--channels 4] [--cpus 0-3] + +``--baseline-src`` is the ``src`` folder of a checkout without the metrics (for example a +worktree of the commit before them); the code under test is the installed package. The script +writes (once, into ``--folder``) a seeded experiment of ``--images`` uncompressed ``uint16`` +OME-TIFFs of ``--channels`` x ``--side`` x ``--side`` pixels, and a second experiment of one +such image that is read in blocks (memory limit 16 MiB), and publishes their descriptions. + +Each round runs the four configurations (with and without the metrics, whole and in blocks), +each in a fresh Python process into a new output folder (``mode="full"``), in an order that +alternates between rounds (ABBA), and records the wall time of ``run_experiment`` and of its +histogram step (``run.steps.new_rows``: reading every image, the histograms, the metrics and +the staging; the calling thread, one worker). The report gives, per configuration, the median +and range of both times, and the paired ratio (with / without, per round) of the histogram +step. Every run's ``plane_histograms.csv`` and ``experiment_design.csv`` must have the +baseline's SHA-256 (identical outputs), else the script exits with status 1; the runs with +the metrics must also all write the same ``image_qc.csv``. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import shutil +import statistics +import subprocess +import sys +import time +from pathlib import Path + +import numpy as np +import tifffile + +MIB = 2**20 +BLOCK_LIMIT = 16 * MIB +"""The memory limit of the experiment read in blocks.""" +CONFIGURATIONS = ( + ("without", "whole"), + ("with", "whole"), + ("without", "blocks"), + ("with", "blocks"), +) + + +def write_experiment(folder: Path, images: int, shape: tuple[int, int, int]) -> Path: + """Write one experiment of seeded smooth-plus-noise images and its description.""" + from morphobricks_preprocessing.description import ( + Channel, + Condition, + Description, + Member, + Repeat, + Unit, + ) + from morphobricks_preprocessing.testing_described import PUBLISHED_NAME, description_of + + experiment = folder / "experiment" + channels = tuple(f"ch{c}" for c in range(shape[0])) + rng = np.random.default_rng(images) + y, x = np.ogrid[: shape[1], : shape[2]] + for index in range(images): + data = np.empty(shape, dtype=np.uint16) + for c in range(shape[0]): + blobs = (np.sin(y / (6.0 + 4 * c)) * np.cos(x / (9.0 + c)) * 900 + 1500).astype( + np.uint16 + ) + data[c] = blobs + rng.integers(0, 300, shape[1:], dtype=np.uint16) + path = experiment / "ctrl" / "rep1" / f"image{index:02d}.ome.tif" + path.parent.mkdir(parents=True, exist_ok=True) + tifffile.imwrite(path, data, ome=True, photometric="minisblack", metadata={"axes": "CYX"}) + unit = {"single": Unit("single", channels)} + described = Description( + conditions={"ctrl": Condition("ctrl")}, + channels={c: Channel() for c in channels}, + repeats={"rep1": Repeat(True, "2026-01-01", {"ctrl": Member("rep1", images, unit)})}, + used_ids={ + "conditions": ("ctrl",), + "channels": channels, + "repeats": ("rep1",), + "technical_repeats": ("single",), + }, + ) + (folder / PUBLISHED_NAME).write_bytes(description_of(described)[1]) + return experiment + + +def child(experiment: str, output: str, memory_limit: str) -> None: + """Run preprocessing once (mode full) and print the wall and histogram-step times.""" + from morphobricks_preprocessing import prefill_mapping, run_experiment + from morphobricks_preprocessing.run import steps + + spent = {"histogram_step": 0.0} + new_rows = steps.new_rows + + def timed(*args: object, **kwargs: object) -> object: + start = time.perf_counter() + try: + return new_rows(*args, **kwargs) + finally: + spent["histogram_step"] += time.perf_counter() - start + + steps.new_rows = timed + start = time.perf_counter() + result = run_experiment( + experiment, + prefill_mapping("CYX"), + output_folder=output, + memory_limit=int(memory_limit), + mode="full", + ) + wall = time.perf_counter() - start + errors = [issue.code for issue in result.issues if issue.is_error] + print(json.dumps({"written": result.written, "errors": errors, "wall": wall, **spent})) + + +def one_run(folder: Path, configuration: tuple[str, str], args: argparse.Namespace) -> dict: + """Run one configuration in a fresh process; return its times and output digests.""" + metrics, reading = configuration + data = folder / reading + output = folder / f"output_{metrics}_{reading}" + shutil.rmtree(output, ignore_errors=True) + output.mkdir() + shutil.copy(data / "morphobricks.toml", output / "morphobricks.toml") + env = dict(os.environ) + if metrics == "without": + env["PYTHONPATH"] = str(Path(args.baseline_src).resolve()) + limit = BLOCK_LIMIT if reading == "blocks" else 2**30 + command = [sys.executable, str(Path(__file__).resolve()), "--child"] + command += [str(data / "experiment"), str(output), str(limit)] + if args.cpus and shutil.which("taskset"): + command = ["taskset", "-c", args.cpus, *command] + done = subprocess.run(command, capture_output=True, text=True, check=False, env=env) + if done.returncode != 0: + raise SystemExit(f"{configuration} failed:\n{done.stderr}") + found = json.loads(done.stdout.strip().splitlines()[-1]) + if not found["written"]: + raise SystemExit(f"{configuration} published nothing: {found['errors']}") + names = ["plane_histograms.csv", "experiment_design.csv", "image_qc.csv"] + found["digests"] = { + name: hashlib.sha256((output / name).read_bytes()).hexdigest() + for name in names + if (output / name).exists() + } + manifest = json.loads((output / "run_manifest.json").read_text(encoding="utf-8")) + found["read_in_blocks"] = [f["relative_path"] for f in manifest["files"] if f["read_in_blocks"]] + return found + + +def summary(rounds: list[dict]) -> tuple[dict, bool]: + """Return the times per configuration, the paired ratios, and whether outputs agree.""" + report: dict = {} + agree = True + for reading in ("whole", "blocks"): + runs = {m: [r[f"{m}_{reading}"] for r in rounds] for m in ("without", "with")} + for metrics, found in runs.items(): + report[f"{metrics}_{reading}"] = { + key: _spread([run[key] for run in found]) for key in ("histogram_step", "wall") + } + ratios = [ + w["histogram_step"] / b["histogram_step"] + for b, w in zip(runs["without"], runs["with"], strict=True) + ] + report[f"ratio_{reading}"] = _spread(ratios) + for name in ("plane_histograms.csv", "experiment_design.csv"): + agree &= len({run["digests"][name] for m in runs for run in runs[m]}) == 1 + agree &= len({run["digests"].get("image_qc.csv") for run in runs["with"]}) == 1 + agree &= all("image_qc.csv" not in run["digests"] for run in runs["without"]) + return report, agree + + +def _spread(values: list[float]) -> dict: + """Return the median, minimum and maximum of ``values``, rounded.""" + return { + "median": round(statistics.median(values), 4), + "min": round(min(values), 4), + "max": round(max(values), 4), + } + + +def main() -> None: + """Write the experiments once, run the rounds and print the report as JSON.""" + if len(sys.argv) > 1 and sys.argv[1] == "--child": + child(*sys.argv[2:5]) + return + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--baseline-src", required=True) + parser.add_argument("--folder", default="image_qc_benchmark") + parser.add_argument("--repeats", type=int, default=10) + parser.add_argument("--images", type=int, default=10) + parser.add_argument("--side", type=int, default=2048) + parser.add_argument("--channels", type=int, default=4) + parser.add_argument("--cpus", default=None) + args = parser.parse_args() + folder = Path(args.folder) + shape = (args.channels, args.side, args.side) + if not (folder / "done").exists(): + write_experiment(folder / "whole", args.images, shape) + write_experiment(folder / "blocks", 1, shape) + (folder / "done").write_text("ok\n", encoding="utf-8") + one_run(folder, CONFIGURATIONS[0], args) # warm-up (disk cache), not counted + rounds = [] + for index in range(args.repeats): + order = CONFIGURATIONS if index % 2 == 0 else CONFIGURATIONS[::-1] + found = {f"{m}_{r}": one_run(folder, (m, r), args) for m, r in order} + rounds.append(found) + print( + json.dumps({k: round(v["histogram_step"], 3) for k, v in found.items()}), + file=sys.stderr, + ) + report, agree = summary(rounds) + blocks = rounds[0]["with_blocks"]["read_in_blocks"] + report["dataset"] = {"images": args.images, "shape_cyx": shape, "blocks_images": blocks} + report["identical_outputs"] = agree + report["load_average"] = os.getloadavg() if hasattr(os, "getloadavg") else None + report["cpus"] = args.cpus + print(json.dumps(report, indent=2)) + if not agree: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/tools/code_rules_baseline.json b/tools/code_rules_baseline.json index b83b2cae..11c8eaf2 100644 --- a/tools/code_rules_baseline.json +++ b/tools/code_rules_baseline.json @@ -17,7 +17,7 @@ "src/morphobricks_preprocessing/discovery.py _check_names: private function of # lines without a docstring": 14, "src/morphobricks_preprocessing/discovery.py finish: # executable lines (max #)": 145, "src/morphobricks_preprocessing/image_type.py _rgb_problem: private function of # lines without a docstring": 12, - "src/morphobricks_preprocessing/manifest.py file_entry_for: # parameters (max #)": 9, + "src/morphobricks_preprocessing/manifest_files.py file_entry_for: # parameters (max #)": 9, "src/morphobricks_preprocessing/masks/files.py _duplicate_issues: private function of # lines without a docstring": 19, "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, @@ -25,7 +25,7 @@ "src/morphobricks_preprocessing/metadata.py: # lines (max #)": 646, "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 #)": 1324, + "src/morphobricks_preprocessing/planes.py: # lines (max #)": 1299, "src/morphobricks_preprocessing/run/pipeline.py run_experiment: # parameters (max #)": 14, "src/morphobricks_preprocessing/run/preflight.py _exclusion_issues: private function of # lines without a docstring": 34, "src/morphobricks_preprocessing/run/rows.py _bin_count: private function of # lines without a docstring": 12, @@ -33,7 +33,7 @@ "tests/test_discovery.py: # lines (max #)": 826, "tests/test_masks.py: # lines (max #)": 612, "tests/test_metadata.py: # lines (max #)": 629, - "tests/test_notebook_ui.py: # lines (max #)": 1131, + "tests/test_notebook_ui.py: # lines (max #)": 1130, "tests/test_planes.py: # lines (max #)": 818, "tests/test_run.py: # lines (max #)": 849, "tests/test_zarr_input.py: # lines (max #)": 850,