diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c5b8157..7b240c96 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -101,6 +101,30 @@ refuses the skipped label images as unrecorded: refused, never silently wrong. used (`None` under v1). Regression fixture: a 320 x 320 crop of core 1B_D9 (`tests/data/he_core_1B_D9_crop.npz`, CC-BY-4.0, with its generator). Design: `docs/design/he-tissue-mask.md` ("`he_tissue_v2`"). +- **The two plane memory figures are named apart** (the owner's run of the formin OME-Zarr + mosaic, 30720 x 36864, 3 channels, `uint16`, chunks 1 x 1024 x 1024, 4 December 2026). `run` + warned that its planes "would need up to 38.0 GiB" while `xyc_plane_memory`, the bound + `RunInputs.read_plane` enforces and the next bricks check, gave about 14.8 GiB for the same + plane. Both figures are right and measure different things: the run's + (`PlaneLayout.memory_estimate`) is **one channel** read whole *and measured*: the chunks it + touches (2.1 GiB), the plane (2.1 GiB) and the histogram's working arrays (33.8 GiB: the + normalization brick's upper estimate of 32 bytes per pixel for an integer plane) with the + image QC sums; `xyc_plane_memory` is the pixels of **all three channels** in one + `(C, Y, X)` array with no histogram (4 planes and 3 copies of the chunks). No number + changes; the texts now say which is which: `planes_read_in_blocks` (and the notebook's run + plan) says "too large to measure whole ...: one channel and its histogram would need up to ..." + and that reading all channels without a histogram needs another amount; `read_plane`'s `PlaneMemoryError` says "the pixels + only: no histogram is computed". Tested on a lazily written OME-Zarr store of the mosaic's + size (metadata only, `tests/zarr_tree.Unwritten`). +- **`link_outside_folder` says why and what to do.** A link in the experiment (or masks) folder + to an image or OME-Zarr store kept elsewhere (`exp/ctrl/rep1/formin_mosaic.zarr -> + /data/formin_mosaic.zarr`) stays refused: the "contain" rule is the owner's decision of 2 + November 2026 (#81, plan §12 question 64; a run reads, fingerprints and records only what is + inside the selected folder). The message now says that the images behind the links are not + found and why, and the fix says to move (not copy) the data into the folder, instant on the + same drive, or to put the experiment's folders on the drive that holds the data, instead of + "Copy or move the files". Whether to offer an opt-in that follows such links is asked in plan + §12 question 95 (proposed, not decided). ### Added diff --git a/docs/contract.md b/docs/contract.md index bb63eca8..b5279ced 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -54,7 +54,7 @@ identity alone. | Uniqueness | Folder names need only be unique among siblings, ignoring case. Two folder names of one level (condition, biological repeat or technical repeat) that differ only in case are the error `case_conflict`, whether siblings or anywhere in the experiment (`ctrl/Rep1` and `treated/rep1`; decision D-e, §16; siblings only before D86). | | Names | Every label and `position_id` passes `check_identity_text` (§16): no leading or trailing whitespace, and not `""`, `NA`, `nan`, `none`, `null`, `n/a` or `` in any case, which table readers turn into a missing value. A folder or image name that fails is the error `invalid_name` (decision D-e; accepted before D86). | | Depth | At most three folder levels below the root. A folder below the technical-repeat level is an error. | -| Links | Contain (issue #81, owner 2 November 2026): a symbolic link to a file or folder (on Windows also a directory junction, which Python 3.11 does not report as a link) is followed only when its real path (`os.path.realpath`) is inside the experiment folder, itself resolved. A link that leaves it is not followed and is the error `link_outside_folder`, naming each link and its target (a broken link too); a link to a folder on its own path (the folder holding it, or one above) is `link_loop`; one file reached by two paths (a link and its target, two links, a linked folder and its target, or two hard links: the same device and inode, from the one `stat` taken per image or mask; owner, 2 November 2026) is `linked_twice`, naming both. A broken link that stays inside is kept and reported by its reader (`unreadable_tiff`, `unreadable_mask`), never skipped. Hidden and system names (§1) are skipped before any link is looked at, so a hidden link is never followed; a contained link *to* a hidden folder is followed, because that folder is itself never walked, so its files are found once, under the link's name, which the user chose. The links inside an OME-Zarr store are held to the same rule, though the store is not entered as a folder level: its folders are listed and only its links resolved, about 84 ms per 20,000 store files on each discovery (accepted by the owner, 2 November 2026). The masks folder follows the same rule (§15), with `RunInputs` (§9.1) and `convert` (§17) refusing the same links; one helper, `links.LinkGuard`, walks both folders. | +| Links | Contain (issue #81, owner 2 November 2026): a symbolic link to a file or folder (on Windows also a directory junction, which Python 3.11 does not report as a link) is followed only when its real path (`os.path.realpath`) is inside the experiment folder, itself resolved. A link that leaves it is not followed and is the error `link_outside_folder`, naming each link and its target (a broken link too), saying that what is behind it is not found and why, and telling the user to move the data in (v0.10.1; an opt-in to follow such links is plan §12 question 95, not decided); a link to a folder on its own path (the folder holding it, or one above) is `link_loop`; one file reached by two paths (a link and its target, two links, a linked folder and its target, or two hard links: the same device and inode, from the one `stat` taken per image or mask; owner, 2 November 2026) is `linked_twice`, naming both. A broken link that stays inside is kept and reported by its reader (`unreadable_tiff`, `unreadable_mask`), never skipped. Hidden and system names (§1) are skipped before any link is looked at, so a hidden link is never followed; a contained link *to* a hidden folder is followed, because that folder is itself never walked, so its files are found once, under the link's name, which the user chose. The links inside an OME-Zarr store are held to the same rule, though the store is not entered as a folder level: its folders are listed and only its links resolved, about 84 ms per 20,000 store files on each discovery (accepted by the owner, 2 November 2026). The masks folder follows the same rule (§15), with `RunInputs` (§9.1) and `convert` (§17) refusing the same links; one helper, `links.LinkGuard`, walks both folders. | | Mount points | Refused (owner, 3 November 2026), as far as they can be seen: a folder (or file) below the experiment folder or the masks folder that is a mount point by the rules below is not entered and is the error `mounted_folder`, naming it. A mount point is a path listed in Linux's `/proc/self/mountinfo` (the only way to see a bind mount of the same file system, for which `os.path.ismount` and the device number report an ordinary folder), or a folder, image or mask file on another device (`st_dev`) than the selected folder: another file system or Windows volume, or a Btrfs subvolume (a file's device comes from the one `stat` taken per image or mask; review of rc5). The selected folder itself may be on any mount. The same rule holds inside OME-Zarr stores (their files are held to the mount table only: they are not `stat`ed), and `check`, `run`, `convert` and `RunInputs` refuse the same mount points (a refused run publishes no scientific outputs and leaves the sources untouched; its discovery report is written). **Not seen:** a mount created after the walk started (the table is read once per walk); and where no mount table can be read (macOS, BSD, Windows, a Linux without `/proc`), a mounted single file or a mount of the same device (BSD `nullfs`). macOS `bindfs` (FUSE) and Windows mounted folders have another device, and a Windows mounted folder is also a mount-point reparse point, held to the link rule. **Refused although not mounted:** on an overlay file system (`overlayfs`, as in many containers) whose layers are on different file systems, mounted with `xino=off`, files (not folders) may report another `st_dev` than the selected folder and are then `mounted_folder` (copy the experiment to an ordinary folder, or use `xino=on` or `auto`). | | Unlisted store folders | A folder inside an OME-Zarr store (in the experiment or the masks folder) that cannot be listed (permissions, a disconnected drive) is the error `store_unreadable` (#392), naming each such folder: its links and mount points are not known, so the store is not taken as checked. Before, it was only logged and the store passed. Like the link errors, `RunInputs` (§9.1) and `convert` (§17) refuse it too (`links.LINK_CODES`). | | Hard links | An image or mask whose link count is above 1 (`st_nlink`, from the one `stat` taken per image or mask; it has other names, perhaps outside the folder, through which it can change) is the warning `hard_linked_file`, naming it and its count (owner, 3 November 2026). It is read and fingerprinted as any other file; the files inside an OME-Zarr store are not counted. | @@ -379,7 +379,10 @@ It gives: names X before Y (for example `ZXY`) is returned Y before X, as the run read it; nothing else is reordered. The memory limit of `read_plane` (default 1 GiB) counts only reading the plane, not the histogram arrays a run needs (audit I2), and it counts reading **every - channel** (issue #344): the `(C, Y, X)` result is allocated once and filled straight from + channel** (issue #344). It is therefore another figure than the run's + (`PlaneLayout.memory_estimate`, named by `planes_read_in_blocks`: one channel read and + measured); the texts name them apart (v0.10.1: for the 30720 x 36864 x 3 `uint16` mosaic in + 1024 x 1024 chunks, 38.0 GiB for the run, 14.8 GiB for `read_plane`): the `(C, Y, X)` result is allocated once and filled straight from the decoded pages, a page holding several channels (interleaved RGB, planar samples) is decoded once for all of them, and only one page is held at a time. Before any pixel is read, `read_plane` raises `PlaneMemoryError` when the bound of that whole read diff --git a/docs/plan.md b/docs/plan.md index c0b5ca03..affaaa31 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -1865,3 +1865,20 @@ Raised during review; to be decided before the milestones that need them: 2026):* a TOML file beside `morphobricks.toml`, `ignored_masks.toml`, recorded in the run manifest (`ignored_masks`, with its SHA-256); the owner also asked for a review of how many files the output folder holds, and a consolidation if it gets out of hand (a follow-up). +95. Should an experiment folder be allowed to link to images kept elsewhere (the owner's run of + the formin OME-Zarr mosaic, 4 December 2026: `exp/ctrl/rep1/formin_mosaic.zarr -> + /data/formin_mosaic.zarr` was refused with `link_outside_folder` and no image was found)? + *Kept for v0.10.1 (pull request from `fix/symlink-and-plane-memory`, 4 December 2026), as + question 64 decided:* the rule stays "contain"; the message now says that the images + behind the links are not found and why (a run reads, fingerprints and records only what is + inside the selected folder; a file behind a link out can change or move through its other + path unseen), and the fix says to move the data in (instant on the same drive) or to put + the experiment's folders on the drive that holds it. *Proposed, pending the owner's + decision:* an explicit opt-in, for example `run --follow-links` / `describe + --follow-links` and a notebook tick, recorded in the run manifest so that the run's + identity and fingerprints cover the link targets (their real paths, sizes, modification + times and inventory digests, with the content SHA-256 under `--verify-content`), and that + `RunInputs.open` and the bricks refuse a folder whose links lead elsewhere than recorded. + The trade-off: no move or reorganisation of large data, against a run whose inputs live + outside the folder it names (another user or a sync tool can change them; `linked_twice` + and the mount-point rule still apply). Not built until decided. diff --git a/docs/user_guide.md b/docs/user_guide.md index 481c2542..5e8341cc 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -184,9 +184,12 @@ experiment/ `.DS_Store`, `Thumbs.db`, `desktop.ini` and `__MACOSX` are ignored without a message. - Links (symbolic links, and junctions on Windows) are followed only when they stay inside the experiment folder; the same holds for the masks folder. A link to a file or folder - outside it is an error (`link_outside_folder`) naming the link and its target: nothing - outside the folder you selected is read, so copy the data in or select a folder that - holds it. A link back to a folder above it is an error (`link_loop`), and so is one file + outside it is an error (`link_outside_folder`) naming the link and its target, and the + images behind it are not found: a run reads, fingerprints and records only what is inside + the folder you selected, so a file reached through a link out could change or move without + the run seeing it. Move (do not copy) the data into the folder: on the same drive a move is + instant, however large the image. Or put the experiment's folders on the drive that holds + the data and select that folder. A link back to a folder above it is an error (`link_loop`), and so is one file reached by two paths, a link and its target or two hard links (`linked_twice`): it would count twice. - A mounted folder inside the experiment or masks folder (another disk, a network share, or @@ -1745,7 +1748,7 @@ continues. | `description_unreadable` | Error | `morphobricks.toml` or `morphobricks.records.jsonl` cannot be read. A description the reader refuses is reported with its own code (`E_*`, `R_FILE_SYMLINK`) and table path. | | `unreadable_folder` | Error | A folder could not be opened. Check permissions. | | `store_unreadable` | Error | A folder inside an OME-Zarr image could not be listed, so whether it holds links or mount points leading outside the selected folder is not known. Check the folder's permissions (and that the drive is connected), then check again. | -| `link_outside_folder` | Error | A link in the experiment or masks folder leads outside it (the message names each link and its target), and nothing outside the selected folder is read. Copy or move the files in, or select a folder that holds them, then remove the link. | +| `link_outside_folder` | Error | A link in the experiment or masks folder leads outside it (the message names each link and its target), so the images or masks behind it are not found: a run reads, fingerprints and records only what is inside the selected folder. Move (do not copy) the data in, instant on the same drive, or put the experiment's folders on the drive that holds the data and select that folder; then remove the link. | | `link_loop` | Error | A link leads back to a folder that holds it. Remove it. | | `mounted_folder` | Error | A folder (or file) in the experiment or masks folder is a mount point: another disk or share, or a bind mount of another folder, so its files come from outside the selected folder. It is named and not entered. Copy the files in, or select the mounted folder itself. Where the system's mount table cannot be read (macOS, Windows), only a mount of another device is seen. | | `hard_linked_file` | Warning | An image or mask has other names (hard links; the message gives the number), perhaps outside the folder, so it can change through a name the run does not see. It is read as usual. Replace the hard link with a copy if it may change. | @@ -1826,7 +1829,7 @@ continues. | `non_tiff_file`, `empty_folder` | Warning | Files or folders that are skipped. | | `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 for the memory limit are read in blocks. The results are the same; nothing to do. Raise the limit to read them whole, which is faster. | +| `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. | | `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/src/morphobricks_preprocessing/links.py b/src/morphobricks_preprocessing/links.py index 5a3b0cbe..a33d74cc 100644 --- a/src/morphobricks_preprocessing/links.py +++ b/src/morphobricks_preprocessing/links.py @@ -296,11 +296,16 @@ def issues(self) -> list[ValidationIssue]: error( LINK_OUTSIDE, f"{plural(len(self.outside), 'link')} in the {self.what} " - f"{agree(self.outside, 'leads', 'lead')} outside it (link -> target), " - "and nothing outside the selected folder is read: not followed.", + f"{agree(self.outside, 'leads', 'lead')} outside it (link -> target), so " + "the images or masks behind them are not found. Links are followed only " + "inside the selected folder: a run reads, fingerprints and records only " + "what is inside it, and a file behind such a link could be changed or " + "moved through its other path without the run seeing it.", self.outside, - f"Copy or move the files into the {self.what}, or select a folder that " - "holds them, then remove the links.", + f"Move (do not copy) the data into the {self.what}: on the same drive a " + "move is instant, however large the image. Or put the experiment's " + "folders on the drive that holds the data, move the images into them and " + f"select that folder as the {self.what}. Then remove the links.", ) ) if self.loops: diff --git a/src/morphobricks_preprocessing/notebook_run_plan.py b/src/morphobricks_preprocessing/notebook_run_plan.py index 2f97fcfe..2bc54abe 100644 --- a/src/morphobricks_preprocessing/notebook_run_plan.py +++ b/src/morphobricks_preprocessing/notebook_run_plan.py @@ -184,8 +184,9 @@ def _memory_plan(self, review: AxisReview) -> tuple[str, str]: line = ( f"{plural(len(plan.blocked), 'image')} " f"{'has' if len(plan.blocked) == 1 else 'have'} " - f"planes too large to read whole within the memory limit of {limit} (they need " - f"up to {largest}), so they will be read in blocks. The histograms are exactly the " + f"planes too large to measure whole within the memory limit of {limit} " + f"(reading one channel and computing its histogram at once needs up to " + f"{largest}), so they will be read in blocks. The histograms are exactly the " "same; reading takes longer. To read them whole, raise the memory limit to " f"{largest} or more in Settings above (untick Use the recommended " "settings), " diff --git a/src/morphobricks_preprocessing/plane_channels.py b/src/morphobricks_preprocessing/plane_channels.py index a7be09a4..15ed1af0 100644 --- a/src/morphobricks_preprocessing/plane_channels.py +++ b/src/morphobricks_preprocessing/plane_channels.py @@ -87,6 +87,13 @@ def xyc_plane_memory( ) -> int: """Return the working memory :func:`read_xyc_plane` checks, from the header only. + This is the memory of reading the pixels of ``channel_count`` channels into one + ``(C, Y, X)`` array, with no histogram. It is not a run's measuring memory + (:attr:`.planes.PlaneLayout.memory_estimate`, the figure of ``planes_read_in_blocks``: + one channel read and its histogram and image QC computed), so the two figures differ + for the same plane: for the 30720 x 36864 x 3 ``uint16`` mosaic in 1024 x 1024 chunks, + about 14.8 GiB here and 38.0 GiB for the run (most of it the histogram's arrays). + ``channel_count`` defaults to the image's channel count (1 without a channel axis). For TIFF the bound is of the pages holding the plane at ``z`` and ``t``, sized from their own strip or tile byte counts (pages can compress very differently). The request is checked @@ -248,7 +255,8 @@ def _refuse_over(memory: int, layout: PlaneLayout, count: int, path: str | os.Pa return channels = "its channel" if count == 1 else f"all {count} channels" raise PlaneMemoryError( - f"Reading one plane of {Path(path).name} whole, {channels}, needs about " + f"Reading one plane of {Path(path).name} whole, {channels} into one array (the " + f"pixels only: no histogram is computed), needs about " f"{format_bytes(memory)} of working memory, more than the limit of " f"{format_bytes(layout.memory_limit)}. Raise the memory limit if this computer " "has enough memory, or read the plane in windows." diff --git a/src/morphobricks_preprocessing/planes.py b/src/morphobricks_preprocessing/planes.py index dc976fce..6a0ba7b0 100644 --- a/src/morphobricks_preprocessing/planes.py +++ b/src/morphobricks_preprocessing/planes.py @@ -296,8 +296,8 @@ class PlaneLayout: Size of a page as stored in the file (compressed size, if compressed); 0 for OME-Zarr, whose compressed chunk sizes are not known in advance. memory_estimate - Estimated working memory to read one whole plane and, except for - :func:`read_plane`, compute its histogram, in bytes. + Working memory to read one whole plane of one channel and (except for :func:`read_plane`) + compute its histogram and QC, in bytes; not :func:`.plane_channels.xyc_plane_memory`. memory_limit The memory limit the layout was worked out for, in bytes. block_shape @@ -651,10 +651,10 @@ def check_planes( issues.append( warning( "planes_read_in_blocks", - f"The planes of {plural(len(blocked), 'image')} are too large to read whole " - f"within the memory limit of {format_bytes(memory_limit)} (they would need up " - f"to {format_bytes(largest)}), so they will be read in blocks. The histograms " - "are exactly the same; reading takes longer.", + f"The planes of {plural(len(blocked), 'image')} are too large to measure whole " + f"within the limit of {format_bytes(memory_limit)}: one channel and its histogram " + f"would need up to {format_bytes(largest)}, so blocks are read (exactly the same " + "histograms). Reading all channels without a histogram needs another amount.", [rel for rel, _ in blocked], "Nothing needs to be done. To read the planes whole, which is faster, raise " f"the memory limit to {format_bytes(largest)} or more if this computer has " diff --git a/tests/test_links.py b/tests/test_links.py index 2318198e..217736b8 100644 --- a/tests/test_links.py +++ b/tests/test_links.py @@ -291,3 +291,45 @@ def test_a_broken_link_in_the_masks_folder_is_named(clean): pre = preflight(clean.experiment, clean.output, masks_folder=clean.masks) issue = _issue(pre.masks.issues, "unreadable_mask") assert issue.is_error and issue.paths == ("Cells/ctrl/rep1/a.tif",) + + +def _says_why_and_what_to_do(issue): + """The refusal says why links out are not followed and what to do instead (4 Dec 2026).""" + assert "not found" in issue.message + assert "fingerprints and records only what is inside it" in issue.message + assert "Move (do not copy) the data into the experiment folder" in issue.action + assert "instant" in issue.action and "remove the links" in issue.action + + +def test_a_file_link_out_says_why_it_is_refused_and_what_to_do(tree): + root, outside = tree + (root / "ctrl/rep1/b.tif").symlink_to(outside / "far.tif") + found = discover_experiment(root) + assert "ctrl/rep1/b.tif" not in found.images + _says_why_and_what_to_do(_issue(found.issues, "link_outside_folder")) + + +def test_a_linked_ome_zarr_store_says_why_it_is_refused_and_what_to_do(tree): + """The owner's case: exp/ctrl/rep1/mosaic.zarr -> a store kept elsewhere.""" + pytest.importorskip("zarr") + from zarr_tree import write_ngff + + root, outside = tree + write_ngff(outside / "mosaic.zarr", np.zeros((3, 4, 4), np.uint16), axes="cyx") + (root / "ctrl/rep1/mosaic.zarr").symlink_to(outside / "mosaic.zarr", target_is_directory=True) + found = discover_experiment(root) + assert "ctrl/rep1/mosaic.zarr" not in found.images + issue = _issue(found.issues, "link_outside_folder") + assert issue.paths == (f"ctrl/rep1/mosaic.zarr -> {(outside / 'mosaic.zarr').resolve()}",) + _says_why_and_what_to_do(issue) + + +def test_a_mask_link_out_tells_to_move_the_mask_into_the_masks_folder(clean): + mask = clean.masks / "Cells/ctrl/rep1/a.tif" + real = clean.masks.parent / "elsewhere.tif" + mask.rename(real) + mask.symlink_to(real) + pre = preflight(clean.experiment, clean.output, masks_folder=clean.masks) + issue = _issue(pre.masks.issues, "link_outside_folder") + assert "Move (do not copy) the data into the masks folder" in issue.action + assert "select that folder as the masks folder" in issue.action diff --git a/tests/test_notebook_ui.py b/tests/test_notebook_ui.py index 08b78c18..7e9fd921 100644 --- a/tests/test_notebook_ui.py +++ b/tests/test_notebook_ui.py @@ -752,7 +752,7 @@ def fail(*args, **kwargs): nb.confirm_button.click() nb.image_type_checked.button.click() plan = nb.plan.value - assert "1 image has planes too large to read whole" in plan + assert "1 image has planes too large to measure whole" in plan assert "will be read in blocks" in plan and "exactly the same" in plan assert "ctrl/rep1/big.tif" in plan and "small.tif" not in plan assert "cannot be read within the memory limit" not in plan diff --git a/tests/test_plane_memory_names.py b/tests/test_plane_memory_names.py new file mode 100644 index 00000000..f3dc2506 --- /dev/null +++ b/tests/test_plane_memory_names.py @@ -0,0 +1,86 @@ +"""The two plane memory figures, named apart (owner's mosaic run of 4 December 2026). + +For one plane of the formin mosaic (OME-Zarr, 30720 x 36864, 3 channels, uint16, chunks +1 x 1024 x 1024) the run warned that its planes "would need up to 38.0 GiB" while +``xyc_plane_memory`` (the bound ``RunInputs.read_plane`` enforces) gave about 14.8 GiB. Both +are right, and different: the run's figure is one channel read *and measured* (most of it +the histogram's working arrays), the other the pixels of all three channels with no +histogram. The texts now say which is which. The store is written lazily (metadata only). +""" + +from __future__ import annotations + +import numpy as np +import pytest +from morphobricks_normalization.histogram import estimate_histogram_memory + +from morphobricks_preprocessing.axes import AxisMapping +from morphobricks_preprocessing.image_qc import qc_memory +from morphobricks_preprocessing.plane_channels import ( + OPEN_BYTES, + ZARR_COPIES, + read_xyc_plane, + xyc_plane_memory, +) +from morphobricks_preprocessing.planes import ( + PlaneMemoryError, + check_planes, + format_bytes, + plane_layout, +) + +pytest.importorskip("zarr") +from zarr_tree import Unwritten, write_ngff # noqa: E402 + +Y, X, C = 30720, 36864, 3 +CHUNK = 1024 +REL = "ctrl/rep1/formin_mosaic.zarr" +MAPPING = AxisMapping("CYX", ("C", "Y", "X")) +PLANE = Y * X * 2 # one channel, uint16 +CHUNKS = (Y // CHUNK) * (X // CHUNK) * CHUNK * CHUNK * 2 # every chunk one plane touches + + +@pytest.fixture +def mosaic(tmp_path): + root = tmp_path / "exp" + write_ngff(root / REL, Unwritten((C, Y, X), "uint16"), axes="cyx", chunks=(1, CHUNK, CHUNK)) + store_bytes = sum(f.stat().st_size for f in (root / REL).rglob("*") if f.is_file()) + assert store_bytes < 64 * 1024 # metadata only: no chunk is written + return root + + +def test_the_run_figure_is_one_channel_read_and_measured(mosaic): + layout = plane_layout(mosaic / REL, MAPPING) + histogram = estimate_histogram_memory(Y * X, np.dtype("uint16"), range_check=True) + finished = C * 8 * 65536 + assert layout.memory_estimate == ( + CHUNKS + PLANE + histogram + qc_memory(Y, X, False) + finished + ) + assert histogram > 0.8 * layout.memory_estimate # mostly the histogram's arrays + assert format_bytes(layout.memory_estimate) == "38.0 GiB" + + +def test_the_read_plane_figure_is_every_channel_without_a_histogram(mosaic): + memory = xyc_plane_memory(mosaic / REL, MAPPING) + assert memory == (C + 1) * PLANE + ZARR_COPIES * CHUNKS + OPEN_BYTES + assert format_bytes(memory) == "14.8 GiB" + assert format_bytes(xyc_plane_memory(mosaic / REL, MAPPING, 1)) == "10.5 GiB" + + +def test_the_run_warning_names_its_figure_as_one_channel_measured(mosaic): + issues = check_planes(mosaic, {REL: MAPPING}) + (issue,) = issues + assert issue.code == "planes_read_in_blocks" and issue.paths == (REL,) + assert "38.0 GiB" in issue.message and "one channel" in issue.message + assert "one channel and its histogram" in issue.message + assert "all channels without a histogram needs another amount" in issue.message + assert "would need up to 38.0 GiB" in issue.message + assert "raise the memory limit to 38.0 GiB" in issue.action + + +def test_the_read_plane_refusal_names_its_figure_as_pixels_only(mosaic): + with pytest.raises(PlaneMemoryError) as caught: + read_xyc_plane(mosaic / REL, MAPPING) + text = str(caught.value) + assert "all 3 channels" in text and "14.8 GiB" in text + assert "the pixels only: no histogram is computed" in text diff --git a/tests/zarr_tree.py b/tests/zarr_tree.py index cb5a9c39..70485a87 100644 --- a/tests/zarr_tree.py +++ b/tests/zarr_tree.py @@ -15,6 +15,20 @@ def zarr_major() -> int: return int(zarr.__version__.split(".")[0]) +class Unwritten: + """An image's shape and type only: :func:`write_ngff` writes its metadata, no chunk. + + Reading it gives zarr's fill value (0); the store holds no pixel, so an image of any + size (the 30720 x 36864 x 3 mosaic of the owner's 4 December 2026 run) costs a few + kilobytes on disk. + """ + + def __init__(self, shape, dtype): + self.shape = tuple(shape) + self.dtype = np.dtype(dtype) + self.ndim = len(self.shape) + + def write_ngff( # noqa: PLR0913 path, data, @@ -44,7 +58,8 @@ def write_ngff( # noqa: PLR0913 pytest.skip("OME-NGFF 0.5 needs zarr 3") path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) - data = np.asarray(data) + if not isinstance(data, Unwritten): + data = np.asarray(data) group = _group(zarr, path, 3 if version == "0.5" else 2) chunks = chunks or (*(1,) * (data.ndim - 2), *data.shape[-2:]) _array(group, "0", data, chunks) @@ -139,5 +154,6 @@ def _array(group, name, data, chunks): array = group.create_array(name, shape=data.shape, chunks=chunks, dtype=data.dtype) else: array = group.create_dataset(name, shape=data.shape, chunks=chunks, dtype=data.dtype) - array[...] = data + if not isinstance(data, Unwritten): + array[...] = data return array