diff --git a/AGENTS.md b/AGENTS.md index 67accd19..607d1dd1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -298,7 +298,10 @@ src/morphobricks_preprocessing/ WindowLayoutError (shared by both); window_reader.py WindowReader (#304): many windows of one image through a bounded, thread-safe block_cache.BlockCache of decoded pieces (opt-in), - RunInputs.window_reader -> RunWindowReader by channel IDs; + RunInputs.window_reader -> RunWindowReader by channel IDs; it refuses at + open an OME-Zarr whose chunks leave no window within the limit (v0.10.1); + window_chunks.py check_window_chunks: check/run warn about such stores + (chunks_too_large_for_windows, e.g. one chunk per plane); window_map.py map_plan / map_windows / iter_windows: a function over windows in a bounded thread pool, results in window order, memory planned and checked against a budget before any read (lazy-windows §5); @@ -599,7 +602,8 @@ src/morphobricks_preprocessing/ changed right there, the proposal the Axes step starts from notebook_zarr_copy.py the first screen's "Also save a copy as OME-Zarr" and the Axes step's card that writes it once the roles are confirmed; ome_zarr_copy.py - the writers (OME-NGFF 0.4, written directly) and the copy's name + the writers (OME-NGFF 0.4, written directly, chunks of at most + 1 x 1024 x 1024 since v0.10.1) and the copy's name notebook_projection.py the Axes step's card for Z-stacks: choose the projection, write the projected copies into the output folder (convert_experiment), open them as the experiment; the greyed 3-D option diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b240c96..818440f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,35 @@ refuses the skipped label images as unrecorded: refused, never silently wrong. ### Fixed +- **OME-Zarr copies are written in spatial chunks, so a later brick can read them in windows.** + `convert --store ome-zarr`, the notebook's OME-Zarr copy and `convert_experiment(..., + store="ome-zarr")` wrote each plane as one chunk (the whole Y and X). A windowed route + (fiberfeatures' `run.execution_route = "patch_window"`, through `RunInputs.window_reader`) + decodes a chunk whole for any window, so it refused the first patch of a large converted slide + (`WindowMemoryError`) after `check` had passed. Copies are now written in chunks of one plane by + at most 1024 x 1024 pixels (`1 x ... x min(Y, 1024) x min(X, 1024)`, bioformats2raw's default; + `ome_zarr_copy.CHUNK_SIDE`, `chunk_shape`), still uncompressed Zarr version 2 (OME-NGFF 0.4), + one level (no pyramid: the bricks read level 0 only). Each plane is written as it is read, + block by block within the memory limit, each block's part of each chunk written in place + (edge chunks at full size, zeros outside the image, as Zarr 2 stores them); a plane read in + blocks is never held whole. **Byte identity:** the pixels, the `.zattrs` and the conversion + record's other fields are unchanged, but a copy of an image larger than 1024 pixels along Y + or X is new bytes: its `0/.zarray` `chunks` and its chunk files (`0///`, + instead of one `0//0/0` per plane), so its `copy_sha256` differs. Copies of planes of at + most 1024 x 1024 pixels are byte for byte as before. A conversion into a folder that already + holds a copy written before keeps that copy (its plan and content are unchanged): convert + into a new folder to get the chunked copies. +- **`check` and `run` warn about an OME-Zarr image no window reader can serve** + (`chunks_too_large_for_windows`, new module `window_chunks`): from the header, the least a + window reader needs for a window of one pixel, through a cache of one chunk + (`window_chunks.window_chunk_need`, `windows.smallest_window_memory`), against the memory + limit; the warning names the images and says to convert the originals again into a new folder + (for a copy written before v0.10.1) or to save the image with chunks of at most 1024 x 1024 + pixels. `check` uses the default limit (1 GiB); `run` its `--memory-limit`. The same store is + refused when `WindowReader` / `RunInputs.window_reader` is opened on it with a cache that + leaves no room for one window (`WindowMemoryError`, naming the chunks and the fix), instead of + on its first window; a window refused for its memory names the chunks too. + `tests/test_ome_zarr_chunks.py`. - **An entry output is reusable in a conda environment** (Spec ADR 0007 RE10). Conda installs `setuptools` as an `.egg-info` with no `RECORD`, and `brick_identity` followed every requirement of the brick, every extra included, down to it: every record written there was diff --git a/docs/contract.md b/docs/contract.md index b5279ced..c7cf69f6 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -435,7 +435,13 @@ It gives: decodes, hits, evictions and bytes held. The cache holds at most `cache_bytes` (a whole number above 0, below `memory_limit`; a piece larger is used once and not kept), counts in each window's memory estimate (a window whose own working memory and `cache_bytes` together are - over `memory_limit` is `WindowMemoryError`), and is safe to share between threads (a piece + over `memory_limit` is `WindowMemoryError`; an OME-Zarr image whose chunks are so large that + even a window of one pixel is over `memory_limit` with this cache is refused when the reader + is opened, `WindowMemoryError` naming the chunks and what to do, v0.10.1: a chunk is decoded + whole for any window; `check` and `run` warn about such an image first, + `chunks_too_large_for_windows`, from `window_chunks.check_window_chunks`, which counts a + cache of one chunk; `window_chunks.window_chunk_need(path, mapping)` gives that figure for a + consumer's own check), and is safe to share between threads (a piece asked by several at once is decoded once, and every thread that waited gets that decode, also when the piece is not kept; a kept piece is immutable, its bytes in a read-only buffer; the cache is per process, never shared). Pieces are kept under the image's path, the @@ -1525,7 +1531,7 @@ exclude=, missing_as_singleton=, memory_limit=, progress=)` (`conversion`), the | Repeat | A copy already in the tree is reused when its source (fingerprint and axes), roles, copy axes, pixel sizes, unknown sizes (roles and reasons), channel names, significant bits, the copy's fingerprint and the copy's SHA-256 (read whole) are as recorded; a new image is added; when every copy is reused the record is kept as it was (same SHA-256). Anything else (a source changed, other roles, a copy changed, an image no longer in the experiment, another experiment's copy tree, a file at a new image's place that the record does not list) is `copy_differs`: nothing is overwritten. A conversion record that cannot be read, or of another version than 4, is `conversion_record_unreadable`. | | Conversion record | `.morphobricks-conversion.json` in the copy tree's root (a dot-file, so discovery skips it), record version 4: `source_root`, `mapping`, `projection` (null, or `{method, z_range}`: the method and slice range of a tree of Z-projected copies, see "Projected copies" below), `missing_as_singleton`, `written_at`, `versions`, and per image `relative_path`, `action` (`converted` or `copied`), `reason` (the axis code, `excluded`, or null), `source` and `copy` fingerprints (`size`, `mtime_ns`), `copy_sha256` (the copy's SHA-256, computed in one pass after it is written; an OME-Zarr copy's is the SHA-256 of its files' relative paths and SHA-256s in path order, its `labels` group left out as for fingerprints: `content_hash`), `source_axes`, `roles`, `copy_axes`, `pixel_sizes` (by role, as §9), `unknown_sizes` (role: why), `channel_names` (as the copy holds them; `[]` for none), `significant_bits` (or null), `projection` (null, or the projected copy's provenance, below) and, only for an image converted or projected into an OME-Zarr copy, `source_relative_path` (below). Sources keep the fingerprint rule (design v0.4 §1); the copies' SHA-256 is the owner's decision of 2 November 2026 (plan §12 question 59 (16)). Version 2 (PP-11c) added `copy_sha256`, `channel_names` and `significant_bits`; version 3 (issue #176) added the record-level `projection` and the entry's `projection`, and the action `projected`; version 4 (owner decision of 12 November 2026, before v0.5.2) added the entry's `source_relative_path` of an OME-Zarr copy, which a version 3 reader would ignore, looking for the source at the copy's path and warning `conversion_source_changed`. Only version 4 is read (SWEEP-PP: no backward compatibility, Spec ADR 0002 AR10): a record of any other version, 1 to 3 included, is refused everywhere it is read (`convert`, the run's `review_conversion`, `RunInputs`), never converted, with a message to convert the originals again into a new folder. `read_conversion_record(folder)` reads it with its SHA-256. | | Projected copies (issue #176, record version 3 and later) | A tree made with a Z projection holds, for every image, a 2-D copy of its Z-stack made with the record-level `projection` `{method, z_range}` (`max`, `mean` or `sum`; there is no default method; `z_range` is `[start, stop]`, zero-based, stop excluded, the same for every image, or null for every slice). An entry has the action `projected` and a `projection` object with exactly: `source_relative_path`, `source_content_sha256` (the source's content as read while writing), `source_z_axis` (`{letter, index}` of the header's Z axis, or null for an image without one, which is one slice), `source_z_size`, `z_range` (the slices actually used), `method`, `source_dtype`, `output_dtype`, `dtype_rule`, `rounding` (`none`, `float64, one division` or `float64 addition, z ascending`), `nan_policy` (`propagate`), `dropped_sizes` (`{"Z": {value, unit, source}}`, or `{"Z": null}` when the source gave no Z size: the Z size is never written to the copy) and `significant_bits_dropped` (a reason, or null: kept for `max`, dropped for `sum` and `mean`). Excluded images stay plain copies (`copied`, reason `excluded`). The output type depends only on the input type, the method and the slice count (never on the data): `max` keeps the type; `sum` of `uint8`/`uint16` is `uint32`, of `int8`/`int16` is `int32`, of `uint32`/`int32` is `float64` holding the exact integer, of floats is `float64`; `mean` is `float64`; 64-bit integers are refused (`cannot_convert_pixel_type`). A sum or mean whose worst case (the type's extreme times the slices) could not be held exactly is refused (`projection_cannot_be_exact`), never wrapped or clipped. A NaN makes its pixel NaN, infinities are kept. The reader refuses an entry whose output type or rounding is not the table's for its method, a projected entry in a record without a projection (and the reverse), and a method or range that is not the record's. The reuse key holds the projection (everything of it except the content SHA-256, which the write computes), so another method or range into the same tree is `copy_differs`. Masks are never projected: `convert_experiment(..., projection=Projection(...), masks_folder=)` scans the masks folder from the headers only and refuses, before writing anything, masks of the images to project that have depth slices (`projection_masks_3d`) or more than Y and X with axes that are not named (`projection_masks_axes_unknown`); 2-D masks are left alone. The other refusals, all before anything is written: `nothing_to_project` (no image has a Z role), `projection_z_range_outside`, `projection_cannot_be_exact`, `cannot_convert_pixel_type`, `projection_over_memory_limit` (one input plane, the running plane and, when it is another type, the output plane must fit `memory_limit`) and `projection_zarr_not_supported` (OME-Zarr images are not projected yet). The copy's OME-XML holds an `Image/Description` with the method, slices, source, source SHA-256 and types, and a UUID derived from it, so one projection of one source is the same bytes; the source's content SHA-256 is taken before and after the projection and the source fingerprint before and after, and a source that changed is refused. A sum that overflows to infinity (`projection_overflow`) or adds an infinity to its opposite (`projection_undefined`) stops the conversion and is never written. Excluded images are copied byte for byte. | -| OME-Zarr copies (v0.5.2, record version 4) | `convert_experiment(..., store="ome-zarr")` (the notebook's **Also save a copy as OME-Zarr**; default `"ome-tiff"`) writes every image that is read as an OME-Zarr image instead of an OME-TIFF: also the images whose headers name their axes as confirmed, which are otherwise copied byte for byte. Excluded images and OME-Zarr images are copied byte for byte as before. With `projection` the projected copies are OME-Zarr. A copy is named after its image with `.ome.zarr` in place of the TIFF extension, in the same folder, so its position ID is the same; two images that would get one copy name are refused (`copy_names_collide`). In the record the entry's `relative_path` is the copy's path and `source_relative_path` (a key written only for such an entry: required there and refused on any other entry, so a source is never looked for at a copy's path; other entries are written as before) is the source's path relative to `source_root`; `significant_bits` is null (OME-NGFF 0.4 has no field for it). The store is OME-NGFF 0.4 (Zarr version 2), written directly: one array `0`, uncompressed, little-endian, one chunk per plane (the whole Y and X), metadata as sorted JSON, so one copy of one source is the same bytes. Each plane is the plane read under the confirmed roles, bit for bit; the axes are the roles (`t`, `c`, `z`, `y`, `x`) with the units of the copy's sizes, the level-0 `scale` holds the sizes and 1 for an unknown one, which is named under the multiscale's `metadata.unknown_scale` and so read as unknown; channel names are under `omero.channels[].label`, each channel with the `color` (`FFFFFF`) and `window` (the pixel type's whole range as `min`, `max`, `start`, `end`) that OME-NGFF 0.4 requires, display only and never read from the pixels; a projected copy's description is under `morphobricks.description`. Reading the copies needs the `zarr` extra, as for any OME-Zarr image. Plan, lock, `.partial` writes, reuse, the copy's SHA-256 and the checks of the run on the copies are those of the other copies. | +| OME-Zarr copies (v0.5.2, record version 4) | `convert_experiment(..., store="ome-zarr")` (the notebook's **Also save a copy as OME-Zarr**; default `"ome-tiff"`) writes every image that is read as an OME-Zarr image instead of an OME-TIFF: also the images whose headers name their axes as confirmed, which are otherwise copied byte for byte. Excluded images and OME-Zarr images are copied byte for byte as before. With `projection` the projected copies are OME-Zarr. A copy is named after its image with `.ome.zarr` in place of the TIFF extension, in the same folder, so its position ID is the same; two images that would get one copy name are refused (`copy_names_collide`). In the record the entry's `relative_path` is the copy's path and `source_relative_path` (a key written only for such an entry: required there and refused on any other entry, so a source is never looked for at a copy's path; other entries are written as before) is the source's path relative to `source_root`; `significant_bits` is null (OME-NGFF 0.4 has no field for it). The store is OME-NGFF 0.4 (Zarr version 2), written directly: one array `0`, uncompressed, little-endian, in chunks of one plane by at most 1024 x 1024 pixels along Y and X (`1 x ... x min(Y, 1024) x min(X, 1024)`; v0.10.1, one chunk per plane before: see `chunks_too_large_for_windows`), written block by block as the planes are read, each edge chunk at full size with zeros (the `fill_value`) outside the image, one level only (no pyramid), metadata as sorted JSON, so one copy of one source is the same bytes. Each plane is the plane read under the confirmed roles, bit for bit; the axes are the roles (`t`, `c`, `z`, `y`, `x`) with the units of the copy's sizes, the level-0 `scale` holds the sizes and 1 for an unknown one, which is named under the multiscale's `metadata.unknown_scale` and so read as unknown; channel names are under `omero.channels[].label`, each channel with the `color` (`FFFFFF`) and `window` (the pixel type's whole range as `min`, `max`, `start`, `end`) that OME-NGFF 0.4 requires, display only and never read from the pixels; a projected copy's description is under `morphobricks.description`. Reading the copies needs the `zarr` extra, as for any OME-Zarr image. Plan, lock, `.partial` writes, reuse, the copy's SHA-256 and the checks of the run on the copies are those of the other copies. | | The run on the copies | The user runs preprocessing on the copy tree with the same output folder (`--output`): the recorded experiment root becomes the copy tree and the report says so (`experiment_root_changed`, and `conversion` with the record, its SHA-256 and `source_root`; the text says "named-axis copies of ..."); every row is recomputed (the row key includes the read path, §9); the design, image type and calibration are kept (same relative paths). The manifest records `conversion_record_sha256`, and for projected copies the `projection` summary (§9); the report says "max projections of slices 1:4 (2 images) of " (and `conversion.projection` in `discovery_report.json`). Masks are paired as usual (the image has no Z now, so 2-D masks fit; a mask with depth slices stays `mask_planes_mismatch` and stops the run), and the run warns `masks_on_projected_images`, naming the method, for masks paired with projections, in the report and the manifest's `projection.warnings`. The run and `check` warn when a source changed or went missing after the conversion (`conversion_source_changed`) and refuse a copy that changed (its fingerprint or its SHA-256: each copy is read whole, so `check` and `run` on a copy tree cost one more read of the copies), went missing or was added since (`copy_changed_after_conversion`: an error since PP-12, owner decision of 2 November 2026; the run stops after the header checks, before any pixel is read, writing only its report, since `RunInputs` would refuse the run; the message says to convert the originals again into a new folder); an unreadable record stops the run (`conversion_record_unreadable`). `check` and `run` also read the OME `Image/Description` header (first page's description tag only, no pixels) of every analysed TIFF the record does not list as `projected`: a description that begins "MorphoBricks Z projection:" in a tree with no record, or whose record does not list the image as projected, is refused as `projection_record_missing` (owner decision of 8 November 2026; plain images are unaffected). `RunInputs` reads the copies like any images, and refuses a run whose conversion record changed or went missing since (`conversion_record_sha256`), is of version 1, or whose recorded images' copies no longer have the recorded fingerprint and SHA-256 (§9.1). | | Notebook (PP-11b) | Step 2's **Make named-axis copies (optional)** card, under the axis check, shown only when it reports images with `axes_yx_swapped`, `axes_contradict_header`, `axes_x_before_y` or `axes_not_named` for the roles being edited (design v0.4 §5: offered only for files with errors), and not with `folder_step(show_output=False)`. The roles are the user's: those confirmed in step 2, or the roles shown once the preview is checked and the card's own question is answered; any change of a role or of the missing-axes answer takes it back. A required folder for the copies (Browse…, or pasted) checked with the command's rule (`copy_folder_issues`); `preview_conversion` (`conversion_plan`, headers only, writes nothing) gives what will be converted and copied byte for byte (the command's `plan_conversion`), the space needed and the free space; then `convert_experiment` with a progress bar, under the copy tree's lock. Refusals use the existing cards (the lock card with **Remove the lock of a stopped run**, the rule of `--remove-stale-lock`). After the copies: the record's path, and **Check the copies in step 1**, which sets the experiment folder to the copy tree, keeps the output folder and checks again; the card says that the missing-axes answer must be given again and lists the copies whose relabelled sizes are unknown (`ConversionResult.unknown_sizes`), to state under **Pixel sizes**. | diff --git a/docs/user_guide.md b/docs/user_guide.md index 5e8341cc..46c971e3 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -1256,6 +1256,11 @@ no field for colour, so the copies cannot say RGB themselves: describe them with `--image-type rgb --channels R,G,B`, and `check` and `run` then suggest the image type `rgb` from the published description (no `--image-type rgb` needed). Reading OME-Zarr copies needs the `zarr` extra; writing them does not. `--project` writes OME-Zarr projections the same way. +The copies are stored in chunks of one plane by at most 1024 x 1024 pixels (since v0.10.1; +before, one chunk per plane), so a later brick can read a large slide in windows; `check` +warns about an OME-Zarr image whose chunks are too large for that +(`chunks_too_large_for_windows`). Copies written before v0.10.1 are not rewritten by a new +conversion into the same folder: convert into a new folder. ```bash morphobricks-preprocessing convert /data/he --to /data/he_zarr --axes YXC --store ome-zarr @@ -1830,6 +1835,7 @@ continues. | `image_named_as_mask` | Error | An image is named like a mask of another image (`f1_mask.tif` beside `f1.tif`; the endings `_mask`, `_masks`, `_cp_masks`, `_labels`, `_label`, `_seg`, `_segmentation`), and a mask is never analysed as an image. If it is a mask, move it into a masks folder outside the experiment, or exclude it; if it is an image, rename it. | | `mask_folder_in_experiment` | Warning | A folder inside the experiment is named like a masks folder (`masks`, `ctrl_masks`, `CellLabels`) and holds files named like masks of the images; they would be analysed as images. Move it out of the experiment and give it as the masks folder, or rename it if these are images. | | `planes_read_in_blocks` | Warning | Planes too large to measure whole within the memory limit are read and measured in blocks. The figure is the run's own need: one channel read and its histogram computed at once (mostly the histogram's working arrays). Reading every channel of a plane without a histogram, as `RunInputs.read_plane` and later bricks do, needs another amount (`xyc_plane_memory`), checked when they read; for a 30720 x 36864 x 3 `uint16` OME-Zarr mosaic about 38.0 GiB here and 14.8 GiB there. The results are the same; nothing to do. Raise the limit to read them whole, which is faster. | +| `chunks_too_large_for_windows` | Warning | `check` and `run`: an OME-Zarr image is stored in chunks so large that a later brick reading it in windows (a patch-window route, through `RunInputs.window_reader`) cannot read even one window within the memory limit: a chunk is decoded whole for any window it holds, so a store in one chunk per plane is decoded whole for every window. Preprocessing itself reads it (in blocks). The same image is refused when a window reader is opened on it, with the same advice. If it is an OME-Zarr copy written by `convert --store ome-zarr` or the notebook before v0.10.1 (one chunk per plane), convert the original images again into a new folder (copies are now written in chunks of 1024 x 1024 pixels); otherwise save it again with chunks of at most 1024 x 1024 pixels along Y and X. | | `different_sizes` | Warning | Images have different widths or heights. Usually expected; otherwise check the camera settings. For a plain stack (no axes in its file), the sizes are compared once you confirm its axis roles, with those roles. | | `different_plane_counts` | Warning | Images have different numbers of depth slices, time points or other planes. Images with more planes weigh more in pooled statistics. Check the acquisition if this is not expected. For a plain stack, compared with its confirmed axis roles, as `different_sizes`. | | `different_pixel_sizes` | Warning | The physical pixel size or z-step (from the metadata or `calibration.csv`) differs between images by more than 0.1 % (for example different objectives). Images outside the largest group of matching sizes are listed; when sizes only change by small steps from image to image, none is listed. Check the microscope settings if this is not intended. | diff --git a/pyproject.toml b/pyproject.toml index 5f26ec6d..c8057452 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -477,6 +477,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.codec_bounds" = "io" "morphobricks_preprocessing.window_memory" = "pure" "morphobricks_preprocessing.window_reader" = "io" +"morphobricks_preprocessing.window_chunks" = "io" "morphobricks_preprocessing.block_cache" = "pure" "morphobricks_preprocessing.window_map" = "orchestration" "morphobricks_preprocessing.report" = "pure" diff --git a/src/morphobricks_preprocessing/cli.py b/src/morphobricks_preprocessing/cli.py index 4db3a546..6ff42a8e 100644 --- a/src/morphobricks_preprocessing/cli.py +++ b/src/morphobricks_preprocessing/cli.py @@ -41,6 +41,7 @@ from collections.abc import Sequence from pathlib import Path +from .axes import AxisReview from .cli_calibrate import add_calibrate_parser, calibrate_command, calibration_summary from .cli_convert import add_convert_parser, convert_command from .cli_convert_mask import add_convert_mask_parser, convert_mask_command @@ -85,6 +86,7 @@ from .run.description_run import load_description from .run.preflight import Preflight from .validation import ValidationIssue +from .window_chunks import check_window_chunks __all__ = ["build_parser", "main", "parse_size"] @@ -265,6 +267,18 @@ def _remove_stale_lock(args: argparse.Namespace) -> bool: return True +def _window_chunks(pre: Preflight, review: AxisReview) -> list[ValidationIssue]: + """Print and return the warning naming OME-Zarr chunks too large for windows (v0.10.1). + + Named by ``check``, before a later brick's windowed reads refuse them. + """ + chunks = check_window_chunks(pre.discovery.root, review) + if chunks: + print() + print(format_issues(chunks)) + return chunks + + def _check(args: argparse.Namespace) -> int: """Print what the preflight found and the suggested roles, and write the report.""" refusal = description_refusal(args) @@ -296,6 +310,7 @@ def _check(args: argparse.Namespace) -> int: print() print(format_issues(undeclared)) axis_errors = () + chunks: list[ValidationIssue] = [] if review is not None: # The suggested roles are the header's own, so they never contradict it; 'run' # checks the roles given with --axes. @@ -308,6 +323,7 @@ def _check(args: argparse.Namespace) -> int: if review.axis_check: print() print(format_issues(review.axis_check)) + chunks = _window_chunks(pre, review) print() # Suggested only where an image lacks some of the axes and is read with one plane. lacking = any(found.singleton_roles for found in review.file_mappings.values()) @@ -321,7 +337,7 @@ def _check(args: argparse.Namespace) -> int: f"Suggested image type: {type_review.suggested}, because {type_review.reason}. " "'run' uses it unless you give --image-type." ) - path, refusal = write_check_report(pre, args.output, review, extra=undeclared) + path, refusal = write_check_report(pre, args.output, review, extra=[*undeclared, *chunks]) print() print(format_issues([refusal]) if refusal else f"Report written to {path}" if path else "") blocked = not pre.ok or axis_errors or undeclared or refusal is not None diff --git a/src/morphobricks_preprocessing/ome_zarr_copy.py b/src/morphobricks_preprocessing/ome_zarr_copy.py index 0c5e2a6a..3b1447b3 100644 --- a/src/morphobricks_preprocessing/ome_zarr_copy.py +++ b/src/morphobricks_preprocessing/ome_zarr_copy.py @@ -8,8 +8,15 @@ The store is written directly (no ``zarr`` package is needed to write it; reading it needs the ``zarr`` extra, as for any OME-Zarr image): a Zarr version 2 group with one array ``0``, -uncompressed, one chunk per plane (the whole Y and X), little-endian, so every plane has a -fixed file and the same copy is the same bytes. Each plane is the plane read under the +uncompressed, little-endian, in chunks of one plane by at most :data:`CHUNK_SIDE` rows and +columns (``1 x ... x 1024 x 1024``, :func:`chunk_shape`), so every chunk has a fixed file and +the same copy is the same bytes. Spatial chunks let a later brick read a window of a large +image by decoding only the chunks under it (:mod:`.window_reader`): a whole plane in one chunk +had to be decoded whole for every window, which no memory limit could serve on a slide +(v0.10.1). Each plane is written as it is read, block by block (:meth:`.planes.Plane.blocks`, +within the memory limit), each block's part of each chunk written in place: a plane is never +held whole unless it is read whole. One level only (no pyramid): the brick reads level 0 alone +(:data:`.windows.LEVEL`). Each plane is the plane read under the confirmed roles, bit for bit; a projected copy's planes are computed as in :func:`.ome_tiff_copy.write_projected_copy`. The metadata follow the copy's layout (:class:`.copy_axes.CopyLayout`): the axes by role with their units, the level-0 ``scale`` from @@ -31,6 +38,7 @@ import os from dataclasses import replace from pathlib import Path +from typing import BinaryIO import numpy as np @@ -53,6 +61,12 @@ NGFF_VERSION = "0.4" _AXIS_TYPES = {"T": "time", "C": "channel", "Z": "space", "Y": "space", "X": "space"} BITS_NOT_WRITTEN = "OME-NGFF 0.4 has no field for significant bits" +CHUNK_SIDE = 1024 +"""The largest chunk along Y and along X of an OME-Zarr copy (one plane along every other axis). + +1024 x 1024 is bioformats2raw's default and common practice for OME-NGFF 0.4 images: 1 MiB +(``uint8``) to 8 MiB (``float64``) per chunk, so a window reader decodes a few MiB per chunk it +touches, while a slide of 100,000 x 100,000 pixels has about 10,000 chunk files per plane.""" OMERO_COLOUR = "FFFFFF" """The ``color`` of every ``omero`` channel (required by OME-NGFF 0.4; display only).""" @@ -141,6 +155,12 @@ def _json(path: Path, data: dict) -> None: path.write_bytes(text.encode("utf-8")) +def chunk_shape(shape: tuple[int, ...]) -> tuple[int, ...]: + """Return the chunks of a copy of ``shape``: 1 along each leading axis, at most 1024 in Y, X.""" + *leading, rows, cols = shape + return (*([1] * len(leading)), min(rows, CHUNK_SIDE), min(cols, CHUNK_SIDE)) + + def _lay_out(target: Path, layout: CopyLayout, dtype: np.dtype, description: str | None) -> Path: """Write the store's metadata and return the folder of the array's chunks.""" target.mkdir(parents=True) @@ -148,14 +168,13 @@ def _lay_out(target: Path, layout: CopyLayout, dtype: np.dtype, description: str array.mkdir() _json(target / ".zgroup", {"zarr_format": 2}) _json(target / ".zattrs", _metadata(layout, dtype, description)) - rows, cols = layout.plane_shape stored = dtype.newbyteorder("<") if dtype.itemsize > 1 else dtype _json( array / ".zarray", { "zarr_format": 2, "shape": list(layout.shape), - "chunks": [*([1] * (len(layout.shape) - 2)), rows, cols], + "chunks": list(chunk_shape(layout.shape)), "dtype": stored.str, "compressor": None, "filters": None, @@ -167,11 +186,68 @@ def _lay_out(target: Path, layout: CopyLayout, dtype: np.dtype, description: str return array -def _chunk_path(array: Path, position: tuple[int, ...]) -> Path: - """Return the file of the plane at ``position`` (its leading indices), making its folder.""" - path = array.joinpath(*(str(i) for i in position), "0", "0") - path.parent.mkdir(parents=True, exist_ok=True) - return path +class _PlaneChunks: + """The chunk files of one plane, written in place block by block (never the whole plane). + + Each chunk file is created at its full size (an edge chunk too, as Zarr version 2 stores + it, its outside zero, the ``fill_value``) the first time a block reaches it; each block's + part of it is written at its place. Files of the chunk rows a block no longer reaches are + closed, so a plane read in bands holds about two rows of chunk files open at once. + """ + + def __init__( + self, array: Path, position: tuple[int, ...], chunks: tuple[int, int], dtype: np.dtype + ) -> None: + self.folder = array.joinpath(*(str(i) for i in position)) + self.chunks, self.itemsize = chunks, dtype.itemsize + self.open: dict[tuple[int, int], BinaryIO] = {} + self.made: set[tuple[int, int]] = set() + + def _file(self, key: tuple[int, int]) -> BinaryIO: + """Return the open file of the chunk at ``key`` (its grid row and column).""" + stream = self.open.get(key) + if stream is not None: + return stream + path = self.folder / str(key[0]) / str(key[1]) + if key in self.made: + stream = open(path, "r+b") + else: + path.parent.mkdir(parents=True, exist_ok=True) + stream = open(path, "w+b") + stream.truncate(self.chunks[0] * self.chunks[1] * self.itemsize) + self.made.add(key) + self.open[key] = stream + return stream + + def _drop(self, below: int) -> None: + """Close the files of the chunk rows above grid row ``below``.""" + for key in [key for key in self.open if key[0] < below]: + self.open.pop(key).close() + + def write(self, y: int, x: int, pixels: np.ndarray) -> None: + """Write the stored values ``pixels`` (little-endian) at row ``y`` and column ``x``.""" + ch, cw = self.chunks + height, width = pixels.shape + self._drop(y // ch) + for gy in range(y // ch, -(-(y + height) // ch)): + a, b = max(y, gy * ch), min(y + height, (gy + 1) * ch) + for gx in range(x // cw, -(-(x + width) // cw)): + c, d = max(x, gx * cw), min(x + width, (gx + 1) * cw) + part = pixels[a - y : b - y, c - x : d - x] + stream = self._file((gy, gx)) + start = ((a - gy * ch) * cw + (c - gx * cw)) * self.itemsize + if d - c == cw: # whole chunk rows: one contiguous run of the file + stream.seek(start) + stream.write(memoryview(np.ascontiguousarray(part)).cast("B")) + continue + for r in range(b - a): + stream.seek(start + r * cw * self.itemsize) + stream.write(memoryview(np.ascontiguousarray(part[r])).cast("B")) + + def close(self) -> None: + """Close every chunk file still open.""" + while self.open: + self.open.popitem()[1].close() def _little(pixels: np.ndarray, dtype: np.dtype) -> np.ndarray: @@ -219,18 +295,16 @@ def write_named_zarr( """ dtype = np.dtype(dtype) array = _lay_out(Path(target), layout, dtype, layout.description) - rows, cols = layout.plane_shape + chunks = chunk_shape(layout.shape)[-2:] roles = [role.lower() for role in layout.axes[:-2]] - row_nbytes = cols * dtype.itemsize for plane in iter_planes(source, mapping, memory_limit=memory_limit): position = tuple(int(plane.coordinates[role]) for role in roles) - with open(_chunk_path(array, position), "wb") as stream: - stream.truncate(rows * row_nbytes) + files = _PlaneChunks(array, position, chunks, dtype) + try: for block in plane.blocks(): - pixels = _little(block.pixels, dtype) - for r in range(pixels.shape[0]): - stream.seek((block.y + r) * row_nbytes + block.x * dtype.itemsize) - stream.write(memoryview(pixels[r]).cast("B")) + files.write(block.y, block.x, _little(block.pixels, dtype)) + finally: + files.close() def write_projected_zarr( @@ -256,6 +330,7 @@ def write_projected_zarr( start, stop = details.z_range out = np.dtype(details.output_dtype) array = _lay_out(Path(target), layout, out, projection_description(details)) + chunks = chunk_shape(layout.shape)[-2:] roles = [role.lower() for role in layout.axes[:-2]] has_z = mapping.index_of("Z") is not None for position in np.ndindex(*layout.shape[:-2]): @@ -275,12 +350,16 @@ def write_projected_zarr( if plane.pixels is None: raise CopyWriteError(f"a plane of {source} does not fit the memory limit") running.add(plane.pixels) - pixels = _little(running.result(), out) - _chunk_path(array, tuple(int(i) for i in position)).write_bytes(pixels.tobytes()) + files = _PlaneChunks(array, tuple(int(i) for i in position), chunks, out) + try: + files.write(0, 0, _little(running.result(), out)) + finally: + files.close() __all__ = [ "BITS_NOT_WRITTEN", + "CHUNK_SIDE", "NGFF_VERSION", "OMERO_COLOUR", "OME_TIFF", @@ -288,6 +367,7 @@ def write_projected_zarr( "STORES", "ZARR_COPY_SUFFIX", "as_zarr_copy", + "chunk_shape", "write_named_zarr", "write_projected_zarr", "zarr_copy_name", diff --git a/src/morphobricks_preprocessing/run/steps.py b/src/morphobricks_preprocessing/run/steps.py index e5667a47..0978a5d3 100644 --- a/src/morphobricks_preprocessing/run/steps.py +++ b/src/morphobricks_preprocessing/run/steps.py @@ -28,6 +28,7 @@ from ..planes import check_planes from ..source_content import with_content from ..validation import ValidationIssue, error, has_errors, plural +from ..window_chunks import check_window_chunks from .entries import Comparison, compare_with_previous, file_entries from .modes import FULL from .phases import CONTENTS @@ -142,6 +143,8 @@ def header_checks( histogram_settings=inputs.histogram_settings, ) ) + # Chunks too large for a later brick's windows are named before the run (v0.10.1). + issues.extend(check_window_chunks(root, review, memory_limit=memory_limit)) return Checked(review, type_review, design, issues, bins) diff --git a/src/morphobricks_preprocessing/window_chunks.py b/src/morphobricks_preprocessing/window_chunks.py new file mode 100644 index 00000000..0d77c309 --- /dev/null +++ b/src/morphobricks_preprocessing/window_chunks.py @@ -0,0 +1,108 @@ +"""Name, before a run, the OME-Zarr images whose chunks are too large for windowed reads (v0.10.1). + +A later brick reads a large image in windows through ``RunInputs.window_reader`` +(:mod:`.window_reader`), which decodes every OME-Zarr chunk a window touches whole and keeps +the chunks it decoded in a cache. A store in one chunk per plane (as ``convert --store +ome-zarr`` wrote before v0.10.1) is read whole for every window: preprocessing itself reads it +fine (its planes in blocks of rows), so nothing failed before the later brick's first window. + +:func:`check_window_chunks` works out from the headers the least a window reader needs for any +window of each OME-Zarr image (:func:`.windows.smallest_window_memory`: a window of one pixel, +read through a cache that holds one chunk, the least that keeps a chunk for the next window) +and warns, ``chunks_too_large_for_windows``, when it is over the memory limit. The reader +refuses the same store when it is opened with a cache that leaves no room for it +(:class:`.window_reader.WindowReader`), with the same advice (:data:`.windows.CHUNK_FIX`). +TIFF images are not checked here: their strips and tiles have their own refusals +(``plane_over_memory_limit``, issue #356). +""" + +from __future__ import annotations + +import logging +import os +from collections.abc import Mapping +from pathlib import Path + +from .axes import AxisMapping, AxisReview +from .plane_errors import PlaneReadError +from .planes import DEFAULT_MEMORY_LIMIT, format_bytes +from .validation import ValidationIssue, plural, warning +from .windows import CHUNK_FIX, _source, smallest_window_memory +from .zarr_input import is_zarr_store + +logger = logging.getLogger(__name__) + +CODE = "chunks_too_large_for_windows" + + +def window_chunk_need( + path: str | os.PathLike, mapping: AxisMapping, memory_limit: int = DEFAULT_MEMORY_LIMIT +) -> int | None: + """Return the least working memory of a window read of an OME-Zarr image, from its header. + + A window of one pixel through a window reader whose cache holds one chunk; None for a + TIFF image. + + Raises + ------ + PlaneReadError + If the image cannot be read under ``mapping``. + """ + if not is_zarr_store(path): + return None + with _source(path, mapping, memory_limit) as source: + return smallest_window_memory(source, source.layout.blocking.piece_nbytes) + + +def check_window_chunks( + experiment_root: str | os.PathLike, + review: AxisReview | Mapping[str, AxisMapping], + *, + memory_limit: int = DEFAULT_MEMORY_LIMIT, +) -> list[ValidationIssue]: + """Warn about OME-Zarr images that no window reader can read within ``memory_limit``. + + Parameters + ---------- + experiment_root + The experiment folder. + review + The axis review, or its per-file mappings keyed by relative path. + memory_limit + The working-memory limit of one read, in bytes. + + Returns + ------- + list of ValidationIssue + One warning, ``chunks_too_large_for_windows``, naming the images, or nothing. An image + that cannot be read under its mapping is left to :func:`.planes.check_planes`. + """ + mappings = review.file_mappings if isinstance(review, AxisReview) else review + root = Path(experiment_root) + found: list[tuple[str, int]] = [] + for rel in sorted(mappings): + try: + need = window_chunk_need(root / rel, mappings[rel], memory_limit) + except PlaneReadError: + logger.debug("Cannot plan windows of %s", rel, exc_info=True) + continue + if need is not None and need > memory_limit: + found.append((rel, need)) + if not found: + return [] + largest = max(need for _, need in found) + return [ + warning( + CODE, + f"{plural(len(found), 'OME-Zarr image')} cannot be read in windows within the memory " + f"limit of {format_bytes(memory_limit)}: the chunks are so large that even a window " + f"of one pixel needs up to {format_bytes(largest)} (a chunk is decoded whole). " + "Preprocessing reads them, but a later brick that reads windows (a patch-window " + "route) will refuse them.", + [rel for rel, _ in found], + CHUNK_FIX, + ) + ] + + +__all__ = ["CODE", "check_window_chunks", "window_chunk_need"] diff --git a/src/morphobricks_preprocessing/window_reader.py b/src/morphobricks_preprocessing/window_reader.py index 84328323..cc782646 100644 --- a/src/morphobricks_preprocessing/window_reader.py +++ b/src/morphobricks_preprocessing/window_reader.py @@ -57,8 +57,10 @@ _Source, _source, check_level, + chunk_note, plane_position, ) +from .zarr_input import is_zarr_store @dataclass(frozen=True) @@ -162,7 +164,10 @@ class WindowReader: ValueError If ``cache_bytes`` is not a whole number above 0. WindowMemoryError - If ``cache_bytes`` leaves no room under ``memory_limit``. + If ``cache_bytes`` leaves no room under ``memory_limit``, or for an OME-Zarr image + whose chunks are too large for even a window of one pixel to be read within + ``memory_limit`` with this cache (:func:`.windows.chunk_note`: a store written in one + chunk per plane; the message names the chunks and what to do). WindowSourceChangedError If the image is missing, or its fingerprint is not ``fingerprint``. """ @@ -188,6 +193,8 @@ def __init__( self.fingerprint = self._now() if fingerprint is None else fingerprint self._check() self._identity = os.path.realpath(self.path) + if is_zarr_store(self.path): + self._check_chunks() def window_plan( self, @@ -300,6 +307,25 @@ def __exit__(self, *exc_info: object) -> None: """Close the reader (:meth:`close`).""" self.close() + def _check_chunks(self) -> None: + """Refuse an OME-Zarr image no window of which fits the limit with this cache. + + From the header: a chunk is decoded whole for any window, so a store in chunks too + large (one chunk per plane of a slide) is refused when the reader is opened, naming its + chunks and what to do, rather than on its first window. + """ + with _source(self.path, self.mapping, self.memory_limit) as source: + note = chunk_note( + source, self.path, self.memory_limit, cache_bytes=self.cache.max_bytes + ) + if note: + self.close() + raise WindowMemoryError( + f"No window of {self.path.name} can be read within the memory limit of " + f"{format_bytes(self.memory_limit)} with a window cache of " + f"{format_bytes(self.cache.max_bytes)}." + note + ) + def _check_open(self) -> None: """Refuse a window asked after :meth:`close`.""" if self._closed: @@ -325,7 +351,10 @@ def _plan( plan = _plan(source, bounds, channels, self.memory_limit, position) plan = _with_cache(plan, self.cache.max_bytes) if plan.memory_estimate > self.memory_limit: - raise WindowMemoryError(_memory_text(plan, self.path) + _CACHE_NOTE) + note = chunk_note( + source, self.path, self.memory_limit, cache_bytes=self.cache.max_bytes + ) + raise WindowMemoryError(_memory_text(plan, self.path) + _CACHE_NOTE + note) return plan def _cached(self, key: Hashable, decode: Callable[[], np.ndarray | None]) -> np.ndarray | None: diff --git a/src/morphobricks_preprocessing/windows.py b/src/morphobricks_preprocessing/windows.py index 2909473f..de01af4d 100644 --- a/src/morphobricks_preprocessing/windows.py +++ b/src/morphobricks_preprocessing/windows.py @@ -316,7 +316,9 @@ def _read_source( position = _position(source.layout, mapping, {"Z": z, "T": t}) plan = _plan(source, bounds, channels, memory_limit, position) if plan.memory_estimate > memory_limit: - raise WindowMemoryError(_memory_text(plan, path)) + raise WindowMemoryError( + _memory_text(plan, path) + chunk_note(source, path, memory_limit, cache_bytes=0) + ) rows_are_y = source.layout.blocking.rows_are_y y0, y1, x0, x1 = plan.bounds box = (y0, y1, x0, x1) if rows_are_y else (x0, x1, y0, y1) @@ -521,3 +523,48 @@ def _memory_text(plan: WindowPlan, path: str | os.PathLike) -> str: f"{format_bytes(plan.memory_limit)}. Ask for a smaller window or fewer channels, or " "raise the memory limit if this computer has enough memory." ) + + +CHUNK_FIX = ( + "If it is an OME-Zarr copy written by 'convert --store ome-zarr' or the notebook before " + "v0.10.1 (one chunk per plane), convert the original images again into a new folder: " + "copies are now written in chunks of 1024 x 1024 pixels. Otherwise save the image again " + "with chunks of at most 1024 x 1024 pixels along Y and X (one plane along the other axes)." +) +"""What to do about an OME-Zarr image whose chunks are too large for windowed reads.""" + + +def smallest_window_memory(source: _Source, cache_bytes: int = 0) -> int: + """Return the working memory of the smallest window read of an open image, from its header. + + A window of one pixel of one channel, read without a cache (``cache_bytes`` 0) or through a + reader whose cache holds ``cache_bytes`` (counted in the figure, as a reader's plan counts + it). An OME-Zarr chunk is decoded whole however small the window, so for a store in one + chunk per plane this is several times the plane: no window of it can be read in less. + """ + plan = _plan(replace(source, cached=cache_bytes > 0), (0, 1, 0, 1), (0,), 0) + return plan.memory_estimate + cache_bytes + + +def chunk_note( + source: _Source, path: str | os.PathLike, memory_limit: int, *, cache_bytes: int +) -> str: + """Return the sentences naming chunks too large for any window within the limit, or "". + + Only for OME-Zarr images (TIFF pieces are bounded by their own refusals, issue #356): + when even a window of one pixel (:func:`smallest_window_memory`, with ``cache_bytes``) is + over ``memory_limit``, no smaller window helps, and the chunks are what to change. + """ + blocking = source.layout.blocking + if blocking.kind != "zarr": + return "" + need = smallest_window_memory(source, cache_bytes) + if need <= memory_limit: + return "" + rows, cols = blocking.unit + return ( + f" {Path(path).name} is stored in chunks of {rows} x {cols} pixels " + f"({format_bytes(blocking.piece_nbytes)} each), and a chunk is decoded whole for any " + f"window it holds: even a window of one pixel needs about {format_bytes(need)}. " + + CHUNK_FIX + ) diff --git a/tests/test_ome_zarr_chunks.py b/tests/test_ome_zarr_chunks.py new file mode 100644 index 00000000..c0d2d080 --- /dev/null +++ b/tests/test_ome_zarr_chunks.py @@ -0,0 +1,170 @@ +"""OME-Zarr copies in spatial chunks, readable in windows (v0.10.1). + +``convert --store ome-zarr`` wrote each plane as one chunk, so a later brick's windowed route +(``RunInputs.window_reader``) decoded the whole plane for every window and refused the first +patch of a slide (``WindowMemoryError``) after ``check`` had passed. Copies are now written in +chunks of one plane by at most 1024 x 1024 pixels, block by block; ``check`` warns about a +store whose chunks no window reader can serve (``chunks_too_large_for_windows``), and the +reader refuses it when opened, with the same advice. The TIFF slides are written lazily, tile +by tile, and the large single-chunk stores hold metadata only. +""" + +from __future__ import annotations + +import json +import tracemalloc + +import numpy as np +import pytest +import tifffile + +pytest.importorskip("zarr") + +from morphobricks_preprocessing.axes import AxisMapping, prefill_mapping # noqa: E402 +from morphobricks_preprocessing.cli import main # noqa: E402 +from morphobricks_preprocessing.conversion import convert_experiment # noqa: E402 +from morphobricks_preprocessing.ome_zarr_copy import CHUNK_SIDE, chunk_shape # noqa: E402 +from morphobricks_preprocessing.window_chunks import ( # noqa: E402 + CODE, + check_window_chunks, + window_chunk_need, +) +from morphobricks_preprocessing.window_reader import WindowReader, cache_plan # noqa: E402 +from morphobricks_preprocessing.windows import WindowMemoryError, read_window # noqa: E402 +from zarr_tree import Unwritten, write_ngff # noqa: E402 + +C, Y, X, TILE = 2, 3000, 2600, 256 +PLANE = Y * X * 2 # one channel, uint16 +REL = "ctrl/rep1/slide.tif" +COPY = "ctrl/rep1/slide.ome.zarr" +MAPPING = AxisMapping("CYX", ("C", "Y", "X")) +MIB = 2**20 + + +def pixels(c, y0, y1, x0, x1): + """Return the slide's values in a box: a pattern, so every pixel's place is checked.""" + y, x = np.ogrid[y0:y1, x0:x1] + return ((c * 7919 + y * 31 + x * 17) % 65521).astype(np.uint16) + + +def write_slide(path): + """Write the slide tile by tile (never whole in memory), as a scanner's tiled TIFF.""" + + def tiles(): + for c in range(C): + for y in range(0, Y, TILE): + for x in range(0, X, TILE): + tile = np.zeros((TILE, TILE), np.uint16) # edge tiles are padded + part = pixels(c, y, min(y + TILE, Y), x, min(x + TILE, X)) + tile[: part.shape[0], : part.shape[1]] = part + yield tile + + path.parent.mkdir(parents=True, exist_ok=True) + tifffile.imwrite( + path, + tiles(), + shape=(C, Y, X), + dtype=np.uint16, + tile=(TILE, TILE), + photometric="minisblack", + metadata={"axes": "CYX"}, + ) + + +@pytest.fixture(scope="module") +def converted(tmp_path_factory): + tmp = tmp_path_factory.mktemp("slide") + root, dest = tmp / "exp", tmp / "copies" + write_slide(root / REL) + tracemalloc.start() + try: + result = convert_experiment( + root, prefill_mapping("CYX"), dest, store="ome-zarr", memory_limit=8 * MIB + ) + peak = tracemalloc.get_traced_memory()[1] + finally: + tracemalloc.stop() + assert result.written and list(result.converted) == [COPY] + assert [i.code for i in result.issues] == ["planes_read_in_blocks"] + return dest, peak + + +def test_the_copy_is_written_in_1024_px_chunks_one_plane_deep(converted): + dest, _ = converted + store = dest / COPY + array = json.loads((store / "0/.zarray").read_text(encoding="utf-8")) + assert array["shape"] == [C, Y, X] + assert array["chunks"] == [1, CHUNK_SIDE, CHUNK_SIDE] == list(chunk_shape((C, Y, X))) + # 3 x 3 chunk files per channel, each full size (an edge chunk too, as Zarr 2 stores it) + found = (store / "0").rglob("[0-9]") + files = sorted(p.relative_to(store / "0").as_posix() for p in found if p.is_file()) + assert files == [f"{c}/{r}/{k}" for c in range(C) for r in range(3) for k in range(3)] + assert {(store / "0" / f).stat().st_size for f in files} == {CHUNK_SIDE * CHUNK_SIDE * 2} + + +def test_the_copy_holds_every_pixel_and_was_never_held_whole(converted): + import zarr + + dest, peak = converted + data = zarr.open(str(dest / COPY / "0"), mode="r") + for c in range(C): + assert np.array_equal(data[c], pixels(c, 0, Y, 0, X)) + assert peak < PLANE / 2 # written block by block: never one plane, let alone the image + + +def test_a_small_plane_is_one_chunk_no_larger_than_itself(): + assert chunk_shape((3, 4, 16, 20)) == (1, 1, 16, 20) + assert chunk_shape((5000, 700)) == (1024, 700) + + +def test_a_window_of_the_copy_is_read_within_the_memory_limit(converted): + dest, _ = converted + path, limit = dest / COPY, 64 * MIB + assert window_chunk_need(path, MAPPING, limit) < limit + assert check_window_chunks(dest, {COPY: MAPPING}, memory_limit=limit) == [] + plan = cache_plan(path, MAPPING, window=(512, 512), margin=(32, 32), channels=[0, 1]) + with WindowReader(path, MAPPING, cache_bytes=plan.cache_bytes, memory_limit=limit) as reader: + bounds = (900, 1700, 1000, 1800) # across four chunks + window = reader.read_window(bounds=bounds, channels=[1, 0]) + assert reader.window_plan(bounds=bounds, channels=[1, 0]).memory_estimate <= limit + expected = np.stack([pixels(c, 900, 1700, 1000, 1800) for c in (1, 0)]) + assert np.array_equal(window, expected) + + +def test_the_same_image_in_one_chunk_per_plane_is_named_and_refused(tmp_path): + # The copy as v0.10.1 wrote it before the fix: the same pixels, one chunk per plane. + data = np.stack([pixels(c, 0, Y, 0, X) for c in range(C)]) + root, rel, limit = tmp_path / "exp", "ctrl/rep1/slide.ome.zarr", 32 * MIB + path = write_ngff(root / rel, data, axes="cyx") + assert window_chunk_need(path, MAPPING, limit) > 4 * PLANE + (issue,) = check_window_chunks(root, {rel: MAPPING}, memory_limit=limit) + assert issue.code == CODE and not issue.is_error and issue.paths == (rel,) + assert "even a window of one pixel" in issue.message + assert "convert the original images again into a new folder" in issue.action + assert "1024 x 1024" in issue.action + with pytest.raises(WindowMemoryError) as opened: + WindowReader(path, MAPPING, cache_bytes=MIB, memory_limit=limit) + text = str(opened.value) + assert f"chunks of {Y} x {X} pixels" in text and "convert the original images" in text + with pytest.raises(WindowMemoryError) as read: # without a reader, the same advice + read_window(path, MAPPING, bounds=(0, 1, 0, 1), channels=[0], memory_limit=limit) + assert f"chunks of {Y} x {X} pixels" in str(read.value) + + +def test_check_warns_about_a_slide_stored_in_one_chunk_per_plane(tmp_path, capsys): + # A 12000 x 12000 slide (metadata only): preprocessing reads it in blocks, so the run's + # check passes, but a 275 MiB chunk is decoded whole for every window: no reader serves it. + root, out = tmp_path / "exp", tmp_path / "out" + for condition in ("a", "b"): + write_ngff(root / condition / "slide.zarr", Unwritten((2, 12000, 12000), "uint16"), "cyx") + describe = ["describe", str(root), "--output", str(out), "--channels", "DNA,ACTIN"] + describe += ["--image-type", "channels", "--accept-ids", "--comparable"] + assert main([*describe, "--confirmed-on", "2026-12-04", "--publish"]) == 0 + capsys.readouterr() + assert main(["check", str(root), "--output", str(out)]) == 0 # a warning, not an error + text = capsys.readouterr().out + assert "2 OME-Zarr images cannot be read in windows within the memory limit of 1.0 GiB" in text + assert " - a/slide.zarr\n - b/slide.zarr" in text + assert "convert the original images again" in text + report = json.loads((out / "discovery_report.json").read_text(encoding="utf-8")) + assert CODE in json.dumps(report)