Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,27 @@ refuses the skipped label images as unrecorded: refused, never silently wrong.

### Fixed

- **`check` checks what the next `run` reads**: without `--exclude` and `--masks`, it takes the
earlier run's exclusions and masks folder, as `run` does, and says so. A check of an output
folder whose run used `--masks` checked no masks before.
- **Without `--comparable`, `describe` says where to answer for repeats that are not comparable**:
the notebook's *Check and save* card (step 1); the command line has no answer for them.
- **`tissue-mask` checks the rule, the `he-mask` extra and every image before it creates a masks
folder**: a refusal (scikit-image missing, an image not declared rgb or not 8-bit RGB) used to
come after the folder was created and recorded in the run manifest.
- **`declare-masks --type ... --ignore ...` either applies both or neither**: the `--ignore`
values (names, a type also declared, a missing output folder, an unreadable
`ignored_masks.toml`) are checked before any type is declared (`mask_declare.check_ignore`).
- **`describe` refuses the fast-mode options (`--channels`, `--image-type`, `--accept-ids`,
`--comparable`, `--confirmed-on`) for an output folder whose description is published**: they
were ignored, so a changed channel list looked accepted. Nothing is written; the message names
the options, the notebook and another output folder.
- **`describe --publish` exits with status 1 when the image headers contradict the published
description** (it printed "Nothing to publish" and exited 0, so a script read it as a success).
- **`convert` refuses axis roles that put an RGB image's colours on rows or columns**
(`rgb_axes_contradict_header`, independent review of v0.10.1). `--axes CYX` on an RGB TIFF
(stored `YXS`) was written as channels of mixed colours and rows; the conversion now stops
before anything is written and names `--axes YXC`.
- **OME-Zarr copies are written in spatial chunks, so a later brick can read them in windows.**
`convert --store ome-zarr`, the notebook's OME-Zarr copy and `convert_experiment(...,
store="ome-zarr")` wrote each plane as one chunk (the whole Y and X). A windowed route
Expand Down
10 changes: 8 additions & 2 deletions docs/user_guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -858,7 +858,9 @@ 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:
suggested axis roles, for example `--axes ZCYX`. In an output folder that already holds a run,
`check` without `--exclude` or `--masks` uses that run's exclusions and masks folder, as the next
`run` does, and says so (v0.10.1). Then:

```bash
morphobricks-preprocessing run /data/exp1 --axes ZCYX
Expand Down Expand Up @@ -1084,7 +1086,10 @@ given in the notebook), so `--publish` publishes nothing from a draft made of fo
lists what is missing. For
a published description that matches the folders it says `Nothing to publish` and exits with
status 0; for one whose only change is in the image headers, it says that no answer is
missing and that the run stops until the headers fit, and exits with status 0; for one that
missing and that the run stops until the headers fit, and exits with status 1 (v0.10.1: a
header contradiction is never reported as a success); the fast-mode options (`--channels`, `--image-type`,
`--accept-ids`, `--comparable`, `--confirmed-on`) are refused for a published description, which
`describe` never changes (v0.10.1); for one that
no longer matches otherwise, it lists the new, gone or changed folders and leaves the file as
it is. Like the other commands, `describe` exits with status 1 when it reports an
error (an experiment folder that is not found, an unreadable description) and 0 otherwise.
Expand Down Expand Up @@ -1797,6 +1802,7 @@ continues.
| `copy_folder_overlaps_masks` | Error | `convert`: the folder for the copies is the masks folder, inside it, or holds it; copies there would be read as masks. Choose a folder outside the masks folder. |
| `copy_folder_not_a_folder` | Error | `convert`: the path given with `--to` is a file. Choose a folder. |
| `copy_path_too_long` | Error | `convert` on Windows: a copy would have a file whose path, while it is written in the conversion's work folder, is longer than 259 characters, or a folder whose path is longer than 247, which Windows cannot handle. Nothing is written. Choose a folder for the copies with a shorter path, or shorten the names of the images or folders named. Not checked when Windows' long paths are enabled (the `LongPathsEnabled` setting). |
| `rgb_axes_contradict_header` | Error | `convert`: an image stored as RGB colour (three samples per pixel) was given axis roles that put the colour samples on another role than C, so the copies would mix colours with rows or columns (v0.10.1). Nothing is written. Give the stored order with the colours as C: an RGB TIFF stores them last, `--axes YXC`. |
| `copy_names_collide` | Error | An OME-Zarr copy: two images of one folder differ only by their extension, so their copies would have the same name. Nothing is written. Rename or exclude one of them. |
| `copy_folder_has_links` | Error | `convert`: the folder for the copies holds symbolic links (directory junctions on Windows) or mount points, named `link -> target`, through which the copies would be written elsewhere, perhaps over the originals. Nothing is written; remove them or choose a new, empty folder. |
| `copy_folder_unreadable` | Error | `convert`: a folder below the folder for the copies cannot be read, or disappeared while it was checked, so it cannot be checked for links or mount points; it is named. Nothing is written. Make it readable or remove it, or choose a new, empty folder. |
Expand Down
46 changes: 37 additions & 9 deletions src/morphobricks_preprocessing/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
from .discovery import default_output_folder
from .image_type import review_image_type
from .log_target import log_refusal, run_log_refusal
from .manifest import RunManifest
from .mask_text import mask_summary
from .masks import mask_axes_option
from .physical_check import undeclared_mask_types
Expand Down Expand Up @@ -287,21 +288,16 @@ def _check(args: argparse.Namespace) -> int:
return 1
# As 'run' reads images lacking some axes (F10); no Z or T size without the axis.
recorded = recorded_run(args)
reused_inputs = _reuse_recorded_inputs(args, recorded)
missing = missing_as_singleton(args, recorded)
pre, review = suggested_review(command_preflight(args), missing_as_singleton=missing)
if reused_inputs:
print(reused_inputs, end="\n\n")
print(preflight_summary(pre))
if pre.discovery.leaves:
print()
print(label_tree(pre.discovery))
if pre.masks is not None:
print()
print(mask_summary(pre.masks))
if pre.dataset.balance.cells:
print()
print(balance_summary(pre.dataset.balance))
if pre.calibration.calibration is not None:
print()
print(calibration_summary(pre.calibration.calibration))
_print_found(pre)
if pre.issues:
print()
print(format_issues(pre.issues))
Expand Down Expand Up @@ -344,6 +340,38 @@ def _check(args: argparse.Namespace) -> int:
return 1 if blocked else 0 # every error printed exits with 1, as 'run' does


