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
1 change: 1 addition & 0 deletions docs/AUTHORING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion docs/CAPABILITIES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
2 changes: 1 addition & 1 deletion docs/HOST_FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
3 changes: 3 additions & 0 deletions docs/PROTOCOL.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ Output names are file names (`<name>.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.

Expand All @@ -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:
Expand Down
2 changes: 2 additions & 0 deletions labconstrictor_tools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
ToolError,
Unit,
Widget,
WithAxes,
)

__all__ = [
Expand All @@ -54,6 +55,7 @@
"RegionOf",
"ShapesOut",
"Widget",
"WithAxes",
"Description",
"EnabledWhen",
"File",
Expand Down
2 changes: 1 addition & 1 deletion labconstrictor_tools/_version.py
Original file line number Diff line number Diff line change
@@ -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"
73 changes: 66 additions & 7 deletions labconstrictor_tools/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
12 changes: 12 additions & 0 deletions labconstrictor_tools/examples/roundtrip.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
1 change: 1 addition & 0 deletions labconstrictor_tools/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)",
}
14 changes: 14 additions & 0 deletions labconstrictor_tools/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
38 changes: 37 additions & 1 deletion tests/roundtrip_cases.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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())
Expand Down
Loading
Loading