scikit-ops 0.1.0.dev7__py3-none-any.whl → 0.1.0.dev9__py3-none-any.whl

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: scikit-ops
3
- Version: 0.1.0.dev7
3
+ Version: 0.1.0.dev9
4
4
  Summary: Appose-powered ops, and the machinery for running them.
5
5
  Project-URL: homepage, https://github.com/apposed/scikit-ops
6
6
  Project-URL: documentation, https://github.com/apposed/scikit-ops/blob/main/README.md
@@ -30,7 +30,7 @@ Classifier: Topic :: Utilities
30
30
  Requires-Python: >=3.10
31
31
  Requires-Dist: numpy
32
32
  Requires-Dist: ophelper<0.2,>=0.1.0.dev0
33
- Requires-Dist: oprunner<0.2,>=0.1.0.dev3
33
+ Requires-Dist: oprunner<0.2,>=0.1.0.dev4
34
34
  Requires-Dist: opspec<0.2,>=0.1.0.dev0
35
35
  Description-Content-Type: text/markdown
36
36
 
@@ -1,7 +1,8 @@
1
1
  skop/__init__.py,sha256=q3aBnPDP8M-mFYHVcXGB3nIwAJ9Woq6i5TKJp-T6_3o,518
2
- skop/models.py,sha256=fWPjTVLoqISXYBsf2HllaRhCx0c_QoOInA5cxp6mgH4,5311
2
+ skop/models.py,sha256=_ATqsfgG1ssusQNzEaL4HI9UhNdS3Rlni5-pIBxwVys,6795
3
3
  skop/ops/__init__.py,sha256=DYALgX7N8j17grfDurLsAEYe90MY6xnAvWBH1ctJWik,808
4
4
  skop/ops/_microsam.py,sha256=bCjtIDlgQxTdih9SBzCMEy1VA61D8KO9D_fSrKy-1oA,763
5
+ skop/ops/_monai.py,sha256=rz9jCnsFWEC9KNoaTcdHVwmDIT4ZUapnHqO5H5QPX9w,4140
5
6
  skop/ops/_util.py,sha256=4aTMa_NVv6IqmRXmVnQB6NZY_qHa7yvjduMYme-rGd4,4076
6
7
  skop/ops/edges.py,sha256=oom-p_Qgvdp64dG2k5clqvzNNMeSTC7u_LsC1pem3DA,13777
7
8
  skop/ops/generate.py,sha256=0cKxIdDyJXIRloFfAeypx7DxIYhvvxdux1WwrkgBMBw,2722
@@ -34,21 +35,23 @@ skop/ops/mask/microsam2.py,sha256=5fF0iqc5sJQM5qL8Mhs3yvgFN7sPAZRh7XHtu6Y_jHs,43
34
35
  skop/ops/mask/mobilesam.py,sha256=PqiXvF0CrH4n7PnJPItXg_24PpMMw0JzRoqnzBu8FXk,7436
35
36
  skop/ops/prompt/__init__.py,sha256=uk3Bn0zgSBoI1ajorhXYD5p2t94hOfCP14tdITV00nA,678
36
37
  skop/ops/prompt/microsam.py,sha256=F90g6pXyR3Bnjj_xGVEPPxKGMUwWvVWp8l6CRsrbuOQ,6783
37
- skop/ops/segment/__init__.py,sha256=YrhqQclX9BZOhVDL2JyflDI7u8xJhoQXVQAW35cX7xI,714
38
+ skop/ops/segment/__init__.py,sha256=QLbUA-fBV2V6dEf03yvpLqVtKVQPBNyyrJIZifVsw5Q,767
38
39
  skop/ops/segment/cellpose3.py,sha256=GxEAVOpAMYurYMcbTf5hMlzQDt0KgJq1qMPTxRFFF60,10375
39
40
  skop/ops/segment/cellpose4.py,sha256=y7g7ZXK0M8l11IJAPKJ-OtIZBrxWK5-mmNdJRUUMlqc,5149
40
41
  skop/ops/segment/instanseg.py,sha256=TvQbmwqDm4_pqBbQX6H1kYvKuNb5fdppxoIIJOK8G9M,6296
41
42
  skop/ops/segment/microsam.py,sha256=RZ9bvsGnyrqgjwPCm9jy_Eed6z2QO26W4rFKtB3nXzU,4512
42
43
  skop/ops/segment/microsam2.py,sha256=ipr3tggcN1RKC8e-y1fbGiv88QH5XSi4_2AjJCDtOJY,5277
44
+ skop/ops/segment/monai_unet.py,sha256=08U08og207QHMso3yYQiaTyYQaRwDoW6fhhf7yc3iq4,3467
43
45
  skop/ops/segment/stardist2d.py,sha256=XSG4kabcfeY5fsQr1e3kYmGbkWOqyoTTyEp98MB679M,6605
