From 55470cbaed4f5e611498bf90a5487d3ffe662ec7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 4 Dec 2026 14:15:19 +0000 Subject: [PATCH] CLI wording: help, success, next-step and refusal messages; guide and README Every subcommand gets a description and examples; success lines say what was saved and print the next commands with the user's options (quoted); refusals say what, why and what to do. Codes, severities and paths are unchanged. README and user guide follow the complete workflow. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01G3qp99saj5j4QZfMeAZQUm --- CHANGELOG.md | 15 + README.md | 128 +++-- docs/user_guide.md | 484 ++++++++++++------ pyproject.toml | 2 + src/morphobricks_preprocessing/cli.py | 134 ++++- .../cli_calibrate.py | 33 +- src/morphobricks_preprocessing/cli_convert.py | 164 ++++-- .../cli_declare_masks.py | 84 ++- .../cli_describe.py | 157 ++---- .../cli_describe_options.py | 127 +++++ src/morphobricks_preprocessing/cli_masks.py | 35 +- src/morphobricks_preprocessing/cli_run.py | 193 ++----- .../cli_run_options.py | 149 ++++++ .../cli_tissue_mask.py | 62 ++- .../conversion_issues.py | 53 +- .../describe_ids.py | 89 +++- .../describe_questions.py | 18 +- .../description_run_text.py | 127 ++++- .../fast_answers.py | 27 +- .../he_tissue_mask.py | 30 +- .../ignored_masks.py | 25 +- .../mask_declare.py | 18 +- src/morphobricks_preprocessing/mask_text.py | 30 +- .../physical_check.py | 4 +- .../projection_issues.py | 22 +- src/morphobricks_preprocessing/report.py | 5 +- .../required_description.py | 35 +- .../run/preflight.py | 12 +- .../run_inputs_text.py | 30 +- .../run_inputs_tissue.py | 30 +- .../tissue_masks_folder.py | 9 +- tests/test_axis_check.py | 2 +- tests/test_brick_checks.py | 12 + tests/test_calibration.py | 2 +- tests/test_cli.py | 15 +- tests/test_cli_describe.py | 14 +- tests/test_cli_tissue_mask.py | 15 +- tests/test_cli_usability.py | 65 ++- tests/test_convert_work_folder.py | 2 +- tests/test_declare_masks.py | 2 +- tests/test_he_tissue_mask.py | 6 +- tests/test_ignored_masks.py | 4 +- tests/test_mask_step.py | 2 +- tests/test_mask_ties.py | 7 +- tests/test_notebook_mask_step.py | 5 +- tests/test_notebook_tag_by_repeat_drafts.py | 5 +- tests/test_notebook_tissue_mask.py | 2 +- tests/test_report.py | 2 +- tests/test_run_description.py | 4 +- tests/test_stopped_run_text.py | 4 +- 50 files changed, 1741 insertions(+), 760 deletions(-) create mode 100644 src/morphobricks_preprocessing/cli_describe_options.py create mode 100644 src/morphobricks_preprocessing/cli_run_options.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 818440f0..ee6f4ce6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,21 @@ are unchanged; one optional output-folder file (`ignored_masks.toml`) and one op key (`ignored_masks`) are new. A v0.10.0 reader of a run that uses them ignores the key and so refuses the skipped label images as unrecorded: refused, never silently wrong. +### Changed + +- **Command-line wording (independent review of v0.10.1, owner answers of 4 December 2026).** + Every subcommand has a description and examples in `--help`; option help is rewritten in plain + language. Success lines say what was saved and where, then print the next commands with the + user's own options, shell-quoted (`describe --publish`, `check`, `run`, `convert`, + `calibrate`, `declare-masks`, `tissue-mask`, `masks`). Refusals say what was refused, why and + what to do, with commands on their own lines (`A_DESCRIPTION_REQUIRED`, ID reasons in + `describe --id`, undeclared mask types with each representation's meaning, an unreadable + `ignored_masks.toml`, projection, conversion and tissue-mask refusals); the `zarr` install line + names the installed release. Issue codes, severities and paths are unchanged. README and user + guide follow (complete workflow, both masks-folder layouts, `plane_histograms.parquet`). + `cli_run_options` and `cli_describe_options` hold option definitions moved out of `cli_run` + and `cli_describe` (line limit); `parse_size` and `add_describe_parser` are re-exported. + ### Fixed - **OME-Zarr copies are written in spatial chunks, so a later brick can read them in windows.** diff --git a/README.md b/README.md index dcb2d0bd..40240334 100644 --- a/README.md +++ b/README.md @@ -2,14 +2,20 @@ [![CI](https://github.com/CellMigrationLab/morphobricks-preprocessing/actions/workflows/ci.yml/badge.svg)](https://github.com/CellMigrationLab/morphobricks-preprocessing/actions/workflows/ci.yml) -The preprocessing brick of MorphoBricks. It reads an experiment folder of -microscopy TIFFs, computes one intensity histogram per channel of every plane, and writes -them, with each plane's experimental labels, to `plane_histograms.csv`: one row per plane -(an image at one time point), each channel in its own columns. MorphoBricks v1 analyses 2-D -planes: a Z-stack (more than one depth slice) is refused (`z_stack_not_supported`); make -recorded 2-D projected copies first with `convert --project max|mean|sum`, and use the copies. Later bricks -(for example patch extraction) use that table to calculate normalization -parameters for any group of images without rereading the pixels. +MorphoBricks preprocessing is the first step before analysing a microscopy experiment. It +records experimental conditions, repeats, channels, pixel sizes and masks, checks the images, +and prepares the files used by downstream MorphoBricks analysis tools. + +Its main output is `plane_histograms.parquet`: the intensity histograms of every image plane, +with its experimental labels and channel IDs. The table contains one row per plane and stores +each channel's histogram as lists of bin indices and counts. Later MorphoBricks tools read this +file to calculate normalisation parameters without rereading the image pixels. From v0.10.0, +this file replaces `plane_histograms.csv`. To update an older preprocessing run, run +preprocessing again. + +MorphoBricks v1 analyses 2-D planes: a Z-stack (more than one depth slice) is refused +(`z_stack_not_supported`); make recorded 2-D projected copies first with +`convert --project max|mean|sum`, and use the copies. The brick never modifies source images and never applies a normalization itself. The histograms, the table format, pooling and the normalization methods come from the @@ -50,16 +56,16 @@ Pre-alpha; the current release is v0.10.0 (what is planned next is in - A step-by-step notebook ([notebooks/MorphoBricks_Preprocessing.ipynb](notebooks/MorphoBricks_Preprocessing.ipynb)) and a command line (`morphobricks-preprocessing check` / `run` / `masks` / `calibrate` / `describe` / `convert`) -- **Every run is described** (v0.5.1): the output folder must hold a published experiment - description, `morphobricks.toml`, written by the notebook's describe steps (*Check and - save*). A run without one is refused with `A_DESCRIPTION_REQUIRED` on every route. +- **Every run is described:** publish the experiment description using `describe --publish` + or the notebook. Every preprocessing run requires a published description + (`morphobricks.toml`); a run without one is refused with `A_DESCRIPTION_REQUIRED`. Every feature, message code and output file is described in the [user guide](docs/user_guide.md). From the normalization brick (`morphobricks_normalization`, a required dependency, pinned -to its release v0.8.0): per-plane histograms with the robust range and the range check -(`histogram`, `ranges`), the histogram table (`csv_io`, schema version 5: channels by canonical -ID, so acquisitions may have different channels), pooled group statistics +to its release v0.10.0): per-plane histograms with the robust range and the range check +(`histogram`, `ranges`), the histogram table (`parquet_io`, `plane_histograms.parquet` schema +version 6: channels by canonical ID, so acquisitions may have different channels), pooled group statistics (`pooling`) and normalization parameters (`normalization`); import them from `morphobricks_normalization` (the deprecated paths through `morphobricks_preprocessing` were removed in v0.4.0). @@ -81,8 +87,17 @@ contract version 3 and an objects use with `RunInputs.read_objects`. See the ## Installation +You need Python 3.11 or newer, Git and an internet connection. We recommend installing into a +new Python virtual environment. JupyterLab is not required for command-line use. + ```bash -pip install "git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.0" +python -m pip install "morphobricks-preprocessing @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1" +``` + +For OME-Zarr images or the H&E tissue mask, install the extras too: + +```bash +python -m pip install "morphobricks-preprocessing[zarr,he-mask] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1" ``` For development, from a clone: @@ -92,7 +107,7 @@ pip install -e ".[dev]" ``` The optional `notebook` extra installs the widget dependencies for the notebook -(`pip install "morphobricks-preprocessing[notebook] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.0"`). +(`python -m pip install "morphobricks-preprocessing[notebook] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1"`). The notebook's first code cell (**1. Install**) can set this up automatically: it uses a nearby checkout or an installed package only when it is the pinned `RELEASE_REF` commit (never by version alone), and installs missing requirements into the active kernel. A standalone @@ -143,12 +158,7 @@ LabConstrictor's JupyterLab/LabConstrictor before their release candidate is tagged; see [docs/colab-release-check.md](docs/colab-release-check.md). -From a terminal: - -```bash -morphobricks-preprocessing check /data/exp1 -morphobricks-preprocessing run /data/exp1 --axes ZCYX --image-type fluorescence -``` +From a terminal, see [Command line](#command-line) below. ## Running an experiment @@ -185,30 +195,57 @@ the [user guide](docs/user_guide.md) §9, "Settings". ## Command line +A complete workflow. This example assumes that every image contains collagen and fibronectin +in that order, that the image axes are named correctly, and that your biological repeats were +prepared and acquired comparably. Replace the channel names and date with your own. Review the +proposed IDs before accepting them. If these assumptions do not fit your experiment, use the +relevant instructions in the [user guide](docs/user_guide.md) §5. + +```bash +morphobricks-preprocessing describe my_experiment # preview: proposed IDs, open questions +morphobricks-preprocessing describe my_experiment --channels COL,FN --image-type channels \ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish +morphobricks-preprocessing check my_experiment +morphobricks-preprocessing run my_experiment +``` + +Your experiment is now described, checked and processed. The default output folder is +`my_experiment_MorphoBricks_Preprocessing`. Give this folder to the MorphoBricks tool that will +analyse your images. + +Fast publication from the command line creates a new description for an experiment with a +shared channel layout. Use the notebook to edit an existing description, change repeat pairing +or describe acquisitions with different channel lists or orders. Give `--comparable` only if +the samples of each biological repeat were prepared and acquired comparably; never give it +just to get past the question. + +Other commands: + ```bash -morphobricks-preprocessing describe /data/exp1 # the draft description, what is open -morphobricks-preprocessing check /data/exp1 # report, suggested --axes -morphobricks-preprocessing run /data/exp1 --axes ZCYX -morphobricks-preprocessing run --output /data/exp1_MorphoBricks_Preprocessing # later runs -morphobricks-preprocessing masks --output /data/exp1_MorphoBricks_Preprocessing # mask step -morphobricks-preprocessing calibrate --output /data/exp1_MorphoBricks_Preprocessing -morphobricks-preprocessing convert /data/exp1 --to /data/exp1_named_axes --axes ZXY # axis errors -morphobricks-preprocessing convert-mask --output /data/exp1_MorphoBricks_Preprocessing --mask TumorRegion --to-instances TumorObjects # new mask files -morphobricks-preprocessing tissue-mask --output /data/exp1_MorphoBricks_Preprocessing --to HETissue # H&E tissue region (he-mask extra; provisional rule) +morphobricks-preprocessing run --output my_experiment_MorphoBricks_Preprocessing # later runs +morphobricks-preprocessing declare-masks --output my_experiment_MorphoBricks_Preprocessing \ + --masks my_masks --type Cells=instances # declare masks +morphobricks-preprocessing masks --output my_experiment_MorphoBricks_Preprocessing # check masks +morphobricks-preprocessing calibrate my_experiment --size . XY 0.65 um # pixel sizes +morphobricks-preprocessing convert my_experiment --to my_experiment_max --axes ZCYX --project max # 2-D projections +morphobricks-preprocessing convert-mask --output my_experiment_MorphoBricks_Preprocessing --mask TumorRegion --to-instances TumorObjects # new mask files +morphobricks-preprocessing tissue-mask --output my_experiment_MorphoBricks_Preprocessing --to HETissue # H&E tissue region (he-mask extra; provisional rule) ``` `check`, `run` and `masks` need the experiment description published in the output folder -(the notebook's describe steps); without it they stop with `A_DESCRIPTION_REQUIRED` and write -nothing. `describe` shows the draft and what is still to be answered. `check` writes the -report. `run` and `masks` reuse every input the run in the -output folder recorded. A run that stops writes its report and says so. Every output file -gets the permissions a file you save yourself would (your umask). `convert` saves the -images whose metadata name their axes wrongly or not at all as named-axis OME-TIFF copies -with your roles in a new folder (each plane bit for bit the plane read with those roles; -every other image copied as it is; a conversion record written last), then you run -preprocessing on that folder with the same output folder. The notebook offers the same -conversion in step 2, under the axis check, when it finds such images. Details in the -[user guide](docs/user_guide.md) §5. +(`describe --publish` or the notebook's describe steps); without it they stop with +`A_DESCRIPTION_REQUIRED` and write nothing. `check` inspects the folders, image headers and +supplied masks, and suggests axis roles; it does not measure image pixels or perform every +validation of the published description. `run` validates the description and confirmed axis +roles before processing. `run` and `masks` reuse every input the run in +the output folder recorded. External TIFF masks are stored in a separate masks folder, given +with `--masks`; OME-Zarr label images are discovered automatically. If your analysis uses +masks, run `masks` after preprocessing. After `calibrate`, run preprocessing again. Every +output file gets the permissions a file you save yourself would (your umask). `convert` writes +copies of the images in a new folder (named-axis OME-TIFF, OME-Zarr with `--store ome-zarr`, +or 2-D projections with `--project`); the copies are a new experiment folder, described and +published before `check` and `run`. Use the actual stored axis order of your images: RGB TIFFs store their colour samples +last (`YXC`). Details in the [user guide](docs/user_guide.md) §5. ## Example @@ -232,13 +269,14 @@ record = PlaneRecord( technical_repeat="tech_rep1", histograms=[compute_plane_histogram(plane)], # one per channel position_id="img_01", # required: the XY position within its technical repeat + channels=("DNA",), # the channel ID of each histogram, in order ) -write_plane_histograms([record], "plane_histograms.csv") +write_plane_histograms([record], "plane_histograms.parquet", channel_ids=["DNA"]) # In a later brick: pool one channel of any group and derive normalization parameters -records = read_plane_histograms("plane_histograms.csv") +records = read_plane_histograms("plane_histograms.parquet") for key, members in group_records(records, "condition").items(): - pooled = PooledHistogram(members, channel=0) + pooled = PooledHistogram(members, channel="DNA") params = percentile_range(pooled, low=1, high=99.8) normalized = params.apply(plane, clip=(0, 1)) ``` diff --git a/docs/user_guide.md b/docs/user_guide.md index 46c971e3..0165e4ac 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -3,16 +3,21 @@ The preprocessing brick reads an experiment folder of microscopy images (TIFF or OME-Zarr) and computes one intensity histogram for every 2D plane. The histograms, with each plane's labels, are -saved in `plane_histograms.csv`. Later MorphoBricks bricks (for example patch extraction) -use this table to normalise images per condition, repeat or image without reading the -pixels again. +saved in `plane_histograms.parquet`. Later MorphoBricks tools (for example patch extraction) +use this table to calculate normalisation parameters per condition, repeat or image without +reading the pixels again. + +New to the command line? Start with the [quick start](#quick-start-from-a-terminal) after +the installation section. The brick **never changes your images** and never normalises them itself. It writes only to its own output folder, which is never inside the experiment folder. ## 1. Installation -You need Python 3.11 or newer and JupyterLab (or Google Colab). Download +For the notebook, you need Python 3.11 or newer and JupyterLab (or Google Colab). For the +command line only, see [Installing for the command line](#installing-for-the-command-line) +below. Download [`notebooks/MorphoBricks_Preprocessing.ipynb`](../notebooks/MorphoBricks_Preprocessing.ipynb), open it and run its three code cells in order: @@ -64,12 +69,12 @@ To install everything manually instead, run these commands in the environment us your notebook kernel: ```bash -pip install "morphobricks-preprocessing[notebook] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git" -pip install jupyterlab +python -m pip install "morphobricks-preprocessing[notebook] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1" +python -m pip install jupyterlab ``` To read OME-Zarr images, install the `zarr` extra too: -`pip install "morphobricks-preprocessing[notebook,zarr] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git"`. +`python -m pip install "morphobricks-preprocessing[notebook,zarr] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1"`. Start JupyterLab with `jupyter lab` and open the notebook. **Browse…** opens your computer's folder dialog; where no dialog can open (Google Colab, a remote server), it says so and you @@ -128,6 +133,48 @@ Google Drive is wiped when it disconnects (after some idle time, or after severa run. Untick it (CLI `--no-verify-content`) to compare size and time only; the manifest then records `verify_content: false`. An output folder keeps the choice of its earlier run. +### Installing for the command line + +You need Python 3.11 or newer, Git and an internet connection. We recommend installing into a +new Python virtual environment. JupyterLab is not required for command-line use. + +```bash +python -m pip install "morphobricks-preprocessing @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1" +``` + +To read OME-Zarr images, or to make the optional H&E tissue mask (`tissue-mask`, §5), install +the extras too: + +```bash +python -m pip install "morphobricks-preprocessing[zarr,he-mask] @ git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.1" +``` + +The package is installed from GitHub; it is not on a package index. + +## Quick start from a terminal + +This is the shortest route for an experiment whose images all have the same channels in the +same order. §5 explains each step and what to do when your experiment differs. + +```bash +morphobricks-preprocessing describe my_experiment +morphobricks-preprocessing describe my_experiment --channels COL,FN --image-type channels \ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish +morphobricks-preprocessing check my_experiment +morphobricks-preprocessing run my_experiment +``` + +1. The first `describe` shows the proposed IDs and the open questions. It writes nothing. +2. The second `describe` publishes the experiment description. Every preprocessing run needs + it. Give `--comparable` only if the samples of each biological repeat were prepared and + acquired comparably. +3. `check` inspects the folders, image headers and masks, and writes a report. +4. `run` computes the histograms and writes the output folder, + `my_experiment_MorphoBricks_Preprocessing`. + +If your analysis uses masks, declare them and run the `masks` command after preprocessing +(§5, "Declaring existing masks or adding new masks"). + ## 2. Organising the experiment folder The folder you select is the **experiment folder**. Below it, up to three levels of folders @@ -221,10 +268,34 @@ masks/ control/bio_rep1/tech_rep1/img_02.tif ``` -- Or keep the masks in the same folders as the experiment, each named after its image - followed by `_` and its kind (`img_01_cells.tif`, `img_01_nuclei.tif`), as many - segmentation tools write them; the kind is the part after the image name. Both ways may be - mixed in one masks folder. +- OME-Zarr label images are discovered automatically. External TIFF masks must be stored in a + separate masks folder. Give that folder with `--masks`, unless an earlier preprocessing run + already recorded it. +- Inside the masks folder, a mask type can be named in one of two ways. Both ways may be mixed + in one masks folder. + + **(a) One subfolder per mask type**, each mask named exactly as its image: + + ``` + my_experiment/ctrl/image_01.tif + my_masks/Cells/ctrl/image_01.tif + ``` + + Declare it with `--type Cells=instances` (§5, `declare-masks`). + + **(b) The mask type as the file-name ending**, after the image name and `_`, in the + experiment's folders. Cellpose names its masks this way: + + ``` + my_experiment/ctrl/image_01.tif + my_masks/ctrl/image_01_cp_masks.tif + ``` + + The mask type is `cp_masks`. Declare it with `--type cp_masks=instances:Cells`: the ending, + then the mask ID you want to use. + + Do not combine the two. A file `my_masks/Cells/ctrl/image_01_cp_masks.tif` matches no + image: the run warns and leaves it out. - A mask is a TIFF label image with the width and height of its image: background 0, each object its own whole number (or a true/false mask). The extension may differ from the image's (`img_01.tiff` for `img_01.ome.tif`). @@ -243,13 +314,16 @@ masks/ starts another's (`a.tif` and `a_b.tif`), a mask named `a_b_cells.tif` could belong to either and is refused: rename the masks or the images. - The label images stored inside an OME-Zarr image (its `labels` group) are used as masks - too, named after the label image. + too, named after the label image, except for mask types listed in `ignored_masks.toml` + (§5, `declare-masks --ignore`). - An image without a mask of one kind is reported; its objects of that kind cannot be measured. -Masks do not change `plane_histograms.csv`. They are checked and recorded for the bricks -that measure objects; the optional `masks` command (§5), or **Describe the masks** in the -notebook's step 3 (§4), also tells how they relate. +Masks do not change `plane_histograms.parquet`. They are checked and recorded for the bricks +that measure objects. If your analysis uses masks, run the `masks` command (§5), or +**Describe the masks** in the notebook's step 3 (§4), after preprocessing. It checks the mask +pixels against their declared representation and reports relationships between mask types. +Skip this step only if the downstream analysis does not use masks. ### Making masks with Cellpose (optional) @@ -454,10 +528,23 @@ run the experiment in the app of cell 3. Then: images must have their dimensions in the same order; the number of slices, time points and the size may differ. OME-Zarr images may store them in another order: they are matched by role, so z = 2, c = 1 means the same slice and channel in every image. -- **Channels:** all images of an experiment must have the same number of channels (an - image without a channel dimension has one). Split images with other channels into a - separate experiment, or exclude them. -- **RGB images:** the three colour samples are treated as channels (C). +- **Channels:** images within one acquisition folder must have a consistent channel layout + (an image without a channel dimension has one channel). Different acquisitions may have + different channel lists or orders when each is described separately in the notebook. The + simple command-line publication workflow requires one shared channel list and order for the + experiment. Later analysis tools may require the selected channel to be present in every + image being analysed. +- **RGB images:** RGB images must have exactly three colour channels containing red, green and + blue in that order, with an integer pixel type. Declare them using `--image-type rgb + --channels R,G,B`. TIFF files whose headers do not identify their interleaved colour samples + as RGB may need `--rgb-header-override`. OME-Zarr colour images must be declared RGB + explicitly. The three colour samples are treated as channels (C). The optional + `tissue-mask` command has narrower requirements: 8-bit RGB, one depth plane and one time + point. +- **Image type names:** the experiment description records separate-channel images as + `channels` and colour images as `rgb`. The `run` command's `--image-type` option uses the + older name `fluorescence` for separate-channel images. In the normal described workflow, use + the published description as the authoritative record of what your channels represent. - **Pyramidal images:** only the full-resolution level is read. - **Not supported yet:** files with several positions or scenes (several image series), and position or tile axes. Export each position as its own file. @@ -850,61 +937,98 @@ On Google Colab, cell 3 asks Colab not to put its output in a frame that scrolls ## 5. Command line -The same checks and computations are available from a terminal: +**Before you start.** Every preprocessing run needs a published experiment description +(`morphobricks.toml` in the output folder). `check`, `run` and `masks` refuse an experiment +without one: they print `A_DESCRIPTION_REQUIRED`, write nothing and exit with status 1. Publish +the description first, with `describe ... --publish` (below) or in the notebook's describe +steps. -```bash -morphobricks-preprocessing check /data/exp1 -``` - -prints what will be analysed, the label tree, the number of images per condition and -biological repeat (with `!` marking unbalanced ones), the problems found and the -suggested axis roles, for example `--axes ZCYX`. Then: +**A complete workflow.** This example assumes that every image contains collagen and +fibronectin in that order, that the image axes are named correctly, and that your biological +repeats were prepared and acquired comparably. Replace the channel names and date with your +own. Review the proposed IDs before accepting them. If these assumptions do not fit your +experiment, use the relevant instructions below. ```bash -morphobricks-preprocessing run /data/exp1 --axes ZCYX +# 1. Preview the draft description: proposed IDs and open questions (writes nothing) +morphobricks-preprocessing describe my_experiment +# 2. Publish the description +morphobricks-preprocessing describe my_experiment --channels COL,FN --image-type channels \ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish +# 3. Check the folders, image headers and masks +morphobricks-preprocessing check my_experiment +# 4. Compute the histograms +morphobricks-preprocessing run my_experiment ``` -`--axes` gives one role per dimension of the images, in their order: `X`, `Y`, `Z`, `C`, -`T`, or `-` for a length-1 dimension without a role. It is needed only when some images are +Your experiment is now described, checked and processed. The default output folder is +`my_experiment_MorphoBricks_Preprocessing`. Give this folder to the MorphoBricks tool that will +analyse your images. + +- Fast publication from the command line creates a new description for an experiment with a + shared channel layout. Use the notebook to edit an existing description, change repeat + pairing or describe acquisitions with different channel lists or orders. +- Give `--comparable` only if the samples of each biological repeat were prepared and acquired + comparably. Never give it just to get past the question. +- If `describe` refuses to publish because some image headers do not name their axes or state + their channel count, name the axes with the notebook or with `convert` (below). +- If your analysis uses masks, declare them, run preprocessing with them and run the `masks` + command ("Declaring existing masks or adding new masks", below). +- To state pixel sizes the images do not record, use `calibrate` (below), then run + preprocessing again. + +**What `check` does.** `check` inspects the folders, image headers and supplied masks, and +suggests axis roles. It does not measure image pixels or perform every validation of the +published description. `run` validates the description and confirmed axis roles before +processing. `check` prints what will be analysed, the label tree, the number of images per +condition and biological repeat (with `!` marking unbalanced ones), the problems found and the +suggested axis roles. + +To check the same images and external masks as your intended run, give `check` the same +`--exclude`, `--masks` and `--mask-axes` options. Unlike `run`, `check` does not automatically +reuse all these recorded choices. + +**Axis roles (`--axes`).** `--axes` gives one role per dimension of the images, in their +stored order: `X`, `Y`, `Z`, `C`, `T`, or `-` for a length-1 dimension without a role. For +example, `--axes CYX` is for images stored as channels, then rows, then columns. A Z axis is +allowed only with one slice: multi-slice Z-stacks are refused in this release (make 2-D +projections with `convert --project`, below). `--axes` is needed only when some images are plain stacks, whose metadata do not name their axes: when every image names all its axes, -`run` uses those roles without `--axes` (it prints **Axis roles (as every image names -them)**; design v0.4 §3), and they are still checked as below. A later `run` in the same output folder needs neither the roles nor -the experiment folder again, unless plain stacks were added or changed: +`run` uses those roles without `--axes` (design v0.4 §3), and they are still checked as below. +A later `run` in the same output folder needs neither the roles nor the experiment folder +again, unless plain stacks were added or changed: ```bash -morphobricks-preprocessing run --output /data/exp1_MorphoBricks_Preprocessing +morphobricks-preprocessing run --output my_experiment_MorphoBricks_Preprocessing ``` -uses the experiment folder and everything else the earlier run recorded there. Without an -experiment folder and without an output folder of a v0.4.0 run, `run` stops with -`experiment_not_recorded`, naming what is missing. Giving an experiment folder other than +uses the experiment folder and everything else the earlier run recorded there. If no +experiment folder has been recorded, give the experiment folder explicitly (otherwise `run` +stops with `experiment_not_recorded`). Giving an experiment folder other than the recorded one (for example after moving it) is reported as a change: every row is read again from the new place, and images that do not name their axes (plain stacks) must be confirmed again with `--axes`. Both commands check the axes (§4, step 2): `check` with the suggested roles, which are the headers' own, so only the `axes_not_named` warning of plain stacks can appear there; `run` -with the roles given in `--axes`. They print **Axes checked: every image names its axes in -its metadata, and the roles agree with them** when all is well (and name the plain stacks -whose roles are recorded as confirmed), or the errors naming the images, the likely cause -and the two fixes, and `run` stops (exit status 1). - -`--image-type fluorescence` or `--image-type rgb` gives the image type (§4, step 3). -Without it, `run` uses the type suggested from the image headers and prints it, with why it -was suggested and how to choose the other one; `check` prints the suggestion too. `rgb` -for images that are not three channels of a whole-number pixel type stops the run -(`rgb_not_possible`). - -`check`, `run` and `masks` need the experiment description published in the output folder -(`morphobricks.toml`, v0.5.1): the conditions, which biological repeats pair across conditions -and that they are comparable, the channels and the masks, answered in the notebook's describe -steps and saved with *Check and save*, or published from the command line with `describe ... ---publish` (§5). Without it they print `A_DESCRIPTION_REQUIRED`, naming both routes, write -nothing and exit with status 1. `describe` shows the draft description of the -folders and every question still open. The run writes `experiment_design.csv`, derived from the -description (an output for later bricks; nothing reads it back). `check` and `run` write the -report, `discovery_report.json` and `discovery_report.txt`, to the output folder; `run` writes -it on every run, also one that stops (`status` `stopped` or `written`, with the SHA-256 of the +with the roles given in `--axes`. When all is well they say that every image names its axes +and the roles agree (and name the plain stacks whose roles are recorded as confirmed); +otherwise they print the errors naming the images, the likely cause and the two fixes, and +`run` stops (exit status 1). + +**Image type.** The experiment description records separate-channel images as `channels` and +colour images as `rgb`. The `run` command's `--image-type` option uses the older name +`fluorescence` for separate-channel images. In the normal described workflow, use the +published description as the authoritative record of what your channels represent. Without +`--image-type`, `run` uses the earlier run's type, else the type suggested from the published +description and the image headers, and prints it; `check` prints the suggestion too. `rgb` for images that are not three +channels of a whole-number pixel type stops the run (`rgb_not_possible`). + +**Reports.** `describe` shows the draft description of the folders and every question still +open. The run writes `experiment_design.csv`, derived from the description (an output for +later tools; nothing reads it back). `check` and `run` write the report, +`discovery_report.json` and `discovery_report.txt`, to the output folder; `run` writes it on +every run, also one that stops (`status` `stopped` or `written`, with the SHA-256 of the manifest it describes). A run that stops says so, says that no table or manifest was written, and names what it did write: the report. Only a run refused before it starts (another run holds the lock, or no description is published) writes nothing. @@ -928,20 +1052,39 @@ the same bytes in every file except that time (and the manifest SHA-256 the repo | `--memory-limit SIZE` | Working-memory limit per plane, e.g. `2GiB` or `1.5GiB`: a whole number of bytes above 0 (`1.5` or `0.5B` are refused before anything is read) | | `--workers N\|auto` | How many images are read at once, each in its own thread (default 1: one after another). `auto`: at most the number of CPUs, and with `--max-ram` as many as the largest image's estimated working memory fits. The results are exactly the same with any value; it is not recorded and changes nothing on the next run | | `--max-ram SIZE` | With `--workers auto`: the memory the run may use, e.g. `8GiB` (256 MiB of it kept for the run itself). An image that alone needs more stops the run before any pixel is read (`image_over_max_ram`) | -| `--missing-as-singleton`, `--no-missing-as-singleton` | Confirm that images lacking some dimensions have one plane along them (`check` and `run`; default: the earlier run's answer, else no). `check` then reports what `run` will: an experiment of 2D images and Z-stacks passes `check` once confirmed, and the suggested option says `--axes ZCYX --missing-as-singleton` | +| `--missing-as-singleton`, `--no-missing-as-singleton` | Confirm that images lacking some dimensions have one plane along them (`check` and `run`; default: the earlier run's answer, else no). Confirm that a dimension absent from an image has size 1. This can reconcile missing length-1 dimensions, but does not permit multi-slice Z-stacks. Project Z-stacks to 2-D before preprocessing (`convert --project`) | | `--image-type fluorescence\|rgb` | The image type (default: the earlier run's, else the suggested one, printed) | | `--mode restart\|full` | `restart` (default) reuses the rows of unchanged images; `full` recomputes every row and check. Both keep your confirmations and replace the results only when the run succeeds | | `--verify-content`, `--no-verify-content` | Reuse rows (earlier or staged) only when each image's content SHA-256 is the one recorded with them, not only its size and modification time; every image is read once more. Default: the earlier run's choice, else on; `--no-verify-content` opts out and the manifest records it. Turning it on or off recomputes every row. With `masks`: also compare each mask's content SHA-256 before and after it is read (same default) | -| `--lab-links FILE` | A JSON file of lab-tool links (for example LabChronicle), recorded in `run_manifest.json` only (`lab_links`): exactly the keys `repository_url`, `commit` (the full 40- or 64-character lowercase SHA) and `experiment_path`, as non-empty text, and optionally `repeat_codes`, which maps each lab-tool repeat code to a biological repeat ID of the description (for example `{"R001": "rep1"}`). Any other key, a value of another type, an empty value, spaces around a value, or a key given twice is refused before anything is read (`lab_links_invalid`). A `repository_url` holding a credential (a password, `user:password@`, in any form; a user name before `@` in a URL whose scheme is not `ssh`, `git+ssh` or `ssh+git`, because `https://TOKEN@host/...` carries a token there), a query string or a fragment (`?` or `#`) is refused (`lab_links_invalid`), and the refusal does not repeat the URL: a credential is never written to the manifest. An SSH remote's login name (`git@host:lab/db.git`, `ssh://git@host/...`) is kept. The links change no result: no row, digest, cache or other file. They are not taken over by the next run: give the file to each run it belongs to. Not offered by the notebook | +| `--lab-links FILE` | Record optional lab-tool provenance from a JSON file. See "The lab-links file" below the table for its format. Does not change the image measurements. | | `--confirm-repeat-codes` | Confirm the `repeat_codes` of `--lab-links` for this run. The run prints each pair; without this option a file with repeat codes is refused (`lab_links_repeat_codes_not_confirmed`), also when a code is spelled like the ID: the lab tool's codes and the description's IDs are separate names | | `--no-masks` | Drop the masks folder an earlier run recorded, with the mask axes stated for its masks (those of OME-Zarr label images are kept) | | `--no-exclude` | Clear the exclusions an earlier run recorded, so every image is analysed again (not together with `--exclude`) | | `--remove-stale-lock` | Remove the lock left by a run that was stopped or whose computer restarted (`check`, `run`, `masks` and `calibrate`); give it only when no other run uses the output folder, on any computer (only Linux and macOS can tell whether a process on this computer still runs) | | `--outlier-limit N`, `--saturation-limit FRACTION`, `--min-images N` | Limits of the intensity checks printed after the run (default 3, 0.01 and 5) | -| `--log FILE` | Write technical details to a file (`run`, `masks`, `convert`). It is checked before anything is written and opened only once the other options are checked: a file inside the experiment or masks folder (given or recorded by the earlier run), inside the folder of the copies (`convert`), or named as one of the run's files in the output folder (`plane_histograms.csv`, `run_manifest.json`, the reports, `experiment_design.csv`, `calibration.csv`, `mask_relationships.json`, the lock) is refused and nothing is written; so is a file that is a hard link (it has another name). Any other name in the output folder is fine, for example `run.log` | +| `--log FILE` | Write technical details to a file (`run`, `masks`, `convert`). It is checked before anything is written and opened only once the other options are checked: a file inside the experiment or masks folder (given or recorded by the earlier run), inside the folder of the copies (`convert`), or named as one of the run's files in the output folder (`plane_histograms.parquet`, `run_manifest.json`, the reports, `experiment_design.csv`, `calibration.csv`, `mask_relationships.json`, the lock) is refused and nothing is written; so is a file that is a hard link (it has another name). Any other name in the output folder is fine, for example `run.log` | | `--masks FOLDER` | The masks folder (§2). `check` lists the mask types found and checks every mask from its header; `run` stops on a mask error and records the masks in `run_manifest.json`. A masks folder other than the one an earlier run recorded does not reuse the mask axes stated for that folder's masks (`--mask-axes`): state them again for the new folder (those of OME-Zarr label images are kept) | | `--mask-axes TYPE=ROLES` | The axes of a mask type, one role (Y, X, Z or T) per axis as stored, stated once per type: `Cells=TYX` for plain stacks of time points whose files do not name their axes; a 2D mask needs none, and `Cells=YX` (the removed shared 2D mask) is the error `shared_mask_not_supported` (repeatable; `check`, `run`, `masks`). Masks are never reordered. | +**The lab-links file.** `--lab-links` takes a JSON file of lab-tool links (for example +LabChronicle). It is recorded in `run_manifest.json` only (`lab_links`), and is not offered by +the notebook. + +- It holds exactly the keys `repository_url`, `commit` (the full 40- or 64-character lowercase + SHA) and `experiment_path`, as non-empty text. It may also hold `repeat_codes`, which maps + each lab-tool repeat code to a biological repeat ID of the description (for example + `{"R001": "rep1"}`). +- Any other key, a value of another type, an empty value, spaces around a value, or a key given + twice is refused before anything is read (`lab_links_invalid`). +- A `repository_url` holding a credential (a password, `user:password@`, in any form; a user + name before `@` in a URL whose scheme is not `ssh`, `git+ssh` or `ssh+git`, because + `https://TOKEN@host/...` carries a token there), a query string or a fragment (`?` or `#`) is + refused (`lab_links_invalid`). The refusal does not repeat the URL: a credential is never + written to the manifest. An SSH remote's login name (`git@host:lab/db.git`, + `ssh://git@host/...`) is kept. +- The links change no result: no row, digest, cache or other file. They are not taken over by + the next run: give the file to each run it belongs to. + After writing, `run` prints the intensity checks of the table, grouped by kind, each with the channel, the image or biological repeat and the values compared, and what to do once per kind; it draws no plots (the notebook does). Then it prints the channel check: each @@ -968,16 +1111,16 @@ stored as 8-bit do not. The same experiment in 16 bits and as 0-1 floats gives t findings only while the channel's high percentile is above about 333 counts; below that, the whole-number files have a floor that floats do not. -**Exit status.** Every command (`check`, `run`, `masks`, `calibrate`, `describe` and -`convert`) exits with status 1 when it prints an error, and with 0 otherwise: warnings, -intensity warnings included, never change it. So `check` exits with 1 on every error it -reports, `A_DESCRIPTION_REQUIRED` included. Options that cannot be read exit with 2. Scripts can therefore stop on any -non-zero status. +**Exit status.** Commands use exit status 0 for successful completion and 1 for a refused +operation. Invalid command-line arguments normally return 2. Read the command's final status +message before proceeding. Warnings, intensity warnings included, never change the status. -The optional `masks` command reads the masks and tells how they relate: +If your analysis uses masks, run the `masks` command after preprocessing. It checks the mask +pixels against their declared representation and reports relationships between mask types. +Skip this step only if the downstream analysis does not use masks. ```bash -morphobricks-preprocessing masks /data/exp1 --masks /data/exp1_masks +morphobricks-preprocessing masks my_experiment --masks my_masks ``` It reads every image's masks, one image at a time, and prints for each kind of mask @@ -1167,6 +1310,17 @@ metadata give none, or the wrong one, state them in `calibration.csv` in the out folder. Nothing is ever guessed: an image with neither is *uncalibrated*, and the report says so. +The most common case, 0.65 µm pixels in X and Y for the whole experiment, then a run that +records them: + +```bash +morphobricks-preprocessing calibrate my_experiment --size . XY 0.65 um +morphobricks-preprocessing run my_experiment +``` + +Run preprocessing again after every change made with `calibrate`: the sizes are recorded only +by the next run. More examples: + ```bash # 0.65 um pixels for the whole experiment; a 2 um z-step for one condition morphobricks-preprocessing calibrate /data/exp1 --size . XY 0.65 um --size treated Z 2 um @@ -1227,14 +1381,37 @@ exit status; it is not printed when the experiment is given or recorded. When the metadata of some images name their axes wrongly (the errors `axes_yx_swapped`, `axes_contradict_header`, `axes_x_before_y`) or do not name them at all (the warning `axes_not_named`), and you are sure of the roles, save the images again as named-axis -copies with your roles, then run preprocessing on the copies: +copies with your roles, then run preprocessing on the copies. `convert` has three common uses: ```bash -morphobricks-preprocessing convert /data/exp1 --to /data/exp1_named_axes --axes ZXY --output /data/exp1_MorphoBricks_Preprocessing -morphobricks-preprocessing check /data/exp1_named_axes --output /data/exp1_MorphoBricks_Preprocessing -morphobricks-preprocessing run /data/exp1_named_axes --output /data/exp1_MorphoBricks_Preprocessing --axes ZYX +# Correct axis metadata: write copies whose metadata name your roles +morphobricks-preprocessing convert my_experiment --to my_experiment_named --axes CYX +# Save a large fluorescence mosaic as OME-Zarr, so later tools can read it in windows +morphobricks-preprocessing convert my_slides --to my_slides_zarr --axes CYX --store ome-zarr +# Make maximum projections of Z-stacks (2-D copies) +morphobricks-preprocessing convert my_experiment --to my_experiment_max --axes ZCYX --project max ``` +These axis orders are examples. Use the actual stored order of your images. RGB TIFFs store +their colour samples last, so use `YXC` rather than `CYX`; `convert` does not check the order +against the file, so look at a copy. + +**The copies are a new experiment folder.** Describe and publish the copies before `check` and +`run`, for example for the projections: + +```bash +morphobricks-preprocessing describe my_experiment_max +morphobricks-preprocessing describe my_experiment_max --channels COL,FN --image-type channels \ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish +morphobricks-preprocessing check my_experiment_max +morphobricks-preprocessing run my_experiment_max +``` + +The same applies to `my_experiment_named` and `my_slides_zarr`. Projected copies always need +their own description and output folder. Named-axis and OME-Zarr copies are the one +exception: if the originals already have a published description in an output folder, give +that folder to `check` and `run` on the copies with `--output` instead (see below). + `--axes` gives your roles for the original images, exactly as for `run`; they are never taken from the metadata. `convert` writes a new folder (`--to`, outside the experiment) with the experiment's folders and file names: the images with axis problems as OME-TIFF @@ -1337,7 +1514,8 @@ make a projected copy first: default method; `--z-range 2:10` uses only those slices of every image, zero-based with the end excluded, `4:5` is the single slice 4, and every image must have them), or in Python `convert_experiment(EXP, mapping, FOLDER, projection=Projection("max", (2, 10)))`. -Every image of the experiment is written as a 2-D OME-TIFF of the same folders and names: +Every image of the experiment is written as a 2-D OME-TIFF (or a 2-D OME-Zarr image with +`--store ome-zarr`) of the same folders and names: its axes are your roles without Z (`ZCYX` becomes `CYX`), each (t, c) is projected on its own, and the Z size is not written to the copy (it is recorded in the conversion record as dropped). Your originals are only read. The pixel type is decided by the input type and the @@ -1349,8 +1527,8 @@ to infinity is refused (`projection_overflow`). The copy's OME-XML says how it w the conversion record (version 4) holds the method, the slices used, the source's SHA-256, the types, the rounding and the dropped Z size for every image. Masks are never projected: masks with depth slices stop the projection (`projection_masks_3d`); 2-D masks stay where -they are. OME-Zarr images are not projected yet (`projection_zarr_not_supported`; exclude -them). One folder holds one method and one slice range (`copy_differs` otherwise). The command prints the next commands with a +they are. OME-Zarr source images are not projected in this release (`projection_zarr_not_supported`; +export TIFF copies of them first, or process the TIFF images separately). One folder holds one method and one slice range (`copy_differs` otherwise). The command prints the next commands with a new output folder (by default the copy folder's name with `_MorphoBricks_Preprocessing`): the projected copies are a different source, so the description starts again there (the design and the stated pixel sizes are entered again). A run on the copies records the projection in its manifest (`projection`: the method, the slices used, the source SHA-256 of every image) and the report says "max projections of slices 1:4". Masks next to projected images are used as they are, with the warning `masks_on_projected_images`: check that they were made on, or for, the projection. A run on projected copies reads the conversion record strictly: a record that is missing or does not match the run is refused, never read as a plain image. The notebook card follows. @@ -1388,49 +1566,56 @@ copies (optional)** card appears under it, calling the same functions as the com The card is not shown when another brick embeds step 1 without the output folder (`folder_step(show_output=False)`). -### Declaring masks added after preprocessing (`declare-masks`) +### Declaring existing masks or adding new masks (`declare-masks`) -Masks you make after preprocessing (a segmentation of the output, for example) must be declared -in the published description before `run --masks` accepts them; otherwise the run refuses them -(`R_MASK_TYPE_NOT_DECLARED`). The notebook declares them on its *Masks* question or in its -Register step. On the command line, say what each mask type is: +Declare each mask type before running preprocessing with those masks. You can do this +immediately after publishing the experiment description, or add masks to an existing +preprocessing run later. An undeclared mask type is refused (`R_MASK_TYPE_NOT_DECLARED`). The +notebook declares masks on its *Masks* question or in its Register step. On the command line, +say what each mask type is: ```bash -morphobricks-preprocessing declare-masks --output /data/exp1_MorphoBricks_Preprocessing \ - --masks /data/exp1_masks --type Cells=instances --type Nuclei=instances -morphobricks-preprocessing run --output /data/exp1_MorphoBricks_Preprocessing --masks /data/exp1_masks -morphobricks-preprocessing masks --output /data/exp1_MorphoBricks_Preprocessing --masks /data/exp1_masks +morphobricks-preprocessing describe my_experiment --channels COL,FN --image-type channels \ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish +morphobricks-preprocessing declare-masks --output my_experiment_MorphoBricks_Preprocessing \ + --masks my_masks --type Cells=instances +morphobricks-preprocessing run my_experiment --masks my_masks +morphobricks-preprocessing masks --output my_experiment_MorphoBricks_Preprocessing ``` -- `TYPE` is the mask type's folder name. `REPRESENTATION` is `instances` (each object has its +The last command checks the mask pixels and reports their properties and relationships. Run it +before using the masks in another MorphoBricks tool. + +- `TYPE` is the mask type: its folder name, or the file-name ending of masks such as + `image_01_cp_masks.tif` (§2, "Masks"). `REPRESENTATION` is `instances` (each object has its own number: Cellpose output), `binary` (foreground / background) or `parent_labels` (each non-zero value one group). There is no default; nothing is guessed from the files. -- The mask ID is the folder name. When that is not a valid mask ID (`nuclei-mask`), give one: - `--type nuclei-mask=binary:nuclei`. -- The description is published as the notebook publishes it: under the output folder's lock and - against the version it was read from. Running the command again with the same answers changes - nothing. A mask type already declared otherwise is refused: change it in the notebook's - describe steps. +- The mask ID is the mask type unless you give another after a colon. Give one when the type is + not a valid mask ID (`--type nuclei-mask=binary:nuclei`), or to give a file-name ending a + clearer name (`--type cp_masks=instances:Cells`). +- The command updates the saved experiment description safely. Repeating an identical + declaration makes no change. A mask type already declared otherwise is refused: change it in + the notebook's describe steps. - `--masks` also checks each mask type against the masks folder (no folder there that differs only in upper/lower case). -- Masks that are not in a masks folder of their own, OME-Zarr label images (`.zarr/labels/`) - or `_.tif` beside the images, need no `--masks`: the command then prints the next - commands without it (`run EXPERIMENT --output FOLDER`, the experiment folder left out when a - run of the output folder records it). +- OME-Zarr label images (`.zarr/labels/`) need no `--masks`: the command then + prints the next commands without it (`run EXPERIMENT --output FOLDER`, the experiment folder + left out when a run of the output folder records it). - `check` reports a mask type the description does not declare exactly as `run` refuses it (`R_MASK_TYPE_NOT_DECLARED`, naming the type), so you see it before the run. Its fix names - both ways out: `--type TYPE=REPRESENTATION` to use it, `--ignore TYPE` to skip it. -- **Skipping a mask type you do not use (`--ignore TYPE`, repeatable).** An OME-Zarr image may - carry label images of another tool, or a masks folder a mask type outside your analysis. - `declare-masks --output FOLDER --ignore TYPE` lists it in `ignored_masks.toml` beside - `morphobricks.toml` (the description itself has no place for "not used"); `check` and `run` - then leave it out, without reading or recording it, instead of refusing it. The run records - the list and the file's SHA-256 in `run_manifest.json` (`ignored_masks`), so later bricks - neither refuse those label images as unrecorded nor accept a list changed since the run (run - preprocessing again after changing it). Undeclared types that are not listed are still - refused. A declared type cannot be ignored; declaring it with `--type` takes it off the list - (the file is removed when the list becomes empty). `--type` and `--ignore` may be given - together; at least one is needed. + both ways out: `--type TYPE=instances` (or `binary`, `parent_labels`, each with what it + means; none is guessed) to use it, `--ignore TYPE` to skip it. +- **Skipping a mask type you do not use (`--ignore TYPE`, repeatable).** Ignored mask types are + recorded in `ignored_masks.toml`. Preprocessing skips them. Declare a previously ignored type + with `--type` to use it again. Run preprocessing after changing the list. For example: + + ```bash + morphobricks-preprocessing declare-masks --output my_experiment_MorphoBricks_Preprocessing \ + --type Cells=instances --ignore OtherLabels + ``` + +- Do not declare and ignore the same mask type. If the ignore operation fails after new + declarations have been saved, those declarations remain saved. - In Python: `morphobricks_preprocessing.mask_declare.declare_masks(output, {"Cells": "instances"})`. ### Converting a mask (`convert-mask`) @@ -1470,17 +1655,20 @@ masks** does the same. ### An H&E tissue mask (optional) -For H&E images (a unit declared `image_type = "rgb"`), `tissue-mask` writes a **new** region mask -that leaves out nuclei, red blood cells and empty space, so that a brick such as fiberfeatures -measures the tissue between them. It needs the `he-mask` extra: +For H&E images (a unit declared `image_type = "rgb"`), `tissue-mask` writes a binary region +mask designed to exclude nuclei, red blood cells and empty background, so that a tool such as +fiberfeatures measures the tissue between them. The images must be 8-bit RGB, with three colour +channels, one depth plane and one time point. It needs the `he-mask` extra (see +[Installing for the command line](#installing-for-the-command-line)): ```bash -pip install "morphobricks-preprocessing[he-mask]" -morphobricks-preprocessing tissue-mask --output /data/exp1_MorphoBricks_Preprocessing --to HETissue +morphobricks-preprocessing tissue-mask --output my_experiment_MorphoBricks_Preprocessing --to HETissue ``` -- It is a **fixed rule**, `he_tissue_v2` by default, and it is **provisional**: its numbers are - not frozen until an acceptance report is accepted. `he_tissue_v2` first measures each image's +Inspect the masks (the notebook's preview, or the printed "kept" share) before declaring them. + +- It is a **fixed rule**, `he_tissue_v2` by default. The rule is provisional and may change in a + later version. The rule version is recorded with each mask. `he_tissue_v2` first measures each image's white from its brightest pixels (the glass), so scans whose glass is grey rather than white work; `--rule he_tissue_v1` keeps the white fixed at 255 (it keeps nothing on such scans). An image with no glass or empty space at all takes its brightest tissue as white: check the @@ -1496,15 +1684,18 @@ morphobricks-preprocessing tissue-mask --output /data/exp1_MorphoBricks_Preproce to `mask_lineage.jsonl`, which records the image, the complete rule and its digest, the exact installed code that computed it and the library versions. An image where nothing is kept gives an all-zero mask: a valid, empty region. -- Running the same command again changes nothing. If the printed line says **this mask will not - be reused on retry**, the installed code could not be verified (for example a development - install, `pip install -e`): the mask is written, but a second run with the same ID is refused; - use a new ID. +- Before declaring the generated mask, an identical retry can reuse existing files when their + contents and the software identity can be verified. Once the mask ID is declared, + `tissue-mask` refuses to write under that ID. To generate another version, choose a new ID + with `--to`. If the command says the mask will not be reused on retry, the installed code + could not be verified (for example a development install, `pip install -e`): the mask is + written, but a second run with the same ID is refused; use a new ID. - **A run without a masks folder** (scanner images often have no masks) gets one first: `tissue-mask` creates `_masks` beside the experiment folder (or the new, empty folder `--masks FOLDER` names), records it by running preprocessing again on the output folder - with that masks folder, exactly as `run --masks FOLDER` records one (unchanged images are not - read again), and says so in one line. A folder that exists and is not empty is never adopted: + with that masks folder, exactly as `run --masks FOLDER` records one, and says so in one line. + Histograms of verified unchanged images are reused; content verification may still reread + the source files. A folder that exists and is not empty is never adopted: give another, or run preprocessing with `--masks` yourself if it is your masks folder. - A refusal names the image once, then what to do. - Then declare it, run preprocessing and the masks step again; the command prints these commands @@ -1566,21 +1757,15 @@ it has no lineage file and cannot be declared as a mask of a run: for a MorphoBr The default output folder is next to the experiment folder: `/data/exp1` → `/data/exp1_MorphoBricks_Preprocessing`. -- **`plane_histograms.csv`:** one row per plane (every channel of an image at one depth - slice and time point) with the position (`position_id`, the file name without its - extension), the file name, the zero-based plane coordinates `z` and `t` (0 when the - image has no such dimension), the three labels, the pixel type and the number of - channels; then, for each channel, its exact minimum and maximum, pixel counts and - histogram, in columns ending in the channel number (`Intensity_MinIntensity_C0`, - `Histogram_Count_C1_00042`, …). The table is very wide (one column per bin and channel), - so spreadsheet programs may not open it completely; read it in Python with - `read_plane_histograms()`. The columns are defined in the [normalization brick's - contract](https://github.com/CellMigrationLab/morphobricks-normalization/blob/main/docs/contract.md) - §6.2 (schema version 5: the columns are named by channel ID, for example - `Histogram_Count_DNA_00042`; a `channels` column lists the stains of each plane, and a stain - the image does not have is blank; each channel also has its underflow and overflow, zero - unless the robust range is used). A table written by an earlier version is recomputed on the next - run; later bricks ask you to run this brick again on it. +- **`plane_histograms.parquet`:** the intensity histograms of every image plane, with its + experimental labels and channel IDs. The table contains one row per plane and stores each + channel's histogram as lists of bin indices and counts. Later MorphoBricks tools read this + file to calculate normalisation parameters without rereading the image pixels. Read it in + Python with `read_plane_histograms()` (from `morphobricks_normalization`). The format + (schema version 6) is defined in the [normalization brick's + contract](https://github.com/CellMigrationLab/morphobricks-normalization/blob/main/docs/contract.md). + From v0.10.0, this file replaces `plane_histograms.csv`. To update an older preprocessing + run, run preprocessing again. - **`image_qc.csv`:** one row per plane and channel with image QC metrics measured while the histograms are computed (no extra read): the share of the plane above its Otsu threshold (`foreground_fraction`; `otsu_separation` is about 0.64 for noise and for any dense field @@ -1718,9 +1903,14 @@ Run the notebook or `run` again after adding, changing or removing images: types, and only the manifest records the new type. **After upgrading from an earlier version (v0.5.1 or before):** its run manifest is not read -(only version 5 is, since v0.5.2), so the first run recomputes every row and reuses no recorded +(only versions 5 and 6 are), so the first run recomputes every row and reuses no recorded input: give the axis roles, masks and exclusions again. Later bricks refuse such older runs until they are run again. +**After upgrading from v0.5.2 to v0.9.x:** those runs wrote `plane_histograms.csv`. From v0.10.0, +`plane_histograms.parquet` replaces it, and later tools refuse the old table. To update an +older preprocessing run, run preprocessing again: every row is recomputed and the CSV file is +removed. + Run the brick again after adding images or masks before using a later brick: later bricks read the images and masks this brick's run recorded, and refuse an experiment holding images or masks the run did not record (they name them). @@ -1743,7 +1933,7 @@ continues. | `R_MASK_CONTRADICTS_REPRESENTATION` | Error | The masks step found a file of a mask declared `binary` that is stored as floats, or holds, over all its planes together, a negative value or two or more different positive values (the message names the file and the values found, or its pixel type). A binary mask holds 0 and at most one positive value (an all-zero or all-foreground file is accepted), stored as integers or true/false. Declare the mask as `instances` in the description if every value is an object, or as `parent_labels` (grouped labels) if every value is one group, such as the mitochondria of one cell; or fix the file (save a float mask as integers). The file stays `not yet checked`, so an analysis that names the mask refuses it (`A_MASK_UNCHECKED`) without reading it. | | `R_UNIT_NOT_FOUND`, `R_UNIT_NOT_DECLARED`, `R_UNIT_NOT_HOMOGENEOUS`, `R_CHANNEL_COUNT_MISMATCH`, `R_HEADER_CONTRADICTION`, `R_IMAGE_TYPE_CONTRADICTS_HEADER`, `R_MASK_TYPE_NOT_DECLARED` | Error | The published description and the folder or the image headers disagree (the message says where). Correct the description, publish it again and run again. | | `R_IMAGE_TYPE_CONTRADICTS_HEADER` for colour scanner files, `R_RGB_OVERRIDE_NOT_THREE_SAMPLES`, `E_RGB_OVERRIDE_WITHOUT_RGB` | Error | Some scanners store colour (RGB) images with a header that does not say RGB (for example TIFF photometric *minisblack* with three samples per pixel). The acquisition declared `image_type = "rgb"` is then refused, and the message says so and names `rgb_header_override`. If the three samples are red, green and blue in this order, add `rgb_header_override = true` to that acquisition in `morphobricks.toml` (beside `image_type = "rgb"`; in the notebook, tick **Read these folders as colour (RGB) although their header does not say colour** on the Image type card of the Channels step; on the command line, only while a new fast-mode description is published, `describe ... --image-type rgb --channels R,G,B --rgb-header-override`, §5; a published description is changed in the notebook) and publish again: the run then accepts the header and records the acquisition in the manifest as declared RGB with the header overridden (`image_type_header_overridden`, `header_photometric`). Every image whose header does not say RGB must have exactly three interleaved samples per pixel, else `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` names the image (reported before `R_UNIT_NOT_HOMOGENEOUS`); the key on an acquisition that is not declared `rgb` is `E_RGB_OVERRIDE_WITHOUT_RGB`. Images of the acquisition that differ only in colour interpretation (some *minisblack*, some RGB) are then one layout. Images whose header already says RGB, or whose format states no colour interpretation (OME-Zarr), do not use the key; the manifest records, per image, whether it was used (`rgb_header_override_images`). Adding, removing or changing the key reopens the "same way" confirmation of that replicate. Only headers are read, never pixels. | -| `R_FAST_LAYOUT_CONTRADICTION` | Error | The published description is in **fast mode** (it has a `channel_layout` table: "every imaging unit has the same channels in the same order", Spec ADR 0006) and some images of the acquisitions that follow it (`channels_from = "experiment"`) contradict that list. One message lists **every** contradicting image, with its FOV key (condition, repeat and acquisition folders, then the image name) and path, and every contradiction found in it: `image_type` (the header says colour where the list is not, or the reverse), `channel_count` (another number of channels), `header_order` (header names of the list in another order) or `header_names` (a header name that is no confirmed name of any channel of the list), each with its C index and what was expected and found. It is decided from the image headers only, before any pixel is read; nothing is reordered, dropped or guessed, and nothing was processed. Tag the acquisitions of these images on their own (`channels_from = "unit"`, confirmed per acquisition), publish again and run again. When the contradiction is an `image_type` of colour scanner files whose header does not say colour (three interleaved samples), the suggested action names the RGB header override instead (`rgb_header_override = true`, the notebook's Image type card), once; while a new description is published from the command line, `describe` also names `--rgb-header-override [FOLDER]` (§5). An image whose header gives no channel names (or an empty name) needs no evidence and follows the list; the manifest records each image of a fast acquisition in `fast_layout_images` (`header_verified` true only when every channel was confirmed by its header name). In such acquisitions this one code replaces `R_CHANNEL_COUNT_MISMATCH`, `R_HEADER_CONTRADICTION`, `R_IMAGE_TYPE_CONTRADICTS_HEADER` and `R_UNIT_NOT_HOMOGENEOUS` (which stays for the other axes); `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` keeps its priority. An acquisition tagged on its own is checked as in a description without fast mode. Experiments with extra channels in some acquisitions are refused here: tag those acquisitions on their own. | +| `R_FAST_LAYOUT_CONTRADICTION` | Error | The published description is in **fast mode** (it has a `channel_layout` table: "every imaging unit has the same channels in the same order", Spec ADR 0006) and some images of the acquisitions that follow it (`channels_from = "experiment"`) contradict that list. One message lists **every** contradicting image, with its FOV key (condition, repeat and acquisition folders, then the image name) and path, and every contradiction found in it: `image_type` (the header says colour where the list is not, or the reverse), `channel_count` (another number of channels), `header_order` (header names of the list in another order) or `header_names` (a header name that is no confirmed name of any channel of the list), each with its C index and what was expected and found. It is decided from the image headers only, before any pixel is read; nothing is reordered, dropped or guessed, and nothing was processed. Tag the acquisitions of these images on their own (`channels_from = "unit"`, confirmed per acquisition), save the description and run again. When the contradiction is an `image_type` of colour scanner files whose header does not say colour (three interleaved samples), the suggested action names the RGB header override instead (`rgb_header_override = true`, the notebook's Image type card), once; while a new description is published from the command line, `describe` also names `--rgb-header-override [FOLDER]` (§5). An image whose header gives no channel names (or an empty name) needs no evidence and follows the list; the manifest records each image of a fast acquisition in `fast_layout_images` (`header_verified` true only when every channel was confirmed by its header name). In such acquisitions this one code replaces `R_CHANNEL_COUNT_MISMATCH`, `R_HEADER_CONTRADICTION`, `R_IMAGE_TYPE_CONTRADICTS_HEADER` and `R_UNIT_NOT_HOMOGENEOUS` (which stays for the other axes); `R_RGB_OVERRIDE_NOT_THREE_SAMPLES` keeps its priority. An acquisition tagged on its own is checked as in a description without fast mode. Experiments with extra channels in some acquisitions are refused here: tag those acquisitions on their own. | | `folder_and_id_changed` | Error | *Check and save* (and publication) found an ID changed in the same save as a folder change of the same entity: for example a repeat ID `Day1 -> DayX` while one of its folders was renamed or removed, a condition ID changed while its folder was renamed, or a removed folder's ID typed for the new folder. Neither change is guessed from the other, so the message names the entity, its saved ID and its folders. Undo the ID edit: put the saved ID back (the folder change then saves on its own). A removed folder's ID stays used and is not given to another folder (experiment-v1 4.9). Nothing was published. | | `R_DRAFT_CHANGED` | Error | Notebook: `morphobricks.draft.json` was changed since this notebook read or saved it (another notebook, or a program, saved its own answers in the same output folder). Nothing was saved or published, and the answers saved there are kept. Press **Check folder** in step 1 to read them, then give your change again. | | `R_DRAFT_EXISTS` | Error | Command line (`describe --publish`): the output folder holds `morphobricks.draft.json`, answers saved in the notebook that the command does not read. Nothing was published or written. Finish those answers and publish them in the notebook (step 1, **Check folder**, then **Check and save**), or, if they are not wanted, remove or archive that file yourself and run the command again. | @@ -1787,7 +1977,7 @@ continues. | `plane_over_memory_limit` | Error | A plane cannot be read within the memory limit, not even in blocks (for example, it is stored compressed in one piece). Raise the limit, or save the images again as tiled or uncompressed TIFF files or as OME-Zarr with smaller chunks. | | `compression_not_bounded` | Error | Planes too large to read whole within the memory limit are stored with a TIFF compression whose decoding memory has not been measured (old-style JPEG, PackBits, Zstandard, WebP, JPEG 2000, ..., or JPEG in another form than 8-bit greyscale, RGB or YCbCr), so they are not read in blocks: only uncompressed, deflate (zlib), LZW, LZMA and 8-bit greyscale, RGB or YCbCr JPEG TIFF images are (decoded by imagecodecs, a required dependency: an image is also refused when the installed imagecodecs is missing, older than 2024.12.30 or, for JPEG, not built on libjpeg-turbo 3, and the message says so). The message names the compression. Save the images again as uncompressed, deflate, LZW or LZMA TIFF files (tiled, for large images) or as OME-Zarr, or raise the memory limit so that their planes are read whole. The same refusal, from the header and before any pixel is read, stops window reads and `RunInputs.read_plane` of such an image whatever its size. | | `unsupported_layout` | Error | The image cannot be read one plane at a time. Check the axis roles or export again. | -| `unreadable_planes` | Error | Pixel data cannot be decoded. The message names each plane that failed (its T, Z and C index and the channel ID) and why, at most 20 per image followed by "and N more"; the run report lists every one (`unreadable_planes`; in the notebook's run report, under *Unreadable planes*, one folded list per image); no `plane_histograms.csv` is written, since one channel that cannot be measured fails the whole table. Export again, or exclude the image. | +| `unreadable_planes` | Error | Pixel data cannot be decoded. The message names each plane that failed (its T, Z and C index and the channel ID) and why, at most 20 per image followed by "and N more"; the run report lists every one (`unreadable_planes`; in the notebook's run report, under *Unreadable planes*, one folded list per image); no `plane_histograms.parquet` is written, since one channel that cannot be measured fails the whole table. Export again, or exclude the image. | | `image_over_max_ram` | Error | `--workers auto --max-ram`: an image needs more working memory to read than the budget leaves (estimated from its header). Nothing was read. Raise `--max-ram`, or lower `--memory-limit` so its planes are read in smaller blocks. | | `invalid_bin_count` | Error | Bin count outside the allowed range. Use the default or a value in range. | | `experiment_not_recorded` | Error | `run` was given no experiment folder, and the output folder holds no v0.4.0 run that records one (or no output folder was given). Give the experiment folder. | @@ -1806,15 +1996,15 @@ continues. | `copy_folder_not_empty` | Error | `convert`: the folder for the copies holds files and no conversion record. Nothing is overwritten; choose a new or empty folder. When the folder also holds the work folder of a stopped conversion, the message says the files named may be copies it had moved into place when it was interrupted: remove them, then convert again. | | `copy_differs` | Error | `convert`: images in the folder of copies differ from the copies this conversion would write (an original changed, other roles, a copy changed, an image no longer in the experiment), or the folder holds copies of another experiment. Nothing is overwritten; convert into a new folder, or remove those copies first. | | `cannot_convert_pixel_type` | Error | `convert`: images of 64-bit integers cannot be saved as OME-TIFF, and pixel values are never changed to fit. Save them again with named axes in a 32-bit type if their values fit, or correct the roles. | -| `nothing_to_project` | Error | `convert` with a projection: no image has a depth axis (Z) under the roles you gave. Check the roles; nothing was written. | +| `nothing_to_project` | Error | `convert` with a projection: no image has a depth axis (Z) under the roles you gave. Check the stored axis order: Z must be the axis of the slices of a stack. If these images have no depth dimension, omit `--project`. Nothing was written. | | `projection_z_range_outside` | Error | `convert` with a projection: the slice range does not fit every image; the shorter images are named. Give a range every image has, or leave it out. | | `projection_cannot_be_exact` | Error | `convert` with a projection: a sum or mean of that many slices of that pixel type could not be held exactly. Use max or mean, or a shorter slice range. | | `projection_overflow` | Error | `convert` with a projection: a sum overflows to infinity (float64) at the pixels named. Use max, or mean if the values allow it. | | `projection_undefined` | Error | `convert` with a projection: a sum adds an infinity to its opposite at the pixels named, which is undefined. Use max. | -| `projection_over_memory_limit` | Error | `convert` with a projection: one input plane and its running total do not fit the memory limit. Raise `--memory-limit`. | -| `projection_masks_3d` | Error | `convert` with a projection: masks of the images have depth slices (Z), and masks are never projected. Make 2-D masks on the projected images, or move these masks out of the masks folder. | -| `projection_masks_axes_unknown` | Error | `convert` with a projection: masks have more than Y and X and their axes are not named, so it is not known whether they have depth slices. Name the axes in the masks' metadata, or move them out. | -| `projection_zarr_not_supported` | Error | `convert` with a projection: OME-Zarr images are not projected yet. Exclude them. | +| `projection_over_memory_limit` | Error | `convert` with a projection: one input plane and its running total do not fit the memory limit. Increase `--memory-limit` only if sufficient RAM is available, or export smaller images for projection. | +| `projection_masks_3d` | Error | `convert` with a projection: masks of the images have depth slices (Z), and masks are never projected. Keep the original masks separately, outside the masks folder, then convert the images without those 3-D masks; create new 2-D masks from the projected images and register them with the new experiment. | +| `projection_masks_axes_unknown` | Error | `convert` with a projection: masks have more than Y and X and their axes are not named, so it is not known whether they have depth slices. Check and export the mask axes correctly. If these masks belong to the original 3-D images, keep them separate from the projected experiment. | +| `projection_zarr_not_supported` | Error | `convert` with a projection: projection of OME-Zarr source images is not supported in this release, and no projected copies were written. Export suitable TIFF copies of these images before projection, or process the TIFF images separately. | | `source_changed_during_check` | Error | `convert`: an original changed while its metadata was read, so the metadata may not describe the file that would be copied. Nothing was written; convert again when nothing writes into the experiment. | | `conversion_failed` | Error | `convert`: an image could not be copied (unreadable, changed while copied, or the folder cannot be written). The copies written by this conversion were removed; fix the cause and convert again, or exclude the image. | | `not_enough_space` | Error | `convert`: the copies would not fit on the drive. Free space or choose another drive. | @@ -1857,7 +2047,7 @@ continues. | `lab_links_repeat_unknown` | Error | A lab-tool repeat code names a biological repeat the description does not declare (IDs are compared exactly; a folder name or display name is not an ID). Correct the file. | | `lab_links_repeat_twice` | Error | Two lab-tool repeat codes name the same biological repeat; each repeat has exactly one code. Correct the file. | | `lab_links_repeat_missing` | Error | The lab-tool repeat codes leave out a biological repeat of the description; a mapping names every repeat. Add its code, or leave `repeat_codes` out. | -| `rgb_not_possible` | Error | The image type RGB was chosen, but the images are not three channels of a whole-number pixel type. Choose fluorescence, or check the axis roles: the RGB samples must have the role C. | +| `rgb_not_possible` | Error | The image type RGB was chosen, but the images are not three channels of a whole-number pixel type. If the images are separate stains, describe them as separate channels. If they are genuinely RGB, verify that the stored colour-sample count and axis roles are correct. | | `repeat_group_conflict` | Error | A repeat group holds two folders of the same condition. Move one into another replicate on the *Replicates* page and save the description again (*Check and save*). | | `invalid_experiment_design` | Error | A repeat group has no usable name (empty, `NA`, `nan`, `none`, `null`, `n/a`, ``, or spaces around it), two repeat groups are spelled the same apart from upper and lower case, or a confirmation date is not written `YYYY-MM-DD`. It comes from a description edited by hand or rows built in code; correct the description (the message names the folder). | | `image_intensity_outlier` | Warning (intensity check) | An image's median or high percentile in a channel is far from the other images of its condition and biological repeat. Look at it: it may be out of focus, contain debris or bubbles, or have been acquired differently. Exclude it if it is faulty. | @@ -1878,7 +2068,7 @@ continues. | `manifest_channel_coverage_mismatch` | Error (other bricks) | `RunInputs.open` found a `channel_coverage` in the run manifest that is not the channel coverage of the published `morphobricks.toml` the run read (`ChannelCoverageMismatchError`); the message names `experiment_description.channel_coverage` and each biological repeat that differs. The manifest was changed after the run, so the run is refused, never corrected. Run preprocessing again. | | `manifest_unit_record_malformed` | Error (other bricks) | A record of the run manifest's `experiment_description.units` is not an object with `repeat`, `condition`, `technical_repeat`, `channels` and `image_type_header_verified` of their types, or holds a field the run does not write (`ManifestUnitRecordError`, when the manifest is read). The manifest was changed after the run, or was written by a newer release that records a unit field this one does not know (refused, never ignored); the message names the unit record and the field. Nothing is filled in: run preprocessing again. A manifest written before v0.5.2 never reaches this check: its version is refused first. | | `manifest_unit_record_mismatch` | Error (other bricks) | `RunInputs.open` found a unit record in the run manifest that is not a unit of the published `morphobricks.toml` the run read: an unknown repeat, condition or technical repeat, a unit recorded twice or not at all, other channels, or a declared `rgb_header_override` that the description does not declare (`UnitRecordMismatchError`); the message names the unit record and the field. Run preprocessing again. | -| `ignored_masks_invalid` | Error | `ignored_masks.toml` in the output folder cannot be read as `declare-masks --ignore` writes it (other keys, another version, a name twice or with a `/`, a link). Write it again with `declare-masks --ignore`, or remove the file. | +| `ignored_masks_invalid` | Error | `ignored_masks.toml` in the output folder cannot be read as `declare-masks --ignore` writes it (other keys, another version, a name twice or with a `/`, a link). `declare-masks` reads the list before changing it, so it cannot rewrite an unreadable one: move the file out of the output folder (keep it as a backup), recreate the list with `declare-masks --output FOLDER --ignore TYPE` for every mask type you still intend to skip, and run preprocessing again. | | `masks_folder_not_found` | Error | The masks folder does not exist. Select the folder that holds one folder per kind of mask. Later bricks opening a run (`RunInputs.open(..., masks_root=...)`) refuse a masks folder given that does not exist or is a file with the same code (`MasksFolderNotFoundError`); it is never read as a folder without masks. Give the folder that holds the masks, or leave `masks_root` out to use the one the run recorded. | | `masks_folder_unreadable` | Error | A masks folder given to a later brick (`RunInputs.open(..., masks_root=...)`) cannot be listed, for example for lack of permission, so its masks cannot be checked against the run (`MasksFolderUnreadableError`); the message names the folder and the reason. Check its permissions, or give another folder. | | `output_inside_masks` | Error | The output folder is inside the masks folder, where the run's files would be read as masks. Choose another output folder. | @@ -1992,8 +2182,8 @@ write_mask_report(report, "/data/exp1_MorphoBricks_Preprocessing/mask_relationsh ``` `scan_masks(..., thresholds={"inside_object_share": 0.8})` changes a threshold (the others -keep their defaults, `DEFAULT_THRESHOLDS`). The label images of OME-Zarr images are always -used, with or without a masks folder; `preflight(..., mask_axes={"Cells": "TYX"})` states +keep their defaults, `DEFAULT_THRESHOLDS`). OME-Zarr label images are discovered +automatically, except for mask types explicitly listed in `ignored_masks.toml`; `preflight(..., mask_axes={"Cells": "TYX"})` states the axes of a mask type whose files do not name them; `read_mask` reads one mask's pixels (a `ValueError` for a negative label or a label above 2,147,483,647, the int32 limit of every MorphoBricks brick, as in `piece_counts`, `pair_counts` and `scan_masks`; `check_labels` diff --git a/pyproject.toml b/pyproject.toml index c8057452..2d1673e0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -283,9 +283,11 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.preview_render" = "pure" "morphobricks_preprocessing.cli" = "ui" "morphobricks_preprocessing.cli_run" = "ui" +"morphobricks_preprocessing.cli_run_options" = "ui" "morphobricks_preprocessing.cli_calibrate" = "ui" "morphobricks_preprocessing.cli_masks" = "ui" "morphobricks_preprocessing.cli_describe" = "ui" +"morphobricks_preprocessing.cli_describe_options" = "ui" "morphobricks_preprocessing.cli_convert" = "ui" "morphobricks_preprocessing.cli_convert_mask" = "ui" "morphobricks_preprocessing.cli_declare_masks" = "ui" diff --git a/src/morphobricks_preprocessing/cli.py b/src/morphobricks_preprocessing/cli.py index 6ff42a8e..0843eb60 100644 --- a/src/morphobricks_preprocessing/cli.py +++ b/src/morphobricks_preprocessing/cli.py @@ -37,6 +37,7 @@ import argparse import logging +import shlex import sys from collections.abc import Sequence from pathlib import Path @@ -90,6 +91,48 @@ __all__ = ["build_parser", "main", "parse_size"] +_CHECK_DESCRIPTION = """\ +Check a described experiment without measuring image pixels: the folders, the +image headers and any masks folder you give. Write a report and suggest the +image axis roles. + +Requires: a published experiment description (describe --publish). +check does not perform every validation of the description that run performs, +and it does not reuse the recorded --exclude, --masks and --mask-axes choices: +give the same options as your intended run.""" + +_CHECK_EXAMPLE = """\ +Example: + morphobricks-preprocessing check my_experiment + +If the check passes, run preprocessing next (run).""" + +_RUN_DESCRIPTION = """\ +Process a described experiment: validate the description and the axis roles, +then compute one intensity histogram per channel of every image plane +(plane_histograms.parquet). A rerun reads only new or changed images and reuses +the recorded exclusions and masks folder. + +Requires: a published experiment description (describe --publish).""" + +_RUN_EXAMPLE = """\ +Example: + morphobricks-preprocessing run my_experiment + +Then, if your analysis uses masks, check them (masks). Give the output folder +(my_experiment_MorphoBricks_Preprocessing) to the next MorphoBricks tool.""" + +_MASKS_DESCRIPTION = """\ +Check the mask pixels of a preprocessing run against their declared +representation, and report how the mask types relate. Run it after run when +your analysis uses masks; skip it otherwise. + +Requires: a preprocessing run whose masks are declared (declare-masks).""" + +_MASKS_EXAMPLE = """\ +Example: + morphobricks-preprocessing masks --output my_experiment_MorphoBricks_Preprocessing""" + def build_parser() -> argparse.ArgumentParser: """Build the argument parser.""" @@ -102,18 +145,31 @@ def build_parser() -> argparse.ArgumentParser: check = commands.add_parser( "check", - help="check the folder and image headers, suggest axis roles and write the report", + help="check a described experiment without measuring image pixels; write a report " + "and suggest the image axis roles", + description=_CHECK_DESCRIPTION, + epilog=_CHECK_EXAMPLE, + formatter_class=argparse.RawDescriptionHelpFormatter, ) _common(check) add_missing_as_singleton(check) - run = commands.add_parser("run", help="compute or update the histogram table") + run = commands.add_parser( + "run", + help="process a described experiment: compute or update the histogram table", + description=_RUN_DESCRIPTION, + epilog=_RUN_EXAMPLE, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) _common(run, recorded=True) add_run_arguments(run) masks = commands.add_parser( "masks", - help="find every image's masks, describe them and how they relate (reads the masks)", + help="check the mask pixels of a preprocessing run and how the mask types relate", + description=_MASKS_DESCRIPTION, + epilog=_MASKS_EXAMPLE, + formatter_class=argparse.RawDescriptionHelpFormatter, ) _common(masks, recorded=True) add_masks_arguments(masks) @@ -198,11 +254,16 @@ def _common(parser: argparse.ArgumentParser, *, recorded: bool = False) -> None: help="the experiment folder (default: the one the run in --output recorded)", ) else: - parser.add_argument("experiment", help="the experiment folder") + parser.add_argument( + "experiment", + help="folder containing your original experiment images, organised by condition " + "and repeat", + ) parser.add_argument( "--output", metavar="FOLDER", - help="output folder (default: next to the experiment, _MorphoBricks_Preprocessing)", + help="folder containing the published experiment description and preprocessing " + "results (default: EXPERIMENT_MorphoBricks_Preprocessing beside the images folder)", ) parser.add_argument( "--exclude", @@ -214,8 +275,9 @@ def _common(parser: argparse.ArgumentParser, *, recorded: bool = False) -> None: parser.add_argument( "--masks", metavar="FOLDER", - help="masks folder: one subfolder per mask type, each mirroring the experiment's " - "folders, outside the experiment; the label images of OME-Zarr images are added", + help="external masks folder, separate from the experiment folder: one subfolder per " + "mask type, or the mask type as an ending of each file name (image_01_cp_masks.tif); " + "OME-Zarr label images are also found automatically", ) _mask_axes_option(parser) _remove_stale_lock_option(parser) @@ -309,8 +371,7 @@ def _check(args: argparse.Namespace) -> int: if undeclared: # as 'run' refuses them, with its words print() print(format_issues(undeclared)) - axis_errors = () - chunks: list[ValidationIssue] = [] + axis_errors, chunks = (), [] if review is not None: # The suggested roles are the header's own, so they never contradict it; 'run' # checks the roles given with --axes. @@ -332,18 +393,59 @@ def _check(args: argparse.Namespace) -> int: f"Suggested option for 'run': --axes {pre.suggested_mapping.roles_string}" f"{singleton} (axes in the files: {pre.suggested_mapping.axes})" ) - type_review = review_image_type(pre.metadata, review, declared=declared_type(args, pre)) - print( - f"Suggested image type: {type_review.suggested}, because {type_review.reason}. " - "'run' uses it unless you give --image-type." - ) + _print_image_type(args, pre, review) path, refusal = write_check_report(pre, args.output, review, extra=[*undeclared, *chunks]) - print() - print(format_issues([refusal]) if refusal else f"Report written to {path}" if path else "") + if refusal is not None: + print("\n" + format_issues([refusal])) blocked = not pre.ok or axis_errors or undeclared or refusal is not None + roles = None if review is None else pre.suggested_mapping.roles_string + print("\n" + check_status(args, path, blocked=bool(blocked), roles=roles, missing=missing)) return 1 if blocked else 0 # every error printed exits with 1, as 'run' does +def _print_image_type(args: argparse.Namespace, pre: Preflight, review: AxisReview) -> None: + """Print the image type the headers suggest, to compare with the published description.""" + type_review = review_image_type(pre.metadata, review, declared=declared_type(args, pre)) + print( + f"Suggested image type: {type_review.suggested}, because {type_review.reason}. " + "Confirm that it agrees with the published experiment description." + ) + + +def check_status( + args: argparse.Namespace, + path: Path | None, + *, + blocked: bool, + roles: str | None, + missing: bool, +) -> str: + """Return the final line of ``check``: passed (with the run command) or failed (P1.8). + + The run command keeps the experiment, ``--output``, ``--exclude``, ``--masks`` and + ``--mask-axes`` given to ``check``, and adds the suggested ``--axes``; paths are quoted. + """ + saved = f" Report saved to {path}." if path else "" + if blocked: + return f"Header check failed.{saved} Correct the errors above, then repeat the check." + words = ["morphobricks-preprocessing run", shlex.quote(args.experiment)] + if args.output: + words.append(f"--output {shlex.quote(args.output)}") + words += [f"--exclude {shlex.quote(item)}" for item in args.exclude] + if args.masks: + words.append(f"--masks {shlex.quote(args.masks)}") + stated = args.mask_axes or {} # read by main into {type: roles} + words += [f"--mask-axes {shlex.quote(f'{kind}={value}')}" for kind, value in stated.items()] + if roles: + words.append(f"--axes {roles}") + if missing: + words.append("--missing-as-singleton") + return ( + f"Header check passed.{saved} Review the warnings and axis roles above, then run " + f"preprocessing:\n {' '.join(words)}" + ) + + def undeclared_mask_issues(args: argparse.Namespace, pre: Preflight) -> list[ValidationIssue]: """Return ``run``'s refusal of every mask type found that the description does not declare. diff --git a/src/morphobricks_preprocessing/cli_calibrate.py b/src/morphobricks_preprocessing/cli_calibrate.py index 9356a290..5e724fdb 100644 --- a/src/morphobricks_preprocessing/cli_calibrate.py +++ b/src/morphobricks_preprocessing/cli_calibrate.py @@ -36,7 +36,19 @@ def add_calibrate_parser(commands: argparse._SubParsersAction) -> argparse.Argum """Add the ``calibrate`` command and its options; return its parser.""" parser = commands.add_parser( "calibrate", - help="show or state the pixel sizes in calibration.csv in the output folder", + help="show or state the physical pixel sizes of the images", + description="""\ +Show or state the physical pixel sizes of the images (calibration.csv in the +output folder). A stated size replaces what the image metadata say; images +without a stated size keep the sizes in their metadata, or stay uncalibrated. +The image pixels are never changed.""", + epilog="""\ +Example (every image: 0.65 micrometres along X and Y): + morphobricks-preprocessing calibrate my_experiment --size . XY 0.65 um + morphobricks-preprocessing run my_experiment + +Run preprocessing again afterwards to record the sizes.""", + formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument( "experiment", @@ -50,9 +62,9 @@ def add_calibrate_parser(commands: argparse._SubParsersAction) -> argparse.Argum action="append", default=[], metavar=("TARGET", "AXES", "SIZE", "UNIT"), - help="state a size: TARGET is . for the whole experiment, or a folder or image " - "relative to the experiment folder; AXES are X, Y and/or Z (XY: the same size for " - "both); UNIT is a length unit such as um or nm (repeatable)", + help="state the physical pixel size: TARGET is . for every image, or a folder or image " + "path relative to the experiment; AXES are X, Y and/or Z (XY: the same size for both); " + "UNIT is a length unit such as um or nm. Example: --size . XY 0.65 um (repeatable)", ) parser.add_argument( "--pixels", @@ -60,7 +72,8 @@ def add_calibrate_parser(commands: argparse._SubParsersAction) -> argparse.Argum action="append", default=[], metavar=("TARGET", "AXES"), - help="state that these axes are measured in pixels: deliberately uncalibrated (repeatable)", + help="use pixel units rather than physical lengths for these axes; does not rescale or " + "modify the image pixels (repeatable)", ) parser.add_argument( "--remove", @@ -114,7 +127,10 @@ def calibrate_command(args: argparse.Namespace) -> int: print(f"Nothing was changed: {exc}") return 1 if written is not None: - print(f"Written to {written}. The next run records these sizes; no row is recomputed.") + print( + f"Calibration saved to {written}. Run preprocessing again to record these pixel " + "sizes; existing verified histograms can be reused." + ) print(calibration_summary(changed)) return 0 @@ -143,7 +159,10 @@ def _axes(text: str) -> tuple[str, ...]: def calibration_summary(calibration: Calibration) -> str: """Describe the statements, one per line, or say there are none.""" if not calibration.entries: - return "No pixel size is stated: every image uses the sizes in its metadata." + return ( + "No pixel sizes have been stated. Pixel sizes are taken from the image metadata " + "where available; otherwise the images remain uncalibrated." + ) lines = ["Stated pixel sizes (calibration.csv):"] lines.extend( f" {entry.target} {entry.axis}: {entry.describe()}" for entry in calibration.entries diff --git a/src/morphobricks_preprocessing/cli_convert.py b/src/morphobricks_preprocessing/cli_convert.py index 6a0259e5..c55aa98b 100644 --- a/src/morphobricks_preprocessing/cli_convert.py +++ b/src/morphobricks_preprocessing/cli_convert.py @@ -26,7 +26,9 @@ from __future__ import annotations import argparse +import shlex import sys +from dataclasses import dataclass from pathlib import Path from .cli_run import mapping_option, parse_size, print_progress @@ -57,11 +59,29 @@ def add_convert_parser(commands: argparse._SubParsersAction) -> argparse.Argumen """ convert = commands.add_parser( "convert", - help="save the images whose axes are wrong or not named as named-axis OME-TIFF copies " - "with your roles (or every image as OME-Zarr, --store ome-zarr), in a new folder (the " - "originals are only read)", + help="write image copies with corrected axis metadata, convert images to OME-Zarr, or " + "project Z-stacks to 2-D; the original images are unchanged", + description="""\ +Write image copies in a new folder: with corrected axis metadata (OME-TIFF), as +OME-Zarr (--store ome-zarr), or as 2-D projections of Z-stacks (--project). +The original images are only read. The copies are an experiment of their own: +describe and publish it before you check and run preprocessing on it.""", + epilog="""\ +Examples (the axis orders are examples: give the stored order of your images; +an RGB TIFF stores its colours last, YXC): + morphobricks-preprocessing convert my_experiment --to my_experiment_named --axes CYX + morphobricks-preprocessing convert my_slides --to my_slides_zarr --axes CYX \\ + --store ome-zarr + morphobricks-preprocessing convert my_experiment --to my_experiment_max \\ + --axes ZCYX --project max + +convert does not check the axis order against the image: look at a copy.""", + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + convert.add_argument( + "experiment", + help="folder containing your original experiment images, organised by condition and repeat", ) - convert.add_argument("experiment", help="the experiment folder") convert.add_argument( "--to", metavar="FOLDER", @@ -73,22 +93,33 @@ def add_convert_parser(commands: argparse._SubParsersAction) -> argparse.Argumen "--axes", metavar="ROLES", required=True, - help="the role of each axis of the images, in the order of their axes (X, Y, Z, C, T, " - "or - for none): the roles the copies are written with", + help="roles of the stored dimensions, in their stored order: Y and X are image height " + "and width, C is channel, Z is depth, T is time, - an unused length-1 dimension; for " + "example CYX (an RGB TIFF: YXC). The copies are written with these roles", ) convert.add_argument( "--exclude", action="append", default=[], metavar="PATH", - help="image to leave unread, relative to the experiment folder; it is copied as it " - "is (repeatable)", + help="copy this image unchanged instead of converting it, relative to the experiment " + "folder (repeatable). The next commands printed keep it excluded; give the same " + "exclusion whenever you describe, check or run the copies", ) convert.add_argument( "--missing-as-singleton", action="store_true", - help="confirm that images lacking some axes have one plane along them", + help="confirm that an image without a particular dimension has size 1 along it; " + "this does not enable analysis of multi-slice Z-stacks", ) + _add_folder_options(convert) + _add_projection_options(convert) + _add_store_options(convert) + return convert + + +def _add_store_options(convert: argparse.ArgumentParser) -> None: + """Add the memory, lock, store and log options of ``convert``.""" convert.add_argument( "--memory-limit", type=parse_size, @@ -106,15 +137,11 @@ def add_convert_parser(commands: argparse._SubParsersAction) -> argparse.Argumen "--store", choices=STORES, default=OME_TIFF, - help="how the copies are written: ome-tiff (default; only the images whose axes are " - "wrong or not named, the others copied as they are) or ome-zarr (every image that is " - "read, as an OME-Zarr image .ome.zarr, OME-NGFF 0.4; RGB colour images " - "too). Reading OME-Zarr copies needs the zarr extra", + help="ome-tiff (default): correct the axis metadata where needed and copy the other " + "images unchanged; ome-zarr: convert every selected image to OME-Zarr (OME-NGFF 0.4), " + "RGB images included. Writing and reading OME-Zarr needs the zarr extra", ) - _add_folder_options(convert) - _add_projection_options(convert) convert.add_argument("--log", metavar="FILE", help="write technical details to this file") - return convert def _add_folder_options(convert: argparse.ArgumentParser) -> None: @@ -122,14 +149,16 @@ def _add_folder_options(convert: argparse.ArgumentParser) -> None: convert.add_argument( "--output", metavar="FOLDER", - help="the output folder of your runs on the originals, named in the next commands " - "(default: the experiment folder's name with _MorphoBricks_Preprocessing)", + help="preprocessing output folder of the original experiment (default: " + "EXPERIMENT_MorphoBricks_Preprocessing); --to says where the copies go. Projected " + "copies get a new output folder of their own", ) convert.add_argument( "--masks", metavar="FOLDER", - help="the masks folder of your runs, which the copies may not be inside; by default " - "the one recorded by the run in the output folder (--output)", + help="masks folder of the original experiment, used to check that the copies are not " + "written inside it and that projection can proceed; masks are not converted " + "(default: the one recorded in --output)", ) @@ -141,19 +170,19 @@ def _add_projection_options(convert: argparse.ArgumentParser) -> None: const="", type=_method, metavar="METHOD", - help="write every image as a recorded 2-D projection of its Z-stack: max, mean or " - "sum (there is no default). Z must be among the roles in --axes. The copies are " - "named-axis OME-TIFFs without Z; a 16-bit sum is written in 32 bits, a mean in 64-bit " - "floats, a maximum keeps the type; the Z size is not written but recorded. Masks " - "are never projected: masks with depth slices stop the projection", + help="project the Z slices of each selected image with max, mean or sum (no " + "default); Z must be among the roles in --axes. The output has no Z dimension and is " + "OME-TIFF by default, OME-Zarr with --store ome-zarr. A maximum keeps the pixel type; " + "a 16-bit sum uses 32-bit values, a mean 64-bit floats. Masks are not projected: " + "masks with depth slices stop the projection", ) convert.add_argument( "--z-range", type=_z_range, metavar="START:STOP", - help="with --project: use only these slices of every image (zero-based, STOP " - "excluded, for example 2:10; 4:5 is the single slice 4). Every image must have " - "them. Default: all slices", + help="with --project: the Z slices to project; 2:10 uses slices 2 to 9, counting the " + "first slice as 0 (4:5 is slice 4 alone). Every selected image must contain that " + "range. Default: all slices", ) @@ -213,12 +242,44 @@ def convert_command(args: argparse.Namespace) -> int: print() if result.projection is not None: output, given = default_output_folder(Path(args.to).resolve()), True - print(conversion_text(result, output, given=given, store=args.store)) + after = _NextOptions(tuple(args.exclude), args.missing_as_singleton) + print(conversion_text(result, output, given=given, store=args.store, after=after)) return 0 if result.written else 1 +@dataclass(frozen=True) +class _NextOptions: + """The options of a conversion the next commands on the copies keep (review P0.2, P1.18).""" + + exclude: tuple[str, ...] = () + missing_as_singleton: bool = False + + def arguments(self) -> str: + """Return the options as command-line text, each path quoted for the shell.""" + words = [f" --exclude {shlex.quote(path)}" for path in self.exclude] + return "".join(words) + (" --missing-as-singleton" if self.missing_as_singleton else "") + + +def _next_commands(dest: Path, output: Path, axes: str, after: _NextOptions) -> list[str]: + """Return the describe, check and run lines for the copies in ``dest`` (paths quoted).""" + folder, out, keep = shlex.quote(str(dest)), shlex.quote(str(output)), after.arguments() + exclude = "".join(f" --exclude {shlex.quote(path)}" for path in after.exclude) + return [ + f" morphobricks-preprocessing describe {folder} --output {out}{exclude}", + "Publish the description with describe --publish and your confirmed channel and " + "design options (or in the notebook). Once it is published, run:", + f" morphobricks-preprocessing check {folder} --output {out}{keep}", + f" morphobricks-preprocessing run {folder} --output {out}{axes}{keep}", + ] + + def conversion_text( - result: ConversionResult, output: Path, *, given: bool = True, store: str = OME_TIFF + result: ConversionResult, + output: Path, + *, + given: bool = True, + store: str = OME_TIFF, + after: _NextOptions | None = None, ) -> str: """Say what a conversion wrote and what to run next, in plain ASCII-safe words. @@ -233,17 +294,21 @@ def conversion_text( says to give the folder of the runs on the originals if it is another one. store ``"ome-tiff"`` or ``"ome-zarr"``: the format the copies were written in. + after + The exclusions and ``--missing-as-singleton`` of the conversion, kept in the next + commands (default: none). Returns ------- str """ + after = after or _NextOptions() dest = result.destination fmt = "OME-Zarr" if store == OME_ZARR else "OME-TIFF" if not result.written: return f"No copies were written in {dest}: read the messages above." if result.projection is not None: - return projection_text(result, output, store=store) + return projection_text(result, output, store=store, after=after) # Cross-brick test F8: the next commands name the output folder of the user's runs, # given with --output; a default one may hold no run (the user then gives theirs). where = "" if given else f" (by default {output}; if your runs used another one, give it)" @@ -252,18 +317,26 @@ def conversion_text( f" written as {fmt} with your roles: {plural(len(result.converted), 'image')}", f" copied as they are: {plural(len(result.copied), 'image')}", f" already there and unchanged: {plural(len(result.reused), 'image')}", - f"Conversion record: {dest / RECORD_FILENAME} (SHA-256 {result.record_sha256})", + f"Conversion details saved to {dest / RECORD_FILENAME}.", "", - "Next, run preprocessing on the copies with the output folder of your runs on the " - f"originals{where}:", - f" morphobricks-preprocessing check {dest} --output {output}", + f"Next, preprocess the copies with the output folder of your runs on the originals" + f"{where}. If it already holds a published description that matches these copies, " + "keep using it and skip describe. Otherwise describe the copied experiment first:", ] axes = f" --axes {result.suggested_axes}" if result.suggested_axes else " --axes ROLES" - lines.append(f" morphobricks-preprocessing run {dest} --output {output}{axes}") + lines += _next_commands(dest, output, axes, after) + if not result.suggested_axes: + lines.append("Replace ROLES with the roles of the copies' stored dimensions.") return "\n".join(lines) -def projection_text(result: ConversionResult, output: Path, *, store: str = OME_TIFF) -> str: +def projection_text( + result: ConversionResult, + output: Path, + *, + store: str = OME_TIFF, + after: _NextOptions | None = None, +) -> str: """Say what a projection wrote and what to run next (a new output folder, a new source). Parameters @@ -275,11 +348,15 @@ def projection_text(result: ConversionResult, output: Path, *, store: str = OME_ different source, so its description starts a new lineage. store ``"ome-tiff"`` or ``"ome-zarr"``: the format the copies were written in. + after + The exclusions and ``--missing-as-singleton`` of the conversion, kept in the next + commands (default: none). Returns ------- str """ + after = after or _NextOptions() dest, projection = result.destination, result.projection bounds = projection.z_range slices = "all slices" if bounds is None else f"slices {bounds[0]}:{bounds[1]}" @@ -294,13 +371,12 @@ def projection_text(result: ConversionResult, output: Path, *, store: str = OME_ f" already there and unchanged: {plural(len(result.reused), 'image')}", " The Z size is not written to the copies; the record keeps it, the slices used " "and the SHA-256 of every source.", - f"Conversion record: {dest / RECORD_FILENAME} (SHA-256 {result.record_sha256})", + f"Conversion details saved to {dest / RECORD_FILENAME}.", "", - "The projected copies are a different source: run preprocessing on them with a new " - f"output folder ({output}), which starts a new description; the design and the " - "pixel sizes are then entered again. Masks are never projected: 2-D masks pair " - "with the projected images as usual.", - f" morphobricks-preprocessing check {dest} --output {output}", - f" morphobricks-preprocessing run {dest} --output {output}{axes}", + f"Projected images were saved in {dest}. Describe them as a new experiment before " + f"running preprocessing, with a new output folder ({output}). Review the channel " + "names, experimental design and pixel sizes. Masks are not projected: make 2-D " + "masks for the projected images.", + *_next_commands(dest, output, axes, after), ] ) diff --git a/src/morphobricks_preprocessing/cli_declare_masks.py b/src/morphobricks_preprocessing/cli_declare_masks.py index b4e1c7fd..44a902d9 100644 --- a/src/morphobricks_preprocessing/cli_declare_masks.py +++ b/src/morphobricks_preprocessing/cli_declare_masks.py @@ -8,8 +8,8 @@ unless ``:ID`` is given (needed when the folder name is not a valid mask ID). ``--masks`` also checks each mask type against the masks folder. The command prints what it declared and the two commands that follow (``run``, then ``masks``): with ``--masks`` they name that folder; without -it they name none, because OME-Zarr label images and ``_.tif`` masks beside the -images are found without a masks folder, and say when to add one. The experiment folder is +it they name none, because OME-Zarr label images are found without a masks folder (other masks are +always in a separate masks folder), and say when to add one. The experiment folder is named only when no run of the output folder records it. ``--ignore TYPE`` (repeatable; owner, 4 December 2026) lists a mask type or OME-Zarr label image the runs do not use in ``ignored_masks.toml`` (:mod:`.ignored_masks`): ``check`` and ``run`` skip it instead of @@ -36,9 +36,9 @@ from .run.reuse import recorded_experiment_root NO_MASKS_FOLDER = ( - "Add --masks FOLDER to both only when the masks are in a masks folder of their own: " - "OME-Zarr label images, and masks named _.tif beside their images, are found " - "without it." + "OME-Zarr label images are discovered automatically. External TIFF masks must be stored " + "in a separate masks folder: add --masks FOLDER to both commands, unless an earlier " + "preprocessing run already recorded it." ) @@ -57,11 +57,37 @@ def add_declare_masks_parser(commands: argparse._SubParsersAction) -> argparse.A """ declare = commands.add_parser( "declare-masks", - help="declare mask types (added after preprocessing) in the published description, " - "so run --masks accepts them", + help="declare mask types (existing masks, or masks added later) in the published " + "description, so preprocessing accepts them", + description="""\ +Declare each mask type before running preprocessing with those masks: right +after publishing the experiment description, or later for masks added to an +existing preprocessing run. Then run preprocessing, and check the mask pixels +with the masks command. + +Mask representations: + instances one positive label per object (for example a Cellpose mask) + binary foreground and background (a region) + parent_labels one label per group of objects""", + epilog="""\ +Examples: + morphobricks-preprocessing declare-masks \\ + --output my_experiment_MorphoBricks_Preprocessing \\ + --masks my_masks --type Cells=instances + morphobricks-preprocessing declare-masks \\ + --output my_experiment_MorphoBricks_Preprocessing \\ + --masks my_masks --type cp_masks=instances:Cells + +The second declares masks named like image_01_cp_masks.tif (the mask type as a +file-name ending) with the mask ID Cells. Do not declare and ignore the same +mask type.""", + formatter_class=argparse.RawDescriptionHelpFormatter, ) declare.add_argument( - "--output", metavar="FOLDER", required=True, help="the output folder of the run" + "--output", + metavar="FOLDER", + required=True, + help="the preprocessing output folder containing morphobricks.toml", ) declare.add_argument( "--type", @@ -69,23 +95,25 @@ def add_declare_masks_parser(commands: argparse._SubParsersAction) -> argparse.A action="append", default=[], metavar="TYPE=REPRESENTATION[:ID]", - help=f"a mask type (its folder name) and what it is: {', '.join(REPRESENTATIONS)}; " - "optionally its ID (default: the folder name). Repeatable", + help="mask type and representation: instances (one positive label per object), " + "binary (foreground and background) or parent_labels (one label per group of " + "objects); optionally a different mask ID after a colon. Example: Cells=instances " + f"(representations: {', '.join(REPRESENTATIONS)}; repeatable)", ) declare.add_argument( "--ignore", action="append", default=[], metavar="TYPE", - help="a mask type or OME-Zarr label image the runs do not use (repeatable): left out " - "of check and run instead of refused as undeclared; listed in ignored_masks.toml " - "beside morphobricks.toml and recorded by the run. Declaring a type with --type " - "takes it off the list", + help="skip a mask type you do not want to analyse: give its exact folder name, " + "file-name ending or OME-Zarr label name (repeatable). A declared type cannot be " + "ignored; declaring an ignored type with --type uses it again", ) declare.add_argument( "--masks", metavar="FOLDER", - help="the masks folder: each mask type is also checked against it", + help="external masks folder, used to check the mask-type names; the mask pixels are " + "checked later by the masks command", ) return declare @@ -127,8 +155,14 @@ def declare_masks_command(args: argparse.Namespace) -> int: args.output, args.ignore, declared=declared_types(args.output) ) except (ValueError, OutputLockedError, OSError) as exc: - kept = "the --ignore list was not changed" - return _refused(exc, f"{'The masks above were declared; ' if done else ''}{kept}.") + if done is not None and done.publication is not None: + saved = ( + f"Mask declarations saved to {done.publication.path}: {', '.join(done.added)}. " + "The ignore list was not updated. The saved declarations remain in place." + ) + else: + saved = "No mask declaration changed. The ignore list was not updated." + return _refused(exc, saved, ignore=True) if done is not None and done.publication is None: print("Every mask type is declared as asked already; nothing was written.") elif done is not None: @@ -143,10 +177,10 @@ def declare_masks_command(args: argparse.Namespace) -> int: return 0 -def _refused(exc: Exception, written: str) -> int: +def _refused(exc: Exception, written: str, *, ignore: bool = False) -> int: """Print a refusal with its codes and what was (not) written; return exit status 1.""" codes = f" ({', '.join(exc.codes)})" if getattr(exc, "codes", ()) else "" - print(f"Not declared{codes}: {exc}") + print(f"{'Mask settings not updated' if ignore else 'Not declared'}{codes}: {exc}") print(written[0].upper() + written[1:]) return 1 @@ -155,18 +189,20 @@ def next_commands(output: str, masks: str | None) -> list[str]: """Return the lines naming the commands that follow a declaration. ``masks`` is the masks folder given, or None: the masks may then be OME-Zarr label images - or masks beside the images, which ``run`` finds without ``--masks``, so no placeholder - folder is named. The experiment folder is named (``EXPERIMENT``) unless a run of the - output folder records it. + or a masks folder the run already records, which ``run`` finds without ``--masks``, so no + placeholder folder is named. The experiment folder is named (``EXPERIMENT``) unless a run + of the output folder records it, and the text then says to replace it. """ recorded, _ = recorded_experiment_root(Path(output).resolve()) target = ("" if recorded is not None else "EXPERIMENT ") + f"--output {shlex.quote(output)}" if masks is not None: option = f" --masks {shlex.quote(masks)}" - lines = ["Next, run preprocessing with the masks folder, then describe the masks:"] + lines = ["Next, run preprocessing with the masks folder, then check the masks:"] else: option = "" - lines = ["Next, run preprocessing again, then describe the masks:"] + lines = ["Next, run preprocessing again, then check the masks:"] + if recorded is None: + lines.append("Replace EXPERIMENT below with the folder containing your original images.") lines += [ f" morphobricks-preprocessing run {target}{option}", f" morphobricks-preprocessing masks {target}{option}", diff --git a/src/morphobricks_preprocessing/cli_describe.py b/src/morphobricks_preprocessing/cli_describe.py index f49ecfad..fd2e48ae 100644 --- a/src/morphobricks_preprocessing/cli_describe.py +++ b/src/morphobricks_preprocessing/cli_describe.py @@ -45,8 +45,10 @@ from __future__ import annotations import argparse +import shlex from pathlib import Path +from .cli_describe_options import add_describe_parser as add_describe_parser from .describe_ids import apply_ids from .describe_questions import fast_question_lines, proposal, question_blockers, question_lines from .description import Description, DescriptionError @@ -129,98 +131,18 @@ def _confirm_again(rec: Reconciliation) -> dict[str, tuple[str, ...]]: return {repeat: reasons for repeat, reasons in found.items() if reasons} -def add_describe_parser(commands: argparse._SubParsersAction) -> argparse.ArgumentParser: - """Add the ``describe`` command and its options; return its parser.""" - describe = commands.add_parser( - "describe", - help="show the draft experiment description (proposals, open questions) in plain " - "language; writes nothing, and confirms nothing", - ) - describe.add_argument("experiment", help="the experiment folder") - describe.add_argument( - "--output", - metavar="FOLDER", - help="output folder holding morphobricks.toml " - "(default: next to the experiment, _MorphoBricks_Preprocessing)", - ) - describe.add_argument( - "--exclude", - action="append", - default=[], - metavar="PATH", - help="image to leave out, relative to the experiment folder (repeatable)", - ) - describe.add_argument( - "--strict", - action="store_true", - help="describe in the strict per-unit mode: each acquisition's channels confirmed on " - "its own (in the notebook). Default: fast mode, one channel list for the experiment " - "(Spec ADR 0006)", - ) - _add_fast_options(describe) - describe.add_argument( - "--publish", - action="store_true", - help="publish the description only when no question is open and every decision is " - "confirmed; otherwise exit with status 1 and list what is missing. Nothing is " - "confirmed for you", - ) - return describe - +PREVIEW_NOTE = ( + "Preview only. No description has been saved. Your options are reflected above; the " + "channel list and the image headers are validated when you publish (--publish)." +) +"""Said after a preview of a new description (review P1.3).""" -def _add_fast_options(describe: argparse.ArgumentParser) -> None: - """Add the fast-mode statements of ``describe`` (Spec ADR 0006, :mod:`.fast_answers`).""" - describe.add_argument( - "--channels", - metavar="ID,ID,...", - help="fast mode: the channel IDs of the first acquisition in folder order (the tagged " - "unit, named in the output), in source order C0, C1, ...; its header names are " - "confirmed as their header names. Every acquisition is stated to have them", - ) - describe.add_argument( - "--image-type", - choices=("channels", "rgb"), - help="fast mode: the image type of the list (never inferred)", - ) - describe.add_argument( - "--accept-ids", action="store_true", help="fast mode: accept every proposed ID" - ) - describe.add_argument( - "--id", - action="append", - default=[], - metavar="FOLDER=ID", - help="fast mode: the ID of a condition, biological-repeat or technical-repeat folder, " - "as you type it (repeatable), for example --id control=ctrl for a folder whose name " - "cannot be an ID; checked with the notebook's rules. A label used at two levels takes " - "the level: condition:FOLDER, repeat:FOLDER or technical:FOLDER", - ) - describe.add_argument( - "--comparable", - action="store_true", - help="fast mode: every biological repeat's folders were prepared and acquired under " - "the same circumstances (your answer, dated --confirmed-on)", - ) - describe.add_argument( - "--confirmed-on", - metavar="YYYY-MM-DD", - help="fast mode: the day of your statements (never read from the clock)", - ) - describe.add_argument( - "--rgb-header-override", - action="append", - nargs="?", - const=True, - default=[], - metavar="FOLDER", - help="fast mode, with --image-type rgb (give the experiment folder before this " - "option, or it is taken as FOLDER): the images of this acquisition folder (relative " - "to the experiment, for example CTRL/rep1; repeatable; without a folder: every " - "acquisition) store R, G and B as three interleaved samples per pixel although their " - "TIFF header does not say colour. Records rgb_header_override = true on those units, " - "as the notebook's Image type card does; an image that is not three interleaved " - "samples is still refused", - ) +PUBLISHED_NOTE = ( + "This experiment already has a published description. The command displays it but does " + "not change its channel list or experimental design. To edit it, open the existing " + "description in the notebook and use Check and save." +) +"""Said whenever describe shows an existing description (review P1.4).""" def describe_command(args: argparse.Namespace) -> int: @@ -261,13 +183,20 @@ def describe_command(args: argparse.Namespace) -> int: print(OVERRIDE_NEEDS_CHANNELS if new_fast else OVERRIDE_ONLY_FAST) return 1 print("\n".join(lines)) + if found is not None: + print() + print(PUBLISHED_NOTE) if not args.publish: + if found is None: + print() + print(PREVIEW_NOTE) return 0 print() if not blockers and any(line.startswith(" headers changed:") for line in lines): print( - "Nothing to publish: no answer is missing. The run stops until the image headers " - "fit the published description (headers changed, above)." + "The published description no longer matches the image headers. It was not " + "changed. Correct the channel names or order in the notebook, save the " + "description, then run preprocessing again." ) return 0 if not blockers: @@ -332,6 +261,8 @@ def describe_fast( ] print("\n".join(lines)) if not args.publish: + print() + print(PREVIEW_NOTE) return 0 print() channels = [c for c in (args.channels or "").split(",") if c] @@ -362,7 +293,10 @@ def describe_fast( print("Not published: some images cannot be checked against the channel list.") print(format_issues(refused)) return 1 - return _publish_fast(draft, answers, discovery, headers, output) + if not _publish_fast(draft, answers, discovery, headers, output): + return 1 + print("\n".join(next_steps(args, excluded))) + return 0 def override_units( @@ -409,25 +343,41 @@ def _image_units(discovery: DiscoveryResult) -> dict[str, tuple[str, str, str]]: return {image: leaf.labels for leaf in discovery.leaves for image in leaf.images} +def next_steps(args: argparse.Namespace, excluded: list[str]) -> list[str]: + """Return the check and run commands after a publication (review P1.2), paths quoted. + + The experiment folder is the one given; ``--output`` and ``--exclude`` are kept when given. + """ + options = f" --output {shlex.quote(args.output)}" if args.output else "" + options += "".join(f" --exclude {shlex.quote(path)}" for path in excluded) + experiment = shlex.quote(args.experiment) + return [ + "Next, check the experiment and run preprocessing:", + f" morphobricks-preprocessing check {experiment}{options}", + f" morphobricks-preprocessing run {experiment}{options}", + "If check suggests an --axes value, review it and give it to run.", + ] + + def _publish_fast( draft: Draft, answers: DraftAnswers, discovery: DiscoveryResult, headers: list, output: Path, -) -> int: - """Check every image against the list, then publish; nothing is written on any refusal.""" +) -> bool: + """Check every image against the list, then publish; False (nothing written) on a refusal.""" try: candidate = description_from_draft(draft, answers) except DraftError as exc: print(f"Not published: {exc}") - return 1 + return False report = check_physical(candidate, discovery, headers) if report.issues: print(format_issues(physical_issues(report.issues))) if any(issue.override_fits for issue in report.issues): print(OVERRIDE_CLI) - return 1 + return False if report.unchecked: # every image's count and type checked, never a guessed count print( "Not published: these images could not be checked against the channel list (their " @@ -435,7 +385,7 @@ def _publish_fast( "example with the notebook or convert, and describe again):" ) print("\n".join(f" - {path}" for path in report.unchecked)) - return 1 + return False output.mkdir(parents=True, exist_ok=True) try: publication = publish_description( @@ -443,12 +393,13 @@ def _publish_fast( ) except (PublicationRefused, DescriptionError, ValueError) as exc: print(f"Not published: {exc}") - return 1 + return False print( - f"Published {publication.path} in fast mode (channel list " - f"{list(candidate.channel_layout.channels)})." + f"Experiment description saved to {publication.path}. Channels, in their stored " + f"order: {', '.join(candidate.channel_layout.channels)}. The channel list agrees " + "with the image headers checked during publication." ) - return 0 + return True def draft_lines(draft: Draft, root: Path, *, questions: bool = True) -> list[str]: diff --git a/src/morphobricks_preprocessing/cli_describe_options.py b/src/morphobricks_preprocessing/cli_describe_options.py new file mode 100644 index 00000000..b04ed175 --- /dev/null +++ b/src/morphobricks_preprocessing/cli_describe_options.py @@ -0,0 +1,127 @@ +"""The ``describe`` command's options: its parser, help texts and fast-mode options. + +Moved from :mod:`.cli_describe` (which re-exports :func:`add_describe_parser`) to keep that +module within the line limit. What the options mean is in :mod:`.cli_describe`. +""" + +from __future__ import annotations + +import argparse + +__all__ = ["add_describe_parser"] + + +def add_describe_parser(commands: argparse._SubParsersAction) -> argparse.ArgumentParser: + """Add the ``describe`` command and its options; return its parser.""" + describe = commands.add_parser( + "describe", + help="preview an experiment description or publish it with --publish", + description="""\ +Preview an experiment description: the proposed IDs of conditions and repeats, +and the questions still open. With --publish and the options below, validate +and save it (morphobricks.toml in the output folder); every check, run and masks +command needs a published description. + +Fast publication from the command line creates a new description for an +experiment with one shared channel list. Use the notebook to edit an existing +description, change repeat pairing or describe acquisitions with different +channel lists or orders.""", + epilog="""\ +Example (two fluorescence channels stored in the order collagen, fibronectin): + morphobricks-preprocessing describe my_experiment + morphobricks-preprocessing describe my_experiment \\ + --channels COL,FN --image-type channels \\ + --accept-ids --comparable --confirmed-on 2026-12-04 --publish + +Review the proposed IDs before accepting them. Give --comparable only if it is +true. Then check and run preprocessing.""", + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + describe.add_argument( + "experiment", + help="folder containing your original experiment images, organised by condition and repeat", + ) + describe.add_argument( + "--output", + metavar="FOLDER", + help="folder that holds (or will hold) the published description, morphobricks.toml " + "(default: EXPERIMENT_MorphoBricks_Preprocessing beside the images folder)", + ) + describe.add_argument( + "--exclude", + action="append", + default=[], + metavar="PATH", + help="image to leave out, relative to the experiment folder (repeatable)", + ) + describe.add_argument( + "--strict", + action="store_true", + help="use separate channel descriptions for each acquisition; complete and publish " + "them in the notebook. By default, one channel list is used for the whole experiment", + ) + _add_fast_options(describe) + describe.add_argument( + "--publish", + action="store_true", + help="validate and save the description; without --publish, show a preview only. " + "When a question is still open, exit with status 1 and list it", + ) + return describe + + +def _add_fast_options(describe: argparse.ArgumentParser) -> None: + """Add the fast-mode statements of ``describe`` (Spec ADR 0006, :mod:`.fast_answers`).""" + describe.add_argument( + "--channels", + metavar="ID,ID,...", + help="channel names separated by commas, in the order stored in the images (C0, C1, " + "...), for example COL,FN; give it only when all acquisitions have the same channels " + "in the same order", + ) + describe.add_argument( + "--image-type", + choices=("channels", "rgb"), + help="channels: separate stains or markers, such as fluorescence; rgb: red, green " + "and blue colour images (use --channels R,G,B). Never inferred", + ) + describe.add_argument( + "--accept-ids", + action="store_true", + help="accept the proposed identifiers of conditions and repeats; review them with " + "describe first, and give --id for folders without a valid proposed ID", + ) + describe.add_argument( + "--id", + action="append", + default=[], + metavar="FOLDER=ID", + help="assign a folder an identifier without renaming it, for example " + "--id control=ctrl (repeatable). If a name occurs at more than one folder level, " + "write condition:NAME=ID, repeat:NAME=ID or technical:NAME=ID", + ) + describe.add_argument( + "--comparable", + action="store_true", + help="confirm that the samples of each biological repeat were prepared and acquired " + "under comparable conditions; give this option only if that statement is true", + ) + describe.add_argument( + "--confirmed-on", + metavar="YYYY-MM-DD", + help="the date on which you confirm the description, written YYYY-MM-DD", + ) + describe.add_argument( + "--rgb-header-override", + action="append", + nargs="?", + const=True, + default=[], + metavar="FOLDER", + help="with --image-type rgb: use only for images known to store red, green and " + "blue as three interleaved samples per pixel although their TIFF headers do not say " + "RGB. Without a folder, applies to all acquisitions; otherwise give an acquisition " + "folder relative to the experiment, for example CTRL/rep1 (repeatable). Place the " + "experiment folder before this option. An image that is not three interleaved " + "samples is still refused", + ) diff --git a/src/morphobricks_preprocessing/cli_masks.py b/src/morphobricks_preprocessing/cli_masks.py index ccfcb7b7..43608b88 100644 --- a/src/morphobricks_preprocessing/cli_masks.py +++ b/src/morphobricks_preprocessing/cli_masks.py @@ -21,14 +21,15 @@ from .mask_scan import DEFAULT_THRESHOLDS, mask_thresholds from .mask_text import mask_report_summary, mask_summary from .report import format_issues -from .run.mask_step import describe_masks, prepare_mask_step +from .run.mask_step import MaskStepResult, describe_masks, prepare_mask_step from .validation import has_errors THRESHOLD_HELP = { "inside_pixel_share": "share of a child's pixels in one parent for it to be inside", "inside_object_share": "share of the children inside for a mask to be inside another", "parent_larger_share": "share of the inside children whose parent is larger", - "same_objects_iou": "intersection over union for two objects to match one to one", + "same_objects_iou": "minimum overlap of two objects, divided by their combined area, for " + "them to count as a match", "same_objects_share": "share of the objects of both masks matched for the same objects", "grouped_label_share": "share of a grouped mask's pixels carrying the parent's label", "grouped_median_pieces": "median pieces per label above which a mask is grouped", @@ -56,7 +57,9 @@ def add_masks_arguments(masks: argparse.ArgumentParser) -> None: "each mask whole twice more; default: as in the earlier run, else no)", ) limits = masks.add_argument_group( - "relationship thresholds", "change the defaults (contract §15.1); shares are 0 to 1" + "relationship thresholds", + "optional thresholds for identifying mask relationships; fractions range from 0 to 1 " + "(0.8 means 80 percent)", ) for name, text in THRESHOLD_HELP.items(): limits.add_argument( @@ -96,7 +99,10 @@ def masks_command(args: argparse.Namespace) -> int: if has_errors(step.issues): return 1 if not step.masks.types: - print("Give the masks folder with --masks, or use OME-Zarr images with label images.") + print( + "No masks were found. If you have external masks, give their folder with --masks. " + "If you do not intend to analyse masks, skip this command." + ) return 1 def progress(done: int, total: int, path: str) -> None: @@ -118,11 +124,26 @@ def progress(done: int, total: int, path: str) -> None: if result.report is None: # the description is gone or unreadable: nothing read (#418) print(format_issues(result.issues)) return 1 + return _report(result) + + +def _report(result: MaskStepResult) -> int: + """Print the mask report, its issues and the closing line; return the exit status.""" print() print(mask_report_summary(result.report)) - print() - print(f"Report written to {result.path}") if result.issues: print() print(format_issues(result.issues)) - return 1 if has_errors(result.issues) else 0 + print() + if has_errors(result.issues): + print( + f"Mask check failed. A report was saved to {result.path}, but some masks did not " + "pass validation. Correct the errors above and repeat the mask check before using " + "those masks." + ) + return 1 + print( + f"Mask check completed. Relationships saved to {result.path}. The checked masks can " + "now be used in the next MorphoBricks analysis." + ) + return 0 diff --git a/src/morphobricks_preprocessing/cli_run.py b/src/morphobricks_preprocessing/cli_run.py index 16b2bff1..eaa65577 100644 --- a/src/morphobricks_preprocessing/cli_run.py +++ b/src/morphobricks_preprocessing/cli_run.py @@ -9,28 +9,28 @@ uses the recorded experiment folder (``experiment_not_recorded`` without one). ``--lab-links FILE`` gives lab-tool links, recorded in the run manifest only (never taken over by a later run), and ``--confirm-repeat-codes`` confirms their repeat codes (:mod:`.lab_links`). -Also the helpers every command shares: :func:`parse_size` and :func:`command_preflight`. +Also the helper every command shares, :func:`command_preflight`; :func:`parse_size` is in +:mod:`.cli_run_options` (re-exported here). """ from __future__ import annotations import argparse -import re +import shlex from dataclasses import replace -from fractions import Fraction from pathlib import Path from typing import Literal from morphobricks_normalization.checks import IntensityCheckSettings from morphobricks_normalization.ranges import ( - DEFAULT_ROBUST_QUANTILES, - HISTOGRAM_RANGES, HistogramSettings, ) from .axes import AxisMapping, reference_axes from .axis_review import review_axes from .channel_identity import channel_identity_text +from .cli_run_options import INTENSITY_HELP, add_run_settings +from .cli_run_options import parse_size as parse_size from .discovery import default_output_folder from .image_type import IMAGE_TYPES, RGB, ImageTypeReview, review_image_type from .intensity import intensity_text @@ -38,7 +38,6 @@ from .lab_links_file import read_lab_links from .manifest import RunManifest from .metadata import header_axes -from .planes import DEFAULT_MEMORY_LIMIT from .report import ( axis_check_summary, format_issues, @@ -52,60 +51,6 @@ from .run.reuse import read_previous, recorded_experiment_root from .validation import ValidationIssue, error -_UNITS = { - "": 1, - "B": 1, - "KIB": 2**10, - "MIB": 2**20, - "GIB": 2**30, - "KB": 10**3, - "MB": 10**6, - "GB": 10**9, -} - - -def parse_size(text: str) -> int: - """Parse a memory size such as ``"1GiB"``, ``"1.5 GiB"`` or ``"1073741824"``. - - The size must be an exact whole number of bytes above 0, computed without rounding - (``"1.5GiB"`` is 1610612736 bytes; ``"1.5"`` and ``"0.5B"`` are refused, issue #80). - ``argparse`` calls it while reading the command line, so a refused size stops the - command before anything is read. - - Raises - ------ - argparse.ArgumentTypeError - If the text is not a whole positive number of bytes. - """ - match = re.fullmatch(r"\s*([0-9]+(?:\.[0-9]+)?)\s*([A-Za-z]*)\s*", text, flags=re.ASCII) - unit = match.group(2).upper() if match else None - if not match or unit not in _UNITS: - raise argparse.ArgumentTypeError( - f"{text!r} is not a memory size; use for example 1GiB, 512MiB or a number of bytes." - ) - size = Fraction(match.group(1)) * _UNITS[unit] - if size.denominator != 1 or size <= 0: - raise argparse.ArgumentTypeError( - f"{text!r} is not a whole number of bytes above 0; use for example 1GiB, 512MiB " - "or a whole number of bytes." - ) - return int(size) - - -def parse_workers(text: str) -> int | str: - """Parse ``--workers``: a whole number of at least 1, or ``auto`` (issue #107). - - Raises - ------ - argparse.ArgumentTypeError - For any other text. - """ - if text == "auto": - return text - if not re.fullmatch(r"[0-9]+", text, flags=re.ASCII) or int(text) < 1: - raise argparse.ArgumentTypeError(f"{text!r} is not a whole number of at least 1 or auto.") - return int(text) - def command_preflight(args: argparse.Namespace) -> Preflight: """Run :func:`preflight` with the options every command shares.""" @@ -162,8 +107,9 @@ def add_missing_as_singleton(parser: argparse.ArgumentParser) -> None: parser.add_argument( "--missing-as-singleton", action=argparse.BooleanOptionalAction, - help="confirm that images lacking some axes have one plane along them (default: as " - "in the earlier run, else no)", + help="confirm that an image without a particular dimension has size 1 along it " + "(default: as in the earlier run, else no). This does not enable analysis of " + "multi-slice Z-stacks", ) @@ -239,7 +185,7 @@ def add_run_arguments(run: argparse.ArgumentParser) -> None: The ``run`` command's parser. """ _run_inputs(run) - _run_settings(run) + add_run_settings(run) run.add_argument("--log", metavar="FILE", help="write technical details to this file") @@ -248,20 +194,24 @@ def _run_inputs(run: argparse.ArgumentParser) -> None: run.add_argument( "--axes", metavar="ROLES", - help="role of each axis of the images, in the order of their axes: X, Y, Z, C, T, or " - "- for none (for example ZCYX). 'check' prints the suggested value. Needed for the " - "first run unless every image names its axes, and again for plain stacks that are " - "new or changed", + help="roles of the stored dimensions, in their stored order: Y and X are image height " + "and width, C is channel, Z is depth, T is time, - an unused length-1 dimension (for " + "example CYX). 'check' prints the suggested value. Needed for the first run unless " + "every image names its axes, and again for plain stacks that are new or changed", ) run.add_argument( "--image-type", choices=IMAGE_TYPES, - help="fluorescence (each channel a separate stain) or rgb (colour images with " - "three channels); default: the earlier run's, else the type suggested from the " - "image headers, printed", + help="fluorescence (each channel a separate stain; the description calls it " + "channels) or rgb (colour images with three channels); default: the earlier run's, " + "else the type suggested from the image headers. The published description is the " + "record of what your channels are: correct it there, not with this option", ) run.add_argument( - "--no-masks", action="store_true", help="drop the masks folder of the earlier run" + "--no-masks", + action="store_true", + help="stop using the previously recorded external masks folder (does not delete mask " + "files)", ) run.add_argument( "--no-exclude", @@ -293,77 +243,11 @@ def _run_inputs(run: argparse.ArgumentParser) -> None: run.add_argument( "--verify-content", action=argparse.BooleanOptionalAction, - help="reuse rows only when each image's content SHA-256 is the one recorded with them, " - "not only its size and modification time (reads every image once more; changing it " - "recomputes every row; on by default: as in the earlier run, else yes; " - "--no-verify-content opts out and the manifest records that)", - ) - - -def _run_settings(run: argparse.ArgumentParser) -> None: - """Add the settings of ``run``; each one left out is the earlier run's, else the default.""" - run.add_argument("--bins", type=int, help="bins per plane (default: depends on pixel type)") - run.add_argument( - "--histogram-range", - choices=HISTOGRAM_RANGES, - help="range of histograms that are not exact (float images, and integer images with " - "more values than bins): minmax (default, each plane's minimum to maximum) or robust " - "(between the --robust-quantiles, the pixels outside counted separately); 8- and " - "16-bit histograms are the same either way", - ) - run.add_argument( - "--robust-quantiles", - type=float, - nargs=2, - metavar=("LOW", "HIGH"), - help="quantiles in percent of the robust range, also used by the range check " - f"(default {DEFAULT_ROBUST_QUANTILES[0]:g} {DEFAULT_ROBUST_QUANTILES[1]:g})", - ) - run.add_argument( - "--memory-limit", - type=parse_size, - default=DEFAULT_MEMORY_LIMIT, - metavar="SIZE", - help="working-memory limit per plane, e.g. 2GiB (default: 1GiB)", - ) - run.add_argument( - "--workers", - type=parse_workers, - default=1, - metavar="N|auto", - help="images read at once, each in its own thread (default 1: one after another); " - "auto: at most the CPUs and, with --max-ram, what the largest image's estimate fits. " - "The outputs are the same with any value", - ) - run.add_argument( - "--max-ram", - type=parse_size, - metavar="SIZE", - help="with --workers auto: memory the run may use, e.g. 8GiB (an image that does not " - "fit stops the run before any pixel is read)", + help="verify that each image's contents are unchanged before reusing its histogram " + "(on by default for a new run; as in the earlier run otherwise). This reads the image " + "files again but avoids recomputing unchanged histograms; changing it recomputes " + "every row. --no-verify-content opts out, and the run manifest records that", ) - checks = run.add_argument_group( - "intensity checks", "limits of the warnings printed after the run; the defaults suit most" - ) - for name, (kind, metavar, text) in _INTENSITY_HELP.items(): - checks.add_argument( - "--" + name.replace("_", "-"), dest=name, type=kind, metavar=metavar, help=text - ) - - -_INTENSITY_HELP = { - "outlier_limit": ( - float, - "N", - "robust deviations beyond which an image or biological repeat is reported (default 3)", - ), - "saturation_limit": ( - float, - "FRACTION", - "fraction of saturated pixels above which an image is reported (default 0.01, 1 %%)", - ), - "min_images": (int, "N", "fewest images a comparison needs (default 5)"), -} def run_command(args: argparse.Namespace) -> int: @@ -417,9 +301,34 @@ def run_command(args: argparse.Namespace) -> int: print(intensity_text(result.intensity)) if result.channel_identity is not None: print(f"\n{channel_identity_text(result.channel_identity)}") + if result.written: + print(f"\n{completed_text(result.output_folder)}") return 0 if result.written else 1 +def completed_text(output: Path) -> str: + """Return the hand-off of a run that wrote its outputs (review 7.1): which folder to give on. + + Parameters + ---------- + output + The run's output folder. + + Returns + ------- + str + """ + folder = shlex.quote(str(output)) + return "\n".join( + [ + f"Preprocessing completed. Review the warnings above. Use {output} as the input " + "folder for your next MorphoBricks analysis.", + "If your analysis uses masks, check their pixel values and relationships first:", + f" morphobricks-preprocessing masks --output {folder}", + ] + ) + + def lab_links_option(args: argparse.Namespace) -> LabLinks | None | Literal[False]: """Return the links of ``--lab-links``, None without it, or False after printing a refusal. @@ -530,7 +439,7 @@ def _settings_options( Each is None when none of its options is given (the run then uses the recorded one); None as a whole when a value is refused, which is printed. """ - intensity = {k: getattr(args, k) for k in _INTENSITY_HELP if getattr(args, k) is not None} + intensity = {k: getattr(args, k) for k in INTENSITY_HELP if getattr(args, k) is not None} histogram = { k: v for k, v in ( diff --git a/src/morphobricks_preprocessing/cli_run_options.py b/src/morphobricks_preprocessing/cli_run_options.py new file mode 100644 index 00000000..6dad77b7 --- /dev/null +++ b/src/morphobricks_preprocessing/cli_run_options.py @@ -0,0 +1,149 @@ +"""The ``run`` command's settings options and the size parsers the commands share. + +Moved from :mod:`.cli_run` to keep that module within the line limit: :func:`parse_size` +(memory sizes such as ``1GiB``), :func:`parse_workers` (``--workers``) and +:func:`add_run_settings` (the histogram, memory, worker and intensity-check options of ``run``). +""" + +from __future__ import annotations + +import argparse +import re +from fractions import Fraction + +from morphobricks_normalization.ranges import DEFAULT_ROBUST_QUANTILES, HISTOGRAM_RANGES + +from .planes import DEFAULT_MEMORY_LIMIT + +__all__ = ["INTENSITY_HELP", "add_run_settings", "parse_size", "parse_workers"] + +_UNITS = { + "": 1, + "B": 1, + "KIB": 2**10, + "MIB": 2**20, + "GIB": 2**30, + "KB": 10**3, + "MB": 10**6, + "GB": 10**9, +} + + +def parse_size(text: str) -> int: + """Parse a memory size such as ``"1GiB"``, ``"1.5 GiB"`` or ``"1073741824"``. + + The size must be an exact whole number of bytes above 0, computed without rounding + (``"1.5GiB"`` is 1610612736 bytes; ``"1.5"`` and ``"0.5B"`` are refused, issue #80). + ``argparse`` calls it while reading the command line, so a refused size stops the + command before anything is read. + + Raises + ------ + argparse.ArgumentTypeError + If the text is not a whole positive number of bytes. + """ + match = re.fullmatch(r"\s*([0-9]+(?:\.[0-9]+)?)\s*([A-Za-z]*)\s*", text, flags=re.ASCII) + unit = match.group(2).upper() if match else None + if not match or unit not in _UNITS: + raise argparse.ArgumentTypeError( + f"{text!r} is not a memory size; use for example 1GiB, 512MiB or a number of bytes." + ) + size = Fraction(match.group(1)) * _UNITS[unit] + if size.denominator != 1 or size <= 0: + raise argparse.ArgumentTypeError( + f"{text!r} is not a whole number of bytes above 0; use for example 1GiB, 512MiB " + "or a whole number of bytes." + ) + return int(size) + + +def parse_workers(text: str) -> int | str: + """Parse ``--workers``: a whole number of at least 1, or ``auto`` (issue #107). + + Raises + ------ + argparse.ArgumentTypeError + For any other text. + """ + if text == "auto": + return text + if not re.fullmatch(r"[0-9]+", text, flags=re.ASCII) or int(text) < 1: + raise argparse.ArgumentTypeError(f"{text!r} is not a whole number of at least 1 or auto.") + return int(text) + + +def add_run_settings(run: argparse.ArgumentParser) -> None: + """Add the settings of ``run``; each one left out is the earlier run's, else the default. + + Parameters + ---------- + run + The ``run`` command's parser. + """ + run.add_argument( + "--bins", + type=int, + help="number of intensity-histogram bins for each channel of an image plane (default: " + "depends on the pixel type)", + ) + run.add_argument( + "--histogram-range", + choices=HISTOGRAM_RANGES, + help="range of histograms that are not exact (float images, and integer images with " + "more values than bins): minmax (default, each plane's minimum to maximum) or robust " + "(between the --robust-quantiles, the pixels outside counted separately); 8- and " + "16-bit histograms are the same either way", + ) + run.add_argument( + "--robust-quantiles", + type=float, + nargs=2, + metavar=("LOW", "HIGH"), + help="quantiles in percent of the robust range, also used by the range check " + f"(default {DEFAULT_ROBUST_QUANTILES[0]:g} {DEFAULT_ROBUST_QUANTILES[1]:g})", + ) + run.add_argument( + "--memory-limit", + type=parse_size, + default=DEFAULT_MEMORY_LIMIT, + metavar="SIZE", + help="working-memory limit per plane, e.g. 2GiB (default: 1GiB)", + ) + run.add_argument( + "--workers", + type=parse_workers, + default=1, + metavar="N|auto", + help="number of images processed in parallel (default 1: one after another); with " + "auto, chosen from the available CPUs and, with --max-ram, memory. Does not change " + "the scientific results", + ) + run.add_argument( + "--max-ram", + type=parse_size, + metavar="SIZE", + help="total memory budget, used only with --workers auto, for example --workers auto " + "--max-ram 8GiB (an image that does not fit stops the run before any pixel is read)", + ) + checks = run.add_argument_group( + "intensity checks", "limits of the warnings printed after the run; the defaults suit most" + ) + for name, (kind, metavar, text) in INTENSITY_HELP.items(): + checks.add_argument( + "--" + name.replace("_", "-"), dest=name, type=kind, metavar=metavar, help=text + ) + + +INTENSITY_HELP = { + "outlier_limit": ( + float, + "N", + "robust deviations beyond which an image or biological repeat is reported (default 3)", + ), + "saturation_limit": ( + float, + "FRACTION", + "fraction of saturated pixels above which an image is reported (default 0.01, 1 %%)", + ), + "min_images": (int, "N", "fewest images a comparison needs (default 5)"), +} diff --git a/src/morphobricks_preprocessing/cli_tissue_mask.py b/src/morphobricks_preprocessing/cli_tissue_mask.py index 6f5d3611..4f4b0b67 100644 --- a/src/morphobricks_preprocessing/cli_tissue_mask.py +++ b/src/morphobricks_preprocessing/cli_tissue_mask.py @@ -26,7 +26,7 @@ from .run_inputs_tissue import ( HE_TISSUE_V2, NOT_REUSED, - PROVISIONAL_NOTE, + provisional_note, rgb_positions, tissue_next_steps, ) @@ -49,25 +49,46 @@ def add_tissue_mask_parser(commands: argparse._SubParsersAction) -> argparse.Arg """ tissue = commands.add_parser( "tissue-mask", - help="write an H&E tissue mask (nuclei, red blood cells and empty space left out) of " - "each RGB image as a new binary region mask (needs the he-mask extra)", + help="create a binary H&E tissue mask for each 8-bit RGB image of a preprocessing run " + "(provisional rule; needs the he-mask extra)", + description="""\ +Create a binary region mask for each selected 8-bit RGB H&E image in a +completed preprocessing run. A provisional fixed rule attempts to exclude +nuclei, red blood cells and empty background. Inspect the masks before you use +them. + +Requires: + 8-bit RGB images (three colour channels), one depth plane and one time point + the he-mask installation extra""", + epilog="""\ +Example: + morphobricks-preprocessing tissue-mask \\ + --output he_MorphoBricks_Preprocessing --to HETissue + +Inspect the generated masks, then declare them as binary. The command prints +the next commands to run.""", + formatter_class=argparse.RawDescriptionHelpFormatter, ) tissue.add_argument( - "--output", metavar="FOLDER", required=True, help="the output folder of the run" + "--output", + metavar="FOLDER", + required=True, + help="the preprocessing output folder containing morphobricks.toml", ) tissue.add_argument( "--to", metavar="NEW_ID", required=True, - help="the new mask ID; declare it binary afterwards", + help="new, unused mask identifier, for example HETissue; declare it as binary after " + "checking the generated masks", ) tissue.add_argument( "--image", action="append", default=[], metavar="PATH", - help="only this image, relative to the experiment folder (repeatable; default: every " - "image of a unit declared rgb)", + help="create masks only for this image, relative to the experiment folder " + "(repeatable). By default, every RGB image; other images do not receive this mask", ) tissue.add_argument( "--masks", @@ -93,7 +114,10 @@ def tissue_mask_command(args: argparse.Namespace) -> int: return 1 images = tuple(args.image) or rgb_positions(run) if not images: - print("The run has no image of a unit declared rgb; nothing was written.") + print( + "No images in this preprocessing run are declared RGB; tissue-mask requires RGB " + "H&E images. Nothing was written." + ) return 1 if args.masks and run.masks_root is not None: print( @@ -101,17 +125,18 @@ def tissue_mask_command(args: argparse.Namespace) -> int: f"{run.masks_root}, where the tissue masks go. Nothing was written." ) return 1 - if run.masks_root is None: + created = run.masks_root is None + if created: try: run = create_masks_folder(run, args.masks).run except MasksFolderRefused as exc: print(f"No tissue mask written. {exc}") return 1 print( - f"The run had no masks folder: created {run.masks_root} and recorded it, as " - "run --masks does." + f"Masks folder created and registered: {run.masks_root}. The preprocessing run " + "now records this folder." ) - print(PROVISIONAL_NOTE) + print(provisional_note(args.rule)) written = [] for image in images: try: @@ -119,15 +144,20 @@ def tissue_mask_command(args: argparse.Namespace) -> int: # Every refusal: RunInputsError, a missing extra, and a plane that cannot be read (#469). except (ValueError, ImportError, PlaneReadError, OSError) as exc: print(_refusal(image, exc)) + if created: + print(f"The registered masks folder {run.masks_root} remains in place.") if written: - print(f"{plural(len(written), 'image')} before it stay written.") + print( + f"The masks of {plural(len(written), 'earlier image')} remain available. " + "Complete the required masks before declaring this mask type." + ) return 1 written.append(result) - state = "written" if result.published else "already written" + state = "saved" if result.published else "already saved" kept = 100 * result.fractions["kept"] - line = f"{image}: {result.path} ({state}), kept {kept:.1f} %" + line = f"{image}: mask {state} to {result.path}; retained area: {kept:.1f} % of the image" if kept == 0: - line += " (nothing kept: an empty region)" + line += " (empty region: no tissue pixels retained; inspect this image)" print(line if result.reusable else f"{line}; {NOT_REUSED}") print() ids = sorted({r.mask_id for r in written}) diff --git a/src/morphobricks_preprocessing/conversion_issues.py b/src/morphobricks_preprocessing/conversion_issues.py index 8146bf48..14eb7493 100644 --- a/src/morphobricks_preprocessing/conversion_issues.py +++ b/src/morphobricks_preprocessing/conversion_issues.py @@ -87,25 +87,18 @@ def work_folder_issue(dest: Path, name: str, all_nul: bool = False) -> Validatio """ if all_nul: cause = ( - "Its owner file is unreadable: it holds only NUL bytes, possibly left by a power " - "loss while a conversion wrote it, so it cannot be proven that a conversion made " - "this folder." + "'s ownership record is unreadable (it holds only NUL bytes, possibly left by a " + "power loss)" ) else: - cause = ( - "So it was not made by a conversion, or was changed since, and it cannot be " - "proven that a conversion made it." - ) + cause = " has an invalid or missing ownership record, or contains unexpected files" return error( "conversion_work_folder_unowned", - f"The folder for the named-axis copies holds {name}, the name of the folder a " - "conversion writes its copies in, but not as a conversion leaves it: the owner file a " - "conversion writes into it first is missing or not well formed, or it holds something " - f"else than that file and the folder 'files'. {cause} Nothing was removed and " - "nothing was written.", + f"The temporary conversion folder {dest / name}{cause}. The folder has not been " + "removed: it has been left untouched. Nothing was removed and nothing was written.", [name], - f"Check {dest / name}, then move or remove it yourself if you no longer need what it " - "holds, or choose a new, empty folder for the copies.", + "Use a new, empty folder for the copies (--to), or inspect the temporary folder before " + "moving it.", ) @@ -117,13 +110,12 @@ def work_folder_in_use_issue(dest: Path, name: str, holder: LockHolder) -> Valid """ return error( "conversion_work_folder_in_use", - f"The folder for the named-axis copies holds {name}, the work folder of a " - f"conversion by {holder.describe()}, which is still running on this computer, so it " - "may still be writing there (its lock was probably removed by mistake). Nothing was " - "removed and nothing was written.", + "A process associated with an earlier conversion is still running on this computer " + f"({holder.describe()}). The temporary folder {dest / name} has been left untouched. " + "Nothing was removed and nothing was written.", [name], - "Wait for that conversion to finish, then convert again. If that process is not a " - f"conversion (process IDs are reused), move or remove {dest / name} yourself.", + "Wait for the conversion to finish, or use another destination. If that process is not " + "a conversion (process IDs are reused), inspect the temporary folder before moving it.", ) @@ -131,13 +123,11 @@ def work_folder_not_removed_issue(dest: Path, name: str, exc: OSError) -> Valida """Refuse a conversion whose leftover work folder ``name`` cannot be removed (#488).""" return error( "conversion_work_folder_not_removed", - f"The folder for the named-axis copies holds {name}, the work folder of a conversion " - f"that was stopped, and it cannot be removed ({exc}): a file in it may be open in " - "another program, such as an antivirus or a sync client (OneDrive, Dropbox). Part of " - "it may have been removed. Nothing was written.", + f"The temporary conversion folder {dest / name}, left by a stopped conversion, could " + f"not be removed: {exc}. Part of it may have been removed; nothing was written.", [name], - "Close the programs that may use it, or wait for them to finish, then convert again " - f"(the conversion removes it). Or remove {dest / name} yourself.", + f"Close programs using {dest / name} (such as an antivirus or a sync client like " + "OneDrive) and retry, or choose another empty destination.", ) @@ -154,13 +144,12 @@ def path_too_long_issue( ) return error( "copy_path_too_long", - f"{plural(len(paths), 'copy', 'copies')} would have {what} while it is written in the " - f"conversion's work folder in {dest}, and Windows cannot handle such paths without " - "long paths enabled. Nothing was written.", + f"The converted files would exceed Windows' path-length limit: " + f"{plural(len(paths), 'copy', 'copies')} would have {what} in the conversion's work " + f"folder in {dest}. Nothing was written.", paths, - "Choose a folder for the copies with a shorter path (for example near the top of the " - "drive), or shorten the names of these images or of their folders, or ask your " - "administrator to enable Windows' long paths (LongPathsEnabled).", + "Choose a destination with a shorter path, shorten the named folders or ask your " + "administrator to enable long paths.", ) diff --git a/src/morphobricks_preprocessing/describe_ids.py b/src/morphobricks_preprocessing/describe_ids.py index 8456a1ba..4475c13c 100644 --- a/src/morphobricks_preprocessing/describe_ids.py +++ b/src/morphobricks_preprocessing/describe_ids.py @@ -14,10 +14,12 @@ from __future__ import annotations -from collections.abc import Sequence +import shlex +import unicodedata +from collections.abc import Collection, Iterable, Sequence from .draft import Draft, DraftError -from .draft_ids import IdKind +from .draft_ids import IdKind, id_problems LEVELS: dict[str, IdKind] = { "condition": "conditions", @@ -32,9 +34,74 @@ } -def id_option(folder: str, value: str = "") -> str: - """Return the ``--id`` option that names ``folder``'s ID (```` as a placeholder).""" - return f"--id {folder}={value}" +_RESERVED = "This name is reserved. Choose another identifier." +_USED = "This identifier has already been used for another entry. Choose an unused identifier." +REASONS: dict[str, str] = { + "E_FORBIDDEN_FIELD": _RESERVED, + "E_ID_RESERVED": _RESERVED, + "E_ID_SYNTAX": ( + "This identifier contains characters that are not permitted. Choose a valid identifier." + ), + "E_ID_TEXT": ( + "This identifier is empty, starts or ends with a space, or reads as a missing value " + "(such as NA or none). Choose a valid identifier." + ), + "E_ID_NOT_NFC": ( + "This identifier contains accented characters in a form that is not permitted (not " + "Unicode NFC). Type it again, or choose another identifier." + ), + "E_SINGLE_MISUSE": ( + "'single' is kept, in lower case, for a level without its own folder. Choose another " + "identifier." + ), + "E_ID_CASE_COLLISION": ( + "This identifier differs from another identifier only in upper/lower case. Choose a " + "distinct identifier." + ), + "R_USED_ID_REUSED": _USED, + "id_in_use_in_draft": _USED, + "in_use": _USED, +} +"""Why an ID is refused, in words, by the code the ID rules give (``id_problems``, the draft).""" + + +def reasons(codes: Iterable[str]) -> str: + """Say why an ID is refused, each reason once, then the codes in brackets.""" + codes = tuple(dict.fromkeys(codes)) or ("in_use",) + said = dict.fromkeys(REASONS.get(code, "This identifier is not permitted.") for code in codes) + shown = ", ".join(code for code in codes if code != "in_use") + text = " ".join(said) + return f"{text[:-1]} ({shown})." if shown else text + + +def example_id(kind: IdKind, folder: str, used: Collection[str] = ()) -> str: + """Return an allowed ID to show for ``folder``: ``ctrl`` for ``control``, else from its name.""" + if folder == "control": + return "ctrl" + base = unicodedata.normalize("NFC", folder.strip()) or "Group" + for candidate in (base, f"{base}_1", f"{base}_2", "Group1"): + if not id_problems(kind, candidate, used): + return candidate + return "Group1" + + +def id_option(folder: str, value: str) -> str: + """Return the ``--id`` option that names ``folder``'s ID, quoted for the shell where needed.""" + return f"--id {shlex.quote(f'{folder}={value}')}" + + +def needs_id(kind: IdKind, folder: str, used: Collection[str] = ()) -> str: + """Say why ``folder`` has no proposed ID and which ``--id`` names one (a concrete example).""" + codes = id_problems(kind, folder, used) + noun, option = NOUNS[kind], id_option(folder, example_id(kind, folder, used)) + if {"E_FORBIDDEN_FIELD", "E_ID_RESERVED"} & set(codes): + why = f" because {folder!r} is reserved ({', '.join(codes)})." + else: + why = f". {reasons(codes)}" + return ( + f"The {noun} {folder!r} needs another identifier{why} Keep the folder name and add " + f"{option} (or type the ID in the notebook)." + ) def _keys(draft: Draft, kind: IdKind) -> Sequence[str]: @@ -79,7 +146,10 @@ def apply_ids(draft: Draft, given: Sequence[str]) -> tuple[Draft, list[str]]: if len(found) > 1: prefixes = [p for p, kind in LEVELS.items() if (kind, folder) in found] levels = " or ".join(id_option(f"{p}:{folder}", value) for p in prefixes) - refusals.append(f"--id {item}: {folder!r} names folders of two levels: give {levels}") + refusals.append( + f"--id {item}: the name {folder!r} occurs at more than one folder level. " + f"Specify which level you mean: {levels}." + ) continue key = found[0] if key in seen: @@ -89,11 +159,12 @@ def apply_ids(draft: Draft, given: Sequence[str]) -> tuple[Draft, list[str]]: try: draft = draft.confirm_id(key[0], key[1], value) except DraftError as exc: + example = example_id(key[0], key[1], draft.used_ids.get(key[0], ())) refusals.append( - f"--id {item}: {value!r} cannot be the ID of {NOUNS[key[0]]} {key[1]} " - f"({', '.join(exc.codes) or exc}); give an allowed ID: {id_option(folder)}" + f"--id {item}: {value!r} cannot be the ID of {NOUNS[key[0]]} {key[1]!r}. " + f"{reasons(exc.codes)} For example: {id_option(folder, example)}" ) return draft, refusals -__all__ = ["LEVELS", "apply_ids", "id_option"] +__all__ = ["LEVELS", "REASONS", "apply_ids", "example_id", "id_option", "needs_id", "reasons"] diff --git a/src/morphobricks_preprocessing/describe_questions.py b/src/morphobricks_preprocessing/describe_questions.py index 71452e9c..dd6e131b 100644 --- a/src/morphobricks_preprocessing/describe_questions.py +++ b/src/morphobricks_preprocessing/describe_questions.py @@ -8,16 +8,17 @@ from __future__ import annotations -from .describe_ids import id_option +from .describe_ids import needs_id from .draft import Draft, OpenQuestion -from .draft_ids import IdKind, id_problems +from .draft_ids import IdKind from .validation import plural QUESTION_TEXT = { "id_pending": "choose the ID of {subject} (accept the proposal or type another)", "repeat_not_confirmed": ( - "confirm that the folders of {subject} were prepared and acquired under the same " - "circumstances, so they are comparable" + "confirm, only if it is true, that the samples of {subject} were prepared and acquired " + "comparably; otherwise review the experimental grouping in the notebook. Do not confirm " + "an incorrect experimental design" ), "confirmed_on_missing": "{subject} is confirmed but has no date: confirm it again", } @@ -30,8 +31,7 @@ def proposal(kind: IdKind, folder: str, proposed: str | None, named: str | None return f"ID {named!r} (yours, --id)" if proposed is not None: return f"proposed ID {proposed!r}" - why = ", ".join(id_problems(kind, folder)) - return f"no ID can be proposed ({why or 'in use'}): you name it ({id_option(folder)})" + return f"no ID proposed. {needs_id(kind, folder)}" def unproposed(draft: Draft) -> dict[str, tuple[IdKind, str]]: @@ -54,11 +54,7 @@ def unproposed(draft: Draft) -> dict[str, tuple[IdKind, str]]: def _text(q: OpenQuestion, named_by: dict[str, tuple[IdKind, str]]) -> str: """Return one open question in words; an unproposable ID names its ``--id`` option.""" if q.code == "id_pending" and q.subject in named_by: - kind, label = named_by[q.subject] - why = ", ".join(id_problems(kind, label)) or "in use" - return ( - f"name the ID of {q.subject}: {label!r} cannot be one ({why}); give {id_option(label)}" - ) + return needs_id(*named_by[q.subject]) return QUESTION_TEXT[q.code].format(subject=q.subject) diff --git a/src/morphobricks_preprocessing/description_run_text.py b/src/morphobricks_preprocessing/description_run_text.py index 38458e93..b6d19334 100644 --- a/src/morphobricks_preprocessing/description_run_text.py +++ b/src/morphobricks_preprocessing/description_run_text.py @@ -10,6 +10,7 @@ import shlex from collections.abc import Iterable +from pathlib import PurePath from .channel_plan import channel_coverage, partial_repeats from .description import Description @@ -21,7 +22,6 @@ from .description_report import DescriptionIssue from .description_rules import Code from .fast_layout import FAST_LAYOUT_CONTRADICTION, contradiction_message -from .fast_layout import FIX as FAST_FIX from .physical_check import ( CHANNEL_COUNT_MISMATCH, HEADER_CONTRADICTION, @@ -44,17 +44,43 @@ _ACTIONS = { UNIT_NOT_FOUND: "Remove that acquisition from the description or restore its folder.", UNIT_NOT_DECLARED: "Add the acquisition to the description, or exclude its images.", - MASK_TYPE_NOT_DECLARED: ( - "Declare the mask type in the description (the notebook's describe steps, or " - "morphobricks-preprocessing declare-masks --output FOLDER --type " - "TYPE=REPRESENTATION, where REPRESENTATION is what the mask is: instances, binary or " - "parent_labels); or, if the run does not use it (an OME-Zarr label image of another " - "tool, for example), skip it: declare-masks --output FOLDER --ignore TYPE; or remove " - "its files." - ), } +_DECLARE = ( + "If every object has its own positive label, declare it as instance labels{where}:\n" + " morphobricks-preprocessing declare-masks --output {output} --type {instances}\n" + "To skip this mask type instead:\n" + " morphobricks-preprocessing declare-masks --output {output} --ignore {name}\n" + "For a foreground/background mask, use {binary} instead. For labels grouping several " + "objects, use {parent}. Then run preprocessing again." +) +"""The undeclared mask type's fix: each representation with what it means, none guessed.""" + + +def declare_action(mask_type: str, output_folder: str | PurePath | None = None) -> str: + """Return how to declare or skip an undeclared mask type, its name and folder quoted.""" + where = "" + if output_folder is None: + where, output = " (replacing OUTPUT with your output folder)", "OUTPUT" + else: + output = shlex.quote(str(output_folder)) + return _DECLARE.format( + where=where, + output=output, + instances=shlex.quote(f"{mask_type}=instances"), + name=shlex.quote(mask_type), + binary=shlex.quote(f"{mask_type}=binary"), + parent=shlex.quote(f"{mask_type}=parent_labels"), + ) +FAST_ACTION = ( + "Review the channel order in the acquisitions listed above. Tag acquisitions separately in " + 'the notebook where their channel lists differ (channels_from = "unit"), save the ' + "description and run again." +) +"""The fix of ``R_FAST_LAYOUT_CONTRADICTION`` (experiment-v1 section 8 names it: tag those units +on their own, ``channels_from = "unit"``); the message lists every image and its unit once.""" + OVERRIDE_FIX = ( "Images that store R, G and B as three interleaved samples under a header that does not " "say colour need no own tags: declare the RGB header override on their acquisitions " @@ -82,8 +108,8 @@ def _what(issue: PhysicalIssue) -> str: return f"The experiment has images in {where}, which the description does not list." if issue.code == MASK_TYPE_NOT_DECLARED: return ( - f"Masks of type {issue.detail!r} were found (in the masks folder, beside the " - "images or as OME-Zarr label images), but are not declared in the description." + f"The mask type {issue.detail!r} was found but has not been declared. Choose how " + "its pixel values should be interpreted." ) reasons = { UNIT_NOT_HOMOGENEOUS: "Images of one acquisition differ in their layout", @@ -99,14 +125,18 @@ def _what(issue: PhysicalIssue) -> str: return f"{reasons[issue.code]} in {where}{image}: {issue.detail}." -def physical_issue(issue: PhysicalIssue) -> ValidationIssue: - """Return one physical check refusal as an error naming its code, unit and image.""" +def physical_issue( + issue: PhysicalIssue, output_folder: str | PurePath | None = None +) -> ValidationIssue: + """Return one physical check refusal as an error naming its code, unit and image. + + ``output_folder``, when known, is named in an undeclared mask type's commands; without it + they say OUTPUT and what to replace it with. + """ paths = () if issue.path is None else (issue.path,) action = _ACTIONS.get(issue.code, FIX) if issue.code == MASK_TYPE_NOT_DECLARED: # the type found, never a guessed representation - typed = shlex.quote(f"{issue.detail}=REPRESENTATION") - action = action.replace("TYPE=REPRESENTATION", typed) - action = action.replace("--ignore TYPE", f"--ignore {shlex.quote(issue.detail)}") + action = declare_action(issue.detail, output_folder) return error(issue.code, _what(issue), paths, action) @@ -115,15 +145,14 @@ def fast_layout_issue(issues: Iterable[PhysicalIssue]) -> ValidationIssue: Every image of every fast unit is listed once, with its FOV key, path and every contradiction found in it (kind, C index, expected and found), and the action names the - one fix: tag those units on their own, then run again. + one fix: tag those acquisitions separately in the notebook, then run again. """ listed = { (fov_text(issue), issue.path): issue.contradictions for issue in issues if issue.code == FAST_LAYOUT_CONTRADICTION } - units = sorted({unit_text(i.unit) for i in issues if i.code == FAST_LAYOUT_CONTRADICTION}) - action = f"{FAST_FIX} Units: " + "; ".join(units) + "." + action = FAST_ACTION if any(i.override_fits for i in issues if i.code == FAST_LAYOUT_CONTRADICTION): action += f" {OVERRIDE_FIX}" paths = [path for _, path in listed] @@ -136,29 +165,71 @@ def fov_text(issue: PhysicalIssue) -> str: return f"{unit.condition}/{unit.biological_repeat}/{unit.technical_repeat}/{issue.fov}" -def physical_issues(issues: Iterable[PhysicalIssue]) -> list[ValidationIssue]: +def physical_issues( + issues: Iterable[PhysicalIssue], output_folder: str | PurePath | None = None +) -> list[ValidationIssue]: """Return the physical refusals, every fast-mode contradiction as one issue (ADR 0006). One publication or run carries ``R_FAST_LAYOUT_CONTRADICTION`` at most once, with all images, beside every other applicable code (AQ2); the others are one issue each. + ``output_folder`` is as in :func:`physical_issue`. """ issues = list(issues) - out = [physical_issue(i) for i in issues if i.code != FAST_LAYOUT_CONTRADICTION] + out = [physical_issue(i, output_folder) for i in issues if i.code != FAST_LAYOUT_CONTRADICTION] if any(i.code == FAST_LAYOUT_CONTRADICTION for i in issues): out.append(fast_layout_issue(issues)) return out +_MEANINGS = { + "E_FILE_ENCODING": "is not saved as UTF-8 text", + "E_TOML_SYNTAX": "is not valid TOML text", + "E_DUPLICATE_KEY": "names the same entry twice", + "E_SCHEMA_ID": "is not an experiment description of this format", + "E_SCHEMA_VERSION_MISSING": "does not say which format version it is", + "E_SCHEMA_VERSION_UNSUPPORTED": "is of a format version this release does not read", + "E_TYPE": "has a value of the wrong kind", + "E_UNKNOWN_FIELD": "has a field this release does not know", + "E_FORBIDDEN_FIELD": "has a field that is not allowed in it", + "E_MISSING_FIELD": "is missing a required field", + "E_EMPTY": "has an empty list or table", + "E_TEXT_EMPTY": "has an empty text", + "E_ENUM": "has a value that is not one of the allowed choices", + "E_DATE_FORMAT": "has a date that is not written as YYYY-MM-DD", + "E_VALUE_RANGE": "has a number out of its allowed range", + "E_REPEAT_UNCONFIRMED": "has a biological repeat that is not confirmed", + "E_UNKNOWN_CONDITION": "refers to a condition it does not define", + "E_UNKNOWN_CHANNEL": "refers to a channel it does not define", + "E_REFERENCE_UNKNOWN": "compares a condition against one it does not define", + "E_REFERENCE_SELF": "compares a condition against itself", + "E_REFERENCE_CYCLE": "has conditions compared against each other in a circle", +} +"""What a reader code means, in plain words, after "The experiment description".""" + + +def _meaning(code: str) -> str: + """Say in plain words what a reader code means (a family's meaning for the others).""" + if code in _MEANINGS: + return _MEANINGS[code] + if code.startswith(("E_ID_", "E_SINGLE_")): + return "has an identifier that is not permitted" + if code.startswith("E_RGB_"): + return "has colour (RGB) settings that do not agree" + if code.startswith("R_"): + return "differs from what was published before in a way that is not allowed" + return "breaks one of its rules" + + def reader_issue(issue: DescriptionIssue) -> ValidationIssue: - """Return one reader (or file) refusal as an error with its code, table path and value.""" + """Return one reader (or file) refusal: its plain meaning, then its table path and code.""" code = issue.code.value - shown = "" if issue.value is None else f" (value {issue.value!r})" + parts = [f"at {issue.path}"] if issue.path else [] if issue.code is Code.E_TYPE: # the type found, which the code alone does not say - shown = f" (value {issue.value!r}, of type {type_name(issue.value)})" - message = ( - f"The experiment description morphobricks.toml cannot be used: {code} at " - f"{issue.path}{shown}." - ) + parts.append(f"value {issue.value!r} of type {type_name(issue.value)}") + elif issue.value is not None: + parts.append(f"value {issue.value!r}") + shown = ", ".join([*parts, code]) + message = f"The experiment description (morphobricks.toml) {_meaning(code)} ({shown})." return error(code, message, (), FIX) diff --git a/src/morphobricks_preprocessing/fast_answers.py b/src/morphobricks_preprocessing/fast_answers.py index 044f0bb9..ea033bbf 100644 --- a/src/morphobricks_preprocessing/fast_answers.py +++ b/src/morphobricks_preprocessing/fast_answers.py @@ -29,6 +29,7 @@ from collections.abc import Collection, Sequence +from .describe_ids import needs_id from .draft import Draft from .draft_answers import ( CHANNELS, @@ -62,31 +63,25 @@ def _ids(draft: Draft) -> tuple[dict, dict, dict, list[str]]: for folder, slot in sorted(draft.conditions.items()): chosen = slot.confirmed or slot.proposed if chosen is None: - missing.append(f"condition folder {folder!r} has no proposed ID: {_name(folder)}") + missing.append(needs_id("conditions", folder, draft.used_ids.get("conditions", ()))) conditions[folder] = ConditionAnswer(chosen) technical = {} for folder, slot in sorted(draft.technical_repeats.items()): chosen = slot.confirmed or slot.proposed if chosen is None: - missing.append( - f"technical repeat folder {folder!r} has no proposed ID: {_name(folder)}" - ) + used = draft.used_ids.get("technical_repeats", ()) + missing.append(needs_id("technical_repeats", folder, used)) else: technical[folder] = chosen repeats = {} for label, repeat in sorted(draft.repeats.items()): chosen = repeat.id.confirmed or repeat.id.proposed if chosen is None: - missing.append(f"repeat {label!r} has no proposed ID: {_name(label)}") + missing.append(needs_id("repeats", label, draft.used_ids.get("repeats", ()))) repeats[label] = RepeatAnswer(chosen) return conditions, technical, repeats, missing -def _name(folder: str) -> str: - """Say how the user names an ID that cannot be proposed.""" - return f"name it with --id {folder}= (or in the notebook)" - - def _all_named(draft: Draft) -> bool: """Return whether every ID of the draft is already the user's (``--id``).""" slots = [*draft.conditions.values(), *draft.technical_repeats.values()] @@ -106,8 +101,10 @@ def _statements( ) if not comparable: blockers.append( - "say that every biological repeat's folders were prepared and acquired under the " - "same circumstances (--comparable)" + "Comparability has not been confirmed. Add --comparable only if the samples in each " + "biological repeat were prepared and acquired comparably. Otherwise, review the " + "experimental grouping in the notebook. Do not confirm an incorrect experimental " + "design." ) if confirmed_on is None or not valid_day(confirmed_on): blockers.append("give the day of your statements as YYYY-MM-DD (--confirmed-on)") @@ -150,8 +147,10 @@ def fast_answers( blockers.append("--channels lists each channel ID once") if len(header_names) not in (0, len(channels)): blockers.append( - f"the tagged unit's image has {len(header_names)} named channels, --channels " - f"lists {len(channels)}: tag it again" + f"The first acquisition has {len(header_names)} named channels, but --channels lists " + f"{len(channels)}. Check the number and stored order of the channels, then correct " + "--channels. If acquisitions have different channel lists, describe their channels " + "separately in the notebook." ) conditions, technical, repeats, missing = _ids(draft) blockers += missing diff --git a/src/morphobricks_preprocessing/he_tissue_mask.py b/src/morphobricks_preprocessing/he_tissue_mask.py index d2acf192..15cfaf10 100644 --- a/src/morphobricks_preprocessing/he_tissue_mask.py +++ b/src/morphobricks_preprocessing/he_tissue_mask.py @@ -267,8 +267,9 @@ def current_rule(rule: str) -> dict: found = stain.PRESETS[PRESET].version if found != PRESET_VERSION: raise ValueError( - f"The installed normalization's {PRESET} preset is version {found}; {rule} is " - f"defined on version {PRESET_VERSION}" + "The installed normalization version is incompatible with this tissue-mask rule " + f"({rule} needs its {PRESET} preset at version {PRESET_VERSION}, found {found}). " + "Reinstall this preprocessing release with its required dependencies and retry." ) source, digest = hed_matrix() return rule_record(rule, hed_source=source, hed_sha256=digest) @@ -296,18 +297,21 @@ def resolved_fov(run: RunInputs, fov: object) -> Fov: raise RunInputsError(f"{relative} is not an image of this run.") if found.image_type != "rgb": raise ValueError( - f"{relative} is declared {found.image_type}; the H&E tissue mask takes a unit declared " - 'image_type = "rgb"' + f"{relative} was described as separate channels rather than RGB. If it is genuinely " + "a colour image, correct the experiment description and run preprocessing again." ) if found.z_count > 1 or found.t_count > 1: raise ValueError( - f"{relative} has {found.z_count} Z planes and {found.t_count} time points; the H&E " - "tissue mask takes one 2-D plane" + f"{relative} has {found.z_count} Z planes and {found.t_count} time points. The H&E " + "tissue mask does not accept Z-stacks or time-lapses. Use a supported single-plane " + "RGB image, or create appropriate masks with another segmentation tool." ) if found.dtype != "uint8" or found.c_count != 3: raise ValueError( - f"{relative} has the pixel type {found.dtype} and {found.c_count} channels; the H&E " - "tissue mask takes 8-bit RGB (uint8, three channels R, G, B)" + f"{relative} has the pixel type {found.dtype} and {found.c_count} channels. This " + "helper requires 8-bit colour images containing red, green and blue (uint8). Export " + "a suitable RGB copy (converting to 8-bit changes the intensities the rule's " + "thresholds apply to) or create a region mask using another tool." ) return found @@ -396,14 +400,14 @@ def _differences( def _collision(relative: str, differences: list[str]) -> ValueError: """Return the refusal of an existing output that is not this computation's.""" text = ( - f"{relative} exists in the masks folder and is not this computation's output (it " - f"differs in: {', '.join(differences)}); nothing is overwritten. Choose another output " - "mask ID" + f"A different mask already exists at {relative} in the masks folder (it differs in: " + f"{', '.join(differences)}). It will not be overwritten. Choose another output mask ID " + "(--to on the command line), for example HETissue_v2." ) if "rule" in differences or "rule_sha256" in differences: text += ( - ": a rule with another record (a frozen rule included) makes a new mask under a new " - "output mask ID, declared binary, with the masks step run again" + " A rule with another record (a frozen rule included) makes a new mask under a new " + "output mask ID, declared binary, with the masks step run again." ) return ValueError(text) diff --git a/src/morphobricks_preprocessing/ignored_masks.py b/src/morphobricks_preprocessing/ignored_masks.py index 3d779a5e..06c84576 100644 --- a/src/morphobricks_preprocessing/ignored_masks.py +++ b/src/morphobricks_preprocessing/ignored_masks.py @@ -30,6 +30,7 @@ from __future__ import annotations import os +import shlex import tomllib from collections.abc import Iterable from dataclasses import dataclass @@ -104,12 +105,31 @@ def ignored_types(manifest: object) -> frozenset[str]: return frozenset(() if entry is None else entry["types"]) +def unreadable_fix(output_folder: str | os.PathLike) -> str: + """Say how to recover from an ignore list that cannot be read (declare-masks reads it first). + + ``declare-masks`` reads the file before it writes it, so it refuses while the unreadable + file is there: the file is moved out (kept as a backup), then the list is made again. + """ + output = shlex.quote(Path(output_folder).as_posix()) + return ( + f"Move {IGNORED_FILENAME} out of the output folder and keep it as a backup: " + "declare-masks reads the list before changing it, so it cannot rewrite an unreadable " + "one. Then recreate the list with morphobricks-preprocessing declare-masks --output " + f"{output} --ignore TYPE, once for every mask type you still intend to skip (replacing " + "TYPE with its name; --ignore can be repeated), and run preprocessing again." + ) + + def name_problem(name: str) -> str | None: """Return why ``name`` cannot be an ignored mask type, or None when it can.""" if not name or name != name.strip(): - return "a mask type's name is not empty and has no space at its start or end" + return "Give a non-empty mask-type name without leading or trailing spaces." if any(c in name for c in "/\\") or any(ord(c) < 32 for c in name): - return "a mask type's name is one folder or label name: no '/', '\\' or control character" + return ( + "Give a mask-type name that is one folder or label name, without '/', '\\' or " + "control characters." + ) return None @@ -187,4 +207,5 @@ def read_ignored(output_folder: str | os.PathLike) -> IgnoredMasks: "parse_ignored", "read_ignored", "recorded_ignored", + "unreadable_fix", ] diff --git a/src/morphobricks_preprocessing/mask_declare.py b/src/morphobricks_preprocessing/mask_declare.py index ac0df19c..f26a4d5d 100644 --- a/src/morphobricks_preprocessing/mask_declare.py +++ b/src/morphobricks_preprocessing/mask_declare.py @@ -25,12 +25,14 @@ from __future__ import annotations import os +import shlex import unicodedata from collections.abc import Iterable, Mapping from dataclasses import dataclass, replace from pathlib import Path from ._io import write_text_atomic +from .describe_ids import reasons from .description import Description, DescriptionError, Mask from .description_rules import REPRESENTATIONS from .draft_ids import id_problems, propose_id @@ -40,6 +42,7 @@ ignored_text, name_problem, read_ignored, + unreadable_fix, ) from .run.description_file import Publication, PublicationRefused, publish_description from .run.description_run import load_description @@ -75,15 +78,17 @@ def _mask_id(item: MaskDeclaration) -> str: codes = id_problems("masks", item.mask_id) if codes: raise MaskDeclarationRefused( - f"{item.mask_id!r} cannot be a mask ID: {', '.join(codes)}", tuple(codes) + f"{item.mask_id!r} cannot be a mask ID. {reasons(codes)}", tuple(codes) ) return item.mask_id proposal = propose_id("masks", item.source_type) if proposal is None: codes = id_problems("masks", item.source_type) + example = shlex.quote(f"{item.source_type}=instances:Nuclei") raise MaskDeclarationRefused( - f"The mask type {item.source_type!r} is not a valid mask ID ({', '.join(codes)}): " - f"give its ID (for example --type {item.source_type}=:).", + f"The mask type {item.source_type!r} needs a different ID ({', '.join(codes)}). " + f"Keep its folder name and supply an ID, for example --type {example}, if it " + "contains instance labels.", ("mask_id_needed",), ) return proposal @@ -272,7 +277,12 @@ def ignore_masks( if not folder.is_dir(): raise IgnoredMasksError(f"The output folder {folder} does not exist.") with output_lock(folder): - before = read_ignored(folder).types + try: + before = read_ignored(folder).types + except IgnoredMasksError as exc: + raise IgnoredMasksError( + f"The ignored-mask list cannot be read: {exc}. {unreadable_fix(folder)}" + ) from exc after = tuple(sorted((set(before) | set(add)) - declared)) if after == before: return after, False diff --git a/src/morphobricks_preprocessing/mask_text.py b/src/morphobricks_preprocessing/mask_text.py index 91ecd522..018ee732 100644 --- a/src/morphobricks_preprocessing/mask_text.py +++ b/src/morphobricks_preprocessing/mask_text.py @@ -49,14 +49,17 @@ def mask_summary(masks: MaskInventory) -> str: def mask_report_summary(report: MaskReport) -> str: """Describe the mask types, their relationships and the hierarchy in plain words. - Every statement is a suggestion from the masks' pixels; the text ends by asking the - user to name the masks and check the relationships. + Every statement is measured from the masks' pixels and never replaces the declared + representation; the text ends by saying the relationships are inferred from overlap. """ - lines = [f"Mask types ({plural(report.images, 'image')} scanned):"] + lines = [ + f"Mask properties measured from the pixel values ({plural(report.images, 'image')} " + "scanned). These properties do not replace the declared mask representation.", + ] for name, summary in sorted(report.types.items()): lines.append( - f" {name}: {_MASK_KINDS[summary.kind]}; {plural(summary.objects, 'object')}, " - f"median {summary.median_pieces_per_label:g} piece(s) per label" + f" {name}: {_MASK_KINDS[summary.kind]}; {plural(summary.objects, 'positive label')}; " + f"median {summary.median_pieces_per_label:g} connected piece(s) per label" ) relationships = [pair for pair in report.relationships if pair.relation != "same_objects"] if relationships: @@ -67,15 +70,15 @@ def mask_report_summary(report: MaskReport) -> str: lines += [f" {first} and {second}" for first, second in report.same_objects] ambiguous = mask_ambiguous_lines(report) if ambiguous: - lines += ["", "Objects given no parent (equally in two or more objects of the other mask):"] + lines += ["", "Objects with no assigned parent because of equal overlap:"] lines += [f" {line}" for line in ambiguous] lines += ["", "Hierarchy (direct parents only):"] lines += _hierarchy_lines(report.hierarchy) lines += ["", f"Thresholds: {mask_thresholds_used(report)}"] lines += [ "", - "These are suggestions from the masks' pixels: name each mask, then check the " - "relationships before using them.", + "The relationships above are inferred from spatial overlap. Review them before using " + "them in a biological analysis.", ] return "\n".join(lines) @@ -179,8 +182,9 @@ def mask_ambiguous_lines(report: MaskReport) -> list[str]: the relation of the pair, so every pair is listed, ``none`` included. """ return [ - f"{pair.child} in {pair.parent}: {plural(pair.evidence['ambiguous_parent'], 'object')}" - f" of {pair.evidence['children']:,} equally in two or more {pair.parent}" + f"{pair.child} in {pair.parent}: {pair.evidence['ambiguous_parent']:,} of " + f"{plural(pair.evidence['children'], pair.child + ' label')} overlap two or more " + f"{pair.parent} labels equally; no parent was assigned" for pair in report.pairs if pair.evidence.get("ambiguous_parent") ] @@ -198,9 +202,9 @@ def _relationship_line(pair: PairRelation) -> str: f" {pair.child} {_RELATIONS[pair.relation]} {pair.parent}" f"{'' if pair.direct else ' (through another mask)'}: " f"{e['inside']} of {plural(e['children'], 'object')} inside; " - f"{pair.parent} with 0/1/2/3+ {pair.child}: {e['parents_with_0_children']}/" - f"{e['parents_with_1_child']}/{e['parents_with_2_children']}/" - f"{e['parents_with_3_or_more_children']}" + f"{pair.parent} containing {pair.child}: none = {e['parents_with_0_children']}, " + f"one = {e['parents_with_1_child']}, two = {e['parents_with_2_children']}, three or " + f"more = {e['parents_with_3_or_more_children']}" ) extra = [] if e["outside_parents"]: diff --git a/src/morphobricks_preprocessing/physical_check.py b/src/morphobricks_preprocessing/physical_check.py index 4ece9ff6..66914674 100644 --- a/src/morphobricks_preprocessing/physical_check.py +++ b/src/morphobricks_preprocessing/physical_check.py @@ -288,8 +288,8 @@ def undeclared_mask_types( """Return ``R_MASK_TYPE_NOT_DECLARED`` for each mask type found that is not declared. The one rule of ``run`` (through :func:`check_physical`) and ``check``: a mask type found - (a masks folder's subfolder, ``_.tif`` beside the images, or an OME-Zarr - label image) must be the ``source_type`` of a declared mask. Only names are compared. + (a masks folder's subfolder, ``_.tif`` in the masks folder, or an + OME-Zarr label image) must be the ``source_type`` of a declared mask. Only names are compared. """ known = {mask.source_type for mask in description.masks.values()} return [ diff --git a/src/morphobricks_preprocessing/projection_issues.py b/src/morphobricks_preprocessing/projection_issues.py index e608c555..046c8ce7 100644 --- a/src/morphobricks_preprocessing/projection_issues.py +++ b/src/morphobricks_preprocessing/projection_issues.py @@ -29,8 +29,8 @@ def nothing_to_project_issue(roles: str) -> ValidationIssue: f"--project was given, but no image has a depth axis (Z) under the roles {roles}. " "Nothing was written.", [], - "Check the roles: Z must be the axis of the slices of a stack, and every image is " - "otherwise left as it is.", + "Check the stored axis order: Z must be the axis of the slices of a stack. If these " + "images have no depth dimension, omit --project.", ) @@ -77,7 +77,8 @@ def over_memory_issue(path: str, needed: str, limit: str, count: int) -> Validat f"Projecting {path}{more} needs {needed} for one plane and its running total; the " f"limit is {limit}. Nothing was written.", [path], - "Raise the memory limit (--memory-limit).", + "Increase --memory-limit only if sufficient RAM is available, or export smaller images " + "for projection.", ) @@ -85,10 +86,11 @@ def zarr_issue(paths: Sequence[str]) -> ValidationIssue: """Refuse OME-Zarr images in a projection (they are not projected yet).""" return error( "projection_zarr_not_supported", - f"{plural(len(paths), 'OME-Zarr image')} cannot be projected yet: a projected copy is " - "an OME-TIFF, and the copy tree keeps each image's path. Nothing was written.", + "Projection of OME-Zarr source images is not supported in this release " + f"({plural(len(paths), 'OME-Zarr image')}). No projected copies were written.", paths, - "Exclude these images, or project the TIFF images in a separate experiment folder.", + "Export suitable TIFF copies of these images before projection, or process the TIFF " + "images separately.", ) @@ -102,7 +104,10 @@ def masks_3d_issue(by_type: Mapping[str, Sequence[str]]) -> ValidationIssue: "Masks are never projected: a projected label image merges different objects. " "Nothing was written.", paths, - "Make 2-D masks on the projected images, or move these masks out of the masks folder.", + "Existing 3-D masks cannot be used with this projection. Keep the original masks " + "separately, outside the masks folder, then convert the images without those 3-D masks. " + "Create new 2-D masks from the projected images and register them with the new " + "experiment.", ) @@ -114,7 +119,8 @@ def masks_axes_unknown_issue(paths: Sequence[str]) -> ValidationIssue: "are not named, so it is not known whether they have depth slices (Z). Masks are " "never projected, and no axis is guessed. Nothing was written.", paths, - "Name the axes in the masks' metadata, or move these masks out of the masks folder.", + "Check and export the mask axes correctly. If these masks belong to the original 3-D " + "images, keep them separate from the projected experiment.", ) diff --git a/src/morphobricks_preprocessing/report.py b/src/morphobricks_preprocessing/report.py index bdf97015..95af6798 100644 --- a/src/morphobricks_preprocessing/report.py +++ b/src/morphobricks_preprocessing/report.py @@ -238,11 +238,12 @@ def _stopped_summary(result: RunResult) -> str: if result.report_written: written.append(f"{REPORT_FILENAME} and {REPORT_TEXT_FILENAME} (the report)") lines = [ - f"The run stopped ({issue_counts(result.issues)}): no table or manifest was written.", + f"Preprocessing stopped ({issue_counts(result.issues)}). No new histogram table or run " + "manifest was published; existing results from an earlier successful run were kept.", f"Written to {result.output_folder}: {', '.join(written)}." if written else "Nothing was written.", - "Resolve the errors and run again.", + "Review the errors, correct the problems and run again.", ] return "\n".join(lines) diff --git a/src/morphobricks_preprocessing/required_description.py b/src/morphobricks_preprocessing/required_description.py index 21642883..168f8369 100644 --- a/src/morphobricks_preprocessing/required_description.py +++ b/src/morphobricks_preprocessing/required_description.py @@ -11,6 +11,7 @@ from __future__ import annotations import os +import shlex from pathlib import Path from typing import Literal @@ -22,15 +23,33 @@ DESCRIPTION_REQUIRED = "A_DESCRIPTION_REQUIRED" """The refusal of a run without a published description (ADR 0002 AR11 ruling 1).""" -FIX = ( - "Describe the experiment first, which publishes morphobricks.toml in the output folder: " - "either in the notebook (its describe steps, then Check and save), or on the command line " - "with 'morphobricks-preprocessing describe EXPERIMENT --output FOLDER --channels ID,ID " - "--image-type channels|rgb --accept-ids --comparable --confirmed-on YYYY-MM-DD --publish' " - "(without --publish it shows what is still to be answered)." +_EXAMPLE = ( + "morphobricks-preprocessing describe my_experiment{output} --channels COL,FN " + "--image-type channels --accept-ids --comparable --confirmed-on 2026-12-04 --publish" +) +_FIX = ( + "Describe the experiment before running preprocessing. Start with the command below, " + "replacing EXPERIMENT with your images folder, and review the proposed IDs and channel " + "order:\n" + " morphobricks-preprocessing describe EXPERIMENT{output}\n" + "To publish a simple two-channel fluorescence experiment, use the following example, " + "replacing my_experiment, the channels and the confirmation date with your own:\n" + " {example}\n" + "If your acquisitions have different channel lists or orders, describe them in the notebook " + "instead." +) +FIX = _FIX.format(output="", example=_EXAMPLE.format(output="")) + ( + " Add --output with your output folder to both commands when it is not the default one." ) """What the user does about it: either route publishes (owner, 4 December 2026): the notebook's -describe steps, or the command line's ``describe --publish`` (fast mode).""" +describe steps, or the command line's ``describe --publish`` (fast mode). Placeholders are +named in words, never as shell-unsafe text such as ``a|b`` (external review, 4 December 2026).""" + + +def fix_text(output_folder: str | os.PathLike) -> str: + """Return :data:`FIX` naming the refused output folder in both commands (``--output``).""" + output = f" --output {shlex.quote(Path(output_folder).as_posix())}" + return _FIX.format(output=output, example=_EXAMPLE.format(output=output)) def is_published(output_folder: str | os.PathLike) -> bool: @@ -56,7 +75,7 @@ def description_required_issue(output_folder: str | os.PathLike) -> ValidationIs DESCRIPTION_REQUIRED, required_message(output_folder), [Path(output_folder).as_posix()], - FIX, + fix_text(output_folder), ) diff --git a/src/morphobricks_preprocessing/run/preflight.py b/src/morphobricks_preprocessing/run/preflight.py index 2cfa22f2..e8640802 100644 --- a/src/morphobricks_preprocessing/run/preflight.py +++ b/src/morphobricks_preprocessing/run/preflight.py @@ -26,7 +26,13 @@ from ..dataset import DatasetReport, check_dataset from ..discovery import DiscoveryResult, default_output_folder, discover_experiment from ..fingerprint import Fingerprint, current_fingerprint -from ..ignored_masks import IGNORED_FILENAME, IgnoredMasks, IgnoredMasksError, read_ignored +from ..ignored_masks import ( + IGNORED_FILENAME, + IgnoredMasks, + IgnoredMasksError, + read_ignored, + unreadable_fix, +) from ..mask_names import MASK_NAME_CODES, mask_name_issues from ..masks import MaskFile, MaskInventory, find_masks from ..metadata import ( @@ -309,9 +315,9 @@ def _ignored(output: Path) -> tuple[IgnoredMasks, tuple[ValidationIssue, ...]]: return IgnoredMasks(), ( error( "ignored_masks_invalid", - f"The list of ignored mask types cannot be read: {exc}", + f"The ignored-mask list cannot be read: {exc}", [IGNORED_FILENAME], - "Write it again with declare-masks --ignore, or remove the file.", + unreadable_fix(output), ), ) diff --git a/src/morphobricks_preprocessing/run_inputs_text.py b/src/morphobricks_preprocessing/run_inputs_text.py index f622b4e8..0d0e0ca5 100644 --- a/src/morphobricks_preprocessing/run_inputs_text.py +++ b/src/morphobricks_preprocessing/run_inputs_text.py @@ -7,6 +7,8 @@ from __future__ import annotations +import re +from importlib.metadata import PackageNotFoundError, version from typing import TYPE_CHECKING from .validation import plural @@ -30,10 +32,36 @@ def _without_axes_text(paths: list[str]) -> str: ) +REPOSITORY = "git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git" + + +def zarr_install_line(installed: str | None) -> str: + """Return the install command of the ``zarr`` extra for the installed release. + + A release version (``X.Y.Z``) names its tag, so the extra comes with the same release; any + other version (a development build, or none known) gets the unpinned extra and says so. + """ + if installed is not None and re.fullmatch(r"\d+\.\d+\.\d+", installed): + pinned = f"morphobricks-preprocessing[zarr] @ {REPOSITORY}@v{installed}" + return f'python -m pip install "{pinned}"' + return ( + 'python -m pip install "morphobricks-preprocessing[zarr]" (install the same release ' + "of morphobricks-preprocessing as the one you use)" + ) + + +def _installed() -> str | None: + """Return the installed version of this package, or None when it is not known.""" + try: + return version("morphobricks-preprocessing") + except PackageNotFoundError: + return None + + _ZARR_MISSING = ( "The run holds OME-Zarr images, and the zarr package is not installed, so their label " "images cannot be checked against the run (none is ever skipped). Install it with: " - 'pip install "morphobricks-preprocessing[zarr]"' + f"{zarr_install_line(_installed())}" ) diff --git a/src/morphobricks_preprocessing/run_inputs_tissue.py b/src/morphobricks_preprocessing/run_inputs_tissue.py index 24784400..0edf4601 100644 --- a/src/morphobricks_preprocessing/run_inputs_tissue.py +++ b/src/morphobricks_preprocessing/run_inputs_tissue.py @@ -84,9 +84,26 @@ def preview_he_tissue_mask( return preview(self, fov, rule=rule) -PROVISIONAL_NOTE = ( - "Sizes are in pixels. Fixed rule he_tissue_v2 (provisional), not a trained segmentation." -) +def provisional_note(rule: str) -> str: + """Return the note naming the tissue-mask ``rule`` actually used (review P1.14). + + Parameters + ---------- + rule + The rule the masks are computed with, for example ``he_tissue_v1``. + + Returns + ------- + str + """ + return ( + f"Tissue-mask rule: {rule} (provisional, a fixed rule, not a trained segmentation). " + "All spatial thresholds are in pixels. Inspect the resulting masks before analysis." + ) + + +PROVISIONAL_NOTE = provisional_note(HE_TISSUE_V2) +"""The note of the default rule (the notebook's previews use it).""" NOT_REUSED = "this mask will not be reused on retry" """Said whenever a code identity is unverified (the mask is written but never reused).""" @@ -108,7 +125,12 @@ def tissue_next_steps( ids = sorted(set(mask_ids)) if not ids: return "No mask was written." - lines = [f"Written to the masks folder {masks_root}. Next:"] + lines = [ + f"Masks saved in the masks folder {masks_root}.", + "Inspect representative images with their masks overlaid (in Fiji or QuPath). Check " + "that the retained regions are the tissue you intend to measure. If the masks are " + "suitable, register and check them:", + ] commands = list(commands) if commands: lines += [f" {command}" for command in commands] diff --git a/src/morphobricks_preprocessing/tissue_masks_folder.py b/src/morphobricks_preprocessing/tissue_masks_folder.py index 0671d82d..679df93a 100644 --- a/src/morphobricks_preprocessing/tissue_masks_folder.py +++ b/src/morphobricks_preprocessing/tissue_masks_folder.py @@ -15,6 +15,7 @@ from __future__ import annotations import os +import shlex from dataclasses import dataclass from pathlib import Path @@ -63,10 +64,12 @@ def create_masks_folder(run: RunInputs, folder: str | os.PathLike | None) -> Cre target = Path(folder).resolve() if folder else default_masks_folder(run.experiment_root) created = not target.exists() if not created and (not target.is_dir() or any(target.iterdir())): + output, masks = shlex.quote(str(run.output_folder)), shlex.quote(str(target)) raise MasksFolderRefused( - f"{target} exists and is not an empty folder, so it is not made the run's masks " - "folder. Give another with --masks FOLDER, or run preprocessing with " - f"--masks {target} if it is your masks folder." + f"{target} already exists and is not an empty folder. Choose another empty folder " + "with --masks. If this is your experiment's existing masks folder, register it " + f"using morphobricks-preprocessing run --output {output} --masks {masks} before " + "retrying." ) try: target.mkdir(parents=True, exist_ok=True) diff --git a/tests/test_axis_check.py b/tests/test_axis_check.py index 4d9fb9b1..576effa8 100644 --- a/tests/test_axis_check.py +++ b/tests/test_axis_check.py @@ -390,7 +390,7 @@ def test_cli_run_names_the_swapped_files(tmp_path, capsys): assert main_described(["run", str(root), "--axes", "CXY"]) == 1 out = capsys.readouterr().out assert "header CYX, confirmed CXY: ctrl/a.tif" in out - assert "no table or manifest was written" in out + assert "No new histogram table or run manifest was published" in out def test_notebook_marks_roles_that_disagree_with_the_header(tmp_path): diff --git a/tests/test_brick_checks.py b/tests/test_brick_checks.py index 004729a2..74d7041b 100644 --- a/tests/test_brick_checks.py +++ b/tests/test_brick_checks.py @@ -288,3 +288,15 @@ def refuse(path="."): assert raised.value.code == "masks_folder_unreadable" assert str(raised.value).startswith("masks_folder_unreadable: ") assert str(locked) in str(raised.value) + + +def test_the_zarr_install_line_names_the_installed_release(): + from morphobricks_preprocessing.run_inputs_text import zarr_install_line + + assert zarr_install_line("0.10.0") == ( + 'python -m pip install "morphobricks-preprocessing[zarr] @ ' + 'git+https://github.com/CellMigrationLab/morphobricks-preprocessing.git@v0.10.0"' + ) + for unreleased in ("0.10.1.dev3+g197b6db", None): # no tag to name: never a made-up one + line = zarr_install_line(unreleased) + assert "@v" not in line and "the same release" in line diff --git a/tests/test_calibration.py b/tests/test_calibration.py index e928f5d6..26a4f013 100644 --- a/tests/test_calibration.py +++ b/tests/test_calibration.py @@ -462,7 +462,7 @@ def test_the_calibrate_command_keeps_an_unreadable_file(tmp_path, capsys): def test_the_calibrate_command_states_shows_and_removes(tmp_path, capsys): output = tmp_path / "out" assert main(["calibrate", "--output", str(output)]) == 0 - assert "No pixel size is stated" in capsys.readouterr().out + assert "No pixel sizes have been stated" in capsys.readouterr().out assert not (output / CALIBRATION_FILENAME).exists() args = ["calibrate", "--output", str(output), "--size", ".", "YX", "0.65", "um"] assert main_described([*args, "--pixels", "ctrl/rep1", "Z"]) == 0 diff --git a/tests/test_cli.py b/tests/test_cli.py index 588fabef..fbb6c4e4 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -48,7 +48,11 @@ def test_check_prints_summary_and_suggested_axes(experiment, capsys): assert "Suggested option for 'run': --axes TCYX (axes in the files: TCYX)" in out # 'check' is the run's step stopped after the report: it writes the report only. output = experiment.parent / "exp_MorphoBricks_Preprocessing" - assert check_outputs(output) and f"Report written to {output}" in out + assert ( + check_outputs(output) + and f"Report saved to {output}" in out + and "Header check passed." in out + ) def test_check_exits_with_1_on_errors(experiment, capsys): @@ -113,7 +117,10 @@ def test_rgb_is_refused_for_images_that_cannot_be_rgb(experiment, capsys): out = capsys.readouterr().out assert "contradict their header" in out assert "RGB images need exactly three colour channels" in out - assert "8 channels of type uint8" in out and "no table or manifest was written" in out + assert ( + "8 channels of type uint8" in out + and "No new histogram table or run manifest was published" in out + ) def test_image_type_must_be_known(experiment): @@ -188,7 +195,7 @@ def test_run_reports_blocking_errors(experiment, capsys): assert main_described(["run", str(experiment), "--axes", "Z-YX"]) == 1 out = capsys.readouterr().out assert "No role is chosen for the axis C (channel)" in out - assert "no table or manifest was written" in out + assert "No new histogram table or run manifest was published" in out def test_run_without_readable_images(tmp_path, capsys): @@ -217,7 +224,7 @@ def test_different_channel_counts_stop_check_and_run(tmp_path, capsys): assert "different numbers of channels: 3 channels (2 images), 2 channels (1 image)" in out assert main_described(["run", str(root), "--axes", "TCYX"]) == 1 out = capsys.readouterr().out # one described unit: its images are not homogeneous - assert "b.tif" in out and "no table or manifest was written" in out + assert "b.tif" in out and "No new histogram table or run manifest was published" in out def test_axes_are_needed_for_the_first_run_of_plain_stacks_only(tmp_path, capsys): diff --git a/tests/test_cli_describe.py b/tests/test_cli_describe.py index 6837cd80..129ae94e 100644 --- a/tests/test_cli_describe.py +++ b/tests/test_cli_describe.py @@ -68,7 +68,7 @@ def test_describe_prints_the_proposals_and_the_open_questions_and_writes_nothing assert "rep1: proposed ID 'rep1'; not confirmed" in out assert "CTRL / rep1: 2 images" in out assert "open questions (answered by you, in the notebook)" in out - assert "confirm that the folders of repeat rep1 were prepared and acquired" in out + assert "only if it is true, that the samples of repeat rep1 were prepared and acquired" in out assert "choose the ID of condition CTRL" in out assert listing(tmp_path) == before and not output.exists() @@ -77,7 +77,9 @@ def test_a_folder_that_cannot_be_an_id_has_no_proposal_and_is_not_repaired(tmp_p root = tree(tmp_path / "exp", "control/rep1", "DrugA/rep1") assert main(["describe", str(root)]) == 0 out = capsys.readouterr().out - assert "control: no ID can be proposed" in out and "you name it" in out + assert "control: no ID proposed. The condition folder 'control' needs another" in out + assert "because 'control' is reserved (E_FORBIDDEN_FIELD)" in out + assert "Keep the folder name and add --id control=ctrl" in out assert "DrugA: proposed ID 'DrugA'" in out @@ -123,7 +125,7 @@ def test_publish_refuses_a_draft_with_open_questions_and_lists_them(experiment, assert "Not published. What is missing:" in out missing = out.split("Not published. What is missing:")[1] assert missing.count(" - choose the ID of") == 5 # 2 conditions, single, 2 repeats - assert " - confirm that the folders of repeat rep2" in out + assert " - confirm, only if it is true, that the samples of repeat rep2" in out assert not (output / TOML).exists() and not output.exists() assert listing(tmp_path) == before @@ -142,7 +144,7 @@ def test_a_complete_draft_is_still_not_publishable_from_the_command_line(tmp_pat ]: draft = draft.confirm_id(kind, key, key) assert [q.code for q in draft.open_questions()] == ["repeat_not_confirmed"] - assert any("same circumstances" in item for item in draft_blockers(draft)) + assert any("prepared and acquired comparably" in item for item in draft_blockers(draft)) done = replace( draft, repeats={"rep1": replace(draft.repeats["rep1"], confirmed=True, confirmed_on="2026-11-01")}, @@ -208,4 +210,6 @@ def test_a_description_that_cannot_be_read_is_refused(tmp_path, capsys): root, output = published(tmp_path) (output / TOML).write_text("schema = 'nope'\n", encoding="utf-8") assert main(["describe", str(root), "--output", str(output)]) == 1 - assert "cannot be used" in capsys.readouterr().out + out = capsys.readouterr().out # the plain meaning first, then the field path and code + assert "The experiment description (morphobricks.toml) is not an experiment" in out + assert "(at schema, value 'nope', E_SCHEMA_ID)" in out diff --git a/tests/test_cli_tissue_mask.py b/tests/test_cli_tissue_mask.py index 78edc1f1..3a61ed80 100644 --- a/tests/test_cli_tissue_mask.py +++ b/tests/test_cli_tissue_mask.py @@ -44,8 +44,8 @@ def test_it_writes_every_rgb_image_and_names_the_next_steps(tmp_path, capsys, mo args = ["tissue-mask", "--output", str(run.output_folder), "--to", "HETissue"] assert main(args) == 0 printed = capsys.readouterr().out - assert "Fixed rule he_tissue_v2 (provisional)" in printed - assert f"{IMAGE}: HETissue/{IMAGE} (written), kept 80.4 %" in printed + assert "Tissue-mask rule: he_tissue_v2 (provisional" in printed + assert f"{IMAGE}: mask saved to HETissue/{IMAGE}; retained area: 80.4 % of the image" in printed output = run.output_folder assert ( f"morphobricks-preprocessing declare-masks --output {output} --type HETissue=binary " @@ -60,7 +60,7 @@ def test_it_writes_every_rgb_image_and_names_the_next_steps(tmp_path, capsys, mo assert line["operation"] == "he_tissue_mask" and line["reusable"] is True before = tree(run.masks_root) assert main([*args, "--image", IMAGE]) == 0 # the same call: a no-op - assert "(already written)" in capsys.readouterr().out + assert "mask already saved to" in capsys.readouterr().out assert tree(run.masks_root) == before @@ -144,9 +144,10 @@ def test_a_run_without_masks_folder_gets_one_recorded_as_run_masks_would( assert main(args) == 0 printed = capsys.readouterr().out folder = (tmp_path / "experiment_masks").resolve() - created = [line for line in printed.splitlines() if "had no masks folder" in line] + created = [line for line in printed.splitlines() if "Masks folder created" in line] assert created == [ - f"The run had no masks folder: created {folder} and recorded it, as run --masks does." + f"Masks folder created and registered: {folder}. The preprocessing run now records " + "this folder." ] assert (folder / "HETissue" / IMAGE).is_file() manifest = json.loads((run.output_folder / "run_manifest.json").read_text()) @@ -156,7 +157,7 @@ def test_a_run_without_masks_folder_gets_one_recorded_as_run_masks_would( assert RunInputs.open(run.output_folder).masks_root == folder assert main(args) == 0 # the same call again: the recorded folder, nothing created printed = capsys.readouterr().out - assert "had no masks folder" not in printed and "(already written)" in printed + assert "Masks folder created" not in printed and "mask already saved to" in printed def test_masks_names_the_folder_to_create_and_a_busy_folder_is_refused( @@ -174,7 +175,7 @@ def test_masks_names_the_folder_to_create_and_a_busy_folder_is_refused( assert not (manifest.get("masks") or {}).get("folder") chosen = tmp_path / "chosen" assert main([*args, "--masks", str(chosen)]) == 0 - assert f"created {chosen.resolve()}" in capsys.readouterr().out + assert f"Masks folder created and registered: {chosen.resolve()}." in capsys.readouterr().out assert (chosen / "HETissue" / IMAGE).is_file() assert main([*args, "--masks", str(tmp_path / "third")]) == 1 # the run has one now assert "this run records" in capsys.readouterr().out diff --git a/tests/test_cli_usability.py b/tests/test_cli_usability.py index 36ab6972..44c58cb1 100644 --- a/tests/test_cli_usability.py +++ b/tests/test_cli_usability.py @@ -223,14 +223,21 @@ def test_check_reports_an_undeclared_ome_zarr_label_mask_as_run_refuses_it(tmp_p assert main(["run", str(root), "--output", str(out)]) == 1 ran = capsys.readouterr().out message = ( - "Masks of type 'cells' were found (in the masks folder, beside the images or as " - "OME-Zarr label images), but are not declared in the description." + "The mask type 'cells' was found but has not been declared. Choose how its pixel " + "values should be interpreted." + ) + # Every representation is offered with what it means; none is guessed from the name. + action = ( + "If every object has its own positive label, declare it as instance labels (replacing " + "OUTPUT with your output folder):\n" + " morphobricks-preprocessing declare-masks --output OUTPUT --type cells=instances\n" ) - action = "declare-masks --output FOLDER --type cells=REPRESENTATION" for text in (checked, ran): assert message in text and action in text - assert "declare-masks --output FOLDER --ignore cells" in text # owner, 4 Dec 2026 - assert "--type TYPE=instances" not in checked # no representation is suggested for you + assert "declare-masks --output OUTPUT --ignore cells" in text # owner, 4 Dec 2026 + assert "For a foreground/background mask, use cells=binary instead." in text + assert "For labels grouping several objects, use cells=parent_labels." in text + assert "beside the images" not in checked # masks live in a masks folder, never there import json report = json.loads((out / "discovery_report.json").read_text()) @@ -243,8 +250,14 @@ def test_an_undeclared_mask_type_with_a_space_is_quoted_in_the_fix(): from morphobricks_preprocessing.physical_unit import PhysicalIssue issue = physical_issue(PhysicalIssue(MASK_TYPE_NOT_DECLARED, None, detail="Cell outlines")) - assert "--type 'Cell outlines=REPRESENTATION'" in issue.action + assert "--type 'Cell outlines=instances'" in issue.action assert "--ignore 'Cell outlines'" in issue.action + assert "use 'Cell outlines=binary'" in issue.action + named = physical_issue( + PhysicalIssue(MASK_TYPE_NOT_DECLARED, None, detail="cells"), "/data/my out" + ) + assert "declare-masks --output '/data/my out' --type cells=instances" in named.action + assert "OUTPUT" not in named.action def test_declare_masks_ignore_skips_a_label_image_and_the_run_records_it(tmp_path, capsys): @@ -300,9 +313,18 @@ def test_an_invalid_ignore_file_stops_check_and_run(tmp_path, capsys): capsys.readouterr() (out / "ignored_masks.toml").write_text('version = 2\nignore = ["cells"]\n') assert main(["check", str(root), "--output", str(out)]) == 1 - assert "The list of ignored mask types cannot be read" in capsys.readouterr().out + checked = capsys.readouterr().out + assert "The ignored-mask list cannot be read" in checked + # declare-masks reads the list first, so the fix moves the file out before recreating it. + assert "Move ignored_masks.toml out of the output folder and keep it as a backup" in checked + assert f"declare-masks --output {out.as_posix()} --ignore TYPE" in checked assert main(["declare-masks", "--output", str(out), "--ignore", "x"]) == 1 - assert "this release reads version 1" in capsys.readouterr().out + refused = capsys.readouterr().out + assert "this release reads version 1" in refused + assert "Move ignored_masks.toml out of the output folder" in refused + (out / "ignored_masks.toml").rename(tmp_path / "ignored_masks.toml.bak") # as it says + assert main(["declare-masks", "--output", str(out), "--ignore", "cells"]) == 0 + assert main(["check", str(root), "--output", str(out)]) == 0 def test_declare_masks_without_a_masks_folder_names_no_placeholder_folder(tmp_path, capsys): @@ -325,7 +347,8 @@ def test_declare_masks_with_a_masks_folder_names_it(tmp_path, capsys): from morphobricks_preprocessing.cli_declare_masks import next_commands lines = next_commands(str(tmp_path / "out"), str(tmp_path / "my masks")) - assert lines[1].endswith(f"--masks '{tmp_path / 'my masks'}'") + run_line = next(line for line in lines if "morphobricks-preprocessing run" in line) + assert run_line.endswith(f"--masks '{tmp_path / 'my masks'}'") assert all("Add --masks" not in line for line in lines) @@ -344,7 +367,7 @@ def test_fast_describe_lists_open_questions_only_while_some_remain(tmp_path, cap assert main(["describe", str(root), "--output", str(tmp_path / "o2"), *partial]) == 0 text = capsys.readouterr().out assert "1 open question (answer them with --comparable and --confirmed-on" in text - assert "confirm that the folders of repeat rep1" in text + assert "confirm, only if it is true, that the samples of repeat rep1" in text assert "choose the ID" not in text # --accept-ids answered those @@ -357,7 +380,8 @@ def test_an_id_with_no_proposal_stays_open_under_accept_ids(tmp_path, capsys): text = capsys.readouterr().out assert "are answered by your options" not in text assert "1 open question (answer them with --id FOLDER=ID, or in the notebook)" in text - assert "give --id files=" in text + assert "needs another identifier because 'files' is reserved" in text + assert "add --id files=files_1" in text and "" not in text # --- 4b. describe --id FOLDER=ID (owner, 4 December 2026) ---------------------------------- @@ -372,10 +396,11 @@ def test_describe_id_names_a_forbidden_folder_and_publishes(tmp_path, capsys): text = capsys.readouterr().out assert "answer them with --id FOLDER=ID, or in the notebook" in text assert "--accept-ids, " not in text.split("open question")[1].split("\n")[0] - assert "name it with --id control=" in text + assert "The condition folder 'control' needs another identifier because 'control' is" in text + assert "Keep the folder name and add --id control=ctrl" in text and "" not in text assert not (out / DESCRIPTION_FILENAME).exists() assert main([*command, "--id", "control=ctrl"]) == 0 - assert "Published" in capsys.readouterr().out + assert "Experiment description saved to" in capsys.readouterr().out published = description_from_bytes((out / DESCRIPTION_FILENAME).read_bytes()) assert published.conditions["ctrl"].source_folder == "control" assert set(published.conditions) == {"ctrl", "DrugA"} @@ -387,9 +412,13 @@ def test_describe_id_refuses_what_the_notebook_refuses_and_names_the_option(tmp_ _ome(root / condition / "rep1" / "img.ome.tif") base = ["describe", str(root), "--output", str(out), *CHANNELS, "--publish"] for given, said in [ - ("control=files", "(E_FORBIDDEN_FIELD); give an allowed ID: --id control="), - ("control=druga", "E_ID_CASE_COLLISION"), - ("control=DrugA", "id_in_use_in_draft"), + ( + "control=files", + "This name is reserved. Choose another identifier (E_FORBIDDEN_FIELD). For " + "example: --id control=ctrl", + ), + ("control=druga", "only in upper/lower case. Choose a distinct identifier"), + ("control=DrugA", "already been used for another entry. Choose an unused identifier"), ("nowhere=x", "'nowhere' is not a condition, biological-repeat or technical-repeat"), ("control", "write it as FOLDER=ID"), ]: @@ -417,7 +446,9 @@ def test_describe_id_needs_the_level_for_a_label_of_two_levels(tmp_path, capsys) _ome(root / "b" / "rep1" / "a" / "img.ome.tif") base = ["describe", str(root), "--output", str(out), *CHANNELS, "--publish"] assert main([*base, "--id", "a=A1"]) == 1 - assert "give --id condition:a=A1 or --id technical:a=A1" in capsys.readouterr().out + text = capsys.readouterr().out + assert "the name 'a' occurs at more than one folder level. Specify which level" in text + assert "--id condition:a=A1 or --id technical:a=A1" in text assert main([*base, "--id", "condition:a=A1"]) == 0 published = description_from_bytes((out / DESCRIPTION_FILENAME).read_bytes()) assert published.conditions["A1"].source_folder == "a" diff --git a/tests/test_convert_work_folder.py b/tests/test_convert_work_folder.py index 69557df2..27916549 100644 --- a/tests/test_convert_work_folder.py +++ b/tests/test_convert_work_folder.py @@ -256,5 +256,5 @@ def test_an_owner_file_of_nul_bytes_is_refused_as_possibly_from_a_power_loss( message = result.issues[0].message assert ("possibly left by a power loss" in message) is named assert ("is unreadable" in message) is named - assert ("So it was not made by a conversion" in message) is not named + assert ("has an invalid or missing ownership record" in message) is not named assert _tree(copies) == before diff --git a/tests/test_declare_masks.py b/tests/test_declare_masks.py index 69e90c7b..fc991463 100644 --- a/tests/test_declare_masks.py +++ b/tests/test_declare_masks.py @@ -42,7 +42,7 @@ def test_the_masks_of_a_run_are_declared_run_and_described_from_the_command_line out = str(run.output) assert main(["run", str(run.experiment), "--output", out, "--masks", str(masks)]) == 1 refused = capsys.readouterr().out - assert "not declared" in refused and "declare-masks" in refused + assert "has not been declared" in refused and "declare-masks" in refused assert main(["declare-masks", "--output", out, "--type", "Cells=instances"]) == 0 said = capsys.readouterr().out diff --git a/tests/test_he_tissue_mask.py b/tests/test_he_tissue_mask.py index 6b8b89c8..a4685cce 100644 --- a/tests/test_he_tissue_mask.py +++ b/tests/test_he_tissue_mask.py @@ -194,7 +194,7 @@ def test_a_hand_built_rgb_fov_of_a_channels_position_is_refused(tmp_path, monkey run = channels_run(tmp_path) (own,) = run.fovs() no_reads(monkeypatch) - with pytest.raises(ValueError, match="is declared channels; the H&E tissue mask takes a unit"): + with pytest.raises(ValueError, match="was described as separate channels rather than RGB"): run.he_tissue_mask(dataclasses.replace(own, image_type="rgb"), output_mask_id="HETissue") @@ -324,7 +324,9 @@ def test_a_foreign_file_and_an_existing_file_are_refused_before_any_read(run, mo no_reads(monkeypatch) with pytest.raises(ValueError, match="holds masks of the type 'Other' that this helper"): run.he_tissue_mask(IMAGE, output_mask_id="Other") - with pytest.raises(ValueError, match=f"{OUT} exists .* unverified code identity"): + with pytest.raises( + ValueError, match=f"A different mask already exists at {OUT} .* unverified code identity" + ): run.he_tissue_mask(IMAGE, output_mask_id="HETissue") assert tree(run.masks_root) == before diff --git a/tests/test_ignored_masks.py b/tests/test_ignored_masks.py index e72f539e..06b97501 100644 --- a/tests/test_ignored_masks.py +++ b/tests/test_ignored_masks.py @@ -33,8 +33,8 @@ def test_the_text_is_canonical_and_reads_back(): (b'version = true\nignore = ["a"]\n', "reads version 1"), (b'version = 1\nignore = "a"\n', "list of names"), (b'version = 1\nignore = ["a", "a"]\n', "listed twice"), - (b'version = 1\nignore = [" a"]\n', "no space at its start or end"), - (b'version = 1\nignore = ["a/b"]\n', "no '/'"), + (b'version = 1\nignore = [" a"]\n', "without leading or trailing spaces"), + (b'version = 1\nignore = ["a/b"]\n', "without '/'"), (b"\xff", "not UTF-8 TOML"), (b"version = [", "not UTF-8 TOML"), ], diff --git a/tests/test_mask_step.py b/tests/test_mask_step.py index 3060c6c7..55adbb11 100644 --- a/tests/test_mask_step.py +++ b/tests/test_mask_step.py @@ -58,7 +58,7 @@ def test_describe_masks_writes_the_report_the_command_writes(clean, capsys): result.path.unlink() assert main_described(["masks", "--output", str(clean.output)]) == 0 assert without_versions(clean.output / MASK_REPORT_FILENAME) == written - assert f"Report written to {result.path}" in capsys.readouterr().out + assert f"Mask check completed. Relationships saved to {result.path}." in capsys.readouterr().out def test_without_an_experiment_or_a_recorded_run_the_step_is_refused(tmp_path): diff --git a/tests/test_mask_ties.py b/tests/test_mask_ties.py index c784a9af..2a60bf1b 100644 --- a/tests/test_mask_ties.py +++ b/tests/test_mask_ties.py @@ -192,11 +192,12 @@ def test_the_report_and_its_texts_show_the_tie(tmp_path): (written,) = [p for p in data["pairs"] if (p["child"], p["parent"]) == ("Nuclei", "Cells")] assert written["evidence"]["ambiguous_parent"] == 2 assert mask_ambiguous_lines(report) == [ - "Nuclei in Cells: 2 objects of 4 equally in two or more Cells" + "Nuclei in Cells: 2 of 4 Nuclei labels overlap two or more Cells labels equally; no " + "parent was assigned" ] text = mask_report_summary(report) - assert "Objects given no parent (equally in two or more objects" in text - assert "Nuclei in Cells: 2 objects of 4" in text + assert "Objects with no assigned parent because of equal overlap" in text + assert "Nuclei in Cells: 2 of 4 Nuclei labels" in text def test_the_relationship_table_has_the_tied_children(tmp_path): diff --git a/tests/test_notebook_mask_step.py b/tests/test_notebook_mask_step.py index 6f9ace95..b1aab3e3 100644 --- a/tests/test_notebook_mask_step.py +++ b/tests/test_notebook_mask_step.py @@ -161,7 +161,10 @@ def test_a_child_equally_in_two_parents_is_shown_with_no_parent(tmp_path): nb.mask_step_button.click() shown = nb.mask_step_result.value assert "Objects given no parent (a tie, to check)" in shown - assert "
  • nuclei in cells: 4 objects of 4 equally in two or more cells
  • " in shown + assert ( + "
  • nuclei in cells: 4 of 4 nuclei labels overlap two or more cells labels equally; " + "no parent was assigned
  • " in shown + ) def test_a_locked_output_folder_shows_the_lock_card_and_writes_nothing(tmp_path): diff --git a/tests/test_notebook_tag_by_repeat_drafts.py b/tests/test_notebook_tag_by_repeat_drafts.py index d24839eb..e54c1131 100644 --- a/tests/test_notebook_tag_by_repeat_drafts.py +++ b/tests/test_notebook_tag_by_repeat_drafts.py @@ -18,7 +18,10 @@ from dataclasses import replace # noqa: E402 from morphobricks_preprocessing.description_file import DRAFT_FILENAME # noqa: E402 -from morphobricks_preprocessing.draft_format import answers_from_bytes, answers_to_bytes # noqa: E402 +from morphobricks_preprocessing.draft_format import ( # noqa: E402 + answers_from_bytes, + answers_to_bytes, +) from test_notebook_channels import set_labels # noqa: E402 from test_notebook_check_save import opened # noqa: E402 from test_notebook_tag_by_repeat import EXTRA # noqa: E402 diff --git a/tests/test_notebook_tissue_mask.py b/tests/test_notebook_tissue_mask.py index f54ee53f..56e43987 100644 --- a/tests/test_notebook_tissue_mask.py +++ b/tests/test_notebook_tissue_mask.py @@ -91,7 +91,7 @@ def test_the_preview_writes_nothing_and_shows_the_shares_and_notes(tmp_path, mon ) text = card.numbers.value assert "kept 80.4 % · nuclei 1.6 % · red cells 0.8 % · empty 17.2 %" in text - assert "Sizes are in pixels. Fixed rule he_tissue_v2 (provisional)" in text + assert "Tissue-mask rule: he_tissue_v2 (provisional" in text assert "this mask will not be reused on retry" in text # an unverified identity diff --git a/tests/test_report.py b/tests/test_report.py index 4c9dafa6..e0abf13f 100644 --- a/tests/test_report.py +++ b/tests/test_report.py @@ -124,7 +124,7 @@ def test_run_summaries(experiment): def test_run_summary_when_blocked(experiment): result = run_described(experiment, prefill_mapping("TYX"), bin_count=0) - assert run_summary(result).startswith("The run stopped (1 error") + assert run_summary(result).startswith("Preprocessing stopped (1 error") def test_group_summaries_pool_the_planes(experiment): diff --git a/tests/test_run_description.py b/tests/test_run_description.py index def8459c..7d6e3541 100644 --- a/tests/test_run_description.py +++ b/tests/test_run_description.py @@ -111,7 +111,9 @@ def test_an_invalid_description_stops_the_run_with_its_code_and_path(tmp_path): assert not result.written and not (out / "run_manifest.json").exists() assert result.issues and all(i.is_error for i in result.issues) assert result.issues[0].code.startswith("E_") - assert "morphobricks.toml cannot be used" in result.issues[0].message + message = result.issues[0].message # its plain meaning first, then the path and code + assert "The experiment description (morphobricks.toml) is not an experiment" in message + assert "(at schema, value 'wrong', E_SCHEMA_ID)" in message def test_an_unreadable_records_file_stops_the_run(tmp_path): diff --git a/tests/test_stopped_run_text.py b/tests/test_stopped_run_text.py index a8290d96..aa23bae7 100644 --- a/tests/test_stopped_run_text.py +++ b/tests/test_stopped_run_text.py @@ -27,8 +27,8 @@ def test_a_stopped_api_run_records_that_its_report_was_written(tmp_path): result = run_described(root, prefill_mapping("ZYX"), output_folder=output) # wrong roles assert not result.written and result.report_written text = run_summary(result) - assert text.startswith("The run stopped (") - assert "no table or manifest was written" in text + assert text.startswith("Preprocessing stopped (") + assert "No new histogram table or run manifest was published" in text assert f"Written to {output}: discovery_report.json and discovery_report.txt" in text assert "experiment_design.csv" not in text