From c907d8c3d69247041af97b5028b79888fb0bb008 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 20:36:32 +0000 Subject: [PATCH 1/4] piece_counts: count every label's pieces in one pass (#69) piece_counts sorted every pixel (np.unique with return_inverse) and labelled each label again in its bounding box. Each row is now cut into runs of one label, and runs of one label in neighbouring rows that touch (8-connected, from masks.binary.STRUCTURE) are joined with scipy.sparse.csgraph.connected_components. New pure module mask_pieces; mask_scan.piece_counts is the same function, imported. Results are byte-identical: a property test compares it with the former function on random masks of every label pixel type and on the benchmark masks, and every digest of benchmark_kernels --group masks is unchanged. 4096 px cells: 2.37 s -> 0.18 s; one position's scan 5.2 s -> 1.25 s. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a --- AGENTS.md | 5 +- CHANGELOG.md | 2 + .../2026-11-25-kernels-masks-after-69.json | 253 ++++++++++++++++++ .../2026-11-25-kernels-masks-before-69.json | 253 ++++++++++++++++++ docs/benchmarks.md | 28 ++ pyproject.toml | 1 + src/morphobricks_preprocessing/mask_pieces.py | 114 ++++++++ src/morphobricks_preprocessing/mask_scan.py | 34 +-- tests/test_mask_pieces.py | 120 +++++++++ 9 files changed, 776 insertions(+), 34 deletions(-) create mode 100644 docs/benchmark_results/2026-11-25-kernels-masks-after-69.json create mode 100644 docs/benchmark_results/2026-11-25-kernels-masks-before-69.json create mode 100644 src/morphobricks_preprocessing/mask_pieces.py create mode 100644 tests/test_mask_pieces.py diff --git a/AGENTS.md b/AGENTS.md index b7eeeda7..7613e092 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -398,7 +398,7 @@ src/morphobricks_preprocessing/ mask_review.py what the notebook shows about the masks: mask_type_rows, and mask_axes_questions (the types whose axes must be stated, with the statements mask_roles accepts) - mask_scan.py the optional mask step (Q32): piece_counts (scipy.ndimage, 8-connected), pair_counts, + mask_scan.py the optional mask step (Q32): piece_counts (from mask_pieces), pair_counts, scan_masks -> MaskReport (kinds, relations, direct-parent hierarchy, evidence; each image's masks fingerprinted before and after they are read, #165), write_mask_report (mask_relationships.json); DEFAULT_THRESHOLDS, @@ -406,6 +406,9 @@ src/morphobricks_preprocessing/ mask_pairs.py pair_counts' pure helpers: best_parents (a tie between parents gives no parent, ambiguous_parent; Q74), one_to_one_matches, match_counts and PIECE_STRUCTURE (masks.binary.STRUCTURE, 8-connected, imported) + mask_pieces.py piece_counts (#69): each row cut into runs of one label, runs of one + label in neighbouring rows joined (scipy.sparse.csgraph); no sort of + every pixel and no labelling per label copy_axes.py convert (PP-11, contract §17): the axes, shape, pixel sizes (by role; a relabelled axis gets an unknown scale; equal X and Y kept through a Y/X swap, question 59) and OME metadata of a named-axis copy diff --git a/CHANGELOG.md b/CHANGELOG.md index 07058995..b2551ecd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased +- **`piece_counts` counts every label's pieces in one pass (#69).** It sorted every pixel (`np.unique(..., return_inverse=True)`, most of its time) and labelled each label again in its bounding box, so labels spread over the plane read it once each. Each row is now cut into runs of one label and runs of one label in neighbouring rows that touch (8-connected, from `masks.binary.STRUCTURE`) are joined with `scipy.sparse.csgraph.connected_components` (new pure module `mask_pieces`; `mask_scan.piece_counts` is the same function, imported). The results are byte-identical (labels in the mask's pixel type, counts `int64`): a property test compares it with the former function, kept in the test as the reference, on random masks of every label pixel type (touching labels, holes, single pixels, edges, corners, no background, empty) and on the benchmark masks; every digest of `tools/benchmark_kernels.py --group masks` is unchanged. On the benchmark machine `piece_counts` of the 4096 px cells mask went from 2.37 s to 0.18 s and one position's scan from 5.2 s to 1.25 s (`docs/benchmarks.md`). Two changes outside the former results: a mask of no pixels (a side of length 0) now has no labels, where the former function failed inside SciPy; a mask that is not 2D is refused with a `ValueError` saying so (it was a SciPy `RuntimeError`, or no labels when it was all background). `pair_counts` and the repeated pair work of #69 are not changed. `tests/test_mask_pieces.py`. + - **A saved repeat order is never replaced by an abandoned *Yes* (review of #546 at e40f1ad).** On a reopened per-repeat draft, picking *Yes*, filling its row with rep1's order and going back to *No, per repeat folder* showed rep1's order in every repeat row, under "Pre-answered from your saved tags", and one Submit published it for every unit. A row's own saved tags now rank above a broader choice of the session (`channel_scope.seed`: the row's choice, its saved tags, a broader choice, the header names), and the "Pre-answered" note goes at the first change of the answer or of a row. Tests: `tests/test_notebook_channel_guide_reopen.py`, `tests/test_channel_scope.py`. - **A reopened strict channel draft is never turned into fast mode (review of #546, F1).** The guided step's fast-mode tick is hidden and only Submit sets it, so an unpublished draft does not hold it: reopened, a per-repeat, per-unit or one-list-per-count draft was ticked by default and opening Channels wrote `channel_layout` = the first unit's order with every unit `channels_from = "experiment"`, and *Check and save* published every unit in that order. Opening the guided step now writes nothing, an unpublished draft with saved per-unit tags and no `channel_layout` reopens unticked (`TagMatrix.tick_for_draft`), and the question is answered as the draft is (`channel_scope.scope_of_draft`: fast mode *Yes*; a strict draft the broadest answer whose rows reproduce every saved tag, "Pre-answered from your saved tags"; else "Saved per-unit tags are kept"). Every folder colour still states R, G, B, now right after the image-type answer instead of on opening. The per-unit grid of the Python-interface pages keeps its behaviour (its fast mode tags from headers on opening by design; see the PR). Also: a unit whose images disagree records no other row's tags in its refusal; *Same order within each biological repeat folder*; a row filled from a broader choice says so; per unit, a blank row keeps that unit as it is; the image type's button reads *Validated ✓* after a save. Tests: `tests/test_notebook_channel_guide_reopen.py`, and the #281, #279, mode-switch alias and #257 flows through the guided step in `tests/test_notebook_channel_guide_flows.py`. - **The channel step is a question, a few rows and one Submit (owner design of 25 November 2026).** The owner's Colab test of the v0.9.0 candidate found the tagging widget buggy: every dropdown change saved the draft and redrew the page (lag), there was one row per unit even when every image had the same channels, and values jumped after being picked. The shipped notebook (the stepper) now asks **Is the channel order the same for the whole dataset?** (with the channel counts when they differ). *Yes* opens one row of dropdowns per channel count; *No* asks **Same order within each biological repeat** (one row per repeat folder and count) or **Tag every imaging unit** (one row per unit). Dropdowns change only the form (no draft write, no redraw; choices are kept across redraws and answer switches, and a narrower row starts from the broader choice). **Submit** checks every row and the image headers with the #376 rules (`repeat_tags.repeat_fill`, the same refusal snapshot) and saves the tags, their aliases, the tag review and the statement in ONE draft write through `TagGrid.commit(..., then)` (`R_DRAFT_CHANGED` and every other save refusal apply). A unit whose header contradicts its row is listed and released only by an action on it (the override, a one-click confirmation, or a row of its own that fits its header). Recording: *Yes* with one count is fast mode (`channel_layout`, Spec ADR 0006); several counts, per repeat and per unit are strict per-unit files, each unit holding its row's list (no Spec change). Header names are evidence only and no longer tag a unit with no click in this step. New modules `channel_scope` (pure), `notebook_channels_guide`, `notebook_channels_submit`, `notebook_channels_summary` (split from the grid). The pages of the Python interface (`channels_step()`) keep the per-unit grid; the override editor now updates its highlights in place instead of redrawing the page. Tests: `tests/test_notebook_channel_step_acceptance.py` (eight scenarios clicked through the stepper, each published file checked by the Spec reference validator), `tests/test_notebook_channel_guide.py`, `tests/test_channel_scope.py`; the stepper tests of the per-unit grid pin it with the `legacy_grid` fixture. Human script: `docs/colab-release-check.md` step 10. diff --git a/docs/benchmark_results/2026-11-25-kernels-masks-after-69.json b/docs/benchmark_results/2026-11-25-kernels-masks-after-69.json new file mode 100644 index 00000000..a0dbc971 --- /dev/null +++ b/docs/benchmark_results/2026-11-25-kernels-masks-after-69.json @@ -0,0 +1,253 @@ +{ + "benchmark": "kernels", + "mode": "full", + "repeats": 7, + "machine": { + "processor": "Intel(R) Xeon(R) Processor @ 2.10GHz", + "cpus": 4, + "cpus_usable": 4, + "memory_bytes": 16868675584, + "load_average": [ + 2.19091796875, + 1.298828125, + 1.29248046875 + ], + "system": "Linux-6.18.44-fc-v880-x86_64-with-glibc2.39", + "python": "3.13.18", + "libraries": { + "numpy": "2.5.5", + "scipy": "1.18.1", + "tifffile": "2026.11.16", + "imagecodecs": "2026.11.11", + "zarr": "3.4.2", + "morphobricks-normalization": "0.8.0", + "morphobricks-preprocessing": "0.8.0" + }, + "thread_variables": { + "OMP_NUM_THREADS": null, + "OPENBLAS_NUM_THREADS": null, + "MKL_NUM_THREADS": null + }, + "commit": "c8c3808b17b76be012e0dcb532af4e362c752b81" + }, + "cases": [ + { + "group": "masks", + "name": "check_labels_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024 + }, + "wall_seconds": { + "median": 0.001998, + "min": 0.001888, + "max": 0.002133, + "values": [ + 0.001998, + 0.002133, + 0.002037, + 0.001911, + 0.001987, + 0.001888, + 0.002041 + ] + }, + "digest": "c48ceaf4c6bfc750821874d2296ef001311822644ed70e9d68338c231ae08052", + "digest_stable": true, + "peak_traced_bytes": 906 + }, + { + "group": "masks", + "name": "piece_counts_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024 + }, + "wall_seconds": { + "median": 0.041171, + "min": 0.036741, + "max": 0.046216, + "values": [ + 0.046216, + 0.041171, + 0.040789, + 0.042367, + 0.036741, + 0.041169, + 0.041371 + ] + }, + "digest": "4abd144b846d176cb4b83026fe4653cf3ba8999eb906a5804483eef15c2592ae", + "digest_stable": true, + "peak_traced_bytes": 12648216 + }, + { + "group": "masks", + "name": "pair_counts_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024 + }, + "wall_seconds": { + "median": 0.049326, + "min": 0.04628, + "max": 0.111908, + "values": [ + 0.111908, + 0.060893, + 0.048478, + 0.049326, + 0.060562, + 0.04628, + 0.046498 + ] + }, + "digest": "fb7de56131b3fa8f42c0f23a13fae275c5967deb09bab898c72e55a6817cd62a", + "digest_stable": true, + "peak_traced_bytes": 28708302 + }, + { + "group": "masks", + "name": "scan_position_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024, + "mask_types": 2 + }, + "wall_seconds": { + "median": 0.247, + "min": 0.219788, + "max": 0.30201, + "values": [ + 0.250143, + 0.247, + 0.220121, + 0.225868, + 0.219788, + 0.30201, + 0.251453 + ] + }, + "digest": "69de16bd28281cc3c791e68b8c52246bf95429760d0948b36e2a9eda0e74a8b6", + "digest_stable": true, + "peak_traced_bytes": 82261645 + }, + { + "group": "masks", + "name": "check_labels_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096 + }, + "wall_seconds": { + "median": 0.014363, + "min": 0.013549, + "max": 0.015606, + "values": [ + 0.015606, + 0.014242, + 0.013549, + 0.014663, + 0.015171, + 0.013901, + 0.014363 + ] + }, + "digest": "c48ceaf4c6bfc750821874d2296ef001311822644ed70e9d68338c231ae08052", + "digest_stable": true, + "peak_traced_bytes": 906 + }, + { + "group": "masks", + "name": "piece_counts_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096 + }, + "wall_seconds": { + "median": 0.180798, + "min": 0.159018, + "max": 0.21024, + "values": [ + 0.196094, + 0.21024, + 0.185725, + 0.172789, + 0.180798, + 0.170331, + 0.159018 + ] + }, + "digest": "c575615afca962cf72fc50c2229c14557053ba7e8b7abb636139348693ebb2b0", + "digest_stable": true, + "peak_traced_bytes": 50329400 + }, + { + "group": "masks", + "name": "pair_counts_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096 + }, + "wall_seconds": { + "median": 0.271277, + "min": 0.254412, + "max": 0.324182, + "values": [ + 0.266288, + 0.267709, + 0.254412, + 0.307467, + 0.324182, + 0.307412, + 0.271277 + ] + }, + "digest": "550398e1f131c578ee82c4f220aa74ef2475c15da77d7277d451640f3eff74d1", + "digest_stable": true, + "peak_traced_bytes": 114824538 + }, + { + "group": "masks", + "name": "scan_position_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096, + "mask_types": 2 + }, + "wall_seconds": { + "median": 1.251531, + "min": 1.086103, + "max": 1.407519, + "values": [ + 1.407519, + 1.123353, + 1.274879, + 1.086103, + 1.329764, + 1.251531, + 1.151125 + ] + }, + "digest": "ec5910c05e04c1c70be1da3498630d1e30d68e47ac7dddd62d056dcdd0599d95", + "digest_stable": true, + "peak_traced_bytes": 329032455 + } + ], + "inputs": { + "label_masks_2048_1024_seed0": "6f6b9edfc43758b635ae5e0f10a9cddc7c072f9a4e39aaba172da9cea3ec0820", + "label_masks_4096_4096_seed0": "8479cf81d94e9212f5a8982ea5514bebd686efe7c1f2fc0a2e925368befe6901" + }, + "process": { + "peak_rss_bytes": 661131264, + "source": "VmHWM" + } +} diff --git a/docs/benchmark_results/2026-11-25-kernels-masks-before-69.json b/docs/benchmark_results/2026-11-25-kernels-masks-before-69.json new file mode 100644 index 00000000..905586fd --- /dev/null +++ b/docs/benchmark_results/2026-11-25-kernels-masks-before-69.json @@ -0,0 +1,253 @@ +{ + "benchmark": "kernels", + "mode": "full", + "repeats": 7, + "machine": { + "processor": "Intel(R) Xeon(R) Processor @ 2.10GHz", + "cpus": 4, + "cpus_usable": 4, + "memory_bytes": 16868675584, + "load_average": [ + 0.826171875, + 0.89697265625, + 1.17578125 + ], + "system": "Linux-6.18.44-fc-v880-x86_64-with-glibc2.39", + "python": "3.13.18", + "libraries": { + "numpy": "2.5.5", + "scipy": "1.18.1", + "tifffile": "2026.11.16", + "imagecodecs": "2026.11.11", + "zarr": "3.4.2", + "morphobricks-normalization": "0.8.0", + "morphobricks-preprocessing": "0.8.0" + }, + "thread_variables": { + "OMP_NUM_THREADS": null, + "OPENBLAS_NUM_THREADS": null, + "MKL_NUM_THREADS": null + }, + "commit": "c8c3808b17b76be012e0dcb532af4e362c752b81" + }, + "cases": [ + { + "group": "masks", + "name": "check_labels_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024 + }, + "wall_seconds": { + "median": 0.002036, + "min": 0.001994, + "max": 0.002325, + "values": [ + 0.002036, + 0.002032, + 0.002055, + 0.002094, + 0.002001, + 0.001994, + 0.002325 + ] + }, + "digest": "c48ceaf4c6bfc750821874d2296ef001311822644ed70e9d68338c231ae08052", + "digest_stable": true, + "peak_traced_bytes": 906 + }, + { + "group": "masks", + "name": "piece_counts_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024 + }, + "wall_seconds": { + "median": 0.342689, + "min": 0.330181, + "max": 0.378958, + "values": [ + 0.342689, + 0.37442, + 0.370809, + 0.332056, + 0.330181, + 0.335145, + 0.378958 + ] + }, + "digest": "4abd144b846d176cb4b83026fe4653cf3ba8999eb906a5804483eef15c2592ae", + "digest_stable": true, + "peak_traced_bytes": 138417591 + }, + { + "group": "masks", + "name": "pair_counts_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024 + }, + "wall_seconds": { + "median": 0.045209, + "min": 0.043809, + "max": 0.045972, + "values": [ + 0.045209, + 0.045724, + 0.044547, + 0.045937, + 0.045972, + 0.04406, + 0.043809 + ] + }, + "digest": "fb7de56131b3fa8f42c0f23a13fae275c5967deb09bab898c72e55a6817cd62a", + "digest_stable": true, + "peak_traced_bytes": 28708251 + }, + { + "group": "masks", + "name": "scan_position_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024, + "mask_types": 2 + }, + "wall_seconds": { + "median": 0.91742, + "min": 0.798109, + "max": 1.067031, + "values": [ + 0.97172, + 0.878678, + 0.962361, + 1.067031, + 0.887292, + 0.91742, + 0.798109 + ] + }, + "digest": "69de16bd28281cc3c791e68b8c52246bf95429760d0948b36e2a9eda0e74a8b6", + "digest_stable": true, + "peak_traced_bytes": 138430531 + }, + { + "group": "masks", + "name": "check_labels_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096 + }, + "wall_seconds": { + "median": 0.009551, + "min": 0.008978, + "max": 0.010588, + "values": [ + 0.010588, + 0.00978, + 0.009551, + 0.009805, + 0.009068, + 0.009039, + 0.008978 + ] + }, + "digest": "c48ceaf4c6bfc750821874d2296ef001311822644ed70e9d68338c231ae08052", + "digest_stable": true, + "peak_traced_bytes": 906 + }, + { + "group": "masks", + "name": "piece_counts_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096 + }, + "wall_seconds": { + "median": 2.368892, + "min": 2.237558, + "max": 2.533668, + "values": [ + 2.416621, + 2.519051, + 2.237558, + 2.368892, + 2.262554, + 2.293342, + 2.533668 + ] + }, + "digest": "c575615afca962cf72fc50c2229c14557053ba7e8b7abb636139348693ebb2b0", + "digest_stable": true, + "peak_traced_bytes": 553665975 + }, + { + "group": "masks", + "name": "pair_counts_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096 + }, + "wall_seconds": { + "median": 0.258079, + "min": 0.249646, + "max": 0.29505, + "values": [ + 0.258079, + 0.252204, + 0.249646, + 0.29369, + 0.29505, + 0.253031, + 0.258973 + ] + }, + "digest": "550398e1f131c578ee82c4f220aa74ef2475c15da77d7277d451640f3eff74d1", + "digest_stable": true, + "peak_traced_bytes": 114824538 + }, + { + "group": "masks", + "name": "scan_position_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096, + "mask_types": 2 + }, + "wall_seconds": { + "median": 5.200998, + "min": 5.040348, + "max": 5.649843, + "values": [ + 5.0494, + 5.046973, + 5.649843, + 5.200998, + 5.282038, + 5.040348, + 5.449511 + ] + }, + "digest": "ec5910c05e04c1c70be1da3498630d1e30d68e47ac7dddd62d056dcdd0599d95", + "digest_stable": true, + "peak_traced_bytes": 553827830 + } + ], + "inputs": { + "label_masks_2048_1024_seed0": "6f6b9edfc43758b635ae5e0f10a9cddc7c072f9a4e39aaba172da9cea3ec0820", + "label_masks_4096_4096_seed0": "8479cf81d94e9212f5a8982ea5514bebd686efe7c1f2fc0a2e925368befe6901" + }, + "process": { + "peak_rss_bytes": 882270208, + "source": "VmHWM" + } +} diff --git a/docs/benchmarks.md b/docs/benchmarks.md index cb2ce296..d612e976 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -69,6 +69,34 @@ before timing). Tiles are 512 px, strips 64 rows, Zarr chunks 1024 px. | `pair_counts` (nuclei in cells) | 41.5 ms (40.3–50.0) | 27 MiB | 245 ms (235–260) | 110 MiB | | scan of one position (`_scan_plane`: both masks' pieces, both pairs) | 701 ms (674–734) | 132 MiB | 4,704 ms (4,601–4,933) | 528 MiB | +### `piece_counts` in one pass (#69), before and after + +`python tools/benchmark_kernels.py --group masks` (7 timed calls per case after one warm-up), the +same machine, Python and libraries as above, run four times in turn on 25 November 2026: +before (`main` at `c8c3808`), after (this change), before, after. Every case has the same +digest in all four runs, and the inputs the same digests as the baseline above (reports: +[before](benchmark_results/2026-11-25-kernels-masks-before-69.json) and +[after](benchmark_results/2026-11-25-kernels-masks-after-69.json), the first round; the "after" +report names `c8c3808` as its commit because it was run before this change was committed). +Another job's tests were running on the machine (1-minute load 0.8 to 2.2 at the starts), so +the absolute times are above the baseline's; the before and after runs shared that load. + +| Case | Before, run 1 | After, run 1 | Before, run 2 | After, run 2 | Traced, before / after | Digest (first 16) | +|---|---:|---:|---:|---:|---:|---| +| `piece_counts` 2048 | 343 ms (330–379) | 41.2 ms (36.7–46.2) | 413 ms (388–517) | 38.3 ms (35.8–44.8) | 132 / 12.1 MiB | `4abd144b846d176c` | +| `piece_counts` 4096 | 2,369 ms (2,238–2,534) | 181 ms (159–210) | 2,283 ms (2,199–2,409) | 195 ms (174–233) | 528 / 48.0 MiB | `c575615afca962cf` | +| scan of one position 2048 | 917 ms (798–1,067) | 247 ms (220–302) | 902 ms (788–1,015) | 219 ms (214–239) | 132 / 78.5 MiB | `69de16bd28281cc3` | +| scan of one position 4096 | 5,201 ms (5,040–5,650) | 1,252 ms (1,086–1,408) | 5,603 ms (5,098–5,873) | 1,230 ms (1,102–1,291) | 528 / 314 MiB | `ec5910c05e04c1c7` | +| `pair_counts` 4096 (unchanged) | 258 ms | 271 ms | 279 ms | 267 ms | 110 / 110 MiB | `550398e1f131c578` | + +Peak resident memory of the benchmark process: 841 MiB before, 631 MiB after. The former +function spent most of its time in the sort of every pixel (`np.unique(..., +return_inverse=True)`, about 2.5 s of the 4096 px case when timed alone), not in its loop of +per-label `ndimage.label` (about 0.15 s on these compact cells). The loop dominates when labels +are spread over the plane: on a 2048 px mask of 1,000 labels scattered over 20 % of the pixels +(a check outside the tool, `tests/test_mask_pieces.py`'s reference against the new function, +median of 3 calls) it took 15.8 s, the new function 0.25 s, with equal outputs. + ## Channel identity (`check_channel_identity`, three channels) | Units | Images per unit | Time | Traced | diff --git a/pyproject.toml b/pyproject.toml index 35bf2bea..00e113d2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -379,6 +379,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.testing_described" = "orchestration" "morphobricks_preprocessing.mask_scan" = "io" "morphobricks_preprocessing.mask_pairs" = "pure" +"morphobricks_preprocessing.mask_pieces" = "pure" "morphobricks_preprocessing.masks" = "io" "morphobricks_preprocessing.masks.checks" = "io" "morphobricks_preprocessing.masks.files" = "io" diff --git a/src/morphobricks_preprocessing/mask_pieces.py b/src/morphobricks_preprocessing/mask_pieces.py new file mode 100644 index 00000000..9df5f7ed --- /dev/null +++ b/src/morphobricks_preprocessing/mask_pieces.py @@ -0,0 +1,114 @@ +"""Count the connected pieces of every label of a 2D mask in one pass (issue #69). + +The kernel of :func:`.mask_scan.piece_counts` (``docs/contract.md`` §15), moved from +:mod:`.mask_scan`. Before, the labels were renumbered with a sort of every pixel +(``np.unique(..., return_inverse=True)``) and each label was labelled again in its bounding +box, so labels spread over the plane read most of it once each. Now each row is cut into +runs (consecutive pixels of one nonzero label), runs of one label in neighbouring rows are +joined when they touch (``scipy.sparse.csgraph``), and a label's pieces are its groups of +runs. Each pixel is read a fixed number of times, whatever the labels; the counts are the +same as labelling each label alone with the labeller's structure (:data:`.masks.binary. +STRUCTURE`, imported, not restated: Spec ADR 0005 BM1). No files are read or written. +""" + +from __future__ import annotations + +import numpy as np +from scipy.sparse import coo_matrix +from scipy.sparse.csgraph import connected_components + +from .masks.binary import STRUCTURE +from .masks.labels import check_labels + +__all__ = ["piece_counts"] + + +def piece_counts(mask: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Return the labels of a 2D mask and the number of 8-connected pieces of each. + + Two pixels are in one piece when they carry the same label and touch along an edge or at + a corner (:data:`.masks.binary.STRUCTURE`). Label 0 is the background. + + Returns + ------- + tuple of numpy.ndarray + The sorted nonzero labels (of the mask's pixel type), and the number of pieces of + each (``int64``). + + Raises + ------ + ValueError + If the mask is not 2D, holds a label outside 0 to 2,147,483,647, or pixels that are + not whole numbers (:func:`.masks.check_labels`). + """ + mask = np.asarray(mask) + check_labels(mask) + if mask.ndim != 2: + raise ValueError(f"The mask must be one 2D plane, not {mask.ndim}D.") + row, start, end, label = _runs(mask) + piece = _join_runs(row, start, end, label, _corner_reach()) + # every piece is runs of one label, so a label's pieces are the pieces carrying it + label_of_piece = np.empty(int(piece.max(initial=-1)) + 1, dtype=mask.dtype) + label_of_piece[piece] = label + values, counts = np.unique(label_of_piece, return_counts=True) + return values, counts.astype(np.int64) + + +def _corner_reach() -> int: + """Return 1 if :data:`STRUCTURE` joins pixels touching at a corner, 0 if not.""" + full, cross = np.ones((3, 3), bool), np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], bool) + if np.array_equal(STRUCTURE, full): + return 1 + if np.array_equal(STRUCTURE, cross): + return 0 + raise ValueError("piece_counts supports only the 8- or 4-connected 3 x 3 structure.") + + +def _runs(mask: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """Return the row, first and last column and label of every run of one nonzero label. + + Runs come in row-major order. Pixels of one label next to each other in a row are one + run, so only runs in neighbouring rows still have to be joined. + """ + on = mask != 0 + first = on.copy() + first[:, 1:] &= mask[:, 1:] != mask[:, :-1] + last = on # reused: ``on`` is not needed after this + last[:, :-1] &= mask[:, :-1] != mask[:, 1:] + row, start = np.nonzero(first) + end = np.nonzero(last)[1] + return row, start, end, mask[row, start] + + +def _join_runs( + row: np.ndarray, start: np.ndarray, end: np.ndarray, label: np.ndarray, reach: int +) -> np.ndarray: + """Return the piece of every run: runs of one label in neighbouring rows that touch join. + + A run of row ``r + 1`` touches a run of the same label in row ``r`` when their columns + overlap, widened by ``reach`` (1: corners touch). Runs are grouped by (row, label) and + sorted by first column within a group; as runs of one group never overlap, their last + columns are sorted too, so the runs above each run that touch it are one slice of the + group, found by two binary searches. + """ + if row.size == 0: + return np.zeros(0, dtype=np.intp) + key = row.astype(np.int64) * (int(label.max()) + 1) + label.astype(np.int64) + order = np.argsort(key, kind="stable") # stable: by first column within a group + keys, group = np.unique(key[order], return_inverse=True) + width = int(end.max()) + 3 # every column + 2 fits below it: no overlap between groups + low = group * width + (end[order] + 1) + high = group * width + (start[order] + 1) + above = np.searchsorted(keys, key - (int(label.max()) + 1)) + found = above < keys.size + found[found] = keys[above[found]] == key[found] - (int(label.max()) + 1) + below, above = np.nonzero(found)[0], above[found] + first = np.searchsorted(low, above * width + (start[below] + 1 - reach), side="left") + stop = np.searchsorted(high, above * width + (end[below] + 1 + reach), side="right") + touching = np.maximum(stop - first, 0) + pairs = np.repeat(below, touching) + offset = np.arange(touching.sum()) - np.repeat(np.cumsum(touching) - touching, touching) + other = order[np.repeat(first, touching) + offset] + size = row.size + graph = coo_matrix((np.ones(pairs.size, np.int8), (pairs, other)), shape=(size, size)) + return connected_components(graph, directed=False)[1] diff --git a/src/morphobricks_preprocessing/mask_scan.py b/src/morphobricks_preprocessing/mask_scan.py index 807b190d..2fd5f4a6 100644 --- a/src/morphobricks_preprocessing/mask_scan.py +++ b/src/morphobricks_preprocessing/mask_scan.py @@ -55,7 +55,6 @@ from types import MappingProxyType import numpy as np -from scipy import ndimage from ._io import write_text_atomic from .manifest import package_versions @@ -63,8 +62,8 @@ from .mask_binding import check_scanned, refuse_unbound, scan_fingerprints from .mask_pairs import best_parents, match_counts from .mask_pairs import one_to_one_matches as one_to_one_matches # moved there +from .mask_pieces import piece_counts as piece_counts # moved there (issue #69) from .masks import MaskInventory, check_labels, read_mask -from .masks.binary import STRUCTURE logger = logging.getLogger(__name__) @@ -297,37 +296,6 @@ def mask_thresholds(changes: Mapping[str, float] | None = None) -> Mapping[str, return MappingProxyType(thresholds) -def piece_counts(mask: np.ndarray) -> tuple[np.ndarray, np.ndarray]: - """Return the labels of a 2D mask and the number of 8-connected pieces of each. - - Two pixels are in one piece when they carry the same label and touch along an edge or at - a corner (:data:`.masks.binary.STRUCTURE`). Label 0 is the background. - - Returns - ------- - tuple of numpy.ndarray - The sorted nonzero labels, and the number of pieces of each. - - Raises - ------ - ValueError - If the mask holds a label outside 0 to 2,147,483,647, or pixels that are not - whole numbers (:func:`.masks.check_labels`). - """ - check_labels(mask) - values, dense = np.unique(mask, return_inverse=True) - dense = dense.reshape(mask.shape) - if values.size and values[0] == 0: # labels are never negative, so 0 comes first - values = values[1:] - else: - dense = dense + 1 # no background: every value is a label - counts = np.zeros(values.size, dtype=np.int64) - for index, box in enumerate(ndimage.find_objects(dense)): - if box is not None: - counts[index] = ndimage.label(dense[box] == index + 1, STRUCTURE)[1] - return values, counts - - def pair_counts( child: np.ndarray, parent: np.ndarray, *, thresholds: Mapping[str, float] | None = None ) -> dict[str, int]: diff --git a/tests/test_mask_pieces.py b/tests/test_mask_pieces.py new file mode 100644 index 00000000..875dde6d --- /dev/null +++ b/tests/test_mask_pieces.py @@ -0,0 +1,120 @@ +"""The run-based piece_counts gives byte-identical results to the per-label one (issue #69).""" + +from __future__ import annotations + +import numpy as np +import pytest +from scipy import ndimage + +from morphobricks_preprocessing import piece_counts +from morphobricks_preprocessing.masks import check_labels +from morphobricks_preprocessing.masks.binary import STRUCTURE + +DTYPES = (np.bool_, np.uint8, np.int8, np.uint16, np.int16, np.uint32, np.int32, np.int64) +DTYPES += (np.uint64,) + + +def boxes_piece_counts(mask): + """Return piece_counts as it was before issue #69 (main c8c3808), kept as the reference.""" + check_labels(mask) + values, dense = np.unique(mask, return_inverse=True) + dense = dense.reshape(mask.shape) + if values.size and values[0] == 0: + values = values[1:] + else: + dense = dense + 1 + counts = np.zeros(values.size, dtype=np.int64) + for index, box in enumerate(ndimage.find_objects(dense)): + if box is not None: + counts[index] = ndimage.label(dense[box] == index + 1, STRUCTURE)[1] + return values, counts + + +def assert_identical(mask): + new, old = piece_counts(mask), boxes_piece_counts(mask) + for found, expected in zip(new, old, strict=True): + assert found.dtype == expected.dtype + assert found.shape == expected.shape + assert found.tobytes() == expected.tobytes() + + +def random_mask(rng, dtype): + """Return a random mask of one of several kinds, in the pixel type given.""" + shape = tuple(int(n) for n in rng.integers(1, 40, 2)) + kind = rng.integers(6) + top = 1 if dtype is np.bool_ else int(min(np.iinfo(dtype).max, 2_147_483_647)) + if kind == 0: # few labels, densely touching, holes of background + mask = rng.integers(0, min(top, 4) + 1, shape) + elif kind == 1: # single pixels scattered on background + mask = np.where(rng.random(shape) < 0.05, rng.integers(1, top + 1, shape), 0) + elif kind == 2: # blocks (touching objects with holes), labels far apart + small = rng.integers(0, 4, (shape[0] // 3 + 1, shape[1] // 3 + 1)) + mask = np.kron(small, np.ones((3, 3), int))[: shape[0], : shape[1]] + values = rng.integers(1, top + 1, 3) # possibly equal: one label in several blocks + mask = np.where(mask == 0, 0, values[(mask - 1) % 3]) + mask[rng.random(shape) < 0.1] = 0 # holes + elif kind == 3: # no background at all + mask = rng.integers(1, min(top, 3) + 1, shape) + elif kind == 4: # one label touching the edges, corners only (diagonals) + mask = (np.add.outer(np.arange(shape[0]), np.arange(shape[1])) % 2) * min(top, 7) + else: # empty + mask = np.zeros(shape, int) + return np.asarray(mask).astype(dtype) + + +@pytest.mark.parametrize("dtype", DTYPES) +def test_piece_counts_equal_the_per_label_reference_on_random_masks(dtype): + rng = np.random.default_rng(69) + for _ in range(300): + assert_identical(random_mask(rng, dtype)) + + +@pytest.mark.parametrize( + "mask", + [ + np.zeros((1, 1), np.int32), + np.ones((1, 1), np.int32), + np.full((3, 3), 2_147_483_647, np.int64), + np.array([[1, 0, 1]], np.uint8), + np.eye(5, dtype=np.uint8) + np.fliplr(np.eye(5, dtype=np.uint8)) * 2, + np.array([[1, 2], [2, 1]], np.int32), # two labels crossing at a corner + np.array([[1, 1, 1], [1, 0, 1], [1, 1, 1]], np.int32), # a ring around a hole + np.array([[5], [0], [5], [5]], np.int32), + np.array([[True, False], [False, True]]), + ], +) +def test_piece_counts_equal_the_reference_on_edge_cases(mask): + assert_identical(mask) + + +def test_piece_counts_equal_the_reference_on_the_benchmark_masks(): + import sys + from pathlib import Path + + sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) + try: + import benchmark_inputs + finally: + sys.path.pop(0) + cells, nuclei = benchmark_inputs._label_masks(512, 256, 0) + assert_identical(cells) + assert_identical(nuclei) + assert_identical(np.where(nuclei != 0, nuclei + cells.max(), cells)) # rings round nuclei + + +@pytest.mark.parametrize("shape", [(0, 0), (0, 5), (4, 0)]) +def test_a_mask_without_pixels_has_no_labels(shape): + # the reference failed here (find_objects of no pixels: a NumPy error, not a result); + # a plane of no pixels holds no labels, as a plane of background + values, counts = piece_counts(np.zeros(shape, np.uint16)) + assert values.dtype == np.uint16 and values.size == 0 + assert counts.dtype == np.int64 and counts.size == 0 + with pytest.raises(ValueError, match="zero-size"): + boxes_piece_counts(np.zeros(shape, np.uint16)) + + +def test_piece_counts_refuse_a_mask_that_is_not_2d(): + with pytest.raises(ValueError, match="2D"): + piece_counts(np.ones((2, 2, 2), np.int32)) + with pytest.raises(ValueError, match="negative"): + piece_counts(np.full((2, 2), -1, np.int32)) From 26c94049128616bf9a891a18931caf1bf02f4ec7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 00:59:00 +0000 Subject: [PATCH 2/4] piece_counts: take the former route on pixel-scale masks (review of #568) The runs route of the first version needed up to 3.4 GiB and 7.4 s on a 4096 px two-label checkerboard (464 MiB and 0.93 s before), as runs are almost pixels there and its int64 temporaries were all alive at the graph. Now: - runs are found without a sort: places are row * (columns + 2) + column, increasing, so the runs above a run that touch it are one slice found by two binary searches; places and edges are int32 when they fit (bounds checked), int64 otherwise; temporaries are freed before the graph is built, and the label bound is no longer recomputed; - above RUNS_PER_PIXEL_LIMIT = 0.25 runs per pixel the former route (sort, then ndimage.label per label in its box) is taken, unchanged. Every identity test now runs three times: runs forced, boxes forced and the route chosen. The kernel benchmark gains three pixel-scale masks (two checkerboards and noise); docs/benchmarks.md has before, first version and after, with equal digests, and the trade-off. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a --- AGENTS.md | 5 +- .../2026-11-25-kernels-masks-after-69.json | 253 ----------- .../2026-11-25-kernels-masks-before-69.json | 253 ----------- .../2026-11-26-kernels-masks-after-69.json | 415 ++++++++++++++++++ .../2026-11-26-kernels-masks-before-69.json | 415 ++++++++++++++++++ .../2026-11-26-kernels-masks-first-69.json | 415 ++++++++++++++++++ docs/benchmarks.md | 87 ++-- docs/development.md | 3 +- src/morphobricks_preprocessing/mask_pieces.py | 141 ++++-- tests/test_mask_pieces.py | 32 +- tools/benchmark_inputs.py | 32 ++ tools/benchmark_kernels.py | 9 +- 12 files changed, 1473 insertions(+), 587 deletions(-) delete mode 100644 docs/benchmark_results/2026-11-25-kernels-masks-after-69.json delete mode 100644 docs/benchmark_results/2026-11-25-kernels-masks-before-69.json create mode 100644 docs/benchmark_results/2026-11-26-kernels-masks-after-69.json create mode 100644 docs/benchmark_results/2026-11-26-kernels-masks-before-69.json create mode 100644 docs/benchmark_results/2026-11-26-kernels-masks-first-69.json diff --git a/AGENTS.md b/AGENTS.md index 7613e092..39b56123 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -407,8 +407,9 @@ src/morphobricks_preprocessing/ parent, ambiguous_parent; Q74), one_to_one_matches, match_counts and PIECE_STRUCTURE (masks.binary.STRUCTURE, 8-connected, imported) mask_pieces.py piece_counts (#69): each row cut into runs of one label, runs of one - label in neighbouring rows joined (scipy.sparse.csgraph); no sort of - every pixel and no labelling per label + label in neighbouring rows joined (scipy.sparse.csgraph); above + RUNS_PER_PIXEL_LIMIT (0.25, pixel-scale masks) the former route (sort, + then ndimage.label per label in its box). Same counts either way copy_axes.py convert (PP-11, contract §17): the axes, shape, pixel sizes (by role; a relabelled axis gets an unknown scale; equal X and Y kept through a Y/X swap, question 59) and OME metadata of a named-axis copy diff --git a/docs/benchmark_results/2026-11-25-kernels-masks-after-69.json b/docs/benchmark_results/2026-11-25-kernels-masks-after-69.json deleted file mode 100644 index a0dbc971..00000000 --- a/docs/benchmark_results/2026-11-25-kernels-masks-after-69.json +++ /dev/null @@ -1,253 +0,0 @@ -{ - "benchmark": "kernels", - "mode": "full", - "repeats": 7, - "machine": { - "processor": "Intel(R) Xeon(R) Processor @ 2.10GHz", - "cpus": 4, - "cpus_usable": 4, - "memory_bytes": 16868675584, - "load_average": [ - 2.19091796875, - 1.298828125, - 1.29248046875 - ], - "system": "Linux-6.18.44-fc-v880-x86_64-with-glibc2.39", - "python": "3.13.18", - "libraries": { - "numpy": "2.5.5", - "scipy": "1.18.1", - "tifffile": "2026.11.16", - "imagecodecs": "2026.11.11", - "zarr": "3.4.2", - "morphobricks-normalization": "0.8.0", - "morphobricks-preprocessing": "0.8.0" - }, - "thread_variables": { - "OMP_NUM_THREADS": null, - "OPENBLAS_NUM_THREADS": null, - "MKL_NUM_THREADS": null - }, - "commit": "c8c3808b17b76be012e0dcb532af4e362c752b81" - }, - "cases": [ - { - "group": "masks", - "name": "check_labels_2048", - "params": { - "side": 2048, - "dtype": "int32", - "objects": 1024 - }, - "wall_seconds": { - "median": 0.001998, - "min": 0.001888, - "max": 0.002133, - "values": [ - 0.001998, - 0.002133, - 0.002037, - 0.001911, - 0.001987, - 0.001888, - 0.002041 - ] - }, - "digest": "c48ceaf4c6bfc750821874d2296ef001311822644ed70e9d68338c231ae08052", - "digest_stable": true, - "peak_traced_bytes": 906 - }, - { - "group": "masks", - "name": "piece_counts_2048", - "params": { - "side": 2048, - "dtype": "int32", - "objects": 1024 - }, - "wall_seconds": { - "median": 0.041171, - "min": 0.036741, - "max": 0.046216, - "values": [ - 0.046216, - 0.041171, - 0.040789, - 0.042367, - 0.036741, - 0.041169, - 0.041371 - ] - }, - "digest": "4abd144b846d176cb4b83026fe4653cf3ba8999eb906a5804483eef15c2592ae", - "digest_stable": true, - "peak_traced_bytes": 12648216 - }, - { - "group": "masks", - "name": "pair_counts_2048", - "params": { - "side": 2048, - "dtype": "int32", - "objects": 1024 - }, - "wall_seconds": { - "median": 0.049326, - "min": 0.04628, - "max": 0.111908, - "values": [ - 0.111908, - 0.060893, - 0.048478, - 0.049326, - 0.060562, - 0.04628, - 0.046498 - ] - }, - "digest": "fb7de56131b3fa8f42c0f23a13fae275c5967deb09bab898c72e55a6817cd62a", - "digest_stable": true, - "peak_traced_bytes": 28708302 - }, - { - "group": "masks", - "name": "scan_position_2048", - "params": { - "side": 2048, - "dtype": "int32", - "objects": 1024, - "mask_types": 2 - }, - "wall_seconds": { - "median": 0.247, - "min": 0.219788, - "max": 0.30201, - "values": [ - 0.250143, - 0.247, - 0.220121, - 0.225868, - 0.219788, - 0.30201, - 0.251453 - ] - }, - "digest": "69de16bd28281cc3c791e68b8c52246bf95429760d0948b36e2a9eda0e74a8b6", - "digest_stable": true, - "peak_traced_bytes": 82261645 - }, - { - "group": "masks", - "name": "check_labels_4096", - "params": { - "side": 4096, - "dtype": "int32", - "objects": 4096 - }, - "wall_seconds": { - "median": 0.014363, - "min": 0.013549, - "max": 0.015606, - "values": [ - 0.015606, - 0.014242, - 0.013549, - 0.014663, - 0.015171, - 0.013901, - 0.014363 - ] - }, - "digest": "c48ceaf4c6bfc750821874d2296ef001311822644ed70e9d68338c231ae08052", - "digest_stable": true, - "peak_traced_bytes": 906 - }, - { - "group": "masks", - "name": "piece_counts_4096", - "params": { - "side": 4096, - "dtype": "int32", - "objects": 4096 - }, - "wall_seconds": { - "median": 0.180798, - "min": 0.159018, - "max": 0.21024, - "values": [ - 0.196094, - 0.21024, - 0.185725, - 0.172789, - 0.180798, - 0.170331, - 0.159018 - ] - }, - "digest": "c575615afca962cf72fc50c2229c14557053ba7e8b7abb636139348693ebb2b0", - "digest_stable": true, - "peak_traced_bytes": 50329400 - }, - { - "group": "masks", - "name": "pair_counts_4096", - "params": { - "side": 4096, - "dtype": "int32", - "objects": 4096 - }, - "wall_seconds": { - "median": 0.271277, - "min": 0.254412, - "max": 0.324182, - "values": [ - 0.266288, - 0.267709, - 0.254412, - 0.307467, - 0.324182, - 0.307412, - 0.271277 - ] - }, - "digest": "550398e1f131c578ee82c4f220aa74ef2475c15da77d7277d451640f3eff74d1", - "digest_stable": true, - "peak_traced_bytes": 114824538 - }, - { - "group": "masks", - "name": "scan_position_4096", - "params": { - "side": 4096, - "dtype": "int32", - "objects": 4096, - "mask_types": 2 - }, - "wall_seconds": { - "median": 1.251531, - "min": 1.086103, - "max": 1.407519, - "values": [ - 1.407519, - 1.123353, - 1.274879, - 1.086103, - 1.329764, - 1.251531, - 1.151125 - ] - }, - "digest": "ec5910c05e04c1c70be1da3498630d1e30d68e47ac7dddd62d056dcdd0599d95", - "digest_stable": true, - "peak_traced_bytes": 329032455 - } - ], - "inputs": { - "label_masks_2048_1024_seed0": "6f6b9edfc43758b635ae5e0f10a9cddc7c072f9a4e39aaba172da9cea3ec0820", - "label_masks_4096_4096_seed0": "8479cf81d94e9212f5a8982ea5514bebd686efe7c1f2fc0a2e925368befe6901" - }, - "process": { - "peak_rss_bytes": 661131264, - "source": "VmHWM" - } -} diff --git a/docs/benchmark_results/2026-11-25-kernels-masks-before-69.json b/docs/benchmark_results/2026-11-25-kernels-masks-before-69.json deleted file mode 100644 index 905586fd..00000000 --- a/docs/benchmark_results/2026-11-25-kernels-masks-before-69.json +++ /dev/null @@ -1,253 +0,0 @@ -{ - "benchmark": "kernels", - "mode": "full", - "repeats": 7, - "machine": { - "processor": "Intel(R) Xeon(R) Processor @ 2.10GHz", - "cpus": 4, - "cpus_usable": 4, - "memory_bytes": 16868675584, - "load_average": [ - 0.826171875, - 0.89697265625, - 1.17578125 - ], - "system": "Linux-6.18.44-fc-v880-x86_64-with-glibc2.39", - "python": "3.13.18", - "libraries": { - "numpy": "2.5.5", - "scipy": "1.18.1", - "tifffile": "2026.11.16", - "imagecodecs": "2026.11.11", - "zarr": "3.4.2", - "morphobricks-normalization": "0.8.0", - "morphobricks-preprocessing": "0.8.0" - }, - "thread_variables": { - "OMP_NUM_THREADS": null, - "OPENBLAS_NUM_THREADS": null, - "MKL_NUM_THREADS": null - }, - "commit": "c8c3808b17b76be012e0dcb532af4e362c752b81" - }, - "cases": [ - { - "group": "masks", - "name": "check_labels_2048", - "params": { - "side": 2048, - "dtype": "int32", - "objects": 1024 - }, - "wall_seconds": { - "median": 0.002036, - "min": 0.001994, - "max": 0.002325, - "values": [ - 0.002036, - 0.002032, - 0.002055, - 0.002094, - 0.002001, - 0.001994, - 0.002325 - ] - }, - "digest": "c48ceaf4c6bfc750821874d2296ef001311822644ed70e9d68338c231ae08052", - "digest_stable": true, - "peak_traced_bytes": 906 - }, - { - "group": "masks", - "name": "piece_counts_2048", - "params": { - "side": 2048, - "dtype": "int32", - "objects": 1024 - }, - "wall_seconds": { - "median": 0.342689, - "min": 0.330181, - "max": 0.378958, - "values": [ - 0.342689, - 0.37442, - 0.370809, - 0.332056, - 0.330181, - 0.335145, - 0.378958 - ] - }, - "digest": "4abd144b846d176cb4b83026fe4653cf3ba8999eb906a5804483eef15c2592ae", - "digest_stable": true, - "peak_traced_bytes": 138417591 - }, - { - "group": "masks", - "name": "pair_counts_2048", - "params": { - "side": 2048, - "dtype": "int32", - "objects": 1024 - }, - "wall_seconds": { - "median": 0.045209, - "min": 0.043809, - "max": 0.045972, - "values": [ - 0.045209, - 0.045724, - 0.044547, - 0.045937, - 0.045972, - 0.04406, - 0.043809 - ] - }, - "digest": "fb7de56131b3fa8f42c0f23a13fae275c5967deb09bab898c72e55a6817cd62a", - "digest_stable": true, - "peak_traced_bytes": 28708251 - }, - { - "group": "masks", - "name": "scan_position_2048", - "params": { - "side": 2048, - "dtype": "int32", - "objects": 1024, - "mask_types": 2 - }, - "wall_seconds": { - "median": 0.91742, - "min": 0.798109, - "max": 1.067031, - "values": [ - 0.97172, - 0.878678, - 0.962361, - 1.067031, - 0.887292, - 0.91742, - 0.798109 - ] - }, - "digest": "69de16bd28281cc3c791e68b8c52246bf95429760d0948b36e2a9eda0e74a8b6", - "digest_stable": true, - "peak_traced_bytes": 138430531 - }, - { - "group": "masks", - "name": "check_labels_4096", - "params": { - "side": 4096, - "dtype": "int32", - "objects": 4096 - }, - "wall_seconds": { - "median": 0.009551, - "min": 0.008978, - "max": 0.010588, - "values": [ - 0.010588, - 0.00978, - 0.009551, - 0.009805, - 0.009068, - 0.009039, - 0.008978 - ] - }, - "digest": "c48ceaf4c6bfc750821874d2296ef001311822644ed70e9d68338c231ae08052", - "digest_stable": true, - "peak_traced_bytes": 906 - }, - { - "group": "masks", - "name": "piece_counts_4096", - "params": { - "side": 4096, - "dtype": "int32", - "objects": 4096 - }, - "wall_seconds": { - "median": 2.368892, - "min": 2.237558, - "max": 2.533668, - "values": [ - 2.416621, - 2.519051, - 2.237558, - 2.368892, - 2.262554, - 2.293342, - 2.533668 - ] - }, - "digest": "c575615afca962cf72fc50c2229c14557053ba7e8b7abb636139348693ebb2b0", - "digest_stable": true, - "peak_traced_bytes": 553665975 - }, - { - "group": "masks", - "name": "pair_counts_4096", - "params": { - "side": 4096, - "dtype": "int32", - "objects": 4096 - }, - "wall_seconds": { - "median": 0.258079, - "min": 0.249646, - "max": 0.29505, - "values": [ - 0.258079, - 0.252204, - 0.249646, - 0.29369, - 0.29505, - 0.253031, - 0.258973 - ] - }, - "digest": "550398e1f131c578ee82c4f220aa74ef2475c15da77d7277d451640f3eff74d1", - "digest_stable": true, - "peak_traced_bytes": 114824538 - }, - { - "group": "masks", - "name": "scan_position_4096", - "params": { - "side": 4096, - "dtype": "int32", - "objects": 4096, - "mask_types": 2 - }, - "wall_seconds": { - "median": 5.200998, - "min": 5.040348, - "max": 5.649843, - "values": [ - 5.0494, - 5.046973, - 5.649843, - 5.200998, - 5.282038, - 5.040348, - 5.449511 - ] - }, - "digest": "ec5910c05e04c1c70be1da3498630d1e30d68e47ac7dddd62d056dcdd0599d95", - "digest_stable": true, - "peak_traced_bytes": 553827830 - } - ], - "inputs": { - "label_masks_2048_1024_seed0": "6f6b9edfc43758b635ae5e0f10a9cddc7c072f9a4e39aaba172da9cea3ec0820", - "label_masks_4096_4096_seed0": "8479cf81d94e9212f5a8982ea5514bebd686efe7c1f2fc0a2e925368befe6901" - }, - "process": { - "peak_rss_bytes": 882270208, - "source": "VmHWM" - } -} diff --git a/docs/benchmark_results/2026-11-26-kernels-masks-after-69.json b/docs/benchmark_results/2026-11-26-kernels-masks-after-69.json new file mode 100644 index 00000000..52c06466 --- /dev/null +++ b/docs/benchmark_results/2026-11-26-kernels-masks-after-69.json @@ -0,0 +1,415 @@ +{ + "benchmark": "kernels", + "mode": "full", + "repeats": 7, + "machine": { + "processor": "Intel(R) Xeon(R) Processor @ 2.10GHz", + "cpus": 4, + "cpus_usable": 4, + "memory_bytes": 16868675584, + "load_average": [ + 2.02978515625, + 1.89111328125, + 1.47216796875 + ], + "system": "Linux-6.18.44-fc-v880-x86_64-with-glibc2.39", + "python": "3.13.18", + "libraries": { + "numpy": "2.5.5", + "scipy": "1.18.1", + "tifffile": "2026.11.16", + "imagecodecs": "2026.11.11", + "zarr": "3.4.2", + "morphobricks-normalization": "0.8.0", + "morphobricks-preprocessing": "0.8.0" + }, + "thread_variables": { + "OMP_NUM_THREADS": null, + "OPENBLAS_NUM_THREADS": null, + "MKL_NUM_THREADS": null + }, + "commit": "85715dc336e68c68185f5eaf9d50008057e48b00" + }, + "cases": [ + { + "group": "masks", + "name": "check_labels_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024 + }, + "wall_seconds": { + "median": 0.001869, + "min": 0.001835, + "max": 0.001964, + "values": [ + 0.001964, + 0.001895, + 0.001846, + 0.001869, + 0.001835, + 0.001928, + 0.001844 + ] + }, + "digest": "c48ceaf4c6bfc750821874d2296ef001311822644ed70e9d68338c231ae08052", + "digest_stable": true, + "peak_traced_bytes": 906 + }, + { + "group": "masks", + "name": "piece_counts_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024 + }, + "wall_seconds": { + "median": 0.015933, + "min": 0.015694, + "max": 0.016281, + "values": [ + 0.016281, + 0.015933, + 0.015694, + 0.015762, + 0.015839, + 0.016092, + 0.016049 + ] + }, + "digest": "4abd144b846d176cb4b83026fe4653cf3ba8999eb906a5804483eef15c2592ae", + "digest_stable": true, + "peak_traced_bytes": 8875880 + }, + { + "group": "masks", + "name": "pair_counts_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024 + }, + "wall_seconds": { + "median": 0.040709, + "min": 0.0403, + "max": 0.041669, + "values": [ + 0.041669, + 0.040491, + 0.041277, + 0.0403, + 0.040709, + 0.040462, + 0.041123 + ] + }, + "digest": "fb7de56131b3fa8f42c0f23a13fae275c5967deb09bab898c72e55a6817cd62a", + "digest_stable": true, + "peak_traced_bytes": 28708302 + }, + { + "group": "masks", + "name": "scan_position_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024, + "mask_types": 2 + }, + "wall_seconds": { + "median": 0.206284, + "min": 0.174158, + "max": 0.234271, + "values": [ + 0.177785, + 0.189743, + 0.174158, + 0.206284, + 0.212374, + 0.228102, + 0.234271 + ] + }, + "digest": "69de16bd28281cc3c791e68b8c52246bf95429760d0948b36e2a9eda0e74a8b6", + "digest_stable": true, + "peak_traced_bytes": 82261575 + }, + { + "group": "masks", + "name": "piece_counts_checker_two_labels_2048", + "params": { + "side": 2048, + "dtype": "uint16", + "mask": "checker_two_labels" + }, + "wall_seconds": { + "median": 0.191212, + "min": 0.186133, + "max": 0.217164, + "values": [ + 0.217164, + 0.188943, + 0.191212, + 0.186172, + 0.186133, + 0.20352, + 0.19131 + ] + }, + "digest": "e90ded1a1d3176d93d0b507b78675e8edd586ee05aa73355ea30d64453a92f7c", + "digest_stable": true, + "peak_traced_bytes": 121636335 + }, + { + "group": "masks", + "name": "piece_counts_checker_one_label_2048", + "params": { + "side": 2048, + "dtype": "int32", + "mask": "checker_one_label" + }, + "wall_seconds": { + "median": 0.146806, + "min": 0.120743, + "max": 0.163575, + "values": [ + 0.150495, + 0.160894, + 0.163575, + 0.146806, + 0.120743, + 0.125493, + 0.123564 + ] + }, + "digest": "6543cf267d7ad9900ce44546aa51026889fc9bc24105eb0e261454df6d3595bf", + "digest_stable": true, + "peak_traced_bytes": 138413555 + }, + { + "group": "masks", + "name": "piece_counts_noise_four_labels_2048", + "params": { + "side": 2048, + "dtype": "int32", + "mask": "noise_four_labels" + }, + "wall_seconds": { + "median": 0.234427, + "min": 0.226009, + "max": 0.275019, + "values": [ + 0.275019, + 0.234645, + 0.229895, + 0.226009, + 0.228545, + 0.235392, + 0.234427 + ] + }, + "digest": "484c7df9ddc9e95d8cbecda2ae952a97521b615f6c30f2ef3fa7a1312f8ca82e", + "digest_stable": true, + "peak_traced_bytes": 138413567 + }, + { + "group": "masks", + "name": "check_labels_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096 + }, + "wall_seconds": { + "median": 0.011099, + "min": 0.010308, + "max": 0.012855, + "values": [ + 0.012855, + 0.011799, + 0.011304, + 0.011099, + 0.010624, + 0.010427, + 0.010308 + ] + }, + "digest": "c48ceaf4c6bfc750821874d2296ef001311822644ed70e9d68338c231ae08052", + "digest_stable": true, + "peak_traced_bytes": 906 + }, + { + "group": "masks", + "name": "piece_counts_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096 + }, + "wall_seconds": { + "median": 0.103268, + "min": 0.098926, + "max": 0.109748, + "values": [ + 0.104251, + 0.109748, + 0.099894, + 0.098926, + 0.099146, + 0.103268, + 0.108353 + ] + }, + "digest": "c575615afca962cf72fc50c2229c14557053ba7e8b7abb636139348693ebb2b0", + "digest_stable": true, + "peak_traced_bytes": 35239136 + }, + { + "group": "masks", + "name": "pair_counts_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096 + }, + "wall_seconds": { + "median": 0.246665, + "min": 0.24064, + "max": 0.25314, + "values": [ + 0.25314, + 0.245278, + 0.246665, + 0.248354, + 0.24064, + 0.24626, + 0.249159 + ] + }, + "digest": "550398e1f131c578ee82c4f220aa74ef2475c15da77d7277d451640f3eff74d1", + "digest_stable": true, + "peak_traced_bytes": 114824538 + }, + { + "group": "masks", + "name": "scan_position_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096, + "mask_types": 2 + }, + "wall_seconds": { + "median": 0.965173, + "min": 0.877948, + "max": 1.142134, + "values": [ + 0.998201, + 0.947318, + 0.991084, + 0.965173, + 1.142134, + 0.877948, + 0.913633 + ] + }, + "digest": "ec5910c05e04c1c70be1da3498630d1e30d68e47ac7dddd62d056dcdd0599d95", + "digest_stable": true, + "peak_traced_bytes": 329032385 + }, + { + "group": "masks", + "name": "piece_counts_checker_two_labels_4096", + "params": { + "side": 4096, + "dtype": "uint16", + "mask": "checker_two_labels" + }, + "wall_seconds": { + "median": 1.008785, + "min": 0.916397, + "max": 1.076366, + "values": [ + 1.008785, + 0.916397, + 0.917799, + 1.067104, + 1.056461, + 1.076366, + 0.953025 + ] + }, + "digest": "e90ded1a1d3176d93d0b507b78675e8edd586ee05aa73355ea30d64453a92f7c", + "digest_stable": true, + "peak_traced_bytes": 486540783 + }, + { + "group": "masks", + "name": "piece_counts_checker_one_label_4096", + "params": { + "side": 4096, + "dtype": "int32", + "mask": "checker_one_label" + }, + "wall_seconds": { + "median": 0.555802, + "min": 0.513335, + "max": 0.73844, + "values": [ + 0.555802, + 0.563678, + 0.556308, + 0.73844, + 0.538975, + 0.516233, + 0.513335 + ] + }, + "digest": "6543cf267d7ad9900ce44546aa51026889fc9bc24105eb0e261454df6d3595bf", + "digest_stable": true, + "peak_traced_bytes": 553649651 + }, + { + "group": "masks", + "name": "piece_counts_noise_four_labels_4096", + "params": { + "side": 4096, + "dtype": "int32", + "mask": "noise_four_labels" + }, + "wall_seconds": { + "median": 1.049175, + "min": 1.034844, + "max": 1.077008, + "values": [ + 1.077008, + 1.034844, + 1.058906, + 1.049175, + 1.065827, + 1.035151, + 1.044139 + ] + }, + "digest": "99f3f03132d213f6afe16a46fb554f6d59e3665bf733b7375c6e6aeaa91be070", + "digest_stable": true, + "peak_traced_bytes": 553649663 + } + ], + "inputs": { + "label_masks_2048_1024_seed0": "6f6b9edfc43758b635ae5e0f10a9cddc7c072f9a4e39aaba172da9cea3ec0820", + "label_masks_4096_4096_seed0": "8479cf81d94e9212f5a8982ea5514bebd686efe7c1f2fc0a2e925368befe6901", + "pixel_mask_checker_one_label_2048_seed0": "a597a0206d8d27b6d857efe1f9069e9246522a73edae4aabf744dbcd559b4f31", + "pixel_mask_checker_one_label_4096_seed0": "26ef4b71ccaa65f5a5ff86a31dbe488583b67aa3165cf3ed2e9b7e972aa0d06f", + "pixel_mask_checker_two_labels_2048_seed0": "42afbe3e4b3b9fa658942c265b01fc7960fef661a609ba4b2286e25b0a4c76fa", + "pixel_mask_checker_two_labels_4096_seed0": "841e970fb9f445c3341c8e45018117223fadd478e3c3cb6a85383cbc8874d72c", + "pixel_mask_noise_four_labels_2048_seed0": "7b632ff2353b114032a743330b6ce72a4ed1b2fe1317bf5d12f129f6fc3ef000", + "pixel_mask_noise_four_labels_4096_seed0": "8d0b640079b53089919f8d2b23af1914ca09349668c6880b97ee1f82d8b5b980" + }, + "process": { + "peak_rss_bytes": 932573184, + "source": "VmHWM" + } +} diff --git a/docs/benchmark_results/2026-11-26-kernels-masks-before-69.json b/docs/benchmark_results/2026-11-26-kernels-masks-before-69.json new file mode 100644 index 00000000..31451409 --- /dev/null +++ b/docs/benchmark_results/2026-11-26-kernels-masks-before-69.json @@ -0,0 +1,415 @@ +{ + "benchmark": "kernels", + "mode": "full", + "repeats": 7, + "machine": { + "processor": "Intel(R) Xeon(R) Processor @ 2.10GHz", + "cpus": 4, + "cpus_usable": 4, + "memory_bytes": 16868675584, + "load_average": [ + 2.185546875, + 1.833984375, + 1.396484375 + ], + "system": "Linux-6.18.44-fc-v880-x86_64-with-glibc2.39", + "python": "3.13.18", + "libraries": { + "numpy": "2.5.5", + "scipy": "1.18.1", + "tifffile": "2026.11.16", + "imagecodecs": "2026.11.11", + "zarr": "3.4.2", + "morphobricks-normalization": "0.8.0", + "morphobricks-preprocessing": "0.8.0" + }, + "thread_variables": { + "OMP_NUM_THREADS": null, + "OPENBLAS_NUM_THREADS": null, + "MKL_NUM_THREADS": null + }, + "commit": "85715dc336e68c68185f5eaf9d50008057e48b00" + }, + "cases": [ + { + "group": "masks", + "name": "check_labels_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024 + }, + "wall_seconds": { + "median": 0.00197, + "min": 0.001903, + "max": 0.002053, + "values": [ + 0.002052, + 0.001926, + 0.002053, + 0.002011, + 0.00197, + 0.001911, + 0.001903 + ] + }, + "digest": "c48ceaf4c6bfc750821874d2296ef001311822644ed70e9d68338c231ae08052", + "digest_stable": true, + "peak_traced_bytes": 906 + }, + { + "group": "masks", + "name": "piece_counts_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024 + }, + "wall_seconds": { + "median": 0.322158, + "min": 0.31976, + "max": 0.404595, + "values": [ + 0.321944, + 0.324817, + 0.31976, + 0.324185, + 0.404595, + 0.319879, + 0.322158 + ] + }, + "digest": "4abd144b846d176cb4b83026fe4653cf3ba8999eb906a5804483eef15c2592ae", + "digest_stable": true, + "peak_traced_bytes": 138417591 + }, + { + "group": "masks", + "name": "pair_counts_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024 + }, + "wall_seconds": { + "median": 0.046121, + "min": 0.042481, + "max": 0.072633, + "values": [ + 0.04351, + 0.043466, + 0.042481, + 0.046121, + 0.050732, + 0.060274, + 0.072633 + ] + }, + "digest": "fb7de56131b3fa8f42c0f23a13fae275c5967deb09bab898c72e55a6817cd62a", + "digest_stable": true, + "peak_traced_bytes": 28708302 + }, + { + "group": "masks", + "name": "scan_position_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024, + "mask_types": 2 + }, + "wall_seconds": { + "median": 0.766444, + "min": 0.732504, + "max": 0.847649, + "values": [ + 0.847649, + 0.818197, + 0.825245, + 0.732504, + 0.762277, + 0.755497, + 0.766444 + ] + }, + "digest": "69de16bd28281cc3c791e68b8c52246bf95429760d0948b36e2a9eda0e74a8b6", + "digest_stable": true, + "peak_traced_bytes": 138430582 + }, + { + "group": "masks", + "name": "piece_counts_checker_two_labels_2048", + "params": { + "side": 2048, + "dtype": "uint16", + "mask": "checker_two_labels" + }, + "wall_seconds": { + "median": 0.194761, + "min": 0.18591, + "max": 0.255199, + "values": [ + 0.197105, + 0.197879, + 0.18725, + 0.192354, + 0.18591, + 0.194761, + 0.255199 + ] + }, + "digest": "e90ded1a1d3176d93d0b507b78675e8edd586ee05aa73355ea30d64453a92f7c", + "digest_stable": true, + "peak_traced_bytes": 121636279 + }, + { + "group": "masks", + "name": "piece_counts_checker_one_label_2048", + "params": { + "side": 2048, + "dtype": "int32", + "mask": "checker_one_label" + }, + "wall_seconds": { + "median": 0.135449, + "min": 0.126606, + "max": 0.149589, + "values": [ + 0.144688, + 0.135449, + 0.144362, + 0.132157, + 0.149589, + 0.129514, + 0.126606 + ] + }, + "digest": "6543cf267d7ad9900ce44546aa51026889fc9bc24105eb0e261454df6d3595bf", + "digest_stable": true, + "peak_traced_bytes": 138413499 + }, + { + "group": "masks", + "name": "piece_counts_noise_four_labels_2048", + "params": { + "side": 2048, + "dtype": "int32", + "mask": "noise_four_labels" + }, + "wall_seconds": { + "median": 0.249787, + "min": 0.236475, + "max": 0.286294, + "values": [ + 0.263426, + 0.240202, + 0.286294, + 0.249787, + 0.27199, + 0.2379, + 0.236475 + ] + }, + "digest": "484c7df9ddc9e95d8cbecda2ae952a97521b615f6c30f2ef3fa7a1312f8ca82e", + "digest_stable": true, + "peak_traced_bytes": 138413511 + }, + { + "group": "masks", + "name": "check_labels_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096 + }, + "wall_seconds": { + "median": 0.008296, + "min": 0.00789, + "max": 0.009648, + "values": [ + 0.009648, + 0.008601, + 0.008209, + 0.008296, + 0.007917, + 0.009124, + 0.00789 + ] + }, + "digest": "c48ceaf4c6bfc750821874d2296ef001311822644ed70e9d68338c231ae08052", + "digest_stable": true, + "peak_traced_bytes": 906 + }, + { + "group": "masks", + "name": "piece_counts_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096 + }, + "wall_seconds": { + "median": 2.326556, + "min": 1.975756, + "max": 2.453263, + "values": [ + 2.098495, + 2.326556, + 2.192875, + 2.453263, + 2.366127, + 2.410921, + 1.975756 + ] + }, + "digest": "c575615afca962cf72fc50c2229c14557053ba7e8b7abb636139348693ebb2b0", + "digest_stable": true, + "peak_traced_bytes": 553665975 + }, + { + "group": "masks", + "name": "pair_counts_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096 + }, + "wall_seconds": { + "median": 0.258652, + "min": 0.246476, + "max": 0.323013, + "values": [ + 0.258652, + 0.258429, + 0.249099, + 0.246476, + 0.305424, + 0.269802, + 0.323013 + ] + }, + "digest": "550398e1f131c578ee82c4f220aa74ef2475c15da77d7277d451640f3eff74d1", + "digest_stable": true, + "peak_traced_bytes": 114824538 + }, + { + "group": "masks", + "name": "scan_position_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096, + "mask_types": 2 + }, + "wall_seconds": { + "median": 5.095042, + "min": 4.650744, + "max": 5.397004, + "values": [ + 5.095042, + 5.055642, + 4.707348, + 4.650744, + 5.219992, + 5.397004, + 5.311761 + ] + }, + "digest": "ec5910c05e04c1c70be1da3498630d1e30d68e47ac7dddd62d056dcdd0599d95", + "digest_stable": true, + "peak_traced_bytes": 553827830 + }, + { + "group": "masks", + "name": "piece_counts_checker_two_labels_4096", + "params": { + "side": 4096, + "dtype": "uint16", + "mask": "checker_two_labels" + }, + "wall_seconds": { + "median": 0.930672, + "min": 0.881983, + "max": 1.076093, + "values": [ + 0.932628, + 0.881983, + 0.885793, + 0.930672, + 1.076093, + 0.893257, + 1.003011 + ] + }, + "digest": "e90ded1a1d3176d93d0b507b78675e8edd586ee05aa73355ea30d64453a92f7c", + "digest_stable": true, + "peak_traced_bytes": 486540727 + }, + { + "group": "masks", + "name": "piece_counts_checker_one_label_4096", + "params": { + "side": 4096, + "dtype": "int32", + "mask": "checker_one_label" + }, + "wall_seconds": { + "median": 0.574058, + "min": 0.526084, + "max": 0.645883, + "values": [ + 0.645883, + 0.526084, + 0.574058, + 0.599823, + 0.572416, + 0.542284, + 0.579993 + ] + }, + "digest": "6543cf267d7ad9900ce44546aa51026889fc9bc24105eb0e261454df6d3595bf", + "digest_stable": true, + "peak_traced_bytes": 553649595 + }, + { + "group": "masks", + "name": "piece_counts_noise_four_labels_4096", + "params": { + "side": 4096, + "dtype": "int32", + "mask": "noise_four_labels" + }, + "wall_seconds": { + "median": 1.24831, + "min": 1.158099, + "max": 1.295967, + "values": [ + 1.295967, + 1.239224, + 1.248772, + 1.158099, + 1.251093, + 1.24831, + 1.215493 + ] + }, + "digest": "99f3f03132d213f6afe16a46fb554f6d59e3665bf733b7375c6e6aeaa91be070", + "digest_stable": true, + "peak_traced_bytes": 553649607 + } + ], + "inputs": { + "label_masks_2048_1024_seed0": "6f6b9edfc43758b635ae5e0f10a9cddc7c072f9a4e39aaba172da9cea3ec0820", + "label_masks_4096_4096_seed0": "8479cf81d94e9212f5a8982ea5514bebd686efe7c1f2fc0a2e925368befe6901", + "pixel_mask_checker_one_label_2048_seed0": "a597a0206d8d27b6d857efe1f9069e9246522a73edae4aabf744dbcd559b4f31", + "pixel_mask_checker_one_label_4096_seed0": "26ef4b71ccaa65f5a5ff86a31dbe488583b67aa3165cf3ed2e9b7e972aa0d06f", + "pixel_mask_checker_two_labels_2048_seed0": "42afbe3e4b3b9fa658942c265b01fc7960fef661a609ba4b2286e25b0a4c76fa", + "pixel_mask_checker_two_labels_4096_seed0": "841e970fb9f445c3341c8e45018117223fadd478e3c3cb6a85383cbc8874d72c", + "pixel_mask_noise_four_labels_2048_seed0": "7b632ff2353b114032a743330b6ce72a4ed1b2fe1317bf5d12f129f6fc3ef000", + "pixel_mask_noise_four_labels_4096_seed0": "8d0b640079b53089919f8d2b23af1914ca09349668c6880b97ee1f82d8b5b980" + }, + "process": { + "peak_rss_bytes": 949092352, + "source": "VmHWM" + } +} diff --git a/docs/benchmark_results/2026-11-26-kernels-masks-first-69.json b/docs/benchmark_results/2026-11-26-kernels-masks-first-69.json new file mode 100644 index 00000000..48b7018d --- /dev/null +++ b/docs/benchmark_results/2026-11-26-kernels-masks-first-69.json @@ -0,0 +1,415 @@ +{ + "benchmark": "kernels", + "mode": "full", + "repeats": 7, + "machine": { + "processor": "Intel(R) Xeon(R) Processor @ 2.10GHz", + "cpus": 4, + "cpus_usable": 4, + "memory_bytes": 16868675584, + "load_average": [ + 2.08056640625, + 1.92431640625, + 1.50390625 + ], + "system": "Linux-6.18.44-fc-v880-x86_64-with-glibc2.39", + "python": "3.13.18", + "libraries": { + "numpy": "2.5.5", + "scipy": "1.18.1", + "tifffile": "2026.11.16", + "imagecodecs": "2026.11.11", + "zarr": "3.4.2", + "morphobricks-normalization": "0.8.0", + "morphobricks-preprocessing": "0.8.0" + }, + "thread_variables": { + "OMP_NUM_THREADS": null, + "OPENBLAS_NUM_THREADS": null, + "MKL_NUM_THREADS": null + }, + "commit": "85715dc336e68c68185f5eaf9d50008057e48b00" + }, + "cases": [ + { + "group": "masks", + "name": "check_labels_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024 + }, + "wall_seconds": { + "median": 0.001944, + "min": 0.001917, + "max": 0.001978, + "values": [ + 0.001976, + 0.00194, + 0.001978, + 0.001917, + 0.001963, + 0.001928, + 0.001944 + ] + }, + "digest": "c48ceaf4c6bfc750821874d2296ef001311822644ed70e9d68338c231ae08052", + "digest_stable": true, + "peak_traced_bytes": 906 + }, + { + "group": "masks", + "name": "piece_counts_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024 + }, + "wall_seconds": { + "median": 0.035856, + "min": 0.035253, + "max": 0.036217, + "values": [ + 0.036161, + 0.035856, + 0.035253, + 0.035705, + 0.035531, + 0.036217, + 0.035911 + ] + }, + "digest": "4abd144b846d176cb4b83026fe4653cf3ba8999eb906a5804483eef15c2592ae", + "digest_stable": true, + "peak_traced_bytes": 12648216 + }, + { + "group": "masks", + "name": "pair_counts_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024 + }, + "wall_seconds": { + "median": 0.041415, + "min": 0.040582, + "max": 0.048826, + "values": [ + 0.048826, + 0.040582, + 0.041404, + 0.041341, + 0.041415, + 0.041744, + 0.041579 + ] + }, + "digest": "fb7de56131b3fa8f42c0f23a13fae275c5967deb09bab898c72e55a6817cd62a", + "digest_stable": true, + "peak_traced_bytes": 28708302 + }, + { + "group": "masks", + "name": "scan_position_2048", + "params": { + "side": 2048, + "dtype": "int32", + "objects": 1024, + "mask_types": 2 + }, + "wall_seconds": { + "median": 0.213596, + "min": 0.208419, + "max": 0.286879, + "values": [ + 0.209377, + 0.208419, + 0.214821, + 0.21165, + 0.215603, + 0.213596, + 0.286879 + ] + }, + "digest": "69de16bd28281cc3c791e68b8c52246bf95429760d0948b36e2a9eda0e74a8b6", + "digest_stable": true, + "peak_traced_bytes": 82261645 + }, + { + "group": "masks", + "name": "piece_counts_checker_two_labels_2048", + "params": { + "side": 2048, + "dtype": "uint16", + "mask": "checker_two_labels" + }, + "wall_seconds": { + "median": 1.480678, + "min": 1.39378, + "max": 1.647732, + "values": [ + 1.480678, + 1.461367, + 1.490105, + 1.560894, + 1.39378, + 1.471155, + 1.647732 + ] + }, + "digest": "e90ded1a1d3176d93d0b507b78675e8edd586ee05aa73355ea30d64453a92f7c", + "digest_stable": true, + "peak_traced_bytes": 892991305 + }, + { + "group": "masks", + "name": "piece_counts_checker_one_label_2048", + "params": { + "side": 2048, + "dtype": "int32", + "mask": "checker_one_label" + }, + "wall_seconds": { + "median": 0.678371, + "min": 0.631885, + "max": 0.742859, + "values": [ + 0.631885, + 0.659173, + 0.742859, + 0.685088, + 0.655698, + 0.704427, + 0.678371 + ] + }, + "digest": "6543cf267d7ad9900ce44546aa51026889fc9bc24105eb0e261454df6d3595bf", + "digest_stable": true, + "peak_traced_bytes": 450692945 + }, + { + "group": "masks", + "name": "piece_counts_noise_four_labels_2048", + "params": { + "side": 2048, + "dtype": "int32", + "mask": "noise_four_labels" + }, + "wall_seconds": { + "median": 0.549016, + "min": 0.528301, + "max": 0.570603, + "values": [ + 0.570603, + 0.550615, + 0.549016, + 0.550386, + 0.532511, + 0.538114, + 0.528301 + ] + }, + "digest": "484c7df9ddc9e95d8cbecda2ae952a97521b615f6c30f2ef3fa7a1312f8ca82e", + "digest_stable": true, + "peak_traced_bytes": 265061535 + }, + { + "group": "masks", + "name": "check_labels_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096 + }, + "wall_seconds": { + "median": 0.008901, + "min": 0.008747, + "max": 0.00989, + "values": [ + 0.00989, + 0.008934, + 0.009091, + 0.008901, + 0.008893, + 0.008856, + 0.008747 + ] + }, + "digest": "c48ceaf4c6bfc750821874d2296ef001311822644ed70e9d68338c231ae08052", + "digest_stable": true, + "peak_traced_bytes": 906 + }, + { + "group": "masks", + "name": "piece_counts_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096 + }, + "wall_seconds": { + "median": 0.167969, + "min": 0.160074, + "max": 0.20526, + "values": [ + 0.20526, + 0.182742, + 0.167969, + 0.165633, + 0.162936, + 0.17116, + 0.160074 + ] + }, + "digest": "c575615afca962cf72fc50c2229c14557053ba7e8b7abb636139348693ebb2b0", + "digest_stable": true, + "peak_traced_bytes": 50329400 + }, + { + "group": "masks", + "name": "pair_counts_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096 + }, + "wall_seconds": { + "median": 0.246553, + "min": 0.233886, + "max": 0.277284, + "values": [ + 0.264716, + 0.277284, + 0.246553, + 0.238027, + 0.236199, + 0.233886, + 0.255501 + ] + }, + "digest": "550398e1f131c578ee82c4f220aa74ef2475c15da77d7277d451640f3eff74d1", + "digest_stable": true, + "peak_traced_bytes": 114824538 + }, + { + "group": "masks", + "name": "scan_position_4096", + "params": { + "side": 4096, + "dtype": "int32", + "objects": 4096, + "mask_types": 2 + }, + "wall_seconds": { + "median": 1.099594, + "min": 0.998518, + "max": 1.187248, + "values": [ + 1.127859, + 1.099594, + 1.092796, + 0.998518, + 1.187248, + 1.012845, + 1.165108 + ] + }, + "digest": "ec5910c05e04c1c70be1da3498630d1e30d68e47ac7dddd62d056dcdd0599d95", + "digest_stable": true, + "peak_traced_bytes": 329032404 + }, + { + "group": "masks", + "name": "piece_counts_checker_two_labels_4096", + "params": { + "side": 4096, + "dtype": "uint16", + "mask": "checker_two_labels" + }, + "wall_seconds": { + "median": 7.374215, + "min": 7.107291, + "max": 7.877643, + "values": [ + 7.374215, + 7.560958, + 7.107291, + 7.251895, + 7.518319, + 7.877643, + 7.245473 + ] + }, + "digest": "e90ded1a1d3176d93d0b507b78675e8edd586ee05aa73355ea30d64453a92f7c", + "digest_stable": true, + "peak_traced_bytes": 3572750204 + }, + { + "group": "masks", + "name": "piece_counts_checker_one_label_4096", + "params": { + "side": 4096, + "dtype": "int32", + "mask": "checker_one_label" + }, + "wall_seconds": { + "median": 3.365781, + "min": 3.181152, + "max": 3.502226, + "values": [ + 3.435837, + 3.365781, + 3.420931, + 3.35991, + 3.502226, + 3.25788, + 3.181152 + ] + }, + "digest": "6543cf267d7ad9900ce44546aa51026889fc9bc24105eb0e261454df6d3595bf", + "digest_stable": true, + "peak_traced_bytes": 1803155281 + }, + { + "group": "masks", + "name": "piece_counts_noise_four_labels_4096", + "params": { + "side": 4096, + "dtype": "int32", + "mask": "noise_four_labels" + }, + "wall_seconds": { + "median": 2.917297, + "min": 2.784694, + "max": 3.145618, + "values": [ + 2.784694, + 2.869493, + 3.049356, + 2.917297, + 2.836744, + 3.058967, + 3.145618 + ] + }, + "digest": "99f3f03132d213f6afe16a46fb554f6d59e3665bf733b7375c6e6aeaa91be070", + "digest_stable": true, + "peak_traced_bytes": 1059889320 + } + ], + "inputs": { + "label_masks_2048_1024_seed0": "6f6b9edfc43758b635ae5e0f10a9cddc7c072f9a4e39aaba172da9cea3ec0820", + "label_masks_4096_4096_seed0": "8479cf81d94e9212f5a8982ea5514bebd686efe7c1f2fc0a2e925368befe6901", + "pixel_mask_checker_one_label_2048_seed0": "a597a0206d8d27b6d857efe1f9069e9246522a73edae4aabf744dbcd559b4f31", + "pixel_mask_checker_one_label_4096_seed0": "26ef4b71ccaa65f5a5ff86a31dbe488583b67aa3165cf3ed2e9b7e972aa0d06f", + "pixel_mask_checker_two_labels_2048_seed0": "42afbe3e4b3b9fa658942c265b01fc7960fef661a609ba4b2286e25b0a4c76fa", + "pixel_mask_checker_two_labels_4096_seed0": "841e970fb9f445c3341c8e45018117223fadd478e3c3cb6a85383cbc8874d72c", + "pixel_mask_noise_four_labels_2048_seed0": "7b632ff2353b114032a743330b6ce72a4ed1b2fe1317bf5d12f129f6fc3ef000", + "pixel_mask_noise_four_labels_4096_seed0": "8d0b640079b53089919f8d2b23af1914ca09349668c6880b97ee1f82d8b5b980" + }, + "process": { + "peak_rss_bytes": 3901075456, + "source": "VmHWM" + } +} diff --git a/docs/benchmarks.md b/docs/benchmarks.md index d612e976..69bca062 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -69,33 +69,66 @@ before timing). Tiles are 512 px, strips 64 rows, Zarr chunks 1024 px. | `pair_counts` (nuclei in cells) | 41.5 ms (40.3–50.0) | 27 MiB | 245 ms (235–260) | 110 MiB | | scan of one position (`_scan_plane`: both masks' pieces, both pairs) | 701 ms (674–734) | 132 MiB | 4,704 ms (4,601–4,933) | 528 MiB | -### `piece_counts` in one pass (#69), before and after - -`python tools/benchmark_kernels.py --group masks` (7 timed calls per case after one warm-up), the -same machine, Python and libraries as above, run four times in turn on 25 November 2026: -before (`main` at `c8c3808`), after (this change), before, after. Every case has the same -digest in all four runs, and the inputs the same digests as the baseline above (reports: -[before](benchmark_results/2026-11-25-kernels-masks-before-69.json) and -[after](benchmark_results/2026-11-25-kernels-masks-after-69.json), the first round; the "after" -report names `c8c3808` as its commit because it was run before this change was committed). -Another job's tests were running on the machine (1-minute load 0.8 to 2.2 at the starts), so -the absolute times are above the baseline's; the before and after runs shared that load. - -| Case | Before, run 1 | After, run 1 | Before, run 2 | After, run 2 | Traced, before / after | Digest (first 16) | -|---|---:|---:|---:|---:|---:|---| -| `piece_counts` 2048 | 343 ms (330–379) | 41.2 ms (36.7–46.2) | 413 ms (388–517) | 38.3 ms (35.8–44.8) | 132 / 12.1 MiB | `4abd144b846d176c` | -| `piece_counts` 4096 | 2,369 ms (2,238–2,534) | 181 ms (159–210) | 2,283 ms (2,199–2,409) | 195 ms (174–233) | 528 / 48.0 MiB | `c575615afca962cf` | -| scan of one position 2048 | 917 ms (798–1,067) | 247 ms (220–302) | 902 ms (788–1,015) | 219 ms (214–239) | 132 / 78.5 MiB | `69de16bd28281cc3` | -| scan of one position 4096 | 5,201 ms (5,040–5,650) | 1,252 ms (1,086–1,408) | 5,603 ms (5,098–5,873) | 1,230 ms (1,102–1,291) | 528 / 314 MiB | `ec5910c05e04c1c7` | -| `pair_counts` 4096 (unchanged) | 258 ms | 271 ms | 279 ms | 267 ms | 110 / 110 MiB | `550398e1f131c578` | - -Peak resident memory of the benchmark process: 841 MiB before, 631 MiB after. The former -function spent most of its time in the sort of every pixel (`np.unique(..., -return_inverse=True)`, about 2.5 s of the 4096 px case when timed alone), not in its loop of -per-label `ndimage.label` (about 0.15 s on these compact cells). The loop dominates when labels -are spread over the plane: on a 2048 px mask of 1,000 labels scattered over 20 % of the pixels -(a check outside the tool, `tests/test_mask_pieces.py`'s reference against the new function, -median of 3 calls) it took 15.8 s, the new function 0.25 s, with equal outputs. +### `piece_counts` by runs or by boxes (#69), before and after + +`python tools/benchmark_kernels.py --group masks` (7 timed calls per case after one warm-up) +as of this change, with its three pixel-scale masks (`benchmark_inputs.pixel_mask`: a +two-label `uint16` checkerboard, a one-label `int32` checkerboard, and half the pixels +carrying labels 1 to 4), run on 26 November 2026 on the machine and libraries above, five +times in turn: **before** (`main` at `88a1c42`, the per-label function), **after** (this +change), **first** (the first version of PR #568 at `85715dc`, runs only), before, after. +The source measured was chosen with `PYTHONPATH`; the reports' `machine.commit` is the +tool's checkout (`85715dc`), not the source measured. Every case has the same digest in all +five runs, and the inputs the same digests in all five (and, for the cells and nuclei, as in +the baseline above). Another job's tests were running (1-minute load 1.9 to 2.1 at the +starts), shared by every run. Reports: +[before](benchmark_results/2026-11-26-kernels-masks-before-69.json), +[first](benchmark_results/2026-11-26-kernels-masks-first-69.json) and +[after](benchmark_results/2026-11-26-kernels-masks-after-69.json) (first round). + +| Case | Before (runs 1, 2) | After (runs 1, 2) | First | Traced: before / after / first | Digest (first 16) | +|---|---:|---:|---:|---:|---| +| `piece_counts` cells 2048 | 322, 321 ms | 15.9, 16.9 ms | 35.9 ms | 132 / 8.5 / 12.1 MiB | `4abd144b846d176c` | +| `piece_counts` cells 4096 | 2,327, 2,061 ms | 103, 65.4 ms | 168 ms | 528 / 33.6 / 48.0 MiB | `c575615afca962cf` | +| scan of one position 2048 | 766, 821 ms | 206, 173 ms | 214 ms | 132 / 78.5 / 78.5 MiB | `69de16bd28281cc3` | +| scan of one position 4096 | 5,095, 4,889 ms | 965, 923 ms | 1,100 ms | 528 / 314 / 314 MiB | `ec5910c05e04c1c7` | +| two-label checkerboard 2048 | 195, 210 ms | 191, 178 ms | 1,481 ms | 116 / 116 / 852 MiB | `e90ded1a1d3176d9` | +| one-label checkerboard 2048 | 135, 112 ms | 147, 121 ms | 678 ms | 132 / 132 / 430 MiB | `6543cf267d7ad990` | +| noise, four labels 2048 | 250, 231 ms | 234, 237 ms | 549 ms | 132 / 132 / 253 MiB | `484c7df9ddc9e95d` | +| two-label checkerboard 4096 | 931, 932 ms | 1,009, 961 ms | 7,374 ms | 464 / 464 / 3,407 MiB | `e90ded1a1d3176d9` | +| one-label checkerboard 4096 | 574, 570 ms | 556, 568 ms | 3,366 ms | 528 / 528 / 1,720 MiB | `6543cf267d7ad990` | +| noise, four labels 4096 | 1,248, 1,215 ms | 1,049, 1,235 ms | 2,917 ms | 528 / 528 / 1,011 MiB | `99f3f03132d213f6` | + +Medians (the reports hold the min to max). `pair_counts` is unchanged (241 to 259 ms at 4096 px +in every run). Peak resident memory of the benchmark process: 905 and 891 MiB before, 889 and +889 MiB after, 3,720 MiB first. + +**The trade-off.** The runs route costs time and memory per run (a run is consecutive pixels +of one label in a row), and the former route per pixel (a sort of every pixel, about 32 bytes +each, then a labelling per label in its bounding box). On masks of objects (tens of pixels +across) runs are a few per hundred pixels and the runs route is 10 to 30 times faster with a +tenth of the memory or less. On pixel-scale masks (noise, checkerboards) runs are almost +pixels: the first version took up to 8 times longer and 7 times the memory there (3.4 GiB on +the 4096 px two-label checkerboard). `piece_counts` now counts the runs first and takes +the former route above `RUNS_PER_PIXEL_LIMIT` = 0.25 runs per pixel, so these masks +cost what they cost before (the counting adds one boolean plane, 16 MiB at 4096 px, freed +before the former route starts). The limit was chosen from a sweep at 4096 px outside the tool +(median of 3 calls, `tracemalloc` peak, equal outputs): runs route / former route 0.29 / 0.85 s +and 100 / 528 MiB at 0.08 runs per pixel (8 px blocks of 4 labels), 0.54 / 0.92 s and 183 / +528 MiB at 0.16, 0.74 / 0.91 s and 238 / 528 MiB at 0.21, 0.89 / 0.81 s and 220 / 528 MiB at +0.25 (noise of one label at half the pixels, the most runs one label can make), 1.15 / 1.05 s +and 346 / 528 MiB at 0.32, 1.57 / 1.10 s at 0.44, 2.02 / 0.49 s at 0.5 and 5.0 / 0.92 s and +1,136 / 464 MiB at 1. Below the limit the runs route never used more memory than the former +one and was at most about 10 % slower (at the limit itself); above it the route is the former +one. A mask just below the limit that the runs route handles badly in time is possible but +was not found. + +Outside the tool (the former function kept in `tests/test_mask_pieces.py` against the new +one, median of 3 calls, equal outputs): a 2048 px mask of 1,000 labels scattered over 20 % of +the pixels (0.20 runs per pixel) took 15.2 s before, 0.11 s after; 4,000 touching Voronoi +cells at 2048 px, 0.38 s before, 0.041 s after. The former function's time on the cells was +mostly its sort of every pixel (about 2.5 s of the 4096 px case alone), not its loop of +per-label `ndimage.label` (about 0.15 s); the loop dominates when labels are spread out. ## Channel identity (`check_channel_identity`, three channels) diff --git a/docs/development.md b/docs/development.md index b9a2608e..6add3885 100644 --- a/docs/development.md +++ b/docs/development.md @@ -128,7 +128,8 @@ exits 1 unless every run writes the same `plane_histograms.csv`. `tools/benchmark_kernels.py` times the kernels under a run one call at a time (#106): the plane histogram per pixel type (whole plane and over a region), plane and window reads from TIFF (tiled or stripped, zlib or uncompressed) and OME-Zarr, the mask step's kernels -(`check_labels`, `piece_counts`, `pair_counts`, one position's scan) and the channel-identity +(`check_labels`, `piece_counts` of the cells and of three pixel-scale masks, `pair_counts`, +one position's scan) and the channel-identity check. `tools/benchmark_description_read.py` times the strict description reader by number of repeats, phase by phase, with a `cProfile` of its top functions (#505). Both use `tools/benchmark_harness.py`: fixed seeded inputs (`tools/benchmark_inputs.py`), the median of diff --git a/src/morphobricks_preprocessing/mask_pieces.py b/src/morphobricks_preprocessing/mask_pieces.py index 9df5f7ed..92c2150a 100644 --- a/src/morphobricks_preprocessing/mask_pieces.py +++ b/src/morphobricks_preprocessing/mask_pieces.py @@ -1,26 +1,38 @@ -"""Count the connected pieces of every label of a 2D mask in one pass (issue #69). +"""Count the connected pieces of every label of a 2D mask (issue #69). The kernel of :func:`.mask_scan.piece_counts` (``docs/contract.md`` §15), moved from -:mod:`.mask_scan`. Before, the labels were renumbered with a sort of every pixel -(``np.unique(..., return_inverse=True)``) and each label was labelled again in its bounding -box, so labels spread over the plane read most of it once each. Now each row is cut into -runs (consecutive pixels of one nonzero label), runs of one label in neighbouring rows are -joined when they touch (``scipy.sparse.csgraph``), and a label's pieces are its groups of -runs. Each pixel is read a fixed number of times, whatever the labels; the counts are the -same as labelling each label alone with the labeller's structure (:data:`.masks.binary. -STRUCTURE`, imported, not restated: Spec ADR 0005 BM1). No files are read or written. +:mod:`.mask_scan`. Two routes give the same counts as labelling each label alone with the +labeller's structure (:data:`.masks.binary.STRUCTURE`, imported, not restated: Spec ADR 0005 +BM1): + +- **runs** (most masks): each row is cut into runs (consecutive pixels of one nonzero label), + runs of one label in neighbouring rows that touch are joined (``scipy.sparse.csgraph``), + and a label's pieces are its groups of runs. No pixel is sorted and no label is labelled + again, so labels spread over the plane cost no more than compact ones; +- **boxes** (pixel-scale masks, more than :data:`RUNS_PER_PIXEL_LIMIT` runs per pixel, such + as noise or checkerboards): the former route, kept unchanged: the labels are renumbered + with a sort of every pixel and each label is labelled in its bounding box. There, runs are + almost pixels, and the graph of runs would need several times the memory of the sort. + +No files are read or written. """ from __future__ import annotations import numpy as np +from scipy import ndimage from scipy.sparse import coo_matrix from scipy.sparse.csgraph import connected_components from .masks.binary import STRUCTURE from .masks.labels import check_labels -__all__ = ["piece_counts"] +__all__ = ["RUNS_PER_PIXEL_LIMIT", "piece_counts"] + +RUNS_PER_PIXEL_LIMIT = 0.25 +"""Above this many runs per pixel, the pieces are counted by boxes (the former route).""" + +_INT32_MAX = np.iinfo(np.int32).max def piece_counts(mask: np.ndarray) -> tuple[np.ndarray, np.ndarray]: @@ -45,8 +57,34 @@ def piece_counts(mask: np.ndarray) -> tuple[np.ndarray, np.ndarray]: check_labels(mask) if mask.ndim != 2: raise ValueError(f"The mask must be one 2D plane, not {mask.ndim}D.") - row, start, end, label = _runs(mask) - piece = _join_runs(row, start, end, label, _corner_reach()) + first = mask != 0 + first[:, 1:] &= mask[:, 1:] != mask[:, :-1] + if np.count_nonzero(first) > RUNS_PER_PIXEL_LIMIT * mask.size: + del first + return _pieces_by_boxes(mask) + return _pieces_by_runs(mask, first) + + +def _pieces_by_boxes(mask: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Return :func:`piece_counts` by labelling each label in its bounding box (before #69).""" + values, dense = np.unique(mask, return_inverse=True) + dense = dense.reshape(mask.shape) + if values.size and values[0] == 0: # labels are never negative, so 0 comes first + values = values[1:] + else: + dense = dense + 1 # no background: every value is a label + counts = np.zeros(values.size, dtype=np.int64) + for index, box in enumerate(ndimage.find_objects(dense)): + if box is not None: + counts[index] = ndimage.label(dense[box] == index + 1, STRUCTURE)[1] + return values, counts + + +def _pieces_by_runs(mask: np.ndarray, first: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """Return :func:`piece_counts` from the runs; ``first`` marks the first pixel of each.""" + starts, ends, label = _runs(mask, first) + piece = _join_runs(starts, ends, label, mask.shape[1] + 2, _corner_reach()) + del starts, ends # every piece is runs of one label, so a label's pieces are the pieces carrying it label_of_piece = np.empty(int(piece.max(initial=-1)) + 1, dtype=mask.dtype) label_of_piece[piece] = label @@ -64,51 +102,58 @@ def _corner_reach() -> int: raise ValueError("piece_counts supports only the 8- or 4-connected 3 x 3 structure.") -def _runs(mask: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - """Return the row, first and last column and label of every run of one nonzero label. +def _runs(mask: np.ndarray, first: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Return the first and last pixel of every run, as places, and the run's label. - Runs come in row-major order. Pixels of one label next to each other in a row are one - run, so only runs in neighbouring rows still have to be joined. + A place is ``row * (columns + 2) + column``: the two spare columns keep runs of rows that + are not neighbours out of each other's reach. Places are ``int32`` when every place fits, + ``int64`` otherwise. Runs come in row-major order, so both places increase. """ - on = mask != 0 - first = on.copy() - first[:, 1:] &= mask[:, 1:] != mask[:, :-1] - last = on # reused: ``on`` is not needed after this + rows, columns = mask.shape + width = columns + 2 + kind = np.int32 if rows * width <= _INT32_MAX else np.int64 + flat = np.flatnonzero(first) + label = np.ascontiguousarray(mask).reshape(-1)[flat] # a view when already contiguous + starts = flat.astype(kind) + del flat + last = first # reused: every first pixel is found + np.not_equal(mask, 0, out=last) last[:, :-1] &= mask[:, :-1] != mask[:, 1:] - row, start = np.nonzero(first) - end = np.nonzero(last)[1] - return row, start, end, mask[row, start] + ends = np.flatnonzero(last).astype(kind) + del last + if columns: # no columns, no runs + starts += 2 * (starts // columns) + ends += 2 * (ends // columns) + return starts, ends, label def _join_runs( - row: np.ndarray, start: np.ndarray, end: np.ndarray, label: np.ndarray, reach: int + starts: np.ndarray, ends: np.ndarray, label: np.ndarray, width: int, reach: int ) -> np.ndarray: """Return the piece of every run: runs of one label in neighbouring rows that touch join. - A run of row ``r + 1`` touches a run of the same label in row ``r`` when their columns - overlap, widened by ``reach`` (1: corners touch). Runs are grouped by (row, label) and - sorted by first column within a group; as runs of one group never overlap, their last - columns are sorted too, so the runs above each run that touch it are one slice of the - group, found by two binary searches. + A run touches a run of the row above when their columns overlap, widened by ``reach`` + (1: corners touch). The runs of the row above that a run's widened columns overlap are + one slice of the runs (places increase), found by two binary searches; of those, the + ones with the same label are joined to it. ``width`` is the places per row. """ - if row.size == 0: + size = starts.size + if size == 0: return np.zeros(0, dtype=np.intp) - key = row.astype(np.int64) * (int(label.max()) + 1) + label.astype(np.int64) - order = np.argsort(key, kind="stable") # stable: by first column within a group - keys, group = np.unique(key[order], return_inverse=True) - width = int(end.max()) + 3 # every column + 2 fits below it: no overlap between groups - low = group * width + (end[order] + 1) - high = group * width + (start[order] + 1) - above = np.searchsorted(keys, key - (int(label.max()) + 1)) - found = above < keys.size - found[found] = keys[above[found]] == key[found] - (int(label.max()) + 1) - below, above = np.nonzero(found)[0], above[found] - first = np.searchsorted(low, above * width + (start[below] + 1 - reach), side="left") - stop = np.searchsorted(high, above * width + (end[below] + 1 + reach), side="right") - touching = np.maximum(stop - first, 0) - pairs = np.repeat(below, touching) - offset = np.arange(touching.sum()) - np.repeat(np.cumsum(touching) - touching, touching) - other = order[np.repeat(first, touching) + offset] - size = row.size - graph = coo_matrix((np.ones(pairs.size, np.int8), (pairs, other)), shape=(size, size)) + low = np.searchsorted(ends, starts - (width + reach), side="left") + high = np.searchsorted(starts, ends - (width - reach), side="right") + touching = np.maximum(high - low, 0).astype(starts.dtype) + del high + total = int(touching.sum()) + kind = np.int32 if total <= _INT32_MAX and size <= _INT32_MAX else np.int64 + below = np.repeat(np.arange(size, dtype=kind), touching) + above = np.arange(total, dtype=kind) + shift = (np.cumsum(touching, dtype=np.int64) - touching - low).astype(kind) + above -= np.repeat(shift, touching) + del low, touching, shift + same = label[below] == label[above] + below, above = below[same], above[same] + del same + graph = coo_matrix((np.ones(below.size, bool), (below, above)), shape=(size, size)) + del below, above return connected_components(graph, directed=False)[1] diff --git a/tests/test_mask_pieces.py b/tests/test_mask_pieces.py index 875dde6d..d4f162a3 100644 --- a/tests/test_mask_pieces.py +++ b/tests/test_mask_pieces.py @@ -1,4 +1,8 @@ -"""The run-based piece_counts gives byte-identical results to the per-label one (issue #69).""" +"""piece_counts gives byte-identical results to the former per-label one by both routes (#69). + +Every test runs three times (the ``route`` fixture): runs forced, boxes forced, and the +route piece_counts chooses. +""" from __future__ import annotations @@ -6,7 +10,7 @@ import pytest from scipy import ndimage -from morphobricks_preprocessing import piece_counts +from morphobricks_preprocessing import mask_pieces, piece_counts from morphobricks_preprocessing.masks import check_labels from morphobricks_preprocessing.masks.binary import STRUCTURE @@ -14,6 +18,14 @@ DTYPES += (np.uint64,) +@pytest.fixture(autouse=True, params=["runs", "boxes", "chosen"]) +def route(request, monkeypatch): + limit = {"runs": np.inf, "boxes": -1.0}.get(request.param) + if limit is not None: + monkeypatch.setattr(mask_pieces, "RUNS_PER_PIXEL_LIMIT", limit) + return request.param + + def boxes_piece_counts(mask): """Return piece_counts as it was before issue #69 (main c8c3808), kept as the reference.""" check_labels(mask) @@ -118,3 +130,19 @@ def test_piece_counts_refuse_a_mask_that_is_not_2d(): piece_counts(np.ones((2, 2, 2), np.int32)) with pytest.raises(ValueError, match="negative"): piece_counts(np.full((2, 2), -1, np.int32)) + + +def test_pixel_scale_masks_take_the_boxes_route_and_others_the_runs_route(route, monkeypatch): + if route != "chosen": + pytest.skip("the choice itself is tested with the default limit") + taken = [] + for name in ("_pieces_by_boxes", "_pieces_by_runs"): + real = getattr(mask_pieces, name) + monkeypatch.setattr( + mask_pieces, name, lambda *a, real=real, name=name: taken.append(name) or real(*a) + ) + checkerboard = (np.add.outer(np.arange(64), np.arange(64)) % 2 + 1).astype(np.uint16) + assert_identical(checkerboard) # one run per pixel + blocks = np.kron(np.arange(16, dtype=np.int32).reshape(4, 4), np.ones((16, 16), np.int32)) + assert_identical(blocks) # 1/16 run per pixel + assert taken == ["_pieces_by_boxes", "_pieces_by_runs"] diff --git a/tools/benchmark_inputs.py b/tools/benchmark_inputs.py index 8e981375..bc7a9edd 100644 --- a/tools/benchmark_inputs.py +++ b/tools/benchmark_inputs.py @@ -87,6 +87,38 @@ def _label_masks(side: int, objects: int, seed: int) -> tuple[np.ndarray, np.nda return cells, nuclei +PIXEL_MASKS = ("checker_two_labels", "checker_one_label", "noise_four_labels") +"""The pixel-scale masks (:func:`pixel_mask`): about one run of one label per pixel or two.""" + + +def pixel_mask(side: int, kind: str, seed: int = 0) -> np.ndarray: + """Return the seeded pixel-scale mask (:func:`_pixel_mask`) and record its digest.""" + found = _pixel_mask(side, kind, seed) + INPUT_DIGESTS[f"pixel_mask_{kind}_{side}_seed{seed}"] = digest(found) + return found + + +def _pixel_mask(side: int, kind: str, seed: int) -> np.ndarray: + """Return a ``side x side`` mask whose labels change at almost every pixel (issue #69). + + ``checker_two_labels``: labels 1 and 2 in a checkerboard (``uint16``, one run per pixel); + ``checker_one_label``: label 1 on the black squares, background on the white (``int32``, + every pixel of label 1 one piece through the corners); ``noise_four_labels``: half the + pixels, seeded, carry a seeded label 1 to 4 (``int32``). The worst cases of the runs route + of ``piece_counts``, which counts these by boxes. + """ + board = np.add.outer(np.arange(side), np.arange(side)) % 2 + if kind == "checker_two_labels": + return (board + 1).astype(np.uint16) + if kind == "checker_one_label": + return board.astype(np.int32) + if kind == "noise_four_labels": + rng = np.random.default_rng(seed) + on = rng.random((side, side)) < 0.5 + return np.where(on, rng.integers(1, 5, (side, side)), 0).astype(np.int32) + raise ValueError(f"no pixel-scale mask {kind}") + + def summaries(units: int, images: int, seed: int = 0) -> list: """Return the seeded summaries (:func:`_summaries`) and record their digest.""" found = _summaries(units, images, seed) diff --git a/tools/benchmark_kernels.py b/tools/benchmark_kernels.py index ca00b260..ee9b56de 100644 --- a/tools/benchmark_kernels.py +++ b/tools/benchmark_kernels.py @@ -23,7 +23,9 @@ ``check_labels`` (on the mask, which it accepts, and on a copy with one negative pixel, which it refuses: the digest is of the verdicts, the error type and its message), ``piece_counts``, ``pair_counts`` and the scan of one position - (``mask_scan._scan_plane``: the pieces of both masks and both pairs); + (``mask_scan._scan_plane``: the pieces of both masks and both pairs), and ``piece_counts`` + of three pixel-scale masks (``benchmark_inputs.pixel_mask``: two checkerboards and noise, + #69), the worst cases of its runs route; - ``channel_identity``: ``check_channel_identity`` of the image summaries of 72 and 400 units of three channels. @@ -146,6 +148,11 @@ def scan(cells: object = cells, nuclei: object = nuclei) -> object: lambda c=nuclei, p=cells: pair_counts(c, p, thresholds=limits), ) yield Case("masks", f"scan_position_{side}", {**params, "mask_types": 2}, scan) + for kind in inputs.PIXEL_MASKS: + mask = inputs.pixel_mask(side, kind) + found = {"side": side, "dtype": str(mask.dtype), "mask": kind} + name = f"piece_counts_{kind}_{side}" + yield Case("masks", name, found, lambda m=mask: piece_counts(m)) def channel_identity_cases(sizes: tuple[tuple[int, int], ...]) -> Iterator[Case]: From 5986acbc7750cfa5f659c8b90dbc519e46362d1c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 00:59:00 +0000 Subject: [PATCH 3/4] Mask scan: refuse a mask plane of no pixels (review of #568) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SciPy's failure inside piece_counts was the only guard against a plane of height or width 0; with the runs route it has no labels, so it counted as an image and as a plane of at most one label in its mask type's kind. scan_masks now refuses it, naming the mask (mask_without_pixels). Regression test, user guide, contract §15 and changelog. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a --- CHANGELOG.md | 2 +- docs/contract.md | 3 +++ docs/user_guide.md | 1 + src/morphobricks_preprocessing/mask_scan.py | 16 ++++++++++++++-- tests/test_mask_scan.py | 15 +++++++++++++++ 5 files changed, 34 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 798e25e2..3d63d9fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased -- **`piece_counts` counts every label's pieces in one pass (#69).** It sorted every pixel (`np.unique(..., return_inverse=True)`, most of its time) and labelled each label again in its bounding box, so labels spread over the plane read it once each. Each row is now cut into runs of one label and runs of one label in neighbouring rows that touch (8-connected, from `masks.binary.STRUCTURE`) are joined with `scipy.sparse.csgraph.connected_components` (new pure module `mask_pieces`; `mask_scan.piece_counts` is the same function, imported). The results are byte-identical (labels in the mask's pixel type, counts `int64`): a property test compares it with the former function, kept in the test as the reference, on random masks of every label pixel type (touching labels, holes, single pixels, edges, corners, no background, empty) and on the benchmark masks; every digest of `tools/benchmark_kernels.py --group masks` is unchanged. On the benchmark machine `piece_counts` of the 4096 px cells mask went from 2.37 s to 0.18 s and one position's scan from 5.2 s to 1.25 s (`docs/benchmarks.md`). Two changes outside the former results: a mask of no pixels (a side of length 0) now has no labels, where the former function failed inside SciPy; a mask that is not 2D is refused with a `ValueError` saying so (it was a SciPy `RuntimeError`, or no labels when it was all background). `pair_counts` and the repeated pair work of #69 are not changed. `tests/test_mask_pieces.py`. +- **`piece_counts` counts the pieces of masks of objects by runs (#69).** It sorted every pixel (`np.unique(..., return_inverse=True)`, most of its time) and labelled each label again in its bounding box, so labels spread over the plane read it once each. Each row is now cut into runs of one label and runs of one label in neighbouring rows that touch (8-connected, from `masks.binary.STRUCTURE`) are joined with `scipy.sparse.csgraph.connected_components` (new pure module `mask_pieces`; `mask_scan.piece_counts` is the same function, imported). On pixel-scale masks (noise, checkerboards) runs are almost pixels and that graph needs several times the memory of the sort, so above `RUNS_PER_PIXEL_LIMIT` = 0.25 runs per pixel the former route is taken, unchanged. The results are byte-identical either way (labels in the mask's pixel type, counts `int64`): a property test compares both routes, forced and as chosen, with the former function, kept in the test as the reference, on random masks of every label pixel type (touching labels, holes, single pixels, edges, corners, no background, empty) and on the benchmark masks; every digest of `tools/benchmark_kernels.py --group masks` is unchanged, including its new pixel-scale cases (`benchmark_inputs.pixel_mask`). On the benchmark machine `piece_counts` of the 4096 px cells mask went from 2.1 to 2.3 s to 0.07 to 0.10 s and one position's scan from 4.9 to 5.1 s to 0.9 to 1.0 s; the pixel-scale masks take the time and memory they took before (`docs/benchmarks.md`). Outside the former results: a mask with a side of length 0 now has no labels, where the former function failed inside SciPy; a mask that is not 2D is refused with a `ValueError` saying so (it was a SciPy `RuntimeError`, or no labels when it was all background). **The mask scan refuses a mask plane of no pixels** (`mask_without_pixels`, naming the mask): before, SciPy's failure in `piece_counts` was its only guard, and with no labels such a plane would have counted as an image and as a plane of at most one label in its mask type's kind. `pair_counts` and the repeated pair work of #69 are not changed. `tests/test_mask_pieces.py`, `tests/test_mask_scan.py`. - **Earlier work that does not record its experiment folder no longer leaves the stepper at a dead end (owner's Colab test of v0.9.0 at ca3b3c6).** An output folder holding only saved answers (here an older version's `morphobricks.draft.json`) showed *"The experiment folder it is of is not recorded … Enter the experiment folder and click Check folder"*: the stepper has no *Check folder* button (its check, *Looks right: read all image headers*, stays disabled until **Scan the folders**), and entering the folder showed the same message again, with no scan and no picture. Now the experiment folder entered is scanned at once on the stepper (folder walk and one picture; nothing is written), the message names the stepper's own buttons, and the check, on the user's click, reads the saved answers as always. Saved answers written by another version of the software (`DraftFileError` `unknown_version`, `unknown_key` or `spec_commit_mismatch`; the owner's file is format 3, `unknown_version`) are not earlier work (`EarlierWork.old_answers`): one line says they are not used and the file is left as it is, and the experiment folder entered is scanned and shown as above (an early **Scan the folders** click, before the typed folder reached the kernel, is made good when it arrives). The same scan follows a record and a run that name different folders. Each message names the buttons of the layout shown (the stacked pages say **Check folder**). Tests: `tests/test_notebook_restore.py`. - **A saved repeat order is never replaced by an abandoned *Yes* (review of #546 at e40f1ad).** On a reopened per-repeat draft, picking *Yes*, filling its row with rep1's order and going back to *No, per repeat folder* showed rep1's order in every repeat row, under "Pre-answered from your saved tags", and one Submit published it for every unit. A row's own saved tags now rank above a broader choice of the session (`channel_scope.seed`: the row's choice, its saved tags, a broader choice, the header names), and the "Pre-answered" note goes at the first change of the answer or of a row. Tests: `tests/test_notebook_channel_guide_reopen.py`, `tests/test_channel_scope.py`. - **A reopened strict channel draft is never turned into fast mode (review of #546, F1).** The guided step's fast-mode tick is hidden and only Submit sets it, so an unpublished draft does not hold it: reopened, a per-repeat, per-unit or one-list-per-count draft was ticked by default and opening Channels wrote `channel_layout` = the first unit's order with every unit `channels_from = "experiment"`, and *Check and save* published every unit in that order. Opening the guided step now writes nothing, an unpublished draft with saved per-unit tags and no `channel_layout` reopens unticked (`TagMatrix.tick_for_draft`), and the question is answered as the draft is (`channel_scope.scope_of_draft`: fast mode *Yes*; a strict draft the broadest answer whose rows reproduce every saved tag, "Pre-answered from your saved tags"; else "Saved per-unit tags are kept"). Every folder colour still states R, G, B, now right after the image-type answer instead of on opening. The per-unit grid of the Python-interface pages keeps its behaviour (its fast mode tags from headers on opening by design; see the PR). Also: a unit whose images disagree records no other row's tags in its refusal; *Same order within each biological repeat folder*; a row filled from a broader choice says so; per unit, a blank row keeps that unit as it is; the image type's button reads *Validated ✓* after a save. Tests: `tests/test_notebook_channel_guide_reopen.py`, and the #281, #279, mode-switch alias and #257 flows through the guided step in `tests/test_notebook_channel_guide_flows.py`. diff --git a/docs/contract.md b/docs/contract.md index 258f94ae..db613c21 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1028,6 +1028,9 @@ report is written whole, by one rename, only after every image is scanned), and `mask_relationships.json` is left as it was. With `verify_content` (`prepare_mask_step(..., verify_content=True)`, CLI `masks --verify-content`; by default the recorded run's setting) each mask's content SHA-256 is also taken before and after its scan and must not change. +A mask plane of no pixels (a height or width of 0) stops the scan with a `ValueError` naming +the mask (`mask_without_pixels`, review of #568): it has no labels, and would otherwise count +as an image of its mask type and as a plane of at most one label in its kind. Unchanged masks give the same report as before. The scan reads only masks whose headers are bound (issue #480): a header is evidence about one version of a file, so `scan_masks` given masks found without `bind=True` (`find_masks`; `preflight` without `bind_headers=True`) diff --git a/docs/user_guide.md b/docs/user_guide.md index e4635266..9aa3b28c 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -1619,6 +1619,7 @@ continues. | `mask_changed_during_run` | Error | A mask changed or went missing after the run checked its header and before it published its results (its size or time, or for an OME-Zarr label image its files; with `--verify-content` also its content). Nothing is published; the discovery report is written. Wait until nothing writes to the masks, then run again: the images already read resume from their staged rows. | | `mask_header_unbound` | Error | `scan_masks` called directly with masks found without their headers bound to the files' fingerprints (`find_masks(..., bind=True)` or `preflight(..., bind_headers=True)`), so their headers might describe other versions of the files. No mask is read and no report is made. Find the masks with their headers bound and scan again. The `masks` command and the notebook always bind them. | | `mask_changed_during_scan` | Error | The `masks` command (or **Describe the masks**): a mask changed or went missing after its header was read or while its pixels were read. No report is written; an earlier `mask_relationships.json` is left as it was. Wait until nothing writes to the masks, then describe them again. | +| `mask_without_pixels` | Error | The `masks` command (or **Describe the masks**): a mask plane has no pixels (a height or width of 0), so it has no objects to describe. No report is written. Save the mask again with its image's height and width. | | `design_unreadable` | Error | The `experiment_design.csv` an earlier run wrote cannot be read. Correct it, or delete it to confirm the design again. | | `no_usable_planes` | Error | No plane has finite pixel values. Check the images. | | `tiff_outside_leaf` | Error | Images sit in a folder that also holds subfolders, so they have no condition or repeat of their own. A folder holds either images or subfolders, never both. Move the images into a folder of their own, or out of the experiment folder. | diff --git a/src/morphobricks_preprocessing/mask_scan.py b/src/morphobricks_preprocessing/mask_scan.py index 2fd5f4a6..17fdea1d 100644 --- a/src/morphobricks_preprocessing/mask_scan.py +++ b/src/morphobricks_preprocessing/mask_scan.py @@ -63,7 +63,7 @@ from .mask_pairs import best_parents, match_counts from .mask_pairs import one_to_one_matches as one_to_one_matches # moved there from .mask_pieces import piece_counts as piece_counts # moved there (issue #69) -from .masks import MaskInventory, check_labels, read_mask +from .masks import MaskFile, MaskInventory, check_labels, read_mask logger = logging.getLogger(__name__) @@ -407,7 +407,8 @@ def scan_masks( ValueError For an invalid threshold, before any mask is read; for an image whose masks have different depth slices or time points; for a mask that cannot be read as the planes - its header gave, or holds a label outside 0 to 2,147,483,647 (:func:`.masks.read_mask`). + its header gave, or holds a label outside 0 to 2,147,483,647 (:func:`.masks.read_mask`); + for a mask plane of no pixels (``mask_without_pixels``). """ limits = mask_thresholds(thresholds) root = Path(experiment_root).resolve() @@ -445,6 +446,7 @@ def scan_masks( ) for name, mask in found_masks.items() } + _refuse_no_pixels(masks, found_masks) _scan_plane(masks, pieces, single, totals, limits) check_scanned(found_masks.values(), inventory.folder, root, before, verify_content) if progress is not None: @@ -467,6 +469,16 @@ def write_mask_report(report: MaskReport, path: str | os.PathLike) -> Path: return write_text_atomic(path, text, parents=True) +def _refuse_no_pixels(masks: Mapping[str, np.ndarray], found: Mapping[str, MaskFile]) -> None: + """Refuse a mask plane of no pixels: it has no labels, so it would pass as a plane of one.""" + for name, pixels in masks.items(): + if pixels.size == 0: + raise ValueError( + f"the mask {found[name].path} has no pixels (shape {pixels.shape}); save the " + "mask with the image's height and width (mask_without_pixels)" + ) + + def _scan_plane( masks: Mapping[str, np.ndarray], pieces: dict[str, list[np.ndarray]], diff --git a/tests/test_mask_scan.py b/tests/test_mask_scan.py index a0431ac6..f68fb11d 100644 --- a/tests/test_mask_scan.py +++ b/tests/test_mask_scan.py @@ -411,3 +411,18 @@ def test_the_contract_states_the_current_report_version(): row = re.search(r"^\| `report_version` \| `(\d+)`", contract, re.MULTILINE) assert heading and row assert heading.group(1) == row.group(1) == MASK_REPORT_VERSION + + +@pytest.mark.filterwarnings("ignore:.*writing zero-size array:UserWarning") # the fixture +def test_a_mask_plane_without_pixels_is_refused(tmp_path): + # Review of #568: piece_counts gives no labels for a plane of no pixels, so the scan must + # refuse such a plane itself (before #568 SciPy failed on it); it would otherwise count as + # an image and as a plane of at most one label in the mask type's kind. + root, folder = tmp_path / "exp", tmp_path / "masks" + write_data(root / "ctrl" / "a.tif", np.zeros((0, 8), dtype=np.uint8)) + write_data(folder / "Cells" / "ctrl" / "a.tif", np.zeros((0, 8), dtype=np.uint16)) + write_data(folder / "Nuclei" / "ctrl" / "a.tif", np.zeros((0, 8), dtype=np.uint16)) + inventory = preflight(root, masks_folder=folder, bind_headers=True).masks + assert inventory.ok, inventory.issues + with pytest.raises(ValueError, match=r"Cells/ctrl/a.tif has no pixels.*mask_without_pixels"): + scan_masks(inventory, root) From b2c8e46ee73949daa0356f1e8c0f31e90b58713e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 01:59:58 +0000 Subject: [PATCH 4/4] piece_counts: int32 places only when every search fits (review of #568) A mask of shape (1, 2**31 - 3) chose int32 places (rows * width is the int32 maximum) but the search subtracts width + reach, 2**31, and raised OverflowError. The place type is now chosen by _place_kind, which also counts the reach. Test of the selection only, no large allocation. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a --- src/morphobricks_preprocessing/mask_pieces.py | 27 ++++++++++++++----- tests/test_mask_pieces.py | 19 +++++++++++++ 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/src/morphobricks_preprocessing/mask_pieces.py b/src/morphobricks_preprocessing/mask_pieces.py index 92c2150a..b3a6fe5e 100644 --- a/src/morphobricks_preprocessing/mask_pieces.py +++ b/src/morphobricks_preprocessing/mask_pieces.py @@ -82,8 +82,9 @@ def _pieces_by_boxes(mask: np.ndarray) -> tuple[np.ndarray, np.ndarray]: def _pieces_by_runs(mask: np.ndarray, first: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """Return :func:`piece_counts` from the runs; ``first`` marks the first pixel of each.""" - starts, ends, label = _runs(mask, first) - piece = _join_runs(starts, ends, label, mask.shape[1] + 2, _corner_reach()) + reach = _corner_reach() + starts, ends, label = _runs(mask, first, reach) + piece = _join_runs(starts, ends, label, mask.shape[1] + 2, reach) del starts, ends # every piece is runs of one label, so a label's pieces are the pieces carrying it label_of_piece = np.empty(int(piece.max(initial=-1)) + 1, dtype=mask.dtype) @@ -102,16 +103,28 @@ def _corner_reach() -> int: raise ValueError("piece_counts supports only the 8- or 4-connected 3 x 3 structure.") -def _runs(mask: np.ndarray, first: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]: +def _place_kind(rows: int, columns: int, reach: int) -> type[np.signedinteger]: + """Return ``int32`` if every place and every search of :func:`_join_runs` fits it. + + Places run from 0 to ``rows * (columns + 2) - 3``, and the searches go down to + ``-(columns + 2 + reach)``, so ``rows * (columns + 2) + reach`` must fit too (review of + #568: a mask of shape (1, 2**31 - 3) overflowed the search). + """ + return np.int32 if rows * (columns + 2) + reach <= _INT32_MAX else np.int64 + + +def _runs( + mask: np.ndarray, first: np.ndarray, reach: int +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """Return the first and last pixel of every run, as places, and the run's label. A place is ``row * (columns + 2) + column``: the two spare columns keep runs of rows that - are not neighbours out of each other's reach. Places are ``int32`` when every place fits, - ``int64`` otherwise. Runs come in row-major order, so both places increase. + are not neighbours out of each other's reach. Places are ``int32`` when they and the + searches over them fit (:func:`_place_kind`), ``int64`` otherwise. Runs come in + row-major order, so both places increase. """ rows, columns = mask.shape - width = columns + 2 - kind = np.int32 if rows * width <= _INT32_MAX else np.int64 + kind = _place_kind(rows, columns, reach) flat = np.flatnonzero(first) label = np.ascontiguousarray(mask).reshape(-1)[flat] # a view when already contiguous starts = flat.astype(kind) diff --git a/tests/test_mask_pieces.py b/tests/test_mask_pieces.py index d4f162a3..059c6749 100644 --- a/tests/test_mask_pieces.py +++ b/tests/test_mask_pieces.py @@ -146,3 +146,22 @@ def test_pixel_scale_masks_take_the_boxes_route_and_others_the_runs_route(route, blocks = np.kron(np.arange(16, dtype=np.int32).reshape(4, 4), np.ones((16, 16), np.int32)) assert_identical(blocks) # 1/16 run per pixel assert taken == ["_pieces_by_boxes", "_pieces_by_runs"] + + +@pytest.mark.parametrize( + ("shape", "reach", "kind"), + [ + ((1, 2**31 - 3), 1, np.int64), # review of #568: width + reach is 2**31 + ((1, 2**31 - 4), 1, np.int32), + ((1, 2**31 - 3), 0, np.int32), + ((2, 2**30 - 2), 1, np.int64), # 2 * (2**30) + 1 is above the int32 limit + ((4096, 4096), 1, np.int32), + ], +) +def test_places_are_int32_only_when_every_search_fits(route, shape, reach, kind): + if route != "chosen": + pytest.skip("the choice of place type does not depend on the route") + assert mask_pieces._place_kind(*shape, reach) is kind + if kind is np.int32: # the lowest search value of a run in the first row fits + width = shape[1] + 2 + assert np.array([0], np.int32) - (width + reach) >= np.iinfo(np.int32).min