44
46
  skop/ops/segment/starfun3d.py,sha256=03RB3QL59NkkbgVABXTf9_VKZ-1Li_wUeJFPFjTqeAQ,3417
45
47
  skop/ops/segment/unseg/__init__.py,sha256=nxfXLG3xmnL5zwAlUB7YPdFeLNQk5R6L8JZ8BQ3c1nk,5088
46
48
  skop/ops/segment/unseg/_algorithm.py,sha256=M1l3g8g7hBr3af9aEwLBvnUbo_PvikEoZHRNiED7mfA,68689
47
- skop/ops/train/__init__.py,sha256=KtM51FOiGn47yPtCG27PNkKLLvA7381FZ-XPzBngtq8,3106
49
+ skop/ops/train/__init__.py,sha256=2WTmtKhAZ3STIM2QibJ5i5AzvWJfRSkdIPl5ExSzXSE,3171
48
50
  skop/ops/train/_util.py,sha256=xgQxx4PDBVODntPmmlNGQ65ICs8yAPKHQHHBHqFkg6I,6114
49
- skop/ops/train/cellpose3.py,sha256=uh1SI72eYwnmSQjo0jmKhlkTW3FE5MKTd_H9_6onwac,8482
51
+ skop/ops/train/cellpose3.py,sha256=0Z52Oa61K9ObWa4cTxCbEv85DGScY08fo_On5L5rrVk,8985
50
52
  skop/ops/train/cellpose4.py,sha256=akcfij7wsR4kdqlw9AmBBZ5Jh3UCF6dMLSyUnxFhVYA,7212
51
53
  skop/ops/train/microsam.py,sha256=vSbW5W-_XvTRGNBtgHxik0oZ-8G542bijhEgftxpcYY,7937
54
+ skop/ops/train/monai_unet.py,sha256=lumZaU5pUVNO6tC3xLCZi8M40PdtxeZ6Ly3t89yNiKo,9364
52
55
  skop/ops/train/stardist2d.py,sha256=dioZYyyw6coHoPLGWIBJxVIYmAHtOp6GjxsDkGDBCSQ,18876
53
56
  skop/ops/train/yolo.py,sha256=nof2iyvy79tIpYU15hqN5CRGIEuGmbAApX5Ma6jGMjI,20348
54
57
  skop/ops/workflows/__init__.py,sha256=7GyWvVd9hIuDhup-ElcIeinjoI6xAe_JLwS67UDsIZM,1934
@@ -61,13 +64,13 @@ skop/ops/workflows/segment/connect_2d_in_3d.py,sha256=gV9M5AJQbV0Q4weeP-BF_LHiOg
61
64
  skop/envs/cellpose3/pixi.toml,sha256=iITLZdO4M6UdWI8MYbEPsCT_mDG-mlPEvlPoGvhfRn4,1696
62
65
  skop/envs/cupy/pixi.toml,sha256=JF-jHEh6WpqyK4CtaFnYzHc7OZRNyf2xezuWYb-MFek,1377
63
66
  skop/envs/minimal/pixi.toml,sha256=bZWIUkttfC9klPbRMHl01E4e7OGlrTpJ6V84veVHCr0,1031
64
- skop/envs/pytorch/pixi.toml,sha256=kEYT4BJ0RwaRf9ouirKIrtCXs-WJcPvRVpoE1LSFgw4,3900
67
+ skop/envs/pytorch/pixi.toml,sha256=_rRliK89U4ay5YzQOu7KwjsQ3GEKQPkuZXlnZ_Sog7w,4035
65
68
  skop/envs/sdeconv/pixi.toml,sha256=VNt7w0guatGlS6vU79BqKWKfNKKr9VkfmvU_RwUxi5Y,3822
66
69
  skop/envs/segment-everything/pixi.toml,sha256=1EmfO-fL9bj6SH-RnxdZpGw75pXmx6-g4EGxj_sqBJE,3774
67
70
  skop/envs/skimage/pixi.toml,sha256=wAfyOSuvsUpmKIj_Hqk3ylxck_uh6wYeMZ2BTjoSBTI,1136
68
71
  skop/envs/stardist-tf/pixi.toml,sha256=oIY1XmErvbApe_pLGyQzzSf1K_RgN2rrgAvyVWYfKag,3487
69
72
  skop/envs/unseg-cv/pixi.toml,sha256=TwcYzpAnfBd5taAB0b-kRXBhbw5aXHoLzoKRaebvyDw,1065