def _print_found(pre: Preflight) -> None:
"""Print the masks, the balance of the design and the calibration the preflight found."""
if pre.masks is not None:
print(f"\n{mask_summary(pre.masks)}")
if pre.dataset.balance.cells:
print(f"\n{balance_summary(pre.dataset.balance)}")
if pre.calibration.calibration is not None:
print(f"\n{calibration_summary(pre.calibration.calibration)}")


def _reuse_recorded_inputs(args: argparse.Namespace, recorded: RunManifest | None) -> str:
"""Take the earlier run's exclusions and masks folder where none is given, as ``run`` does.

``check`` then checks what ``run`` would read (review of v0.10.1): without this, a check
of an output folder whose run used a masks folder or exclusions checked other inputs than
the next run. Returns the line saying what was taken over ("" when nothing was).
"""
if recorded is None:
return ""
taken = []
if not args.exclude and recorded.settings.exclude:
args.exclude = list(recorded.settings.exclude)
taken.append(f"{len(args.exclude)} excluded image(s)")
folder = (recorded.masks or {}).get("folder")
if args.masks is None and folder:
args.masks = folder
taken.append(f"the masks folder {folder}")
if not taken:
return ""
return f"Checking with what the earlier run used, as the next run will: {' and '.join(taken)}."


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.

