bioimageflow-segmentation-tools 0.3.1__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/PKG-INFO +4 -7
  2. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/README.md +2 -1
  3. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/bioimageflow_segmentation_tools/instanseg_segmenter.py +38 -11
  4. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/bioimageflow_segmentation_tools/nagini3d_segmenter.py +72 -6
  5. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/index.md +2 -2
  6. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/tools/instanseg_segmenter.md +3 -0
  7. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/tools/nagini3d_segmenter.md +4 -0
  8. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/tools/stardist_segmenter.md +1 -0
  9. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/pyproject.toml +2 -6
  10. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/tests/test_model_adapters.py +75 -29
  11. bioimageflow_segmentation_tools-0.4.0/tests/test_model_content_identity.py +171 -0
  12. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/.gitignore +0 -0
  13. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/LICENSE +0 -0
  14. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/bioimageflow_segmentation_tools/__init__.py +0 -0
  15. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/bioimageflow_segmentation_tools/_arrays.py +0 -0
  16. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/bioimageflow_segmentation_tools/cellpose_sam.py +0 -0
  17. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/bioimageflow_segmentation_tools/cellpose_v3.py +0 -0
  18. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/bioimageflow_segmentation_tools/classical.py +0 -0
  19. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/bioimageflow_segmentation_tools/stardist_segmenter.py +9 -9
  20. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/images/README.md +0 -0
  21. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/tools/cellpose3.md +0 -0
  22. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/tools/cellpose_sam.md +0 -0
  23. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/tools/distance_watershed_segment.md +0 -0
  24. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/tools/filter_labels.md +0 -0
  25. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/tools/local_threshold_segment.md +0 -0
  26. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/tools/otsu_threshold_segment.md +0 -0
  27. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/tools/postprocess_labels.md +0 -0
  28. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/tools/split_touching_objects.md +0 -0
  29. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/tools/threshold_segment.md +0 -0
  30. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/tools/watershed_segment.md +0 -0
  31. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/workflows/bbbc038_segmentation_benchmark.md +0 -0
  32. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/workflows/instanseg_cell_segmentation.md +0 -0
  33. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/docs/workflows/nagini3d_caps_segmentation.md +0 -0
  34. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/tests/conftest.py +0 -0
  35. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/tests/test_execution.py +0 -0
  36. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/tests/test_instanseg_runtime.py +0 -0
  37. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/tests/test_nagini_runtime.py +0 -0
  38. {bioimageflow_segmentation_tools-0.3.1 → bioimageflow_segmentation_tools-0.4.0}/tests/test_schema.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bioimageflow-segmentation-tools
3
- Version: 0.3.1
3
+ Version: 0.4.0
4
4
  Summary: Segmentation tools for BioImageFlow
5
5
  Project-URL: Homepage, https://github.com/Inria-SAIRPICO/bioimageflow
6
6
  Project-URL: Documentation, https://bioimageflow.readthedocs.io/latest/
@@ -21,11 +21,7 @@ Classifier: Programming Language :: Python :: 3.12
21
21
  Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
22
22
  Classifier: Topic :: Scientific/Engineering :: Image Processing
23
23
  Requires-Python: >=3.10
24
- Requires-Dist: bioimageflow-core<0.5,>=0.3.0
25
- Requires-Dist: imageio>=2.31.0
26
- Requires-Dist: numpy>=1.23.5
27
- Requires-Dist: scikit-image>=0.21.0
28
- Requires-Dist: scipy>=1.10.0
24
+ Requires-Dist: bioimageflow-core<0.7,>=0.6.0
29
25
  Description-Content-Type: text/markdown
30
26
 
31
27
  # bioimageflow-segmentation-tools
@@ -51,7 +47,8 @@ Segmentation-focused tool package for BioImageFlow.
51
47
  Classical connected-component tools use face connectivity by default and treat `image > threshold` as foreground when `above` is enabled. Label inputs are validated as finite, integral, non-negative arrays, and object counts are based on distinct positive IDs rather than the largest ID.
52
48
  Default label-output paths use TIFF rather than inheriting an input extension that may be lossy or unable to store UInt32 label IDs.
53
49
 
54
- Heavy model dependencies are declared in isolated `EnvironmentSpec` objects and imported only inside `process_row`. Importing this package does not require Cellpose, TensorFlow, StarDist, or other model packages to be installed in the main process.
50
+ Package discovery requires only `bioimageflow-core`.
51
+ Classical image dependencies and heavy model dependencies are declared in worker `EnvironmentSpec` objects and imported only inside `process_row`. Importing this package does not require ImageIO, NumPy, SciPy, scikit-image, Cellpose, TensorFlow, StarDist, or other model packages in the main process.
55
52
  `Cellpose3`, `CellposeSAM`, and `StarDistSegmenter` lazily keep one model per worker-side tool instance.