70
- scikit_ops-0.1.0.dev7.dist-info/METADATA,sha256=ibxBIGWvnyoFfraYWGmfo4Y1agC7adgi4a6JqaITbYk,1950
71
- scikit_ops-0.1.0.dev7.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
72
- scikit_ops-0.1.0.dev7.dist-info/entry_points.txt,sha256=0gDhmxYQNjvBwJO4L0Q2fB-5fIEBbRVUS5u5heCYulQ,43
73
- scikit_ops-0.1.0.dev7.dist-info/RECORD,,
73
+ scikit_ops-0.1.0.dev9.dist-info/METADATA,sha256=fwej8t89WYTIzwWNuLeC8xgCmB1mm2lyBGDV5yriM9Q,1950
74
+ scikit_ops-0.1.0.dev9.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
75
+ scikit_ops-0.1.0.dev9.dist-info/entry_points.txt,sha256=0gDhmxYQNjvBwJO4L0Q2fB-5fIEBbRVUS5u5heCYulQ,43
76
+ scikit_ops-0.1.0.dev9.dist-info/RECORD,,
@@ -56,6 +56,10 @@ micro_sam = ">=2"
56
56
  # first `from ultralytics import ...`, not at some later feature.
57
57
  torchvision = "*"
58
58
 
59
+ # The semantic UNet ops, segment.monai_unet and train.monai_unet. Plain torch
60
+ # plus numpy, so it solves beside the rest.
61
+ monai = "*"
62
+
59
63
  # PyTorch varies by platform: CUDA builds where there are GPUs to use,
60
64
  # and the plain package on Apple Silicon, where MPS comes built in.
61
65
 
@@ -74,7 +78,7 @@ instanseg-torch = "*"
74
78
  # Note: pinned deliberately -- this is part of the environment's identity,
75
79
  # so bumping it rebuilds every environment. It comes from PyPI, so building
76
80
  # needs no checkout; a checkout still shadows it (see oprunner.host.INIT).
77
- scikit-ops = "==0.1.0.dev5"
81
+ scikit-ops = "==0.1.0.dev7"
78
82
 
79
83
  [target.linux-64.dependencies]
80
84
  pytorch-gpu = "*"
skop/models.py CHANGED
@@ -22,11 +22,24 @@ worker and a front end can all import it.
22
22
 
23
23
  from __future__ import annotations
24
24
 
25
+ import json
25
26
  import zipfile
26
27
  from enum import Enum
27
28
  from pathlib import Path
28
29
 
29
- __all__ = ["BUILTIN_MODELS", "CellposeFlavor", "cellpose_flavor"]
30
+ __all__ = [
31
+ "BUILTIN_MODELS",
32
+ "MONAI_UNET",
33
+ "CellposeFlavor",
34
+ "cellpose_flavor",
35
+ "monai_unet_config",
36
+ ]
37
+
38
+ #: The ``format`` a MONAI UNet model's .json declares.
39
+ MONAI_UNET = "monai_unet"
40
+
41
+ #: In the pickle of a whole MONAI network, the way older tools saved one.
42
+ _MONAI_PICKLE = b"monai.networks.nets"
30
43
 
31
44
 
32
45
  class CellposeFlavor(Enum):
@@ -130,6 +143,42 @@ def cellpose_flavor(model: str | Path) -> CellposeFlavor:
130
143
  raise ValueError(f"{path} is not a recognized Cellpose model")
131
144
 
132
145
 
146
+ def monai_unet_config(model: str | Path) -> dict:
147
+ """What a MONAI UNet model file is, without loading it.
148
+
149
+ Args:
150
+ model: Path of the ``.pth``. Its architecture is in the ``.json``
151
+ beside it, with ``"format": "monai_unet"``.
152
+
153
+ Returns:
154
+ That .json as a dict. For an older whole pickled network,
155
+ ``{"format": "monai_unet", "legacy": True, "axes": "YX"}`` merged
156
+ with whatever .json it has (napari-ai-lab wrote axes and downsize).
157
+
158
+ Raises:
159
+ ValueError: If the file is not a MONAI UNet model.
160
+ """
161
+ path = Path(model)
162
+ if not path.is_file():
163
+ raise ValueError(f"{model} is not a file")
164
+
165
+ config = {}
166
+ sidecar = path.with_suffix(".json")
167
+ if sidecar.is_file():
168
+ try:
169
+ config = json.loads(sidecar.read_text(encoding="utf-8"))
170
+ except (OSError, ValueError):
171
+ config = {}
172
+ if not isinstance(config, dict):
173
+ config = {}
174
+ if config.get("format") == MONAI_UNET:
175
+ return config
176
+
177
+ if zipfile.is_zipfile(path) and _MONAI_PICKLE in _header(path):
178
+ return {"axes": "YX", **config, "format": MONAI_UNET, "legacy": True}
179
+ raise ValueError(f"{path} is not a MONAI UNet model")
180
+
181
+
133
182
  def _header(path: Path) -> bytes:
