diff --git a/docs/AUTHORING.md b/docs/AUTHORING.md index e083184..7a14811 100644 --- a/docs/AUTHORING.md +++ b/docs/AUTHORING.md @@ -70,6 +70,7 @@ Return one value or a tuple. Annotate the return type with what it is: | `Annotated[ShapesOut, ApplyTo("image")]` | `labels_to_shapes(labels)` from `labconstrictor_tools.shapes` (needs scikit-image), a GeoJSON FeatureCollection, or a list of polygons (arrays of `(y, x)` vertices, or dicts with `polygon` plus properties) -> Napari shapes layer, Fiji polygon ROIs, QuPath annotations | | `Annotated[ImageOut, Name("view"), Replace()]` | each run replaces the previous result named `view` (Napari layer / Fiji window) instead of adding "view [1]" | | `Annotated[ImageOut, Name("aligned"), Axes("YX")]` | name the output / say what its axes are | +| `return WithAxes(array, axes)` (for an `ImageOut` / `LabelsOut`) | the axes of this result, when they depend on the input (for example the axes the person typed). With axes in ImageJ order (`TYX`, `TZYX`, `ZCYX`, `TZCYX`...), from `Axes` or `WithAxes`, Fiji opens the result as a hyperstack with its dimensions instead of one long stack; the array is never reordered | ## Rules that keep it fast and pleasant diff --git a/docs/CAPABILITIES.md b/docs/CAPABILITIES.md index c58d3ba..f12528b 100644 --- a/docs/CAPABILITIES.md +++ b/docs/CAPABILITIES.md @@ -35,7 +35,7 @@ Good to know: | Result | napari | Fiji | QuPath | Notebook | Command line | |---|---|---|---|---|---| -| Image, label image | Yes: a new layer | Yes: a new window | Partial: a preview, with an "Open in QuPath" button | Partial: a picture of the first plane | Yes: a TIFF file | +| Image, label image | Yes: a new layer | Yes: a new window; a time-lapse or stack opens with its dimensions when the tool states its axes | Partial: a preview, with an "Open in QuPath" button | Partial: a picture of the first plane | Yes: a TIFF file | | Table | Yes: a table panel | Yes: a Results table | Yes: a table in the results window | Yes | Yes: a CSV file | | Numbers and short values | Yes: in the status line | Yes: in the Log window | Yes: in the results window | Yes | Yes | | Message | Yes | Yes: the Log window and a dialog | Yes | Yes | Yes | diff --git a/docs/HOST_FEATURES.md b/docs/HOST_FEATURES.md index e039de5..94b4cd1 100644 --- a/docs/HOST_FEATURES.md +++ b/docs/HOST_FEATURES.md @@ -46,7 +46,7 @@ Each host reads the registry. Which app each host offers is the app's own `hosts | Progress, Cancel, kept worker, run details | yes | progress and Esc to cancel; a new worker for each run; an error dialog | yes | | Fiji macro | no | a macro line typed by hand runs the tool without a dialog (jar only); the Macro Recorder does not record the plugin | no | -Not yet in any host: tracks, time-lapse and 3D axes, figure output, Repeat, batch. +Not yet in any host: tracks, time-lapse and 3D axes of inputs (a result with known axes does open in Fiji as a hyperstack: `result_axes_v1`), figure output, Repeat, batch. How this table is kept honest: each row has a test in the host's own suite that runs the example app (`labconstrictor_tools.examples.interactions`); a change that breaks a row fails that suite. diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index caa4f3b..f08e458 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -48,6 +48,8 @@ Output names are file names (`.tif`, `.csv`, `.geojson` in the result fold `axes` (an input or an image/labels output) is a string of distinct labels from `T C Z Y X S`, one per array dimension, otherwise a `DeclarationError`. A declared output `axes` is a promise: an array with another number of dimensions is `bad_return` and nothing is written; without `axes` the host gets `YX`, `ZYX` or `CZYX` for 2, 3 or 4 dimensions and no `axes` claim otherwise. +A tool whose output axes depend on its input states them when it runs: it returns `WithAxes(array, "TZYX")` for that output (same letters; a declared `axes` must be the same, otherwise `bad_return`), and the result's `axes` are the returned ones. An image/labels result whose axes are known, declared or returned, with more than two dimensions and none of size 1 (ImageJ cannot record a T, Z or C of size 1), its axes a subsequence of `T Z C Y X` ending in `Y X`, a pixel type ImageJ stores (uint8, uint16, int16, float32) and less than 4 GiB is written as an ImageJ hyperstack TIFF: Fiji opens it with its time points, slices and channels. The array is never reordered, so `tifffile.imread` gives the same array as without the hyperstack metadata. Every other result, including one whose axes are only the default guess above, is written as before (feature `result_axes_v1`). + `folder` is a directory path (the worker checks it exists); hosts show a folder chooser. Output `type`: `image labels table values affine file message points shapes`. `message`: `{text}` (plain text, short). `points`: `{path, n, columns, apply_to?}`, a CSV whose first two columns are `y` and `x` (finite pixel coordinates in the frame of the image named by `apply_to`, else of the first image); other columns are properties of each point. `shapes`: `{path, n, apply_to?}`, a GeoJSON FeatureCollection file (`.geojson`) of Polygon / MultiPolygon features, `[x, y]` coordinates in the same frame and with pixel centres at integers; feature properties are kept (a `label` property links an outline to its label). A host that does not know `shapes` lists the file. Hosts must skip (and report) a schema whose `protocol` they do not support. @@ -68,6 +70,7 @@ Feature ids (the implemented ones are in `FEATURES`; a planned id appears there | `shm_order_v1` | a shared-memory image descriptor's `order` is honoured: `C` / `C_ORDER` (or no `order`) and `F` / `F_ORDER` read the block in the order it was written, the tool always gets a C-ordered copy; any other value is refused with `unreadable_image` and a message naming `'C' or 'F'` (a block read in the wrong order would give the transposed image with no error) | in 0.3.0a1 (the one id added after its behaviour: older versions behave the same but cannot be told apart). A host that sends `F` blocks requires it | | `app_hosts_v1` | `register` records the app's declared `hosts` (a list of `notebook`, `napari`, `fiji`, `qupath`) in the registry entry, and every host lists an app only for a host named in that list ([App hosts](#app-hosts-which-host-lists-an-app) below); an entry without `hosts` stays listed in every host and says so | in 0.3.0a1. Napari, Fiji and QuPath honour the rule and require it | | `host_requirements_v1` | `register --app-manifest` records the app's `host_requirements` (the oldest napari, Fiji or QuPath plugin it needs, and host feature ids) in the registry entry; `host_requirements.check` gives every host the same verdict and sentence ([Host requirements](#host-requirements-which-plugin-an-app-needs) below) | in 0.3.0a2 (tag `v0.3.0-alpha.2`); applied by napari `v0.1.0-alpha.5`, Fiji `v0.1.0-alpha.7` and QuPath `v0.1.0-alpha.7` and later | +| `result_axes_v1` | an image/labels result whose axes are known (declared `axes`, or returned with `WithAxes`) and in ImageJ order is written as an ImageJ hyperstack TIFF, so Fiji opens it with its dimensions; the array is never reordered, and the result's `axes` are the returned ones ([Schema](#schema-what-hosts-read) above) | in 0.3.0a4. Hosts need nothing new: Fiji's TIFF reader reads the hyperstack, other readers get the same array | ### Compatibility rules for hosts A host that needs a minimum states it as `(min_tools_version, required_features)` and applies the rules below to every schema it loads, with `labconstrictor_tools.compat.check_schema` (Python hosts: Napari, notebooks) or the same rules written in its own language (Fiji, QuPath; the data is in `conformance.json`, [CONFORMANCE.md](CONFORMANCE.md), `compat` section). The result is `ok`, `warn` or `refuse`, with one sentence for the person: diff --git a/labconstrictor_tools/__init__.py b/labconstrictor_tools/__init__.py index ae6efd3..393ce25 100644 --- a/labconstrictor_tools/__init__.py +++ b/labconstrictor_tools/__init__.py @@ -39,6 +39,7 @@ ToolError, Unit, Widget, + WithAxes, ) __all__ = [ @@ -54,6 +55,7 @@ "RegionOf", "ShapesOut", "Widget", + "WithAxes", "Description", "EnabledWhen", "File", diff --git a/labconstrictor_tools/_version.py b/labconstrictor_tools/_version.py index d452a36..ca13e53 100644 --- a/labconstrictor_tools/_version.py +++ b/labconstrictor_tools/_version.py @@ -1,3 +1,3 @@ """The one place the Tools version is written. pyproject.toml reads it (dynamic version); everything else imports it.""" -__version__ = "0.3.0a3" +__version__ = "0.3.0a4" diff --git a/labconstrictor_tools/convert.py b/labconstrictor_tools/convert.py index 9f1bfaf..b8069f7 100644 --- a/labconstrictor_tools/convert.py +++ b/labconstrictor_tools/convert.py @@ -18,7 +18,7 @@ from .protocol import RESERVED_INPUTS, RESERVED_PREFIX from .structures import OutputSchema, ParamSchema, Result, ToolSchema -from .types import ToolError +from .types import ToolError, WithAxes UINT16_MAX = ( 65535 # integer images within the 16-bit ranges are narrowed to uint16 / int16, which every host opens @@ -654,22 +654,81 @@ def _photometric(array: Any) -> str | None: return "rgb" if rgb else "minisblack" +IMAGEJ_ORDER = "TZCYX" # the order of an ImageJ hyperstack; T, Z and C may be left out +IMAGEJ_DTYPES = ("uint8", "uint16", "int16", "float32") # what tifffile writes as an ImageJ hyperstack +IMAGEJ_MAX_BYTES = 2**32 - 2**25 # an ImageJ TIFF is a classic TIFF (4 GiB at most, with room for its tags) + + +def _stated_axes(kind: str, name: str, axes: Any, declared: str | None) -> str: + """The axes a tool returned with `WithAxes`: distinct letters from T C Z Y X S, and the same as a declared `Axes`, or `bad_return`.""" + from .introspection import AXIS_LABELS + + if ( + not isinstance(axes, str) + or not axes + or len(set(axes)) != len(axes) + or any(c not in AXIS_LABELS for c in axes) + ): + raise ToolError( + "bad_return", + "the %s output '%s' was returned with axes %r: use distinct letters from %s, one per dimension, e.g. 'TZYX'" + % (kind, name, axes, ", ".join(AXIS_LABELS)), + ) + if declared and axes != declared: + raise ToolError( + "bad_return", + "the %s output '%s' is declared %s but was returned with axes %s" % (kind, name, declared, axes), + ) + return axes + + +def _imagej_hyperstack(array: Any, axes: str) -> bool: + """True when a result with these (known) axes is written as an ImageJ hyperstack: more than two dimensions, none of size 1 + (ImageJ cannot record a T, Z or C of size 1, so tifffile would read the array back without it), the axes a subsequence of + T Z C Y X that ends in Y X (so the array is never reordered), a pixel type ImageJ stores, and less than 4 GiB (an ImageJ + TIFF is never a BigTIFF). + """ + if array.ndim < 3 or min(array.shape) < 2 or array.nbytes >= IMAGEJ_MAX_BYTES: + return False + if not axes.endswith("YX") or any(c not in IMAGEJ_ORDER for c in axes): + return False + positions = [IMAGEJ_ORDER.index(c) for c in axes] + return positions == sorted(positions) and str(array.dtype) in IMAGEJ_DTYPES + + def _write_one(out: OutputSchema, value: Any, job_dir: Path) -> Result: kind, name = out["type"], out["name"] if kind in ("image", "labels"): import tifffile - array = portable_dtype(_as_array(kind, name, value), name) declared = out.get("axes") - if declared and array.ndim != len(declared): + stated = None + if isinstance(value, WithAxes): + stated = _stated_axes(kind, name, value.axes, declared) + value = value.array + array = portable_dtype(_as_array(kind, name, value), name) + known = stated or declared + if known and array.ndim != len(known): raise ToolError( "bad_return", - "the %s output '%s' is declared %s (%dD) but the tool returned a %dD array of shape %s" - % (kind, name, declared, len(declared), array.ndim, tuple(array.shape)), + "the %s output '%s' is %s %s (%dD) but the tool returned a %dD array of shape %s" + % ( + kind, + name, + "returned with axes" if stated else "declared", + known, + len(known), + array.ndim, + tuple(array.shape), + ), ) path = _job_file(job_dir, name, ".tif") - tifffile.imwrite(path, array, photometric=_photometric(array)) - axes = declared or DEFAULT_AXES.get(array.ndim, "") + if known and _imagej_hyperstack(array, known): + # Fiji opens it with its time points, slices and channels; tifffile reads back the same array (same order, shape, values). + tifffile.imwrite(path, array, imagej=True, metadata={"axes": known}) + else: + tifffile.imwrite(path, array, photometric=_photometric(array)) + axes = known or DEFAULT_AXES.get(array.ndim, "") return {"type": kind, "name": name, "path": str(path), "axes": axes} if kind == "table": frame = _as_frame("table", name, value) diff --git a/labconstrictor_tools/examples/roundtrip.py b/labconstrictor_tools/examples/roundtrip.py index 3275024..6acec37 100644 --- a/labconstrictor_tools/examples/roundtrip.py +++ b/labconstrictor_tools/examples/roundtrip.py @@ -84,6 +84,18 @@ def echo_image( return image, _array_report(image) +@tool("Echo image with axes") +def echo_image_with_axes( + image: Image, + axes: str, +) -> tuple[Annotated[ImageOut, Name("image")], Annotated[Scalars, Name("received")]]: + """Returns the image it received with the axes it is given (WithAxes): an ImageJ hyperstack when the axes and the shape + allow it, the same array either way.""" + from labconstrictor_tools import WithAxes + + return WithAxes(image, axes), _array_report(image) + + @tool("Make an array") def make_array(kind: Literal["empty", "complex", "object", "text"]) -> Annotated[ImageOut, Name("image")]: """Returns an array that no host can open as an image: the result must be refused with a readable message.""" diff --git a/labconstrictor_tools/features.py b/labconstrictor_tools/features.py index fb732b4..4595c7d 100644 --- a/labconstrictor_tools/features.py +++ b/labconstrictor_tools/features.py @@ -12,5 +12,6 @@ "shm_order_v1": "a shared-memory image descriptor's `order` is honoured for C and F (a block is read in the order it was written) and anything else is refused with unreadable_image", "app_hosts_v1": "`register` records the app's declared `hosts` (notebook, napari, fiji, qupath) in the registry entry and every host lists an app only for a host in that list (app_hosts.listed_for); an entry without `hosts` is listed everywhere, and said so", "host_requirements_v1": "`register --app-manifest` records the app's `host_requirements` (the oldest napari, Fiji or QuPath plugin and the host features it needs) in the registry entry, and host_requirements.check gives every host the same ok / warn / refuse verdict and sentence", + "result_axes_v1": "an image or label result whose axes are known (declared with Axes, or returned with WithAxes) and in ImageJ order (T, Z, C, Y, X) is written as an ImageJ hyperstack TIFF, so Fiji opens it with its dimensions; the array is never reordered, and the result's `axes` are the returned ones", "retention_prune": "the CLI command `prune` and the `retention` module: only marker-owned, finished folders under results/ and runs/ are removed (hosts only mark a run finished)", } diff --git a/labconstrictor_tools/types.py b/labconstrictor_tools/types.py index 32724bc..3b3fc6d 100644 --- a/labconstrictor_tools/types.py +++ b/labconstrictor_tools/types.py @@ -68,6 +68,20 @@ class Affine: "3x3 homogeneous matrix in (y,x) pixel coordinates mapping SOURCE pixels -> TARGET pixels" +class WithAxes: + """An image or label result together with its axes, for a tool whose axes are only known when it runs (the axes the person + typed, for example): `return WithAxes(corrected, "TZYX")`. One letter per dimension, from T C Z Y X S. When the axes are in + ImageJ's order (T, Z, C, then Y X), the result is written as an ImageJ hyperstack, so Fiji opens it with its dimensions; the + array is never reordered. An `Axes(...)` declared on the output, if any, must be the same.""" + + def __init__(self, array: object, axes: str) -> None: + self.array = array + self.axes = axes + + def __repr__(self) -> str: + return "WithAxes(<%s>, %r)" % (type(self.array).__name__, self.axes) + + INPUT_TYPES = {Image: "image", Labels: "labels", Table: "table", File: "file", Folder: "folder"} OUTPUT_TYPES = { ImageOut: "image", diff --git a/tests/roundtrip_cases.py b/tests/roundtrip_cases.py index c038436..50613c0 100644 --- a/tests/roundtrip_cases.py +++ b/tests/roundtrip_cases.py @@ -442,6 +442,42 @@ def add(case_id: str, tool: str, a: Any, out_name: str, group: str, heavy: bool return cases +def image_axes_cases() -> list[Case]: + """Images returned with their axes (WithAxes, feature result_axes_v1): written as an ImageJ hyperstack when the axes are in + ImageJ order and no dimension is 1, as before otherwise; the array read back is the one sent, every time. + """ + cases: list[Case] = [] + shapes = ( + ("TYX", (4, 6, 7)), + ("TZYX", (3, 4, 6, 7)), + ("ZCYX", (4, 2, 6, 7)), + ("CYX", (3, 6, 7)), + ("TZCYX", (2, 3, 2, 6, 7)), + ("TZYX", (3, 1, 6, 7)), # a single slice: ImageJ cannot record it, written as before + ("TZYX", (1, 4, 6, 7)), # a single time point + ("ZYX", (1, 6, 7)), + ("ZCYX", (4, 1, 6, 7)), # a single channel + ("TZYX", (3, 4, 6, 1)), # X of size 1 + ("CZYX", (2, 3, 6, 7)), # not ImageJ order: never reordered + ) + for axes, shape in shapes: + for dtype in ("uint8", "uint16", "float32", "bool"): + a = ramp(shape, dtype) + case_id = "%s/%s/%s" % (dtype, axes, "x".join(str(n) for n in shape)) + cases.append( + Case( + "echo_image_with_axes/%s" % case_id, + "echo_image_with_axes", + {"image": a, "axes": axes}, + _image_expect(a, "image"), + ("worker", "cli", "snippet", "notebook"), + False, + "image_axes", + ) + ) + return cases + + def labels_cases() -> list[Case]: cases: list[Case] = [] for dtype in LABEL_DTYPES: @@ -2507,7 +2543,7 @@ def all_cases() -> tuple[Case, ...]: """Every case, deterministic order. Ids are unique.""" cases: list[Case] = [] for generator in ( - image_cases, labels_cases, outline_cases, _scalar_cases, _choice_cases, _default_cases, _nullable_cases, _bound_cases, + image_cases, image_axes_cases, labels_cases, outline_cases, _scalar_cases, _choice_cases, _default_cases, _nullable_cases, _bound_cases, table_cases, points_cases, shapes_cases, affine_cases, message_cases, scalars_out_cases, file_cases, transform_cases, ): # fmt: skip cases.extend(generator()) diff --git a/tests/test_result_axes.py b/tests/test_result_axes.py new file mode 100644 index 0000000..b8b98d6 --- /dev/null +++ b/tests/test_result_axes.py @@ -0,0 +1,210 @@ +"""Result images with known axes: an ImageJ hyperstack when the axes are in ImageJ order, never a reordered array. + +A tool states the axes of an image result with `Axes(...)` on the output or, when they depend on its input, by returning +`WithAxes(array, axes)`. Axes that are a subsequence of T Z C Y X (ending in Y X) and a pixel type ImageJ stores give an ImageJ +hyperstack TIFF, so Fiji opens a time-lapse with its time points instead of one long stack. Reading the file back gives the same +array, so napari, notebooks and the case runner see what they saw before. Anything else is written as before (feature +`result_axes_v1`). +""" + +import tempfile +import unittest +from pathlib import Path +from typing import Any + +import numpy as np +import tifffile + +from labconstrictor_tools import ToolError, WithAxes, convert, features + + +def write(value: Any, axes: str | None = None) -> tuple[dict[str, Any], Path]: + out: dict[str, Any] = {"type": "image", "name": "result"} + if axes: + out["axes"] = axes + result = convert._write_one(out, value, Path(tempfile.mkdtemp())) # type: ignore[arg-type] + return dict(result), Path(result["path"]) + + +def imagej(path: Path) -> dict[str, Any] | None: + with tifffile.TiffFile(path) as tif: + return tif.imagej_metadata + + +def array(shape: tuple[int, ...], dtype: Any = np.float32) -> Any: + return (np.arange(int(np.prod(shape))) % 251).astype(dtype).reshape(shape) + + +class ImageJHyperstacks(unittest.TestCase): + CASES = ( # axes, shape, (frames, slices, channels) ImageJ records + ("TYX", (5, 8, 10), (5, None, None)), + ("TZYX", (4, 3, 8, 10), (4, 3, None)), + ("ZCYX", (3, 2, 8, 10), (None, 3, 2)), + ("CYX", (3, 8, 10), (None, None, 3)), + ("TZCYX", (2, 3, 2, 8, 10), (2, 3, 2)), + ) + + def test_returned_axes_give_a_hyperstack_and_the_same_array(self) -> None: + for axes, shape, (frames, slices, channels) in self.CASES: + for dtype in (np.uint8, np.uint16, np.int16, np.float32): + data = array(shape, dtype) + with self.subTest(axes=axes, dtype=np.dtype(dtype).name): + result, path = write(WithAxes(data, axes)) + meta = imagej(path) + assert meta is not None + self.assertEqual( + (meta.get("frames"), meta.get("slices"), meta.get("channels")), + (frames, slices, channels), + ) + self.assertTrue(meta.get("hyperstack")) + back = tifffile.imread(path) + self.assertEqual(back.dtype, data.dtype) + np.testing.assert_array_equal(back, data) + self.assertEqual(result["axes"], axes) + + def test_declared_axes_in_imagej_order_give_a_hyperstack(self) -> None: + result, path = write(array((4, 3, 8, 10)), axes="TZYX") + meta = imagej(path) + assert meta is not None + self.assertEqual((meta.get("frames"), meta.get("slices")), (4, 3)) + self.assertEqual(result["axes"], "TZYX") + + def test_three_channels_with_axes_open_in_fiji_too(self) -> None: + """The case of #163, now with axes: a hyperstack of 3 channels (Fiji opens it), the same array back.""" + data = array((3, 8, 10)) + _, path = write(WithAxes(data, "CYX")) + np.testing.assert_array_equal(tifffile.imread(path), data) + meta = imagej(path) + assert meta is not None + self.assertEqual(meta.get("channels"), 3) + + +class WrittenAsBefore(unittest.TestCase): + def test_unknown_axes_are_never_guessed_into_a_hyperstack(self) -> None: + """A 4D result without axes is labelled CZYX by default; that guess must not decide how Fiji shows it.""" + data = array((4, 3, 8, 10)) + result, path = write(data) + self.assertIsNone(imagej(path)) + self.assertEqual(result["axes"], "CZYX") + np.testing.assert_array_equal(tifffile.imread(path), data) + + def test_axes_not_in_imagej_order_are_kept_and_the_array_is_not_reordered(self) -> None: + for axes, shape in ( + ("CZYX", (2, 3, 8, 10)), + ("ZTYX", (3, 4, 8, 10)), + ("YXC", (8, 10, 3)), + ("YXS", (8, 10, 3)), + ): + data = array(shape, np.uint8 if axes == "YXS" else np.float32) + with self.subTest(axes=axes): + result, path = write(WithAxes(data, axes)) + self.assertIsNone(imagej(path)) + np.testing.assert_array_equal(tifffile.imread(path), data) + self.assertEqual(result["axes"], axes) + + def test_a_pixel_type_imagej_cannot_store_is_written_as_before(self) -> None: + """portable_dtype leaves a big-endian 16-bit array as it is; tifffile cannot write it in ImageJ mode.""" + data = array((4, 8, 10), ">u2") + _, path = write(WithAxes(data, "TYX")) + self.assertIsNone(imagej(path)) + np.testing.assert_array_equal(tifffile.imread(path), data) + + def test_a_dimension_of_size_1_is_never_dropped(self) -> None: + """ImageJ cannot record a T, Z or C of size 1: such a result is written as before and reads back with every dimension, + also when only Axes is declared (found by an independent review).""" + cases = ( + ("TZYX", (3, 1, 8, 9), True), + ("TZYX", (1, 4, 8, 9), True), + ("TYX", (1, 8, 9), True), + ("ZYX", (1, 8, 9), False), + ("ZCYX", (4, 1, 8, 9), True), + ("TZYX", (3, 4, 8, 1), True), + ) + for axes, shape, returned in cases: + data = array(shape, np.uint8) + with self.subTest(axes=axes, shape=shape, returned=returned): + result, path = write(WithAxes(data, axes)) if returned else write(data, axes=axes) + self.assertIsNone(imagej(path)) + back = tifffile.imread(path) + self.assertEqual(back.shape, data.shape) + np.testing.assert_array_equal(back, data) + self.assertEqual(result["axes"], axes) + + def test_a_result_of_4_gib_or_more_is_written_as_before(self) -> None: + """An ImageJ TIFF is never a BigTIFF: above the limit the result is written as before (the limit is lowered here).""" + data = array((4, 8, 10), np.uint16) + limit = convert.IMAGEJ_MAX_BYTES + convert.IMAGEJ_MAX_BYTES = data.nbytes + try: + _, path = write(WithAxes(data, "TYX")) + finally: + convert.IMAGEJ_MAX_BYTES = limit + self.assertIsNone(imagej(path)) + np.testing.assert_array_equal(tifffile.imread(path), data) + + def test_a_2d_result_is_written_as_before(self) -> None: + _, path = write(WithAxes(array((8, 10)), "YX")) + self.assertIsNone(imagej(path)) + + +class OtherResults(unittest.TestCase): + def test_a_label_result_with_axes_is_a_hyperstack_too(self) -> None: + data = array((3, 4, 8, 10), np.uint16) + out = {"type": "labels", "name": "masks"} + result = convert._write_one(out, WithAxes(data, "TZYX"), Path(tempfile.mkdtemp())) # type: ignore[arg-type] + meta = imagej(Path(result["path"])) + assert meta is not None + self.assertEqual((meta.get("frames"), meta.get("slices")), (3, 4)) + np.testing.assert_array_equal(tifffile.imread(result["path"]), data) + + def test_booleans_become_0_and_1_bytes_in_a_hyperstack(self) -> None: + data = array((3, 4, 8, 10), np.uint8) % 2 == 0 + _, path = write(WithAxes(data, "TZYX")) + self.assertIsNotNone(imagej(path)) + np.testing.assert_array_equal(tifffile.imread(path), data.astype(np.uint8)) + + def test_a_declared_axes_result_reads_back_the_same(self) -> None: + for axes, shape in (("ZYX", (4, 8, 10)), ("ZYX", (4, 8, 3)), ("CYX", (3, 8, 10))): + data = array(shape, np.uint8) + with self.subTest(axes=axes, shape=shape): + _, path = write(data, axes=axes) + self.assertIsNotNone(imagej(path)) + back = tifffile.imread(path) + self.assertEqual(back.shape, data.shape) + np.testing.assert_array_equal(back, data) + + +class Refusals(unittest.TestCase): + def refused(self, value: Any, axes: str | None = None) -> str: + with self.assertRaises(ToolError) as caught: + write(value, axes) + self.assertEqual(caught.exception.code, "bad_return") + return caught.exception.message + + def test_axes_that_do_not_fit_the_array(self) -> None: + self.assertIn("returned with axes TZYX (4D)", self.refused(WithAxes(array((5, 8, 10)), "TZYX"))) + + def test_letters_that_are_not_axes_or_repeated(self) -> None: + for axes in ("TQX", "TTYX", "", 3): + with self.subTest(axes=axes): + self.assertIn("was returned with axes", self.refused(WithAxes(array((5, 8, 10)), axes))) # type: ignore[arg-type] + + def test_returned_axes_must_agree_with_the_declared_ones(self) -> None: + self.assertIn( + "is declared TZYX but was returned with axes ZCYX", + self.refused(WithAxes(array((4, 3, 8, 10)), "ZCYX"), "TZYX"), + ) + + def test_the_wrapped_value_is_still_checked(self) -> None: + self.assertIn("array of numbers", self.refused(WithAxes("not an image", "YX"))) + + +class FeatureId(unittest.TestCase): + def test_the_feature_is_listed_and_documented(self) -> None: + self.assertIn("result_axes_v1", features.FEATURES) + protocol = (Path(__file__).resolve().parents[1] / "docs" / "PROTOCOL.md").read_text(encoding="utf-8") + self.assertIn("`result_axes_v1`", protocol) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_run_record_builder.py b/tests/test_run_record_builder.py index 3a275e4..b42210a 100644 --- a/tests/test_run_record_builder.py +++ b/tests/test_run_record_builder.py @@ -256,5 +256,12 @@ def test_there_is_no_feature_id_for_them(self) -> None: self.assertEqual( sorted(features.FEATURES), - ["app_hosts_v1", "host_requirements_v1", "reserved_inputs_v1", "retention_prune", "shm_order_v1"], + [ + "app_hosts_v1", + "host_requirements_v1", + "reserved_inputs_v1", + "result_axes_v1", # result files (0.3.0a4), not run records + "retention_prune", + "shm_order_v1", + ], ) diff --git a/tests/test_tools_features.py b/tests/test_tools_features.py index 3775fe8..9b6d5ec 100644 --- a/tests/test_tools_features.py +++ b/tests/test_tools_features.py @@ -32,7 +32,14 @@ def test_the_ids_of_this_version(self) -> None: # shm_order_v1 (PR #125) is what tells 0.3.0a1 from the rc.1 / rc.2 / main that all reported 0.2.0rc1 with the first two self.assertEqual( sorted(features.FEATURES), - ["app_hosts_v1", "host_requirements_v1", "reserved_inputs_v1", "retention_prune", "shm_order_v1"], + [ + "app_hosts_v1", + "host_requirements_v1", + "reserved_inputs_v1", + "result_axes_v1", + "retention_prune", + "shm_order_v1", + ], ) text = (ROOT / "docs" / "PROTOCOL.md").read_text(encoding="utf-8") self.assertIn("the one id added after its behaviour", text)