56
53
  Repeated calls with the same model selection reuse the weights; changing `model_type` or `model_name` replaces the cached model, and `clear_model_cache()` releases it explicitly.
57
54
  Applications can invalidate remote worker caches by stopping the corresponding Wetlands environment.
@@ -21,7 +21,8 @@ Segmentation-focused tool package for BioImageFlow.
21
21
  Classical connected-component tools use face connectivity by default and treat `image > threshold` as foreground when `above` is enabled. Label inputs are validated as finite, integral, non-negative arrays, and object counts are based on distinct positive IDs rather than the largest ID.
22
22
  Default label-output paths use TIFF rather than inheriting an input extension that may be lossy or unable to store UInt32 label IDs.
23
23
 
24
- Heavy model dependencies are declared in isolated `EnvironmentSpec` objects and imported only inside `process_row`. Importing this package does not require Cellpose, TensorFlow, StarDist, or other model packages to be installed in the main process.
24
+ Package discovery requires only `bioimageflow-core`.
25
+ Classical image dependencies and heavy model dependencies are declared in worker `EnvironmentSpec` objects and imported only inside `process_row`. Importing this package does not require ImageIO, NumPy, SciPy, scikit-image, Cellpose, TensorFlow, StarDist, or other model packages in the main process.
25
26
  `Cellpose3`, `CellposeSAM`, and `StarDistSegmenter` lazily keep one model per worker-side tool instance.
26
27
  Repeated calls with the same model selection reuse the weights; changing `model_type` or `model_name` replaces the cached model, and `clear_model_cache()` releases it explicitly.
27
28
  Applications can invalidate remote worker caches by stopping the corresponding Wetlands environment.
@@ -1,5 +1,6 @@
1
1
  """Production InstanSeg inference adapter."""
2
2
 
3
+ from dataclasses import dataclass
3
4
  from pathlib import Path
4
5
  from typing import Annotated, Any, Literal
5
6
 
@@ -37,6 +38,14 @@ instanseg_env = EnvironmentSpec(
37
38
  )
38
39
 
39
40
 
41
+ @dataclass(frozen=True)
42
+ class _CachedModel:
43
+ source: str
44
+ device: str | None
45
+ metadata: tuple[str | None, str | None, str | None]
46
+ model: Any
47
+
48
+
40
49
  class InstanSegSegment(ProcessingTool):
41
50
  """Segment nuclei or cells with an InstanSeg model."""
42
51
 
@@ -52,28 +61,40 @@ class InstanSegSegment(ProcessingTool):
52
61
 
53
62
  def __init__(self) -> None:
54
63
  super().__init__()
55
- self._model_cache_key: tuple[str, str | None] | None = None
56
- self._cached_model: Any | None = None
64
+ self._cached_model: _CachedModel | None = None
57
65
 
58
66
  def clear_model_cache(self) -> None:
59
67
  """Release the cached model held by this tool instance."""
60
- self._model_cache_key = None
61
68
  self._cached_model = None
62
69
 
63
- def _get_model(self, model_source: str, device: str | None) -> Any:
64
- key = (model_source, device)
65
- if self._cached_model is None or self._model_cache_key != key:
70
+ def _get_model(
71
+ self,
72
+ model_source: str,
73
+ device: str | None,
74
+ metadata: tuple[str | None, str | None, str | None],
75
+ *,
76
+ named: bool,
77
+ ) -> _CachedModel:
78
+ cached = self._cached_model
79
+ if cached is None or (cached.source, cached.device, cached.metadata) != (
80
+ model_source, device, metadata
81
+ ):
66
82
  from instanseg import InstanSeg # type: ignore
67
83
 
68
84
  self.clear_model_cache()