134
183
  """The pickled state dict header, without the tensors it points at.
135
184
 
skop/ops/_monai.py ADDED
@@ -0,0 +1,126 @@
1
+ """Shared by the MONAI UNet ops: the network, its files, its input.
2
+
3
+ A model is ``<name>.pth``, a torch state dict, beside ``<name>.json``, the
4
+ architecture to build before loading it. Models from napari-ai-lab and its
5
+ ancestor are a whole pickled network instead, and load as they are.
6
+
7
+ Heavy imports stay inside the functions, as in an op module.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from pathlib import Path
14
+
15
+ import numpy as np
16
+
17
+ from skop.models import MONAI_UNET, monai_unet_config
18
+
19
+ from ._util import to_gray
20
+
21
+ #: Percentiles for normalization, as napari-ai-lab's patches use.
22
+ PERCENTILES = (1.0, 99.0)
23
+
24
+
25
+ def unet_config(
26
+ in_channels: int,
27
+ out_channels: int,
28
+ depth: int,
29
+ features: int,
30
+ dropout: float,
31
+ spatial_dims: int = 2,
32
+ num_res_units: int = 2,
33
+ ) -> dict:
34
+ """The architecture, as the .json beside a model records it. Channels
35
+ double per level after the first two, as napari-ai-lab built them."""
36
+ channels = [features * (2 ** (i - 1) if i > 1 else 1) for i in range(depth + 1)]
37
+ return {
38
+ "format": MONAI_UNET,
39
+ "spatial_dims": spatial_dims,
40
+ "in_channels": in_channels,
41
+ "out_channels": out_channels,
42
+ "channels": channels,
43
+ "strides": [2] * depth,
44
+ "num_res_units": num_res_units,
45
+ "dropout": dropout,
46
+ }
47
+
48
+
49
+ def build_unet(config: dict):
50
+ """A fresh network from a config. No activation at the end: the loss and
51
+ the argmax each bring their own."""
52
+ from monai.networks.nets import UNet
53
+
54
+ return UNet(
55
+ spatial_dims=config["spatial_dims"],
56
+ in_channels=config["in_channels"],
57
+ out_channels=config["out_channels"],
58
+ channels=tuple(config["channels"]),
59
+ strides=tuple(config["strides"]),
60
+ num_res_units=config["num_res_units"],
61
+ act=("LeakyReLU", {"negative_slope": 0.01, "inplace": True}),
62
+ norm="batch",
63
+ dropout=config["dropout"],
64
+ )
65
+
66
+
67
+ def load_model(path, device):
68
+ """``(net, config)``, in eval mode on *device*. A legacy pickled network
69
+ gets its spatial dims and input channels read off its first convolution."""
70
+ import torch
71
+
72
+ config = monai_unet_config(path)
73
+ if config.get("legacy"):
74
+ net = torch.load(path, map_location=device, weights_only=False)
75
+ conv = next(
76
+ m
77
+ for m in net.modules()
78
+ if isinstance(m, (torch.nn.Conv2d, torch.nn.Conv3d))
79
+ )
80
+ config = {
81
+ **config,
82
+ "spatial_dims": 3 if isinstance(conv, torch.nn.Conv3d) else 2,
83
+ "in_channels": conv.in_channels,
84
+ }
85
+ else:
86
+ net = build_unet(config)
87
+ net.load_state_dict(torch.load(path, map_location=device, weights_only=True))
88
+ return net.to(device).eval(), config
89
+
90
+
91
+ def save_model(net, config: dict, path) -> None:
92
+ """Weights to *path*, the config to the .json beside it."""
93
+ import torch
94
+
95
+ path = Path(path)
96
+ torch.save(net.state_dict(), path)
97
+ path.with_suffix(".json").write_text(json.dumps(config, indent=2))
98
+
99
+
100
+ def prepare(image, in_channels: int | None, normalize: bool) -> np.ndarray:
101
+ """A plane as float32 ``(C, Y, X)``. *in_channels* 1 collapses colour,
102
+ 3 requires it, None keeps what is there."""
103
+ x = np.asarray(image)
104
+ colour = x.ndim == 3 and x.shape[-1] in (3, 4)
105
+ if x.ndim != 2 and not colour:
106
+ raise ValueError(
107
+ f"Expected a 2D plane, (Y, X) or (Y, X, RGB), got shape {x.shape}. "
108
+ "A volume is segmented slice by slice by the caller."
109
+ )
110
+ if colour:
111
+ x = x[..., :3]
112
+ if in_channels == 1:
113
+ x = to_gray(x)
114
+ elif in_channels not in (None, 1):
115
+ raise ValueError(
116
+ f"This model was trained on {in_channels} channels and the image is grey."
117
+ )
118
+
119
+ x = x.astype(np.float32)
120
+ if normalize:
121
+ low, high = np.percentile(x, PERCENTILES)
122
+ if high > low:
123
+ x = np.clip((x - low) / (high - low), 0.0, 1.0)
124
+ # np.percentile's float64 scalars promote x; torch wants float32.
125
+ x = x.astype(np.float32, copy=False)
126
+ return x[None] if x.ndim == 2 else np.moveaxis(x, -1, 0)
@@ -11,6 +11,7 @@ from __future__ import annotations
11
11
  from .cellpose4 import cellpose4