Expand Down
8 changes: 7 additions & 1 deletion src/morphobricks_preprocessing/cli_declare_masks.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from .mask_declare import (
MaskDeclaration,
MaskDeclarationRefused,
check_ignore,
declare_masks,
declared_types,
ignore_masks,
Expand Down Expand Up @@ -115,12 +116,17 @@ def declare_masks_command(args: argparse.Namespace) -> int:
return 1
try:
declarations = [parse_type(text) for text in args.types]
if args.ignore: # refused before anything is declared: both apply or neither
declaring = {item.source_type for item in declarations}
check_ignore(
args.output, args.ignore, declared={*declared_types(args.output), *declaring}
)
done = (
declare_masks(args.output, declarations, masks_folder=args.masks)
if declarations
else None
)
except (ValueError, MaskDeclarationRefused) as exc:
except (ValueError, MaskDeclarationRefused, OutputLockedError, OSError) as exc:
return _refused(exc, "Nothing was written.")
try:
ignored, changed = ignore_masks(
Expand Down
24 changes: 23 additions & 1 deletion src/morphobricks_preprocessing/cli_describe.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,12 @@
"--id names the IDs of a new fast-mode description; a published description, or the "
"strict mode, names them in the notebook. Nothing was written."
)
PUBLISHED_UNCHANGED = (
"{options} would change the published description in {output}, which describe never "
"changes. Nothing was written. To check the experiment against it, repeat the command "
"without these options. To change it, use the notebook's step 1 (Check and save); or publish a "
"new description into another output folder (--output)."
)
NOT_IN_DRAFT = (
"the channels of each acquisition, the image type and the meaning of the masks are not "
"part of this draft and are answered in the notebook; the command line cannot publish "
Expand Down Expand Up @@ -253,6 +259,10 @@ def describe_command(args: argparse.Namespace) -> int:
lines, blockers = draft_lines(draft, root), draft_blockers(draft)
if not args.strict:
lines.append(FAST_HINT)
given = _fast_options_given(args)
if found is not None and given: # never silently ignored (review of v0.10.1)
print(PUBLISHED_UNCHANGED.format(options=", ".join(given), output=output))
return 1
if found is not None and args.id: # never silently ignored
print(ID_ONLY_NEW)
return 1
Expand All @@ -269,7 +279,7 @@ def describe_command(args: argparse.Namespace) -> int:
"Nothing to publish: no answer is missing. The run stops until the image headers "
"fit the published description (headers changed, above)."
)
return 0
return 1 # a header contradiction is never a success (review of v0.10.1)
if not blockers:
print("Nothing to publish: the published description matches the folders.")
return 0
Expand Down Expand Up @@ -409,6 +419,18 @@ 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 _fast_options_given(args: argparse.Namespace) -> list[str]:
"""Return the fast-mode statements given, which only a new description can take."""
given = {
"--channels": args.channels is not None,
"--image-type": args.image_type is not None,
"--accept-ids": args.accept_ids,
"--comparable": args.comparable,
"--confirmed-on": args.confirmed_on is not None,
}
return [name for name, used in given.items() if used]


def _publish_fast(
draft: Draft,
answers: DraftAnswers,
Expand Down
24 changes: 24 additions & 0 deletions src/morphobricks_preprocessing/cli_tissue_mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import argparse
import shlex

from .he_tissue_mask import current_rule, resolved_fov
from .plane_errors import PlaneReadError
from .run_inputs import RunInputs
from .run_inputs_tissue import (
Expand Down Expand Up @@ -101,6 +102,10 @@ def tissue_mask_command(args: argparse.Namespace) -> int:
f"{run.masks_root}, where the tissue masks go. Nothing was written."
)
return 1
refused = _prerequisites(run, images, args.rule)
if refused is not None: # checked before a masks folder is created (review of v0.10.1)
print(refused)
return 1
if run.masks_root is None:
try:
run = create_masks_folder(run, args.masks).run
Expand Down Expand Up @@ -135,6 +140,25 @@ def tissue_mask_command(args: argparse.Namespace) -> int:
return 0


def _prerequisites(run: RunInputs, images: tuple[str, ...], rule: str) -> str | None:
"""Return the first refusal of the rule, scikit-image or an image; None when all are met.

Nothing is read or written: the images are checked from the run's records (declared rgb,
8-bit, three channels, one plane), the rule and the ``he-mask`` extra by
:func:`.he_tissue_mask.current_rule`.
"""
try:
current_rule(rule)
except (TypeError, ValueError, ImportError) as exc:
return f"No tissue mask written; nothing was created. {exc}"
for image in images:
try:
resolved_fov(run, image)
except ValueError as exc: # RunInputsError included
return _refusal(image, exc)
return None


def _refusal(image: str, exc: Exception) -> str:
"""Return the refusal of one image, naming the image once (a message may name it already)."""
text = str(exc).removeprefix(f"{image}: ")
Expand Down
14 changes: 14 additions & 0 deletions src/morphobricks_preprocessing/conversion_issues.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,3 +316,17 @@ def lock_issue(exc: OutputLockedError) -> ValidationIssue:
"Wait for it to finish. If none is going on (it was stopped or the computer "
f"restarted), remove the lock: {removal}",
)


def rgb_axes_issue(paths: list[str]) -> ValidationIssue:
"""Refuse axis roles that put an RGB TIFF's colour samples on another role than C."""
return error(
"rgb_axes_contradict_header",
f"{plural(len(paths), 'image')} {agree(paths, 'is', 'are')} stored as RGB colour "
"(three samples per pixel), but the axis roles given put the colour samples on "
"another role than C, so the copies would mix colours with image rows or columns. "
"Nothing was written.",
paths,
"Give the stored order of these images with the colour samples as C: an RGB TIFF "
"stores its colours last, so --axes YXC.",
)
16 changes: 16 additions & 0 deletions src/morphobricks_preprocessing/conversion_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
overlap_issue,
path_too_long_issue,
pixel_type_issue,
rgb_axes_issue,
)
from .conversion_record import CONVERTED, COPIED, PROJECTED, RECORD_FILENAME, CopyEntry
from .conversion_write import WORK_FOLDER, partial_path
Expand Down Expand Up @@ -166,6 +167,7 @@ def _plan(
for rel, meta in headers.items()
if rel in review.file_mappings and not meta.is_ome_zarr
}
issues += _rgb_contradictions(to_convert, headers, review.file_mappings)
issues += _cannot_convert(root, to_convert, headers, review.file_mappings, memory_limit)
if has_errors(issues):
return (), issues
Expand All @@ -180,6 +182,20 @@ def _plan(
return _stored(tuple(planned), issues, as_zarr)


def _rgb_contradictions(
to_convert: set[str], headers: dict[str, TiffMetadata], mappings: dict[str, AxisMapping]
) -> list[ValidationIssue]:
"""Refuse the RGB TIFFs whose colour samples (``S``) are given another role than C."""
wrong = sorted(
rel
for rel in to_convert
if headers[rel].rgb_samples
and "S" in mappings[rel].axes
and mappings[rel].roles[mappings[rel].axes.index("S")] != "C"
)
return [rgb_axes_issue(wrong)] if wrong else []


WINDOWS_MAX_PATH = 259
"""The longest path Windows handles without long-path support (``MAX_PATH`` 260, with the
terminating NUL)."""
Expand Down
4 changes: 3 additions & 1 deletion src/morphobricks_preprocessing/fast_answers.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,9 @@ def _statements(
if not comparable:
blockers.append(
"say that every biological repeat's folders were prepared and acquired under the "
"same circumstances (--comparable)"
"same circumstances (--comparable). If some were not, do not give --comparable: "
"answer for each biological repeat on the notebook's Check and save card (step 1), "
"which records the repeats that are not comparable"
)
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)")
Expand Down
53 changes: 40 additions & 13 deletions src/morphobricks_preprocessing/mask_declare.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,8 +257,42 @@ def ignore_masks(
IgnoredMasksError
A refused name, a declared type asked to be ignored, or a file that cannot be read.
"""
add = tuple(add)
declared = set(declared)
add, declared = tuple(add), set(declared)
folder = check_ignore(output_folder, add, declared=declared, read=False)
with output_lock(folder):
before = read_ignored(folder).types
after = tuple(sorted((set(before) | set(add)) - declared))
if after == before:
return after, False
path = folder / IGNORED_FILENAME
if after:
write_text_atomic(path, ignored_text(after))
else:
path.unlink()
return after, True


def check_ignore(
output_folder: str | os.PathLike,
add: Iterable[str] = (),
*,
declared: Iterable[str] = (),
read: bool = True,
) -> Path:
"""Refuse what :func:`ignore_masks` would refuse, writing nothing; return the folder.

``declare-masks`` calls it before declaring anything, with the types about to be declared
in ``declared``, so ``--type`` and ``--ignore`` given together either both apply or
neither does (review of v0.10.1). With ``read``, the ignore list is read too, so an
unreadable file is refused first.

Raises
------
IgnoredMasksError
A refused name, a declared type asked to be ignored, a missing output folder or (with
``read``) an ignore list that cannot be read.
"""
add, declared = tuple(add), set(declared)
for name in add:
if name_problem(name) is not None:
raise IgnoredMasksError(f"--ignore {name!r}: {name_problem(name)}")
Expand All @@ -271,20 +305,13 @@ def ignore_masks(
folder = Path(output_folder)
if not folder.is_dir():
raise IgnoredMasksError(f"The output folder {folder} does not exist.")
with output_lock(folder):
before = read_ignored(folder).types
after = tuple(sorted((set(before) | set(add)) - declared))
if after == before:
return after, False
path = folder / IGNORED_FILENAME
if after:
write_text_atomic(path, ignored_text(after))
else:
path.unlink()
return after, True
if read:
read_ignored(folder)
return folder


__all__ = [
"check_ignore",
"DeclaredMasks",
"MaskDeclaration",
"MaskDeclarationRefused",
Expand Down
Loading
Loading