comploss 0.1.0__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.
comploss/__init__.py ADDED
@@ -0,0 +1,22 @@
1
+ """comploss: component-aware losses and object-level metrics for segmentation.
2
+
3
+ Voxel-wise losses (Dice, cross entropy, Tversky) are dominated by large objects, so small
4
+ structures can be missed at almost no cost. The losses here are defined over the connected
5
+ components of the ground truth instead, so every object counts.
6
+
7
+ Quick start::
8
+
9
+ from comploss import get_loss
10
+ loss_fn = get_loss("catmil") # DiceCE + 0.1 * CAT (50-epoch warm-up) + 0.2 * MIL
11
+ for epoch in range(n_epochs):
12
+ loss_fn.set_epoch(epoch)
13
+ ...
14
+ loss = loss_fn(logits, labels) # logits (B, C, *spatial), labels (B, 1, *spatial)
15
+ """
16
+ from .components import label_components, set_backend
17
+ from .losses import * # noqa: F401,F403
18
+ from .losses import __all__ as _losses_all
19
+ from .transforms import LabelComponents, LabelComponentsd
20
+
21
+ __version__ = "0.1.0"
22
+ __all__ = list(_losses_all) + ["LabelComponents", "LabelComponentsd", "label_components", "set_backend"]
comploss/cli.py ADDED
@@ -0,0 +1,114 @@
1
+ """Command line: ``comploss losses | profile <labels_dir> | bench | nnunet {install,uninstall,status}``."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ import time
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+
12
+
13
+ def _load_mask(path: Path) -> np.ndarray:
14
+ name = path.name
15
+ if name.endswith((".nii.gz", ".nii")):
16
+ try:
17
+ import nibabel as nib
18
+ except ImportError as e: # pragma: no cover
19
+ raise SystemExit("reading NIfTI needs nibabel: pip install 'comploss[io]'") from e
20
+ return np.asarray(nib.load(str(path)).dataobj) > 0
21
+ if name.endswith(".npy"):
22
+ return np.load(path) > 0
23
+ if name.endswith(".npz"):
24
+ with np.load(path) as z:
25
+ return z[z.files[0]] > 0
26
+ raise ValueError(f"unsupported file {path}")
27
+
28
+
29
+ def cmd_profile(args) -> int:
30
+ from .metrics import object_size_profile
31
+ files = sorted(p for p in Path(args.labels_dir).iterdir()
32
+ if p.name.endswith((".nii.gz", ".nii", ".npy", ".npz")))
33
+ if not files:
34
+ print(f"no label files in {args.labels_dir}", file=sys.stderr)
35
+ return 1
36
+ prof = object_size_profile([_load_mask(p) for p in files], connectivity=args.connectivity)
37
+ if args.json:
38
+ print(json.dumps(prof, indent=2))
39
+ return 0
40
+ print(f"{int(prof['cases'])} cases, {int(prof['objects'])} objects, "
41
+ f"median size {prof['median_size_vox']:.0f} voxels")
42
+ for b in ("tiny", "small", "medium", "large"):
43
+ print(f" {b:<7}{int(prof[f'n_{b}']):>7} {100 * prof[f'frac_{b}']:5.1f}%")
44
+ small = prof["frac_tiny"] + prof["frac_small"]
45
+ print(f"objects <= 50 voxels: {100 * small:.1f}%"
46
+ + (" -> many small objects; component-aware losses are designed for this case." if small >= 0.3 else ""))
47
+ return 0
48
+
49
+
50
+ def cmd_losses(_args) -> int:
51
+ from .losses import list_losses
52
+ print("\n".join(list_losses()))
53
+ return 0
54
+
55
+
56
+ def cmd_bench(args) -> int:
57
+ import torch
58
+ from .losses import get_loss
59
+ torch.manual_seed(0)
60
+ b, c, *sp = args.shape
61
+ dev = torch.device(args.device)
62
+ logits = torch.randn(b, c, *sp, device=dev, requires_grad=True)
63
+ # random sparse "objects": blobs of a few voxels
64
+ tgt = (torch.rand(b, 1, *sp, device=dev) > 0.999).float()
65
+ tgt = torch.nn.functional.max_pool3d(tgt, 3, 1, 1) if len(sp) == 3 else torch.nn.functional.max_pool2d(tgt, 3, 1, 1)
66
+ names = args.losses or ["dice_ce", "tversky", "focal_tversky", "cc_dice_ce", "cat", "mil", "catmil"]
67
+ print(f"input {tuple(logits.shape)} on {dev}, {args.iters} iterations (forward + backward)")
68
+ for name in names:
69
+ kw = {"cat_warmup_epochs": 0} if name == "catmil" else {}
70
+ loss_fn = get_loss(name, **kw)
71
+ for i in range(args.warmup + args.iters):
72
+ if i == args.warmup:
73
+ if dev.type == "cuda":
74
+ torch.cuda.synchronize()
75
+ t0 = time.perf_counter()
76
+ logits.grad = None
77
+ loss_fn(logits, tgt).backward()
78
+ if dev.type == "cuda":
79
+ torch.cuda.synchronize()
80
+ print(f" {name:<16}{1000 * (time.perf_counter() - t0) / args.iters:9.1f} ms/iter")
81
+ return 0
82
+
83
+
84
+ def cmd_nnunet(args) -> int:
85
+ from .integrations.nnunet import install as inst
86
+ return {"install": inst.install, "uninstall": inst.uninstall, "status": inst.status}[args.action]()
87
+
88
+
89
+ def main(argv=None) -> int:
90
+ ap = argparse.ArgumentParser(prog="comploss", description=__doc__)
91
+ sub = ap.add_subparsers(dest="cmd", required=True)
92
+ p = sub.add_parser("profile", help="object-size distribution of a folder of GT masks")
93
+ p.add_argument("labels_dir")
94
+ p.add_argument("--connectivity", type=int, default=1)
95
+ p.add_argument("--json", action="store_true")
96
+ p.set_defaults(func=cmd_profile)
97
+ p = sub.add_parser("losses", help="list loss names for get_loss()")
98
+ p.set_defaults(func=cmd_losses)
99
+ p = sub.add_parser("bench", help="time forward + backward of each loss")
100
+ p.add_argument("--shape", type=int, nargs="+", default=[2, 2, 64, 64, 64], help="B C *spatial")
101
+ p.add_argument("--device", default="cuda" if __import__("torch").cuda.is_available() else "cpu")
102
+ p.add_argument("--iters", type=int, default=10)
103
+ p.add_argument("--warmup", type=int, default=2)
104
+ p.add_argument("--losses", nargs="*")
105
+ p.set_defaults(func=cmd_bench)
106
+ p = sub.add_parser("nnunet", help="make the nnU-Net trainers visible to nnUNetv2_train")
107
+ p.add_argument("action", choices=["install", "uninstall", "status"])
108
+ p.set_defaults(func=cmd_nnunet)
109
+ args = ap.parse_args(argv)
110
+ return args.func(args)
111
+
112
+
113
+ if __name__ == "__main__":
114
+ sys.exit(main())
@@ -0,0 +1,5 @@
1
+ """Connected-component utilities shared by the losses, transforms and metrics."""
2
+ from .labeling import label_batch, label_components, set_backend
3
+ from .voronoi import voronoi_components
4
+
5
+ __all__ = ["label_batch", "label_components", "set_backend", "voronoi_components"]
@@ -0,0 +1,67 @@
1
+ """Connected-component labelling shared by the losses, transforms and metrics.
2
+
3
+ Connectivity follows ``scipy.ndimage.generate_binary_structure``: 1 = face neighbours
4
+ (6 in 3D, 4 in 2D), ``ndim`` = all neighbours (26 in 3D, 8 in 2D). The paper uses 1.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from typing import Tuple
9
+
10
+ import numpy as np
11
+ import torch
12
+ from scipy import ndimage
13
+
14
+ try: # optional, faster labelling: pip install connected-components-3d
15
+ import cc3d as _cc3d
16
+ _HAS_CC3D = True
17
+ except Exception: # pragma: no cover - depends on the environment
18
+ _cc3d = None
19
+ _HAS_CC3D = False
20
+
21
+ _CC3D_CONN = {(2, 1): 4, (2, 2): 8, (3, 1): 6, (3, 2): 18, (3, 3): 26}
22
+
23
+ BACKEND = "auto" # "auto" (cc3d if installed, else scipy), "scipy" or "cc3d"
24
+
25
+
26
+ def set_backend(name: str) -> None:
27
+ """Select the labelling backend for the whole process ("auto", "scipy", "cc3d")."""
28
+ global BACKEND
29
+ if name not in ("auto", "scipy", "cc3d"):
30
+ raise ValueError(f"unknown backend {name!r}")
31
+ if name == "cc3d" and not _HAS_CC3D:
32
+ raise ImportError("cc3d backend requested but connected-components-3d is not installed")
33
+ BACKEND = name
34
+
35
+
36
+ def label_components(mask, connectivity: int = 1) -> Tuple[np.ndarray, int]:
37
+ """Label the connected components of a binary 2D or 3D mask.
38
+
39
+ Parameters
40
+ ----------
41
+ mask : np.ndarray or torch.Tensor, shape (*spatial)
42
+ Non-zero voxels are foreground.
43
+ connectivity : int
44
+ 1 = faces only (paper default), up to ``mask.ndim``.
45
+
46
+ Returns
47
+ -------
48
+ labels : np.ndarray of int64, same shape, 0 = background, 1..n = components
49
+ n : int, number of components
50
+ """
51
+ if isinstance(mask, torch.Tensor):
52
+ mask = mask.detach().cpu().numpy()
53
+ mask = np.asarray(mask) != 0
54
+ use_cc3d = _HAS_CC3D and BACKEND in ("auto", "cc3d") and (mask.ndim, connectivity) in _CC3D_CONN
55
+ if use_cc3d:
56
+ lab, n = _cc3d.connected_components(
57
+ mask.astype(np.uint8), connectivity=_CC3D_CONN[(mask.ndim, connectivity)], return_N=True)
58
+ return lab.astype(np.int64, copy=False), int(n)
59
+ struct = ndimage.generate_binary_structure(mask.ndim, connectivity)
60
+ lab, n = ndimage.label(mask, structure=struct)
61
+ return lab.astype(np.int64, copy=False), int(n)
62
+
63
+
64
+ def label_batch(mask: torch.Tensor, connectivity: int = 1) -> torch.Tensor:
65
+ """Label each sample of a (B, *spatial) mask; returns int64 labels on ``mask.device``."""
66
+ out = np.stack([label_components(m, connectivity)[0] for m in mask.detach().cpu().numpy()])
67
+ return torch.from_numpy(out).to(mask.device)
@@ -0,0 +1,46 @@
1
+ """Voronoi partition of a mask by its connected components (used by CC-DiceCE)."""
2
+ from __future__ import annotations
3
+
4
+ import numpy as np
5
+ import torch
6
+ from scipy import ndimage
7
+
8
+ try: # GPU Voronoi as in the official code
9
+ import cupy as _cp
10
+ from cupyx.scipy.ndimage import distance_transform_edt as _cp_edt
11
+ from cupyx.scipy.ndimage import label as _cp_label
12
+ _HAS_CUPY = True
13
+ except Exception: # scipy on CPU, same result
14
+ _HAS_CUPY = False
15
+
16
+
17
+ def _voronoi_cupy(fg: torch.Tensor, sampling) -> torch.Tensor:
18
+ m = _cp.from_dlpack(fg.to(torch.uint8).contiguous()) > 0 # uint8: old torch cannot export bool
19
+ lab, _ = _cp_label(m, structure=_cp.ones((3,) * m.ndim, dtype=bool))
20
+ if int(lab.max()) == 0:
21
+ return torch.zeros(fg.shape, dtype=torch.int64, device=fg.device)
22
+ idx = _cp_edt(lab == 0, sampling=sampling, return_distances=False, return_indices=True,
23
+ float64_distances=False)
24
+ return torch.from_dlpack(lab[tuple(idx)].astype(_cp.int64)).to(fg.device)
25
+
26
+
27
+ def voronoi_components(fg: torch.Tensor, sampling=None) -> torch.Tensor:
28
+ """Voronoi map of a binary mask: every voxel gets the id of its nearest GT component.
29
+
30
+ Fully connected components (26 in 3D), Euclidean distance with ``sampling`` (voxel spacing).
31
+ 0 = no component in the patch. Returns int64 on ``fg.device``.
32
+ """
33
+ global _HAS_CUPY
34
+ if _HAS_CUPY and fg.is_cuda:
35
+ try:
36
+ return _voronoi_cupy(fg, sampling)
37
+ except Exception as e: # e.g. cupy/CUDA mismatch: scipy for the rest of the run
38
+ print(f"CC-DiceCE: cupy Voronoi failed ({e!r}); falling back to scipy on CPU", flush=True)
39
+ _HAS_CUPY = False
40
+ m = fg.detach().cpu().numpy()
41
+ lab, n = ndimage.label(m, structure=np.ones((3,) * m.ndim, dtype=bool))
42
+ if n == 0:
43
+ return torch.zeros(fg.shape, dtype=torch.int64, device=fg.device)
44
+ idx = ndimage.distance_transform_edt(lab == 0, sampling=sampling, return_distances=False,
45
+ return_indices=True)
46
+ return torch.from_numpy(lab[tuple(idx)].astype(np.int64)).to(fg.device)
@@ -0,0 +1 @@
1
+ """Framework integrations (``comploss.integrations.nnunet`` needs nnunetv2)."""
@@ -0,0 +1,202 @@
1
+ """nnU-Net v2 trainers for the losses in this package.
2
+
3
+ Use with ``nnUNetv2_train DATASET CONFIG FOLD -tr <trainer>`` after ``comploss nnunet install``
4
+ (nnU-Net only finds trainers inside its own package folder; the installer drops a stub there).
5
+
6
+ Trainers: nnUNetTrainerDiceCE, nnUNetTrainerTversky, nnUNetTrainerFocalTversky,
7
+ nnUNetTrainerCCDiceCE, nnUNetTrainerCAT, nnUNetTrainerMIL, nnUNetTrainerCATMIL.
8
+
9
+ Hyperparameters are class attributes named ``loss_<name>``. Change them with a two-line
10
+ subclass (put it in a module inside nnunetv2/training/nnUNetTrainer/)::
11
+
12
+ class nnUNetTrainerCATMIL_lmil05(nnUNetTrainerCATMIL):
13
+ loss_lambda_mil = 0.5
14
+
15
+ or with environment variables ``COMPLOSS_<NAME>`` (e.g. ``COMPLOSS_LAMBDA_MIL=0.5``)
16
+ for quick experiments. The trainers do not override ``__init__`` (nnU-Net records the
17
+ constructor arguments of the base class), so they work with every nnU-Net v2 version.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import os
22
+ from typing import Any
23
+
24
+ import numpy as np
25
+ import torch.nn as nn
26
+
27
+ from nnunetv2.training.loss.compound_losses import DC_and_CE_loss
28
+ from nnunetv2.training.loss.deep_supervision import DeepSupervisionWrapper
29
+ from nnunetv2.training.loss.dice import MemoryEfficientSoftDiceLoss
30
+ from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer
31
+
32
+ from ...losses import (CATMILLoss, CCDiceCELoss, ComponentAdaptiveTverskyLoss, FocalTverskyLoss,
33
+ ComponentMILLoss, SmallLesionMILLoss, TverskyLoss)
34
+
35
+ __all__ = [
36
+ "nnUNetTrainerDiceCE", "nnUNetTrainerTversky", "nnUNetTrainerFocalTversky", "nnUNetTrainerCCDiceCE",
37
+ "nnUNetTrainerCAT", "nnUNetTrainerMIL", "nnUNetTrainerCATMIL",
38
+ ]
39
+
40
+
41
+ class _Sum(nn.Module):
42
+ def __init__(self, a: nn.Module, b: nn.Module, wa: float = 1.0, wb: float = 1.0) -> None:
43
+ super().__init__()
44
+ self.a, self.b, self.wa, self.wb = a, b, float(wa), float(wb)
45
+
46
+ def forward(self, net_output, target):
47
+ return self.wa * self.a(net_output, target) + self.wb * self.b(net_output, target)
48
+
49
+
50
+ class _LossTrainerMixin:
51
+ """Shared helpers: hyperparameter lookup, deep-supervision weights, optional epoch override."""
52
+
53
+ loss_num_epochs = None # None = keep nnU-Net's num_epochs
54
+
55
+ def _hp(self, name: str) -> Any:
56
+ default = getattr(self, f"loss_{name}")
57
+ env = os.environ.get(f"COMPLOSS_{name.upper()}")
58
+ if env is None:
59
+ return default
60
+ if isinstance(default, bool):
61
+ return env.lower() in ("1", "true", "yes")
62
+ if default is None:
63
+ return int(env)
64
+ return type(default)(env)
65
+
66
+ def _ds_weights(self) -> np.ndarray:
67
+ w = np.array([1 / (2 ** i) for i in range(len(self._get_deep_supervision_scales()))])
68
+ w[-1] = 0
69
+ return w / w.sum()
70
+
71
+ def _wrap_ds(self, loss: nn.Module) -> nn.Module:
72
+ if self.enable_deep_supervision:
73
+ return DeepSupervisionWrapper(loss, self._ds_weights())
74
+ return loss
75
+
76
+ def _activation(self) -> str:
77
+ return "sigmoid" if self.label_manager.has_regions else "softmax"
78
+
79
+ def initialize(self):
80
+ if not self.was_initialized and self._hp("num_epochs") is not None:
81
+ self.num_epochs = int(self._hp("num_epochs"))
82
+ return super().initialize()
83
+
84
+
85
+ class nnUNetTrainerDiceCE(_LossTrainerMixin, nnUNetTrainer):
86
+ """nnU-Net's default loss (DiceCE with deep supervision), under the paper's name."""
87
+
88
+
89
+ class nnUNetTrainerTversky(_LossTrainerMixin, nnUNetTrainer):
90
+ """Tversky loss (alpha 0.3, beta 0.7), equivalent to MONAI TverskyLoss with softmax + one-hot."""
91
+
92
+ loss_alpha = 0.3
93
+ loss_beta = 0.7
94
+
95
+ def _tversky_kwargs(self) -> dict:
96
+ return dict(alpha=self._hp("alpha"), beta=self._hp("beta"),
97
+ ignore_index=self.label_manager.ignore_label, activation=self._activation())
98
+
99
+ def _build_loss(self):
100
+ return self._wrap_ds(TverskyLoss(**self._tversky_kwargs()))
101
+
102
+
103
+ class nnUNetTrainerFocalTversky(nnUNetTrainerTversky):
104
+ """Focal Tversky loss: Tversky ** (1 / gamma), gamma 4/3."""
105
+
106
+ loss_focal_gamma = 4.0 / 3.0
107
+
108
+ def _build_loss(self):
109
+ return self._wrap_ds(FocalTverskyLoss(gamma=self._hp("focal_gamma"), **self._tversky_kwargs()))
110
+
111
+
112
+ class nnUNetTrainerCCDiceCE(_LossTrainerMixin, nnUNetTrainer):
113
+ """CC-DiceCE (Bouteille et al., ISBI 2026): CC-DiceCE + global DiceCE (smooth 0), 1:1, at every
114
+ deep-supervision output. Binary label-based training without ignore label only."""
115
+
116
+ loss_w_cc = 1.0
117
+ loss_w_global = 1.0
118
+
119
+ def _build_loss(self):
120
+ lm = self.label_manager
121
+ assert not lm.has_regions and not lm.has_ignore_label and lm.num_segmentation_heads == 2, \
122
+ "CC-DiceCE requires binary label-based training without ignore label"
123
+ glob = DC_and_CE_loss({'batch_dice': self.configuration_manager.batch_dice, 'smooth': 0,
124
+ 'do_bg': False, 'ddp': self.is_ddp}, {}, weight_ce=1, weight_dice=1,
125
+ ignore_label=lm.ignore_label, dice_class=MemoryEfficientSoftDiceLoss)
126
+ cc = CCDiceCELoss(self.configuration_manager.spacing, self.configuration_manager.patch_size)
127
+ return self._wrap_ds(_Sum(cc, glob, self._hp("w_cc"), self._hp("w_global")))
128
+
129
+
130
+ class nnUNetTrainerCATMIL(_LossTrainerMixin, nnUNetTrainer):
131
+ """nnU-Net DiceCE + lambda_cat * CAT (linear warm-up) + lambda_mil * MIL (the paper's method).
132
+
133
+ The base loss is nnU-Net's own (DiceCE, or Dice+BCE for regions; DDP and ignore label as in
134
+ nnU-Net) with the usual deep supervision. CAT and MIL use the full-resolution output
135
+ (``loss_ds_mode = "highest"``), or every output with ``"all"``.
136
+ """
137
+
138
+ loss_lambda_cat = 0.1
139
+ loss_lambda_mil = 0.2
140
+ loss_cat_warmup_epochs = 50
141
+ loss_alpha = 0.3
142
+ loss_beta = 0.7
143
+ loss_gamma = 1.0
144
+ loss_eps_cc = 5.0
145
+ loss_w_bg = 0.01
146
+ loss_mil_eps = 1e-6
147
+ loss_connectivity = 1
148
+ loss_ds_mode = "highest"
149
+ loss_mode = "union" # "union" (paper), "per_class" or "auto" (per class if > 2 channels)
150
+
151
+ def _build_loss(self):
152
+ base = super()._build_loss()
153
+ ds_weights = None
154
+ if isinstance(base, DeepSupervisionWrapper):
155
+ ds_weights, base = list(base.weight_factors), base.loss
156
+ lm = self.label_manager
157
+ loss = CATMILLoss(
158
+ base_loss=base,
159
+ lambda_cat=self._hp("lambda_cat"),
160
+ lambda_mil=self._hp("lambda_mil"),
161
+ cat_warmup_epochs=self._hp("cat_warmup_epochs"),
162
+ ds_weights=ds_weights,
163
+ ds_mode=self._hp("ds_mode"),
164
+ cat_kwargs=dict(alpha=self._hp("alpha"), beta=self._hp("beta"), gamma=self._hp("gamma"),
165
+ eps_cc=self._hp("eps_cc"), w_bg=self._hp("w_bg")),
166
+ mil_kwargs=dict(eps=self._hp("mil_eps")),
167
+ mode=self._hp("mode"),
168
+ activation=self._activation(),
169
+ ignore_index=lm.ignore_label,
170
+ connectivity=self._hp("connectivity"),
171
+ )
172
+ loss.set_epoch(getattr(self, "current_epoch", 0))
173
+ self._component_loss = loss
174
+ self.print_to_log_file(
175
+ f"CATMIL loss: lambda_cat={loss.lambda_cat_final} (warm-up {loss.cat_warmup_epochs} epochs), "
176
+ f"lambda_mil={loss.lambda_mil}, ds_mode={loss.ds_mode}, mode={self._hp('mode')}, "
177
+ f"activation={self._activation()}, ignore_label={lm.ignore_label}")
178
+ return loss
179
+
180
+ def on_train_epoch_start(self):
181
+ super().on_train_epoch_start()
182
+ loss = getattr(self, "_component_loss", None)
183
+ if loss is not None:
184
+ loss.set_epoch(self.current_epoch)
185
+
186
+
187
+ class nnUNetTrainerCAT(nnUNetTrainerCATMIL):
188
+ """Ablation: nnU-Net DiceCE + CAT only (per-class CAT if more than two output channels)."""
189
+
190
+ loss_lambda_mil = 0.0
191
+ loss_mode = "auto"
192
+
193
+
194
+ class nnUNetTrainerMIL(nnUNetTrainerCATMIL):
195
+ """Ablation: nnU-Net DiceCE + MIL only."""
196
+
197
+ loss_lambda_cat = 0.0
198
+ loss_cat_warmup_epochs = 0
199
+
200
+
201
+ # re-exported so old imports from the research trainers keep working
202
+ _ = (ComponentAdaptiveTverskyLoss, ComponentMILLoss, SmallLesionMILLoss)
@@ -0,0 +1,99 @@
1
+ """``comploss nnunet install | uninstall | status``: make the trainers visible to nnU-Net.
2
+
3
+ ``nnUNetv2_train -tr X`` only searches ``nnunetv2/training/nnUNetTrainer/``. ``install`` writes
4
+ one stub module there (``comploss_trainers.py``) that re-exports the comploss trainers; ``uninstall``
5
+ deletes it (only if it is our stub). Run it again after reinstalling or upgrading nnunetv2.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import re
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ STUB_NAME = "comploss_trainers.py"
15
+ MARKER = "# generated by comploss nnunet install"
16
+ STUB = f'''{MARKER}; remove with: comploss nnunet uninstall
17
+ from comploss.integrations.nnunet import * # noqa: F401,F403
18
+ from comploss.integrations.nnunet import __all__ # noqa: F401
19
+ '''
20
+
21
+
22
+ def trainer_dir() -> Path:
23
+ try:
24
+ import nnunetv2
25
+ except ImportError as e:
26
+ raise SystemExit("nnunetv2 is not installed in this environment (pip install 'comploss[nnunet]')") from e
27
+ return Path(nnunetv2.__path__[0]) / "training" / "nnUNetTrainer"
28
+
29
+
30
+ def _shadowing(d: Path):
31
+ """Other modules in the trainer folder that define classes with our trainer names."""
32
+ from comploss.integrations.nnunet import __all__ as names
33
+ pat = re.compile(r"^class (%s)\(" % "|".join(names), re.M)
34
+ hits = []
35
+ for f in d.rglob("*.py"):
36
+ if f.name == STUB_NAME:
37
+ continue
38
+ try:
39
+ text = f.read_text(errors="ignore")
40
+ except OSError:
41
+ continue
42
+ if "comploss.integrations.nnunet" in text: # already a stub that imports from comploss
43
+ continue
44
+ hits += [(f, m) for m in pat.findall(text)]
45
+ return hits
46
+
47
+
48
+ def install() -> int:
49
+ d = trainer_dir()
50
+ target = d / STUB_NAME
51
+ if target.exists() and MARKER not in target.read_text():
52
+ print(f"{target} exists and was not written by comploss; not touching it", file=sys.stderr)
53
+ return 1
54
+ target.write_text(STUB)
55
+ print(f"installed {target}")
56
+ for f, name in _shadowing(d):
57
+ # nnU-Net imports modules in sorted order and takes the first match; ours sorts first
58
+ # among lowercase names, but warn anyway so nobody trains the wrong class by accident.
59
+ print(f"warning: {f} also defines {name}; consider replacing it with "
60
+ f"'from comploss.integrations.nnunet import {name}'", file=sys.stderr)
61
+ return 0
62
+
63
+
64
+ def uninstall() -> int:
65
+ target = trainer_dir() / STUB_NAME
66
+ if not target.exists():
67
+ print("nothing to remove")
68
+ return 0
69
+ if MARKER not in target.read_text():
70
+ print(f"{target} was not written by comploss; not removing it", file=sys.stderr)
71
+ return 1
72
+ target.unlink()
73
+ print(f"removed {target}")
74
+ return 0
75
+
76
+
77
+ def status() -> int:
78
+ d = trainer_dir()
79
+ target = d / STUB_NAME
80
+ print(f"nnU-Net trainer folder: {d}")
81
+ print(f"stub installed: {target.exists() and MARKER in target.read_text()}")
82
+ from nnunetv2.utilities.find_class_by_name import recursive_find_python_class
83
+ from comploss.integrations.nnunet import __all__ as names
84
+ for n in names:
85
+ cls = recursive_find_python_class(str(d), n, "nnunetv2.training.nnUNetTrainer")
86
+ print(f" {n:<28} -> {cls.__module__ if cls is not None else 'NOT FOUND'}")
87
+ return 0
88
+
89
+
90
+ def main(argv=None) -> int:
91
+ ap = argparse.ArgumentParser(prog="comploss nnunet", description=__doc__,
92
+ formatter_class=argparse.RawDescriptionHelpFormatter)
93
+ ap.add_argument("action", choices=["install", "uninstall", "status"])
94
+ args = ap.parse_args(argv)
95
+ return {"install": install, "uninstall": uninstall, "status": status}[args.action]()
96
+
97
+
98
+ if __name__ == "__main__":
99
+ sys.exit(main())
@@ -0,0 +1,16 @@
1
+ """All losses take raw logits ``(B, C, *spatial)`` and nnU-Net-style targets ``(B, 1, *spatial)``."""
2
+ from ..components import voronoi_components
3
+ from ._utils import foreground_probability, nnunet_ds_weights, squeeze_target
4
+ from .component import (CATMILLoss, CCDiceCEGlobalLoss, CCDiceCELoss, ComponentAdaptiveTverskyLoss,
5
+ ComponentMILLoss, SmallLesionMILLoss, component_max, component_weight_map)
6
+ from .deep_supervision import DeepSupervisionLoss
7
+ from .registry import get_loss, list_losses, register_loss
8
+ from .voxel import DiceCELoss, FocalTverskyLoss, SoftDiceLoss, TverskyLoss
9
+
10
+ __all__ = [
11
+ "CATMILLoss", "ComponentAdaptiveTverskyLoss", "ComponentMILLoss", "SmallLesionMILLoss",
12
+ "DiceCELoss", "SoftDiceLoss", "TverskyLoss", "FocalTverskyLoss", "CCDiceCELoss", "CCDiceCEGlobalLoss",
13
+ "DeepSupervisionLoss", "get_loss", "list_losses", "register_loss",
14
+ "component_weight_map", "component_max", "voronoi_components",
15
+ "foreground_probability", "squeeze_target", "nnunet_ds_weights",
16
+ ]