69
- self._cached_model = InstanSeg(
85
+ cached = None
86
+ model = InstanSeg(
70
87
  model_type=model_source,
71
88
  device=device,
72
89
  image_reader="skimage.io",
73
90
  verbosity=0,
74
91
  )
75
- self._model_cache_key = key
76
- return self._cached_model
92
+ if named and metadata[2] is None:
93
+ # Acquisition can establish a previously absent local weight file.
94
+ metadata = _named_model_metadata(model_source)
95
+ cached = _CachedModel(model_source, device, metadata, model)
96
+ self._cached_model = cached
97
+ return cached
77
98
 
78
99
  class Inputs(IOModel):
79
100
  input_image: Annotated[
@@ -237,9 +258,14 @@ class InstanSegSegment(ProcessingTool):
237
258
  model_url = None
238
259
  model_digest = None
239
260
 
240
- model = self._get_model(model_source, device)
241
261
  if model_kind == "named":
242
262
  model_version, model_url, model_digest = _named_model_metadata(model_source)
263
+ cached = self._get_model(
264
+ model_source, device, (model_version, model_url, model_digest),
265
+ named=model_kind == "named",
266
+ )
267
+ model = cached.model
268
+ model_version, model_url, model_digest = cached.metadata
243
269
  cells_and_nuclei = bool(getattr(model.instanseg, "cells_and_nuclei", False))
244
270
  if target == "cells" and not cells_and_nuclei:
245
271
  raise ValueError(
@@ -302,7 +328,8 @@ def _instanseg_labels(prediction: Any) -> Any:
302
328
  if hasattr(prediction, "detach"):
303
329
  prediction = prediction.detach().cpu().numpy()
304
330
  labels = np.asarray(prediction)
305
- labels = np.squeeze(labels)
331
+ if labels.ndim > 2 and all(size == 1 for size in labels.shape[:-2]):
332
+ labels = labels.reshape(labels.shape[-2:])
306
333
  if labels.ndim != 2:
307
334
  raise ValueError(
308
335
  "InstanSeg selected-target prediction must contain one 2D label image; "
@@ -231,12 +231,9 @@ class Nagini3DSegment(ProcessingTool):
231
231
  f"got {probability.shape} and {image.shape}."
232
232
  )
233
233
  count = object_count(mask)
234
- centers = np.asarray(surface_data["centers"])
235
- parameters = np.asarray(surface_data["params"])
236
- if len(centers) != count or len(parameters) != count:
237
- raise ValueError(
238
- "NAGINI-3D surface count must match the number of mask objects."
239
- )
234
+ surface_data = _validate_surfaces(surface_data, mask, m1, m2)
235
+ centers = surface_data["centers"]
236
+ parameters = surface_data["params"]
240
237
  if count:
241
238
  sampler = SnakeSmoothSampler(P=301, M1=m1, M2=m2, device=device_name)
242
239
  curvature_positions, curvature_values = sampler.get_curvature_and_position(
@@ -247,6 +244,9 @@ class Nagini3DSegment(ProcessingTool):
247
244
  else:
248
245
  curvature_positions = np.empty((0, 3), dtype=np.float32)
249
246
  curvature_values = np.empty((0,), dtype=np.float32)
247
+ curvature_positions, curvature_values = _validate_curvature(
248
+ curvature_positions, curvature_values, count
249
+ )
250
250
 
251
251
  mask_path = Path(arguments.mask)
252
252
  probability_path = Path(arguments.probability)
@@ -302,6 +302,72 @@ class Nagini3DSegment(ProcessingTool):
302
302
  )
303
303
 
304
304
 
305
+ def _numeric_array(value: Any, name: str, *, finite: bool = True) -> Any:
306
+ import numpy as np
307
+
308
+ array = np.asarray(value)
309
+ if not (
310
+ np.issubdtype(array.dtype, np.integer)
311
+ or np.issubdtype(array.dtype, np.floating)
312
+ ):
313
+ raise ValueError(f"NAGINI-3D {name} must contain real numeric values.")
314
+ if finite and not np.isfinite(array).all():
315
+ raise ValueError(f"NAGINI-3D {name} must contain finite values.")
316
+ return array
317
+
318
+
319
+ def _validate_surfaces(data: Any, mask: Any, m1: int, m2: int) -> dict[str, Any]:
320
+ import numpy as np
321
+
322
+ names = ("points", "facets", "values", "centers", "params")
323
+ if not isinstance(data, dict) or any(name not in data for name in names):
324
+ raise ValueError("NAGINI-3D surfaces must contain points, facets, values, centers and params.")
325
+ arrays = {name: _numeric_array(data[name], name) for name in names}
326
+ count = object_count(mask)
327
+ labels = np.unique(mask)
328
+ if not np.array_equal(labels[labels > 0], np.arange(1, count + 1)):
329
+ raise ValueError("NAGINI-3D surface rows require mask object labels 1 through N.")
330
+ centers, parameters = arrays["centers"], arrays["params"]
331
+ if centers.shape != (count, 3):
332
+ raise ValueError("NAGINI-3D centers must have shape (objects, 3).")
333
+ if parameters.shape != (count, m1 * (m2 - 1) + 6, 3):
334
+ raise ValueError("NAGINI-3D params must have shape (objects, M1*(M2-1)+6, 3).")
335
+ points, facets, values = arrays["points"], arrays["facets"], arrays["values"]
336
+ if points.ndim != 3 or points.shape[0] != count or points.shape[2] != 3:
337
+ raise ValueError("NAGINI-3D points must have shape (objects, samples, 3).")
338
+ samples = points.shape[1]
339
+ if samples < 1 or values.shape != (samples,):
340
+ raise ValueError("NAGINI-3D shared values must have one entry per surface sample.")
341
+ if facets.ndim != 2 or facets.shape[1] != 3 or not np.issubdtype(facets.dtype, np.integer):
342
+ raise ValueError("NAGINI-3D shared facets must have integer shape (facets, 3).")
343
+ if np.any(facets < 0) or np.any(facets >= samples):
344
+ raise ValueError("NAGINI-3D facet indices must refer to the shared surface samples.")
345
+ return arrays
346
+
347
+
348
+ def _validate_curvature(positions: Any, values: Any, count: int) -> tuple[Any, Any]:
349
+ import numpy as np
350
+
351
+ positions = _numeric_array(positions, "curvature positions")
352
+ # Degenerate parametric geometry can have undefined curvature.
353
+ values = _numeric_array(values, "curvature values", finite=False)
354
+ if np.isinf(values).any():
355
+ raise ValueError("NAGINI-3D curvature values must be finite or NaN.")
356
+ if count == 0:
357
+ valid = positions.shape == (0, 3) and values.shape == (0,)
358
+ else:
359
+ valid = (
360
+ positions.ndim == 3
361
+ and positions.shape[0] == count
362
+ and positions.shape[2] == 3
363
+ and positions.shape[1] > 0
364
+ and values.shape == positions.shape[:2]
365
+ )
366
+ if not valid:
367
+ raise ValueError("NAGINI-3D curvature positions and values must match the ordered surface rows.")
368
+ return positions, values
369
+
370
+
305
371
  def _threshold(override: Any, default: Any, name: str) -> float:
306
372
  import math
307
373
 
@@ -5,8 +5,8 @@ threshold/watershed workflows and optional deep-learning models. It is the
5
5
  package to install when a workflow needs label images from intensity,
6
6
  probability, or binary inputs.
7
7
 
8
- Install-time libraries are imageio, NumPy, and scikit-image.
9
- Classical tool runtime environments include tifffile where file-format handling needs it.
8
+ Package discovery requires only `bioimageflow-core`.
9
+ Classical tool runtime environments provide ImageIO, NumPy, SciPy, scikit-image, and tifffile where file-format handling needs it.
10
10
  Cellpose, StarDist, TensorFlow, and other model-runtime dependencies live in isolated `EnvironmentSpec` environments and are imported inside `process_row`, so graph construction and schema tests remain lightweight.
11
11
  Default label-output paths use TIFF so label IDs are not written to an unsuitable lossy input format.
12
12
 
@@ -4,8 +4,11 @@
4
4
 
5
5
  Use `model_name` for an official model or `model_path` for a local model bundle; a local path takes precedence.
6
6
  Named models use InstanSeg's download cache on first execution, while the provenance JSON records the resolved selection and input digest.
7
+ The instance cache retains the acquired model together with its source/device/content stamp; changed local model bytes replace it, while unchanged content reuses it.
8
+ Named-model provenance retains the resolved stamp belonging to the cached model; an unavailable digest is reported as unknown.
7
9
 
8
10
  The tool accepts YX, CYX, or explicitly declared YXC arrays, optional channel IDs and pixel size, `small`, `medium`, or automatic processing, and CPU/CUDA/MPS device selection.
9
11
  It returns one uint32 YX mask for `target="nuclei"` or `target="cells"` and rejects cell requests for nucleus-only models.
12
+ Wrapper dimensions are removed without squeezing singleton spatial axes such as 1×N or N×1.
10
13
 
11
14
  Whole-slide inference is intentionally outside the first contract.
@@ -7,6 +7,10 @@ The tool exposes device, per-axis tile count, anisotropy, threshold overrides, s
7
7
 
8
8
  Outputs are a uint32 label volume, float32 probability volume, model-provenance JSON, and a compressed surface archive containing `points`, `facets`, `values`, `centers`, `params`, `curvature_positions`, and `curvature_values`.
9
9
  Surface and curvature object counts must match the number of positive mask labels.
10
+ Before output assets are written, geometry must follow the pinned numeric convention: `points` has shape `(N, P, 3)`, shared `values` has shape `(P,)`, shared integral `facets` indexes those P points, `centers` has shape `(N, 3)`, and `params` has shape `(N, M1 * (M2 - 1) + 6, 3)`.
11
+ Nonempty `curvature_positions` and `curvature_values` have aligned `(N, Q, 3)` and `(N, Q)` shapes; NaN curvature values are retained.
12
+ Infinite curvature values are refused before publication.
13
+ For zero objects, the existing curvature forms `(0, 3)` and `(0,)` remain valid.
10
14
 
11
15
  The NAGINI-3D runtime is AGPL-3.0.
12
16
  Review its license before redistributing a runtime environment; BioImageFlow does not bundle models or datasets.
@@ -18,6 +18,7 @@ array.
18
18
  Each worker-side `StarDistSegmenter` instance lazily caches one model by `model_name`.
19
19
  Repeated rows and retained-engine executions with the same model reuse its weights even when channel, prediction-threshold, or normalization settings change.
20
20
  Changing `model_name` replaces the cached model, and `clear_model_cache()` releases the current-process reference explicitly.
21
+ Invalid probability and NMS thresholds are refused before model acquisition, including on the first call.
21
22
  Applications can invalidate the remote worker cache by stopping the `segmentation-stardist` environment.
22
23
 
23
24
  ## Dependencies and Core Libraries
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "bioimageflow-segmentation-tools"
3
- version = "0.3.1"
3
+ version = "0.4.0"
4
4
  description = "Segmentation tools for BioImageFlow"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -21,11 +21,7 @@ classifiers = [
21
21
  "Topic :: Scientific/Engineering :: Image Processing",
22
22
  ]
23
23
  dependencies = [
24
- "bioimageflow-core>=0.3.0,<0.5",
25
- "imageio>=2.31.0",
26
- "numpy>=1.23.5",
27
- "scikit-image>=0.21.0",
28
- "scipy>=1.10.0",
24
+ "bioimageflow-core>=0.6.0,<0.7",
29
25
  ]
30
26
 
31
27
  [project.urls]
@@ -134,9 +134,22 @@ def test_instanseg_rejects_cells_for_nucleus_only_model(
134
134
  )
135
135
 
136
136
 
137
+ @pytest.mark.parametrize(
138
+ "surface_case",
139
+ [
140
+ "valid",
141
+ "empty",
142
+ "centers",
143
+ "facets",
144
+ "params",
145
+ "curvature",
146
+ "infinite_curvature",
147
+ ],
148
+ )
137
149
  def test_nagini_writes_labels_probability_surfaces_and_provenance(
138
150
  tmp_path: Path,
139
151
  monkeypatch: pytest.MonkeyPatch,
152
+ surface_case: str,
140
153
  ) -> None:
141
154
  class FakeCuda:
142
155
  @staticmethod
@@ -157,16 +170,25 @@ def test_nagini_writes_labels_probability_surfaces_and_provenance(
157
170
 
158
171
  def inference(self, image: np.ndarray, **_: object):
159
172
  mask = np.zeros(image.shape, dtype=np.int32)
160
- mask[1:3, 1:3, 1:3] = 1
173
+ count = 0 if surface_case == "empty" else 1
174
+ if count:
175
+ mask[1:3, 1:3, 1:3] = 1
161
176
  return (
162
177
  mask,
163
178
  np.full(image.shape, 0.75, dtype=np.float32),
164
179
  {
165
- "points": np.ones((1, 4, 3), dtype=np.float32),
166
- "facets": np.array([[0, 1, 2]], dtype=np.int32),
167
- "values": np.ones((1, 4), dtype=np.float32),
168
- "centers": np.array([[2.0, 2.0, 2.0]], dtype=np.float32),
169
- "params": np.ones((1, 4), dtype=np.float32),
180
+ "points": np.ones((count, 4, 3), dtype=np.float32),
181
+ "facets": np.array(
182
+ [[0, 1, 4 if surface_case == "facets" else 2]], dtype=np.int32
183
+ ),
184
+ "values": np.ones((4,), dtype=np.float32),
185
+ "centers": np.full(
186
+ (count, 3), "bad" if surface_case == "centers" else 2.0
187
+ ),
188
+ "params": np.ones(
189
+ (count, 4) if surface_case == "params" else (count, 8, 3),
190
+ dtype=np.float32,
191
+ ),
170
192
  },
171
193
  )
172
194
 
@@ -175,7 +197,13 @@ def test_nagini_writes_labels_probability_surfaces_and_provenance(
175
197
  pass
176
198
 
177
199
  def get_curvature_and_position(self, parameters: np.ndarray):
178
- return np.ones((len(parameters), 3)), np.ones((len(parameters),))
200
+ positions = np.ones((len(parameters), 4, 3))
201
+ values = np.full((len(parameters), 4), np.nan)
202
+ if surface_case == "curvature":
203
+ values = values[:, :3]
204
+ elif surface_case == "infinite_curvature":
205
+ values[0, 0] = np.inf
206
+ return positions, values
179
207
 
180
208
  nagini = types.ModuleType("nagini3D")
181
209
  models = types.ModuleType("nagini3D.models")
@@ -215,30 +243,37 @@ def test_nagini_writes_labels_probability_surfaces_and_provenance(
215
243
  surfaces_path = tmp_path / "surfaces.npz"
216
244
  provenance_path = tmp_path / "provenance.json"
217
245
 
218
- result = Nagini3DSegment().process_row(
219
- Arguments(
220
- input_volume=volume_path,
221
- model_bundle=bundle,
222
- weights_filename="best.pkl",
223
- probability_threshold=None,
224
- nms_threshold=None,
225
- tiles_z=1,
226
- tiles_y=1,
227
- tiles_x=1,
228
- anisotropy_z=1.0,
229
- anisotropy_y=1.0,
230
- anisotropy_x=1.0,
231
- optimize_snakes=True,
232
- otsu_for_snakes=True,
233
- device="cpu",
234
- mask=mask_path,
235
- probability=probability_path,
236
- surfaces=surfaces_path,
237
- model_provenance=provenance_path,
238
- )
246
+ arguments = Arguments(
247
+ input_volume=volume_path,
248
+ model_bundle=bundle,
249
+ weights_filename="best.pkl",
250
+ probability_threshold=None,
251
+ nms_threshold=None,
252
+ tiles_z=1,
253
+ tiles_y=1,
254
+ tiles_x=1,
255
+ anisotropy_z=1.0,
256
+ anisotropy_y=1.0,
257
+ anisotropy_x=1.0,
258
+ optimize_snakes=True,
259
+ otsu_for_snakes=True,
260
+ device="cpu",
261
+ mask=mask_path,
262
+ probability=probability_path,
263
+ surfaces=surfaces_path,
264
+ model_provenance=provenance_path,
239
265
  )
266
+ if surface_case not in {"valid", "empty"}:
267
+ with pytest.raises(ValueError):
268
+ Nagini3DSegment().process_row(arguments)
269
+ assert not any(
270
+ path.exists()
271
+ for path in (mask_path, probability_path, surfaces_path, provenance_path)
272
+ )
273
+ return
274
+ result = Nagini3DSegment().process_row(arguments)
240
275
 
241
- assert result.object_count == 1
276
+ assert result.object_count == (0 if surface_case == "empty" else 1)
242
277
  assert iio.imread(mask_path).dtype == np.uint32
243
278
  assert iio.imread(probability_path).dtype == np.float32
244
279
  with np.load(surfaces_path) as surfaces:
@@ -251,4 +286,15 @@ def test_nagini_writes_labels_probability_surfaces_and_provenance(
251
286
  "curvature_positions",
252
287
  "curvature_values",
253
288
  }
289
+ assert surfaces["points"].shape == (result.object_count, 4, 3)
290
+ assert surfaces["values"].shape == (4,)
291
+ assert surfaces["params"].shape == (result.object_count, 8, 3)
292
+ np.testing.assert_array_equal(surfaces["facets"], [[0, 1, 2]])
293
+ np.testing.assert_allclose(iio.imread(probability_path), 0.75)
294
+ if surface_case == "valid":
295
+ assert surfaces["curvature_positions"].shape == (1, 4, 3)
296
+ assert np.isnan(surfaces["curvature_values"]).all()
297
+ else:
298
+ assert surfaces["curvature_positions"].shape == (0, 3)
299
+ assert surfaces["curvature_values"].shape == (0,)
254
300
  assert '"model_bundle_sha256"' in provenance_path.read_text()
@@ -0,0 +1,171 @@
1
+ """Public finite adapter identity/refusal controls without learned runtimes."""
2
+
3
+ import hashlib
4
+ import importlib.resources
5
+ import json
6
+ from pathlib import Path
7
+ import sys
8
+ import types
9
+
10
+ import imageio.v3 as iio
11
+ import numpy as np
12
+ import pytest
13
+
14
+ from bioimageflow_core import Arguments
15
+ from bioimageflow_segmentation_tools import InstanSegSegment, StarDistSegmenter
16
+
17
+
18
+ pytestmark = pytest.mark.package_tools
19
+
20
+
21
+ def _arguments(tmp_path, *, shape=(2, 5), model_path=None, suffix="0"):
22
+ source = tmp_path / "image.tif"
23
+ iio.imwrite(source, np.ones(shape, dtype=np.uint16))
24
+ return Arguments(
25
+ input_image=source,
26
+ model_name="selected",
27
+ model_path=model_path,
28
+ target="nuclei",
29
+ pixel_size_um=None,
30
+ channel_axis="first",
31
+ channel_ids=None,
32
+ processing_method="small",
33
+ device="cpu",
34
+ mask=tmp_path / f"mask-{suffix}.tif",
35
+ model_provenance=tmp_path / f"provenance-{suffix}.json",
36
+ )
37
+
38
+
39
+ def _fake_instanseg(monkeypatch, read_value):
40
+ constructions = []
41
+
42
+ class Model:
43
+ def __init__(self, **kwargs):
44
+ self.value = read_value(kwargs["model_type"])
45
+ constructions.append(self.value)
46
+ self.instanseg = types.SimpleNamespace(cells_and_nuclei=False)
47
+
48
+ def eval_small_image(self, image, **_kwargs):
49
+ return np.full((1, 1, *image.shape[-2:]), self.value, dtype=np.int32)
50
+
51
+ module = types.ModuleType("instanseg")
52
+ module.InstanSeg = Model
53
+ monkeypatch.setitem(sys.modules, "instanseg", module)
54
+ return constructions
55
+
56
+
57
+ @pytest.mark.parametrize("shape", [(1, 5), (5, 1)])
58
+ def test_instanseg_preserves_singleton_spatial_dimensions(monkeypatch, tmp_path, shape):
59
+ _fake_instanseg(monkeypatch, lambda _: 7)
60
+ output = InstanSegSegment().process_row(_arguments(tmp_path, shape=shape))
61
+ labels = iio.imread(output.mask)
62
+ assert labels.shape == shape and labels.dtype == np.uint32
63
+ np.testing.assert_array_equal(labels, np.full(shape, 7))
64
+ assert output.object_count == 1
65
+
66
+
67
+ def test_instanseg_local_changed_bytes_replace_cached_model_and_used_digest(
68
+ monkeypatch, tmp_path
69
+ ):
70
+ bundle = tmp_path / "bundle"
71
+ bundle.mkdir()
72
+ weights = bundle / "instanseg.pt"
73
+ weights.write_bytes(b"1")
74
+ constructions = _fake_instanseg(
75
+ monkeypatch, lambda source: int((Path(source) / "instanseg.pt").read_bytes())
76
+ )
77
+ tool = InstanSegSegment()
78
+ digests = []
79
+ for index, value in enumerate([1, 9, 9]):
80
+ weights.write_text(str(value))
81
+ output = tool.process_row(
82
+ _arguments(tmp_path, model_path=bundle, suffix=str(index))
83
+ )
84
+ np.testing.assert_array_equal(iio.imread(output.mask), np.full((2, 5), value))
85
+ expected = hashlib.sha256(
86
+ b"instanseg.pt" + hashlib.sha256(str(value).encode()).digest()
87
+ ).hexdigest()
88
+ provenance = json.loads(output.model_provenance.read_text())
89
+ assert provenance["model_sha256"] == expected
90
+ digests.append(expected)
91
+ assert constructions == [1, 9]
92
+ assert digests[0] != digests[1] == digests[2]
93
+
94
+
95
+ def test_instanseg_named_provenance_matches_model_acquired_and_warm_reuse(
96
+ monkeypatch, tmp_path
97
+ ):
98
+ resources = tmp_path / "resources"
99
+ index = resources / "bioimageio_models" / "model-index.json"
100
+ index.parent.mkdir(parents=True)
101
+ for version in [1, 9]:
102
+ directory = tmp_path / "models" / "selected" / str(version)
103
+ directory.mkdir(parents=True)
104
+ (directory / "instanseg.pt").write_text(str(version))
105
+ monkeypatch.setenv("INSTANSEG_BIOIMAGEIO_PATH", str(tmp_path / "models"))
106
+ real_files = importlib.resources.files
107
+ monkeypatch.setattr(
108
+ importlib.resources,
109
+ "files",
110
+ lambda module: resources if module == "instanseg" else real_files(module),
111
+ )
112
+ constructions = _fake_instanseg(
113
+ monkeypatch, lambda _: int(json.loads(index.read_text())[0]["version"])
114
+ )
115
+ tool = InstanSegSegment()
116
+ for iteration, version in enumerate([1, 9, 9]):
117
+ index.write_text(
118
+ json.dumps(
119
+ [
120
+ {
121
+ "name": "selected",
122
+ "version": str(version),
123
+ "url": f"https://example.invalid/{version}",
124
+ }
125
+ ]
126
+ )
127
+ )
128
+ output = tool.process_row(_arguments(tmp_path, suffix=str(iteration)))
129
+ np.testing.assert_array_equal(iio.imread(output.mask), np.full((2, 5), version))
130
+ stamp = json.loads(output.model_provenance.read_text())
131
+ assert stamp["model_version"] == str(version)
132
+ assert stamp["model_url"] == f"https://example.invalid/{version}"
133
+ assert (
134
+ stamp["model_sha256"] == hashlib.sha256(str(version).encode()).hexdigest()
135
+ )
136
+ assert constructions == [1, 9]
137
+
138
+
139
+ @pytest.mark.parametrize("threshold", ["prob_thresh", "nms_thresh"])
140
+ def test_stardist_invalid_threshold_refuses_before_model_acquisition(
141
+ monkeypatch, tmp_path, threshold
142
+ ):
143
+ acquisitions = []
144
+ models = types.ModuleType("stardist.models")
145
+ models.StarDist2D = types.SimpleNamespace(
146
+ from_pretrained=lambda *args: acquisitions.append(args)
147
+ )
148
+ monkeypatch.setitem(sys.modules, "stardist", types.ModuleType("stardist"))
149
+ monkeypatch.setitem(sys.modules, "stardist.models", models)
150
+ utils = types.ModuleType("csbdeep.utils")
151
+ utils.normalize = lambda image, *_args, **_kwargs: image
152
+ monkeypatch.setitem(sys.modules, "csbdeep", types.ModuleType("csbdeep"))
153
+ monkeypatch.setitem(sys.modules, "csbdeep.utils", utils)
154
+ source = tmp_path / "image.tif"
155
+ iio.imwrite(source, np.ones((3, 5), dtype=np.uint8))
156
+ arguments = dict(
157
+ input_image=source,
158
+ model_name="2D_versatile_fluo",
159
+ channel=0,
160
+ channel_axis="last",
161
+ prob_thresh=None,
162
+ nms_thresh=None,
163
+ normalize_low=1,
164
+ normalize_high=99,
165
+ mask=tmp_path / "mask.tif",
166
+ )
167
+ arguments[threshold] = 2.0
168
+ with pytest.raises(ValueError, match=threshold):
169
+ StarDistSegmenter().process_row(Arguments(**arguments))
170
+ assert acquisitions == []
171
+ assert not (tmp_path / "mask.tif").exists()
@@ -216,15 +216,6 @@ class StarDistSegmenter(ProcessingTool):
216
216
  "normalize_low and normalize_high must satisfy "
217
217
  "0 <= normalize_low < normalize_high <= 100."
218
218
  )
219
- normalized = normalize(
220
- image,
221
- normalize_low,
222
- normalize_high,
223
- axis=(0, 1),
224
- )
225
-
226
- print(f"Performing StarDist segmentation (model={model_name})...")
227
- model = self._get_model(model_name)
228
219
  predict_kwargs: dict[str, float] = {}
229
220
  if arguments.prob_thresh is not None:
230
221
  prob_thresh = finite_float(arguments.prob_thresh, name="prob_thresh")
@@ -236,6 +227,15 @@ class StarDistSegmenter(ProcessingTool):
236
227
  if not 0.0 <= nms_thresh <= 1.0:
237
228
  raise ValueError("nms_thresh must be between 0 and 1.")
238
229
  predict_kwargs["nms_thresh"] = nms_thresh
230
+ normalized = normalize(
231
+ image,
232
+ normalize_low,
233
+ normalize_high,
234
+ axis=(0, 1),
235
+ )
236
+
237
+ print(f"Performing StarDist segmentation (model={model_name})...")
238
+ model = self._get_model(model_name)
239
239
  labels, _ = model.predict_instances(normalized, **predict_kwargs)
240
240
  labels = validate_labels(
241
241
  labels,