12
12
  from .cellpose3 import cellpose3
13
13
  from .microsam import microsam
14
+ from .monai_unet import monai_unet
14
15
  from .stardist2d import stardist2d_fluo, stardist2d_he
15
16
  from .starfun3d import segment_nuclei
16
17
  from .unseg import unseg
@@ -19,6 +20,7 @@ __all__ = [
19
20
  "cellpose4",
20
21
  "cellpose3",
21
22
  "microsam",
23
+ "monai_unet",
22
24
  "segment_nuclei",
23
25
  "stardist2d_fluo",
24
26
  "stardist2d_he",
@@ -0,0 +1,94 @@
1
+ """Semantic segmentation with a MONAI UNet you trained.
2
+
3
+ A class per pixel, not an object per label: the output is a class map. No
4
+ built-in models -- train one with ``skop.ops.train.train_monai_unet``.
5
+
6
+ 2D models only for now. ``spatial_dims`` is in every model's .json, so a 3D
7
+ model is refused by name rather than mistaken for a 2D one.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from pathlib import Path
13
+ from typing import Annotated
14
+
15
+ import numpy as np
16
+
17
+ from opspec.op import Axes, op
18
+ from opspec.runtime import progress
19
+ from opspec.types import ImageOf, LabelsOf
20
+
21
+
22
+ @op(env="pytorch")
23
+ def monai_unet(
24
+ image: Annotated[ImageOf[np.ndarray], Axes("y", "x", "c?")],
25
+ model: Path,
26
+ tile_size: Annotated[
27
+ int, {"widget_type": "SpinBox", "min": 64, "max": 4096, "step": 64}
28
+ ] = 1024,
29
+ use_tiles: bool = True,
30
+ normalize: bool = True,
31
+ label_background: bool = True,
32
+ use_gpu: bool = True,
33
+ ) -> LabelsOf[np.ndarray]:
34
+ """Classify every pixel with a trained MONAI UNet.
35
+
36
+ Args:
37
+ image: Plane to segment, grey or RGB. Colour is averaged to grey
38
+ for a model trained on grey.
39
+ model: The ``.pth`` to run. Its .json gives the architecture; an
40
+ older whole pickled network needs none.
41
+ tile_size: Tile edge for sliding-window inference. Smaller uses less
42
+ GPU memory.
43
+ use_tiles: Off runs the whole image at once: faster, more memory.
44
+ normalize: Percentile-normalize (1-99) first, as the training
45
+ patches were.
46
+ label_background: On, background is label 1 and every class has a
47
+ label. Off, background is 0, as though unlabelled.
48
+ use_gpu: Use the GPU when there is one.
49
+
50
+ Returns:
51
+ uint16 class map, the input's height and width.
52
+ """
53
+ import torch
54
+ import torch.nn.functional as F
55
+ from monai.inferers import sliding_window_inference
56
+
57
+ from .._monai import load_model, prepare
58
+
59
+ device = torch.device("cuda" if use_gpu and torch.cuda.is_available() else "cpu")
60
+ progress(f"Loading MONAI UNet {Path(model).name}")
61
+ net, config = load_model(model, device)
62
+ if config["spatial_dims"] != 2:
63
+ raise ValueError(
64
+ f"{Path(model).name} is a {config['spatial_dims']}D model; this op "
65
+ "runs 2D ones."
66
+ )
67
+
68
+ x = prepare(image, config["in_channels"], normalize)
69
+ height, width = x.shape[1:]
70
+ t = torch.from_numpy(np.ascontiguousarray(x))[None].to(device)
71
+
72
+ # Downsized as in training, and the classes sized back afterwards.
73
+ factor = int(config.get("downsize_factor", 1) or 1)
74
+ if factor != 1:
75
+ t = F.interpolate(t, size=(height // factor, width // factor), mode="area")
76
+
77
+ progress("Running MONAI UNet")
78
+ with torch.no_grad():
79
+ if use_tiles:
80
+ y = sliding_window_inference(
81
+ t, (tile_size, tile_size), 1, net, mode="gaussian", overlap=0.125
82
+ )
83
+ else:
84
+ # Each level halves the size, so pad to a multiple of 2**depth.
85
+ stride = 2 ** len(config.get("strides", [2] * 5))
86
+ h, w = t.shape[-2:]
87
+ t = F.pad(t, (0, (-w) % stride, 0, (-h) % stride))
88
+ y = net(t)[..., :h, :w]
89
+
90
+ classes = y.argmax(dim=1, keepdim=True).float()
91
+ if factor != 1:
92
+ classes = F.interpolate(classes, size=(height, width), mode="nearest")
93
+ classes = classes[0, 0].cpu().numpy().astype(np.uint16)
94
+ return classes + 1 if label_background else classes
@@ -22,6 +22,7 @@ import numpy as np
22
22
  from .cellpose4 import train_cellpose4
23
23
  from .cellpose3 import train_cellpose3
24
24
  from .microsam import train_microsam
25
+ from .monai_unet import train_monai_unet
25
26
  from .stardist2d import receptive_field_stardist2d, train_stardist2d
26
27
  from .yolo import train_yolo
27
28
 
@@ -29,6 +30,7 @@ __all__ = [
29
30
  "train_cellpose4",
30
31
  "train_cellpose3",
31
32
  "train_microsam",
33
+ "train_monai_unet",
32
34
  "train_stardist2d",
33
35
  "train_yolo",
34
36
  "receptive_field_stardist2d",
@@ -26,6 +26,22 @@ from skop.ops.segment.cellpose3 import (
26
26
 
27
27
  from ._util import read_pairs, relay_epochs, write_history
28
28
 
29
+ #: Labels smaller than this are set to 0 before training.
30
+ MIN_OBJECT_PIXELS = 5
31
+
32
+
33
+ def _drop_tiny(y):
34
+ """*y* with labels under MIN_OBJECT_PIXELS pixels set to 0. Cellpose 3
35
+ crashes (AxisError in _extend_centers_gpu) when a patch's only label is 1 px."""
36
+ import numpy as np
37
+
38
+ ids, counts = np.unique(y, return_counts=True)
39
+ tiny = ids[(counts < MIN_OBJECT_PIXELS) & (ids != 0)]
40
+ if tiny.size:
41
+ y = y.copy()
42
+ y[np.isin(y, tiny)] = 0
43
+ return y
44
+
29
45
 
30
46
  @op(env="cellpose3")
31
47
  def train_cellpose3(
@@ -143,8 +159,8 @@ def train_cellpose3(
143
159
  # int32 arrives from label arithmetic upstream; normalization chokes on it.
144
160
  X_train = [np.asarray(x).astype(np.float32) for x in X_train]
145
161
  X_val = [np.asarray(x).astype(np.float32) for x in X_val]
146
- Y_train = [np.asarray(y).astype(np.uint16) for y in Y_train]
147
- Y_val = [np.asarray(y).astype(np.uint16) for y in Y_val]
162
+ Y_train = [_drop_tiny(np.asarray(y).astype(np.uint16)) for y in Y_train]
163
+ Y_val = [_drop_tiny(np.asarray(y).astype(np.uint16)) for y in Y_val]
148
164
 
149
165
  # CellposeModel, not Cellpose: the SizeModel it bundles trains separately.
150
166
  if initial_model:
@@ -0,0 +1,234 @@
1
+ """Train a MONAI UNet for semantic segmentation, on sparse labels or full ones.
2
+
3
+ Paths in, a path out, like every training op (design 0011). The model is
4
+ ``<name>.pth`` (state dict) beside ``<name>.json`` (architecture), which
5
+ ``skop.ops.segment.monai_unet`` reads back.
6
+
7
+ Sparse labels: 0 is unlabelled and ignored, 1 is background, 2.. the classes.
8
+ 2D patches only for now; the .json records ``spatial_dims`` for 3D later.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Annotated
14
+
15
+ from opspec.op import op
16
+ from opspec.runtime import progress
17
+
18
+ from ._util import write_history
19
+
20
+
21
+ @op(env="pytorch")
22
+ def train_monai_unet(
23
+ images: list[str],
24
+ labels: list[str],
25
+ model_dir: str,
26
+ name: str = "monai_unet",
27
+ initial_model: str = "",
28
+ sparse: bool = True,
29
+ num_classes: Annotated[int, {"widget_type": "SpinBox", "min": 0, "max": 255}] = 0,
30
+ class_weights: list[float] | None = None,
31
+ depth: Annotated[int, {"widget_type": "SpinBox", "min": 1, "max": 8}] = 5,
32
+ features: Annotated[int, {"widget_type": "SpinBox", "min": 4, "max": 256}] = 32,
33
+ dropout: float = 0.2,
34
+ epochs: Annotated[int, {"widget_type": "SpinBox", "min": 1, "max": 5000}] = 100,
35
+ learning_rate: float = 1e-4,
36
+ batch_size: Annotated[int, {"widget_type": "SpinBox", "min": 1, "max": 64}] = 8,
37
+ downsize_factor: Annotated[
38
+ int, {"widget_type": "SpinBox", "min": 1, "max": 16}
39
+ ] = 1,
40
+ normalize: bool = False,
41
+ val_size: Annotated[int, {"widget_type": "SpinBox", "min": 0, "max": 100}] = 2,
42
+ save_interval: Annotated[
43
+ int, {"widget_type": "SpinBox", "min": 0, "max": 1000}
44
+ ] = 0,
45
+ dataset_id: str = "",
46
+ use_gpu: bool = True,
47
+ ) -> str:
48
+ """Train a 2D MONAI UNet and write it to disk.
49
+
50
+ Args:
51
+ images: Paths to the input patches, (Y, X) or (Y, X, RGB).
52
+ labels: Paths to the label patches, matched to ``images`` by position.
53
+ model_dir: Directory to write the model into.
54
+ name: Model name; written as ``<name>.pth`` and ``<name>.json``.
55
+ initial_model: A ``.pth`` to continue from; it brings its own
56
+ architecture, and the depth/features/dropout here are ignored.
57
+ The same path as the output continues its history too.
58
+ sparse: 0 in a label means unlabelled, and is left out of the loss.
59
+ num_classes: Output classes. 0 counts them from the labels: the
60
+ highest label if sparse, one more if not.
61
+ class_weights: Loss weight per class, in label order. Missing
62
+ entries are 1. Raise a rare class's weight to stop it vanishing.
63
+ depth: Levels in the UNet. Patches must be at least 2**depth across.
64
+ features: Channels at the first level; doubled at each level after.
65
+ dropout: Dropout probability.
66
+ epochs: Passes over the training set.
67
+ learning_rate: Adam's learning rate.
68
+ batch_size: Patches per step.
69
+ downsize_factor: Shrink patches this much in Y and X before training.
70
+ Recorded, so the segment op shrinks images the same way.
71
+ normalize: Percentile-normalize each patch. Off by default: patches
72
+ from napari-ai-lab are normalized when they are written.
73
+ val_size: Pairs held out from the end for validation. 0 for none.
74
+ save_interval: Save a ``<name>_checkpoint.pth`` every this many
75
+ epochs. 0 for none.
76
+ dataset_id: Label for the training data, recorded in the history.
77
+ use_gpu: Use the GPU when there is one.
78
+
79
+ Returns:
80
+ Path of the ``.pth``. ``<name>_history.csv`` beside it holds the
81
+ loss per epoch.
82
+ """
83
+ from pathlib import Path
84
+
85
+ import numpy as np
86
+ import torch
87
+ import torch.nn.functional as F
88
+ from tifffile import imread
89
+ from torch.utils.data import DataLoader, TensorDataset
90
+
91
+ from .._monai import build_unet, load_model, prepare, save_model, unet_config
92
+
93
+ if len(images) != len(labels):
94
+ raise ValueError(
95
+ f"{len(images)} images and {len(labels)} labels: the lists must "
96
+ "be the same length."
97
+ )
98
+ if len(images) <= val_size:
99
+ raise ValueError(
100
+ f"{len(images)} pairs is not enough to hold {val_size} back for "
101
+ "validation and still train on the rest."
102
+ )
103
+
104
+ device = torch.device("cuda" if use_gpu and torch.cuda.is_available() else "cpu")
105
+
106
+ # Read; keep the pairs the size of the first, as a batch needs.
107
+ progress(f"Reading {len(images)} pairs", 0, len(images))
108
+ X, Y, skipped = [], [], 0
109
+ for i, (image_path, label_path) in enumerate(zip(images, labels)):
110
+ x = prepare(imread(image_path), None, normalize)
111
+ y = np.asarray(imread(label_path)).astype(np.int64)
112
+ if y.shape != x.shape[1:]:
113
+ raise ValueError(f"{label_path} is {y.shape}; its image is {x.shape[1:]}")
114
+ if X and x.shape != X[0].shape:
115
+ skipped += 1
116
+ else:
117
+ X.append(x)
118
+ Y.append(y)
119
+ progress(current=i + 1)
120
+ if skipped:
121
+ progress(f"Skipped {skipped} pairs not the size of the first, {X[0].shape}")
122
+
123
+ X = torch.from_numpy(np.stack(X))
124
+ Y = torch.from_numpy(np.stack(Y))[:, None]
125
+ if downsize_factor != 1:
126
+ size = (X.shape[-2] // downsize_factor, X.shape[-1] // downsize_factor)
127
+ X = F.interpolate(X, size=size, mode="area")
128
+ Y = F.interpolate(Y.float(), size=size, mode="nearest").long()
129
+ Y = Y[:, 0]
130
+
131
+ top = int(Y.max())
132
+ if sparse:
133
+ Y = Y - 1 # 0 (unlabelled) becomes -1, which the loss ignores
134
+ n_classes = num_classes or (top if sparse else top + 1)
135
+ if n_classes < 2:
136
+ raise ValueError(
137
+ f"The labels hold {n_classes} class. Label background and at "
138
+ "least one other class."
139
+ )
140
+
141
+ in_channels = X.shape[1]
142
+ if initial_model:
143
+ net, config = load_model(initial_model, device)
144
+ if config.get("legacy"):
145
+ raise ValueError(
146
+ f"{initial_model} is an older pickled network. Continue from "
147
+ "a model this op wrote."
148
+ )
149
+ if (config["in_channels"], config["out_channels"]) != (in_channels, n_classes):
150
+ raise ValueError(
151
+ f"{initial_model} takes {config['in_channels']} channels to "
152
+ f"{config['out_channels']} classes; the patches give "
153
+ f"{in_channels} to {n_classes}."
154
+ )
155
+ else:
156
+ config = unet_config(in_channels, n_classes, depth, features, dropout)
157
+ net = build_unet(config).to(device)
158
+ config = {
159
+ **config,
160
+ "axes": "YX" if in_channels == 1 else "YXC",
161
+ "sparse": sparse,
162
+ "downsize_factor": downsize_factor,
163
+ }
164
+
165
+ n_val = val_size
166
+ train_set = TensorDataset(X[: len(X) - n_val], Y[: len(Y) - n_val])
167
+ val_set = TensorDataset(X[len(X) - n_val :], Y[len(Y) - n_val :]) if n_val else None
168
+ train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True)
169
+ val_loader = DataLoader(val_set, batch_size=batch_size) if val_set else None
170
+
171
+ weights = None
172
+ if class_weights:
173
+ if len(class_weights) > n_classes:
174
+ raise ValueError(
175
+ f"{len(class_weights)} class weights for {n_classes} classes."
176
+ )
177
+ weights = torch.ones(n_classes)
178
+ weights[: len(class_weights)] = torch.tensor(class_weights, dtype=torch.float32)
179
+ weights = weights.to(device)
180
+ loss_fn = torch.nn.CrossEntropyLoss(weight=weights, ignore_index=-1)
181
+ optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate)
182
+
183
+ Path(model_dir).mkdir(parents=True, exist_ok=True)
184
+ model_path = Path(model_dir) / f"{name}.pth"
185
+
186
+ progress(
187
+ f"Training {name}: {len(train_set)} train, {n_val} val, {n_classes} "
188
+ f"classes, {epochs} epochs",
189
+ 0,
190
+ epochs,
191
+ )
192
+ history = []
193
+ for epoch in range(1, epochs + 1):
194
+ net.train()
195
+ total = 0.0
196
+ for feature, label in train_loader:
197
+ optimizer.zero_grad()
198
+ loss = loss_fn(net(feature.to(device)), label.to(device))
199
+ loss.backward()
200
+ optimizer.step()
201
+ total += loss.item()
202
+ loss_value = total / len(train_loader)
203
+
204
+ val_value = float("nan")
205
+ if val_loader is not None:
206
+ net.eval()
207
+ with torch.no_grad():
208
+ val_total = sum(
209
+ loss_fn(net(feature.to(device)), label.to(device)).item()
210
+ for feature, label in val_loader
211
+ )
212
+ val_value = val_total / len(val_loader)
213
+
214
+ history.append((epoch, loss_value, val_value))
215
+ progress(
216
+ f"Epoch {epoch}/{epochs} — loss {loss_value:.4f}, "
217
+ f"val_loss {val_value:.4f}",
218
+ epoch,
219
+ epochs,
220
+ )
221
+ if save_interval and epoch % save_interval == 0 and epoch < epochs:
222
+ save_model(net, config, model_path.with_name(f"{name}_checkpoint.pth"))
223
+
224
+ save_model(net, config, model_path)
225
+ # Suffix dropped, so the history is <name>_history.csv; both sides
226
+ # dropped, so continuing the same model still continues its curve.
227
+ write_history(
228
+ model_path.with_suffix(""),
229
+ history,
230
+ name,
231
+ dataset_id,
232
+ str(Path(initial_model).with_suffix("")) if initial_model else "",
233
+ )
234
+ return str(model_path)