micro_sam.v2.datasets.generalist_loader
1import os 2import re 3import json 4import random 5import shutil 6from glob import glob 7from functools import partial 8 9import numpy as np 10from sklearn.model_selection import train_test_split 11 12import torch 13 14from elf.io import open_file 15 16import torch_em 17from torch_em.transform.generic import Compose 18from torch_em.transform import get_augmentations 19from torch_em.data import datasets, MinInstanceSampler, ConcatDataset 20 21from . import cochleanet_data 22from .wrapper import UniDataWrapper 23from .sampler import UniBatchSampler, RejectBlankSlices, _build_group_map 24from ..transforms.raw import ( 25 _identity, _cellpose_raw_trafo, _to_8bit, _normalize_percentile, _resize_raw_to_512, _resize_to_512, 26 _prepare_identity, _drop_alpha_channel, 27 _enseg_green_channel, _xenium_cell_channels, _pan_multiplex_tissuenet_order, _cvz_cell_channels, 28 _minmax_raw_trafo, 29 get_random_percentile_normalization, 30) 31from ..transforms.labels import ( 32 _em_cell_label_trafo, _joint_em_cell_label_trafo, _background_id_label_trafo, 33 _plantseg_label_trafo, _astih_pre_label_transform, _instance_labels, 34 _ignore_missing_raw_trafo, _ignore_unlabelled_blobs_trafo, _labels_to_uint32, _drop_oversized_label_trafo, 35 _compact_label_ids, _ignore_label_trafo, _connected_components_pre_label_trafo, 36 _JointLabelTransform, _JointGeodesicLabelTransform, 37) 38 39# The training domains. 'all' is LM + EM + HP; the mitochondria EM generalist ('em_mito') and the nucleus EM 40# generalist ('em_nucleus') are separate domains and are not part of 'all'. 41DATASET_CHOICES = ("lm", "em", "hp", "em_mito", "em_nucleus", "all") 42 43# Cap on validation samples drawn per dataset, to keep the per-epoch validation pass cheap. 44# Each access is a random crop (see UniDataWrapper.max_samples), so this is N random samples. 45N_SAMPLES_VAL = 50 46 47# Crops the sampler may reject before a file gives up. Sparse image sets (the worm and CTC HSC frames, the 48# Tsakiroglou crops) reject up to 85 crops per accepted one. A file that gives up is replaced by another draw in 49# UniDataWrapper, so the budget only bounds the time lost on a file whose labels never satisfy the sampler. 50MAX_SAMPLING_ATTEMPTS = 1000 51 52# Fixed seed for deterministic validation. The same value is used to seed the main process 53# (prompt sampling in SAM2Train, object subsampling in ConvertToSam2VideoBatch) in 54# Sam2Trainer._validate_impl, so the validation metric is comparable across epochs. 55VALIDATION_SEED = 42 56 57# Train with uniformly sampled symmetric percentiles. Validate deterministically with the 2nd and 98th percentiles 58# to match the inference-time normalization in normalize_raw. 59TRAIN_LOWER_PERCENTILE_BOUNDS = (0.0, 5.0) 60VALIDATION_LOWER_PERCENTILE_BOUNDS = (2.0, 2.0) 61 62 63def seed_worker(worker_id): 64 """DataLoader worker_init_fn that pins per-worker RNG for deterministic validation crops. 65 66 The torch_em datasets draw a fresh random crop and random object subset on every 67 __getitem__ inside the worker process. Seeding each worker deterministically (and using 68 non-persistent workers so this runs every epoch) makes those crops identical across epochs. 69 """ 70 seed = VALIDATION_SEED + worker_id 71 random.seed(seed) 72 np.random.seed(seed) 73 torch.manual_seed(seed) 74 75 76def _ensure_native_byte_order(y): 77 # tifffile.memmap returns big-endian >f4 for some TIFFs. Byteswap to native so that 78 # Kornia augmentation and skimage or vigra C extensions receive correctly ordered bytes. 79 return y.byteswap().view(y.dtype.newbyteorder()) if not y.dtype.isnative else y 80 81 82def _compact_native_label_ids(y, keep=()): 83 return _compact_label_ids(_ensure_native_byte_order(y), keep=keep) 84 85 86def _set_percentile_normalization(dataset, lower_percentile_bounds): 87 """Replace fixed normalization in all torch-em leaves of a dataset tree.""" 88 if isinstance(dataset, (list, tuple)): 89 for ds in dataset: 90 _set_percentile_normalization(ds, lower_percentile_bounds) 91 return 92 93 if isinstance(dataset, UniDataWrapper): 94 _set_percentile_normalization(dataset.ds, lower_percentile_bounds) 95 return 96 97 if isinstance(dataset, torch.utils.data.Subset): 98 _set_percentile_normalization(dataset.dataset, lower_percentile_bounds) 99 return 100 101 children = getattr(dataset, "datasets", None) 102 if children is not None: 103 for ds in children: 104 _set_percentile_normalization(ds, lower_percentile_bounds) 105 return 106 107 if not hasattr(dataset, "raw_transform"): 108 raise TypeError(f"Cannot configure raw normalization for dataset of type {type(dataset).__name__}.") 109 110 if dataset.raw_transform is _prepare_identity: 111 # The missing-tile transform tests the stored intensities and normalizes the raw itself afterwards. 112 normalizer = get_random_percentile_normalization(_identity, lower_percentile_bounds).normalizer 113 transform = dataset.transform 114 dataset.transform = partial(transform.func, *transform.args, **{**transform.keywords, "normalizer": normalizer}) 115 return 116 117 dataset.raw_transform = get_random_percentile_normalization( 118 dataset.raw_transform, lower_percentile_bounds=lower_percentile_bounds 119 ) 120 121 122def _set_max_sampling_attempts(dataset, n_attempts): 123 """Raise the sampler attempt limit in all torch-em leaves of a dataset tree.""" 124 if isinstance(dataset, (list, tuple)): 125 for ds in dataset: 126 _set_max_sampling_attempts(ds, n_attempts) 127 elif isinstance(dataset, UniDataWrapper): 128 _set_max_sampling_attempts(dataset.ds, n_attempts) 129 elif isinstance(dataset, torch.utils.data.Subset): 130 _set_max_sampling_attempts(dataset.dataset, n_attempts) 131 elif getattr(dataset, "datasets", None) is not None: 132 for ds in dataset.datasets: 133 _set_max_sampling_attempts(ds, n_attempts) 134 elif hasattr(dataset, "max_sampling_attempts"): 135 dataset.max_sampling_attempts = n_attempts 136 137 138def _reject_blank_slices(dataset): 139 """Wrap the sampler of every 3d torch-em leaf so a crop with a constant raw plane is rejected.""" 140 if isinstance(dataset, (list, tuple)): 141 for ds in dataset: 142 _reject_blank_slices(ds) 143 elif isinstance(dataset, UniDataWrapper): 144 _reject_blank_slices(dataset.ds) 145 elif isinstance(dataset, torch.utils.data.Subset): 146 _reject_blank_slices(dataset.dataset) 147 elif getattr(dataset, "datasets", None) is not None: 148 for ds in dataset.datasets: 149 _reject_blank_slices(ds) 150 elif getattr(dataset, "ndim", 2) == 3 and getattr(dataset, "sampler", None) is not None: 151 dataset.sampler = RejectBlankSlices(dataset.sampler) 152 153 154def _configure_training_normalization(train_datasets, val_datasets): 155 """Enable random percentile augmentation for training and deterministic 2nd/98th validation.""" 156 _set_percentile_normalization( 157 train_datasets, lower_percentile_bounds=TRAIN_LOWER_PERCENTILE_BOUNDS, 158 ) 159 _set_percentile_normalization( 160 val_datasets, lower_percentile_bounds=VALIDATION_LOWER_PERCENTILE_BOUNDS, 161 ) 162 _set_max_sampling_attempts([train_datasets, val_datasets], MAX_SAMPLING_ATTEMPTS) 163 _reject_blank_slices([train_datasets, val_datasets]) 164 165 166def _prepare_data_loader(dataset, batch_size, shuffle, batch_size_per_group=None, num_workers=32, deterministic=False): 167 # For deterministic validation, re-seed workers every epoch via worker_init_fn. 168 # This requires non-persistent workers, since persistent workers run worker_init_fn only once. 169 # Persistent workers also require num_workers > 0. 170 persistent = (num_workers > 0) and not deterministic 171 worker_init = seed_worker if deterministic else None 172 if isinstance(dataset, ConcatDataset) and (batch_size > 1 or batch_size_per_group): 173 batch_sampler = UniBatchSampler( 174 group_per_index=_build_group_map(dataset), 175 batch_size=batch_size, 176 batch_size_per_group=batch_size_per_group, 177 shuffle=shuffle, 178 ) 179 loader = torch.utils.data.DataLoader( 180 dataset, batch_sampler=batch_sampler, num_workers=num_workers, 181 pin_memory=True, persistent_workers=persistent, worker_init_fn=worker_init, 182 ) 183 # Monkey-patch shuffle attribute for torch_em DefaultTrainer compatibility. 184 loader.shuffle = shuffle 185 else: 186 loader = torch_em.get_data_loader( 187 dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers, 188 persistent_workers=persistent, worker_init_fn=worker_init, 189 ) 190 191 return loader 192 193 194def _resize_then_em_label_trafo(y, em_trafo_fn): 195 """Resize small label patch to 512×512 then apply the EM label transform.""" 196 y = _resize_to_512(y, is_label=True) 197 return em_trafo_fn(y) 198 199 200def _compute_platy_rois(root, sample_ids, ignore_label, file_template, label_key, cache_prefix="_roi_cache"): 201 """The bounding box of the valid (not ignore_label) voxels of each Platynereis volume, the only region that trains. 202 203 The boxes are cached in a json file in *root*, named by *cache_prefix* and the sample ids. 204 """ 205 cache_path = os.path.join(root, f"{cache_prefix}_{'_'.join(map(str, sample_ids))}.json") 206 if os.path.exists(cache_path): 207 with open(cache_path) as f: 208 data = json.load(f) 209 return {int(k): tuple(slice(s[0], s[1]) for s in v) for k, v in data.items()} 210 211 rois = {} 212 for sample_id in sample_ids: 213 path = os.path.join(root, (file_template % sample_id)) 214 with open_file(path, "r") as f: 215 labels = f[label_key][:] 216 valid_coordinates = np.where(labels != ignore_label) 217 roi = tuple(slice(int(coord.min()), int(coord.max()) + 1) for coord in valid_coordinates) 218 rois[sample_id] = roi 219 220 tmp_path = cache_path + f".tmp{os.getpid()}" 221 with open(tmp_path, "w") as f: 222 json.dump({str(k): [(s.start, s.stop) for s in v] for k, v in rois.items()}, f) 223 os.replace(tmp_path, cache_path) 224 225 return rois 226 227 228def _get_lm_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo): 229 """Get all light microscopy (LM) datasets for generalist training. 230 231 Returns: 232 Tuple of (train_ds, val_ds) lists of UniDataWrapper instances. 233 """ 234 train_ds, val_ds = [], [] 235 n_z = len(z_slices) 236 237 # 1. CellPose (cell segmentation in (2d) fluoroscence microscopy imaging modalities) 238 # NOTE: Training uses both 'cyto' (540) and 'cyto2' (256 additional, disjoint) images. 'cyto2' has no test 239 # split, so the 68-image 'cyto' test split validates; CellPose has no blind in-domain test. 240 cellpose_kwargs = { 241 "path": os.path.join(input_path, "cellpose"), 242 "patch_shape": patch_shape, 243 "raw_transform": _cellpose_raw_trafo, 244 **{k: v for k, v in kwargs.items() if k != "raw_transform"} 245 } 246 train_ds.append( 247 UniDataWrapper( 248 datasets.get_cellpose_dataset(split="train", choice=None, n_samples=600, **cellpose_kwargs), source_ndim=2 249 ) 250 ) 251 val_ds.append( 252 UniDataWrapper(datasets.get_cellpose_dataset(split="test", choice="cyto", **cellpose_kwargs), source_ndim=2) 253 ) 254 255 # 2. CVZ Fluo (cell and nucleus segmentation in (2d) fluorescence CODEX images) 256 # NOTE: Cell and DAPI crops of one field of view are paired, so both stains share one split by patient or 257 # slide (see CVZ_VAL_GROUPS and CVZ_TEST_GROUPS); the test groups are blind. 258 def _get_cvz_dataset(stain_choice, split_choice): 259 raw_paths, label_paths = datasets.cvz_fluo.get_cvz_fluo_paths( 260 path=os.path.join(input_path, "cvz"), stain_choice=stain_choice, 261 ) 262 groups = [cvz_group(p) for p in raw_paths] 263 if split_choice == "train": 264 keep = [g not in CVZ_VAL_GROUPS and g not in CVZ_TEST_GROUPS for g in groups] 265 else: 266 keep = [g in CVZ_VAL_GROUPS for g in groups] 267 ds = torch_em.default_segmentation_dataset( 268 raw_paths=[p for p, k in zip(raw_paths, keep) if k], 269 raw_key=None, 270 label_paths=[p for p, k in zip(label_paths, keep) if k], 271 label_key=None, 272 is_seg_dataset=False, 273 patch_shape=patch_shape, 274 raw_transform=_cvz_cell_channels if stain_choice == "cell" else _to_8bit, 275 n_samples=200 if split_choice == "train" else 100, 276 **{k: v for k, v in kwargs.items() if k != "raw_transform"} 277 ) 278 return ds 279 280 train_ds.append(UniDataWrapper(_get_cvz_dataset("cell", "train"), source_ndim=2)) 281 train_ds.append(UniDataWrapper(_get_cvz_dataset("dapi", "train"), source_ndim=2)) 282 val_ds.append(UniDataWrapper(_get_cvz_dataset("cell", "val"), source_ndim=2)) 283 val_ds.append(UniDataWrapper(_get_cvz_dataset("dapi", "val"), source_ndim=2)) 284 285 # 3. DSB dataset (nucleus segmentation in fluorescence images) 286 # NOTE: The 554 fluorescence images of the 'full' source (all Kaggle stage-1 training images) minus the 50 images 287 # of the StarDist test split, which is the blind test. A random 10 % of the rest (seed 42) validates. The 107 288 # histopathology images train with the histopathology datasets. 289 dsb_raw, dsb_labels = dsb_fluorescence_training_paths(os.path.join(input_path, "dsb")) 290 dsb_train_r, dsb_val_r, dsb_train_l, dsb_val_l = train_test_split( 291 dsb_raw, dsb_labels, test_size=0.1, random_state=42 292 ) 293 dsb_kwargs = {"patch_shape": patch_shape, "is_seg_dataset": False, "raw_key": None, "label_key": None, **kwargs} 294 for raws, labs, n_samples, ds_list in [ 295 (dsb_train_r, dsb_train_l, 600, train_ds), (dsb_val_r, dsb_val_l, 50, val_ds), 296 ]: 297 ds_list.append( 298 UniDataWrapper( 299 torch_em.default_segmentation_dataset( 300 raw_paths=raws, label_paths=labs, n_samples=n_samples, **dsb_kwargs 301 ), source_ndim=2, 302 ) 303 ) 304 305 # 4. EmbedSeg (cell and nucleus segmentation in fluorescence microscopy images) 306 # Anisotropy factors (z/xy) from file metadata or EmbedSeg paper (Table 3, arXiv:2101.10033). 307 # Mouse-Organoid: z=1.0µm, xy=0.1733µm -> ~5.8x -> (6, 1, 1) 308 # Mouse-Skull: z≈0.5µm, xy≈0.1µm -> ~5x -> (5, 1, 1) 309 # Platynereis-ISH: confirmed isotropic from TIFF metadata (z≈xy≈0.45µm) 310 # Platynereis-Nuclei: confirmed from TIFF metadata (z=2.031µm, xy=0.406µm -> ~5x) 311 embedseg_sampling = { 312 "Mouse-Organoid-Cells-CBG": (6, 1, 1), 313 "Mouse-Skull-Nuclei-CBG": (5, 1, 1), 314 "Platynereis-ISH-Nuclei-CBG": None, 315 "Platynereis-Nuclei-CBG": (5, 1, 1), 316 } 317 318 def _embedseg_kwargs(name, z): 319 return { 320 "patch_shape": (z, *patch_shape), 321 "raw_transform": _to_8bit, 322 "n_samples": max(1, 200 // n_z), 323 "label_transform2": ( 324 label_trafo(sampling=embedseg_sampling[name]) 325 if label_trafo is not None else kwargs.get("label_transform2") 326 ), 327 **{k: v for k, v in kwargs.items() if k not in ["raw_transform", "label_transform2"]}, 328 } 329 330 # Mouse-Skull and Platynereis-ISH train on the official train volumes; a slab of the official test volume 331 # validates and the whole test volume is the blind test. Platynereis-Nuclei and the organoid cells are 332 # time-lapses and are split along time. 333 embedseg_root = os.path.join(input_path, "embedseg") 334 platy_nuclei_raw, platy_nuclei_labels = datasets.embedseg_data.get_embedseg_paths( 335 embedseg_root, name="Platynereis-Nuclei-CBG", split="train", 336 ) 337 organoid_raw, organoid_labels = datasets.embedseg_data.get_embedseg_paths( 338 embedseg_root, name="Mouse-Organoid-Cells-CBG", split="train", 339 ) 340 341 def _embedseg_paths_dataset(name, raw, labels, z): 342 return torch_em.default_segmentation_dataset( 343 raw_paths=raw, raw_key=None, label_paths=labels, label_key=None, is_seg_dataset=True, 344 **_embedseg_kwargs(name, z), 345 ) 346 347 for z in z_slices: 348 for name in ["Mouse-Skull-Nuclei-CBG", "Platynereis-ISH-Nuclei-CBG"]: 349 train_ds.append( 350 UniDataWrapper( 351 datasets.get_embedseg_dataset(embedseg_root, name=name, split="train", **_embedseg_kwargs(name, z)), 352 source_ndim=3, group_key=(3, z), 353 ) 354 ) 355 val_ds.append( 356 UniDataWrapper( 357 datasets.get_embedseg_dataset( 358 embedseg_root, name=name, split="test", rois=[(EMBEDSEG_VAL_Z[name],)], 359 **_embedseg_kwargs(name, z) 360 ), source_ndim=3, group_key=(3, z), 361 ) 362 ) 363 for name, raw, labels, splits in [ 364 ( 365 "Platynereis-Nuclei-CBG", platy_nuclei_raw, platy_nuclei_labels, 366 (EMBEDSEG_PLATY_NUCLEI_TRAIN_TIMEPOINTS, EMBEDSEG_PLATY_NUCLEI_VAL_TIMEPOINTS) 367 ), 368 ( 369 "Mouse-Organoid-Cells-CBG", organoid_raw, organoid_labels, 370 (EMBEDSEG_ORGANOID_TRAIN_TIMEPOINTS, EMBEDSEG_ORGANOID_VAL_TIMEPOINTS) 371 ), 372 ]: 373 for timepoints, ds_list in zip(splits, (train_ds, val_ds)): 374 ds_list.append( 375 UniDataWrapper( 376 _embedseg_paths_dataset(name, raw[timepoints], labels[timepoints], z), 377 source_ndim=3, group_key=(3, z), 378 ) 379 ) 380 381 # 5. NIS3D (nucleus segmentation in light-sheet microscopy images) 382 # NOTE: Only the Drosophila volumes are used, the others carry giant unannotated-region instances. Drosophila_2 383 # (official train) trains, the last slices of Drosophila_1 (official test) validate and the whole volume is blind. 384 nis3d_kwargs = {"path": os.path.join(input_path, "nis3d"), "split_type": "cross-image"} 385 386 train_raw_paths, train_label_paths = datasets.nis3d.get_nis3d_paths(split="train", **nis3d_kwargs) 387 val_raw_paths, val_label_paths = datasets.nis3d.get_nis3d_paths(split="test", **nis3d_kwargs) 388 389 def _update_paths(paths): 390 return [p for p in paths if "Drosophila" in p] 391 392 train_raw_paths, train_label_paths = _update_paths(train_raw_paths), _update_paths(train_label_paths) 393 val_raw_paths, val_label_paths = _update_paths(val_raw_paths), _update_paths(val_label_paths) 394 395 for z in z_slices: 396 nis3d_kwargs = { 397 "patch_shape": (z, *patch_shape), 398 "raw_transform": _to_8bit, 399 "n_samples": max(1, 200 // n_z), 400 # NIS3D Drosophila: isotropic 1µm x 1µm x 1µm 401 "label_transform2": ( 402 label_trafo(sampling=None) 403 if label_trafo is not None else kwargs.get("label_transform2") 404 ), 405 **{k: v for k, v in kwargs.items() if k not in ["raw_transform", "label_transform2"]}, 406 } 407 408 train_ds.append( 409 UniDataWrapper( 410 torch_em.default_segmentation_dataset( 411 raw_paths=train_raw_paths, raw_key=None, label_paths=train_label_paths, label_key=None, 412 **nis3d_kwargs, 413 ), source_ndim=3, group_key=(3, z), 414 ) 415 ) 416 val_ds.append( 417 UniDataWrapper( 418 torch_em.default_segmentation_dataset( 419 raw_paths=val_raw_paths, raw_key=None, label_paths=val_label_paths, label_key=None, 420 rois=[(NIS3D_VAL_Z,)] * len(val_raw_paths), **nis3d_kwargs, 421 ), source_ndim=3, group_key=(3, z), 422 ) 423 ) 424 425 # 6. PlantSeg (cell segmentation in confocal microscopy images) 426 # NOTE: Root trains on the official split, the test split stays blind. Label 1 is the background and label 0 427 # the unannotated deeper tissue, which is mapped to the ignore value. Ovules is held out for OOD evaluation 428 # (its 'label_with_ignore' key marks unannotated regions as -1); nuclei is 98-99 % background and redundant 429 # with gonuclear. 430 for z in z_slices: 431 plantseg_kwargs = { 432 "path": os.path.join(input_path, "plantseg"), 433 "patch_shape": (z, *patch_shape), 434 "n_samples": max(1, 200 // n_z), 435 **{k: v for k, v in kwargs.items() if k not in ["sampler", "label_transform2"]} 436 } 437 438 for ds_name, exclude_ids in [("root", [0, 1])]: 439 _plantseg_trafo = partial( 440 _plantseg_label_trafo, data=ds_name, 441 label_trafo=label_trafo() if label_trafo is not None else kwargs.get("label_transform2"), 442 ) 443 for split, ds_list in [("train", train_ds), ("val", val_ds)]: 444 ds_list.append( 445 UniDataWrapper( 446 datasets.get_plantseg_dataset( 447 name=ds_name, split=split, with_ignore=ds_name == "ovules", 448 label_transform2=_plantseg_trafo, 449 sampler=MinInstanceSampler(min_num_instances=3, exclude_ids=exclude_ids), 450 **plantseg_kwargs 451 ), source_ndim=3, group_key=(3, z), 452 ) 453 ) 454 455 # 7. TissueNet (cell segmentation in tissue images) 456 tissuenet_kwargs = { 457 "path": os.path.join(input_path, "tissuenet"), 458 "raw_channel": "rgb", 459 "label_channel": "cell", 460 "patch_shape": patch_shape, 461 "raw_transform": partial(_normalize_percentile, axis=(1, 2)), # TissueNet 'rgb' is (3, H, W) 462 **{k: v for k, v in kwargs.items() if k != "raw_transform"} 463 } 464 465 train_ds.append( 466 UniDataWrapper(datasets.get_tissuenet_dataset(split="train", n_samples=1000, **tissuenet_kwargs), source_ndim=2) 467 ) 468 val_ds.append( 469 UniDataWrapper(datasets.get_tissuenet_dataset(split="val", n_samples=100, **tissuenet_kwargs), source_ndim=2) 470 ) 471 472 # 8. LIVECell (cell segmentation in phase contrast microscopy images) 473 livecell_kwargs = { 474 "path": os.path.join(input_path, "livecell"), 475 "patch_shape": patch_shape, 476 "sampler": MinInstanceSampler(min_num_instances=6, exclude_ids=[0]), 477 **{k: v for k, v in kwargs.items() if k != "sampler"} 478 } 479 train_ds.extend( 480 [ 481 UniDataWrapper( 482 datasets.get_livecell_dataset(split="train", cell_types=[ctype], n_samples=400, **livecell_kwargs), 483 source_ndim=2, 484 ) for ctype in datasets.livecell.CELL_TYPES 485 ] 486 ) 487 val_ds.extend( 488 [ 489 UniDataWrapper( 490 datasets.get_livecell_dataset(split="val", cell_types=[ctype], n_samples=100, **livecell_kwargs), 491 source_ndim=2 492 ) for ctype in datasets.livecell.CELL_TYPES 493 ] 494 ) 495 496 # 9. DeepBacs (bacteria segmentation in label-free microscopy images) 497 # NOTE: The 'mixed' archive pools S. aureus, E. coli and B. subtilis; a random 10 % of its official train images 498 # (seed 42) validate and its official test split is blind. 'e_coli_stationary' is a separate acquisition of 499 # stationary-phase cells with a train split only, which trains as well. 500 deepbacs_kwargs = { 501 "patch_shape": patch_shape, 502 "raw_transform": _to_8bit, 503 **{k: v for k, v in kwargs.items() if k != "raw_transform"} 504 } 505 mixed_images, mixed_labels = datasets.deepbacs.get_deepbacs_paths( 506 os.path.join(input_path, "deepbacs"), bac_type="mixed", split="train", 507 ) 508 mixed_raw = sorted(glob(os.path.join(mixed_images, "*.tif"))) 509 mixed_lab = sorted(glob(os.path.join(mixed_labels, "*.tif"))) 510 assert len(mixed_raw) == len(mixed_lab) and mixed_raw 511 mixed_train_r, mixed_val_r, mixed_train_l, mixed_val_l = train_test_split( 512 mixed_raw, mixed_lab, test_size=0.1, random_state=42 513 ) 514 for raws, labs, n_samples, ds_list in [ 515 (mixed_train_r, mixed_train_l, 400, train_ds), (mixed_val_r, mixed_val_l, 100, val_ds), 516 ]: 517 ds_list.append( 518 UniDataWrapper( 519 torch_em.default_segmentation_dataset( 520 raw_paths=raws, raw_key=None, label_paths=labs, label_key=None, is_seg_dataset=False, ndim=2, 521 n_samples=n_samples, **deepbacs_kwargs, 522 ), source_ndim=2, 523 ) 524 ) 525 train_ds.append( 526 UniDataWrapper( 527 datasets.get_deepbacs_dataset( 528 path=os.path.join(input_path, "deepbacs"), bac_type="e_coli_stationary", split="train", n_samples=200, 529 **deepbacs_kwargs, 530 ), source_ndim=2, 531 ) 532 ) 533 534 # 10. OrgaSegment (organoid segmentation in bright field images) 535 orgasegment_kwargs = { 536 "path": os.path.join(input_path, "orgasegment"), "patch_shape": patch_shape, **kwargs 537 } 538 539 train_ds.append( 540 UniDataWrapper( 541 datasets.get_orgasegment_dataset(split="train", n_samples=300, **orgasegment_kwargs), source_ndim=2, 542 ) 543 ) 544 val_ds.append( 545 UniDataWrapper( 546 datasets.get_orgasegment_dataset(split="val", n_samples=150, **orgasegment_kwargs), source_ndim=2, 547 ) 548 ) 549 550 # 11. OrganoidNet (pancreatic organoid segmentation) 551 organoidnet_kwargs = { 552 "path": os.path.join(input_path, "organoidnet"), "patch_shape": patch_shape, **kwargs 553 } 554 555 train_ds.append( 556 UniDataWrapper( 557 datasets.get_organoidnet_dataset(split="Training", n_samples=700, **organoidnet_kwargs), source_ndim=2, 558 ) 559 ) 560 val_ds.append( 561 UniDataWrapper( 562 datasets.get_organoidnet_dataset(split="Validation", n_samples=200, **organoidnet_kwargs), source_ndim=2, 563 ) 564 ) 565 566 # 12. Omnipose (bacteria and worm segmentation in mixed modality microscopy images) 567 # NOTE: All four subsets are used. The official train split gives up a random 10 % of images (seed 42) for 568 # validation, the official test split is blind. The worm images hold few objects, so the default sampler's three 569 # instances apply there as well. 570 omnipose_root = os.path.join(input_path, "omnipose") 571 omnipose_kwargs = { 572 "patch_shape": patch_shape, 573 "raw_transform": _to_8bit, 574 "is_seg_dataset": False, 575 "raw_key": None, 576 "label_key": None, 577 **{k: v for k, v in kwargs.items() if k != "raw_transform"} 578 } 579 for data_choice, n_train in OMNIPOSE_TRAIN_SAMPLES.items(): 580 raw, labels = datasets.omnipose.get_omnipose_paths(omnipose_root, split="train", data_choice=data_choice) 581 train_raw, val_raw, train_labels, val_labels = train_test_split(raw, labels, test_size=0.1, random_state=42) 582 for raw_paths, label_paths, n_samples, ds_list in [ 583 (train_raw, train_labels, n_train, train_ds), (val_raw, val_labels, n_train // 5, val_ds), 584 ]: 585 ds_list.append( 586 UniDataWrapper( 587 torch_em.default_segmentation_dataset( 588 raw_paths=raw_paths, label_paths=label_paths, n_samples=n_samples, **omnipose_kwargs 589 ), source_ndim=2, 590 ) 591 ) 592 593 # 13. CTC (cell segmentation from Cell Tracking Challenge) 594 # NOTE: The same eight datasets as the v1 generalist (GOWT1 and N2DL-HeLa are held out), both movies of each. 595 # Only the training data has labels, so a random 10 % of the labelled frames (seed 42) validate; there is no 596 # blind test. 597 ctc_kwargs = { 598 "patch_shape": patch_shape, 599 "raw_transform": _to_8bit, 600 "is_seg_dataset": False, 601 "raw_key": None, 602 "label_key": None, 603 **{k: v for k, v in kwargs.items() if k != "raw_transform"} 604 } 605 for name in CTC_DATASETS: 606 image_dirs, label_dirs = datasets.ctc.get_ctc_segmentation_paths( 607 os.path.join(input_path, "ctc"), dataset_name=name, split="train", 608 ) 609 raw = sorted(p for d in image_dirs for p in glob(os.path.join(d, "*.tif"))) 610 labels = sorted(p for d in label_dirs for p in glob(os.path.join(d, "*.tif"))) 611 assert len(raw) == len(labels) and raw 612 train_raw, val_raw, train_labels, val_labels = train_test_split(raw, labels, test_size=0.1, random_state=42) 613 for raw_paths, label_paths, ds_list in [(train_raw, train_labels, train_ds), (val_raw, val_labels, val_ds)]: 614 ds_list.append( 615 UniDataWrapper( 616 torch_em.default_segmentation_dataset(raw_paths=raw_paths, label_paths=label_paths, **ctc_kwargs), 617 source_ndim=2, 618 ) 619 ) 620 621 # 14. YeaZ (yeast cell segmentation in brightfield microscopy images) 622 # NOTE: Only the brightfield subset is used. 14 of the 28 phase contrast train files are 2D+t stacks and the 623 # torch-em loader cannot handle them mixed with 2D crops. Images are ~400x450 uint16 and are zero-padded 624 # to the patch shape by the image collection dataset. The split file 'yeaz_bf_splits.json' lives with the data. 625 yeaz_kwargs = {"path": os.path.join(input_path, "yeaz"), "patch_shape": patch_shape, "choice": "bf", **kwargs} 626 train_ds.append( 627 UniDataWrapper(datasets.get_yeaz_dataset(split="train", n_samples=200, **yeaz_kwargs), source_ndim=2) 628 ) 629 val_ds.append(UniDataWrapper(datasets.get_yeaz_dataset(split="val", n_samples=50, **yeaz_kwargs), source_ndim=2)) 630 631 # 15. BCCD (blood cell segmentation in brightfield blood smear images) 632 # NOTE: No native val split exists: the 146-image test split is blind and a random 10 % of the 1063 train images 633 # (seed 42) validate. The instance labels are connected components of a binary mask, but the cells are 634 # separated cleanly in practice (only 0.8 % of the labelled area sits in objects larger than 2.5x the median). 635 bccd_paths = datasets.bccd.get_bccd_paths(path=os.path.join(input_path, "bccd"), split="train") 636 bccd_train, bccd_val = train_test_split(bccd_paths, test_size=0.1, random_state=42) 637 bccd_kwargs = {"patch_shape": patch_shape, "with_channels": True, "ndim": 2, **kwargs} 638 for paths, ds_list, n_samples in [(bccd_train, train_ds, 400), (bccd_val, val_ds, 50)]: 639 ds_list.append( 640 UniDataWrapper( 641 torch_em.default_segmentation_dataset( 642 raw_paths=paths, raw_key="raw", label_paths=paths, label_key="labels/instances", 643 n_samples=n_samples, **bccd_kwargs, 644 ), source_ndim=2, 645 ) 646 ) 647 648 # 16. NeurIPS CellSeg 2022 (cell segmentation in brightfield, phase contrast, DIC and fluorescence images) 649 # NOTE: The raw images mix grayscale and RGB layouts and uint8, uint16, int32 and float64 dtypes. The default 650 # raw transform covers all of them (channel triplication and per-image percentile normalization). Many images 651 # are only sparsely annotated, so the MinInstanceSampler is essential here. 'val' is the challenge 'Tuning' set. 652 neurips_kwargs = {"root": os.path.join(input_path, "neurips_cellseg"), "patch_shape": patch_shape, **kwargs} 653 train_ds.append( 654 UniDataWrapper( 655 datasets.get_neurips_cellseg_supervised_dataset(split="train", n_samples=500, **neurips_kwargs), 656 source_ndim=2, 657 ) 658 ) 659 val_ds.append( 660 UniDataWrapper( 661 datasets.get_neurips_cellseg_supervised_dataset(split="val", n_samples=100, **neurips_kwargs), 662 source_ndim=2, 663 ) 664 ) 665 666 # 17. BitDepth NucSeg (nucleus segmentation in DAPI fluorescence images at four magnifications) 667 # NOTE: 70 images over four magnifications, split 80 / 10 / 10 at random (seed 42) within each magnification, so 668 # that every magnification validates and is tested; the test images are blind. 669 bitdepth_kwargs = {"patch_shape": patch_shape, **kwargs} 670 bd_train_r, bd_val_r, bd_train_l, bd_val_l = [], [], [], [] 671 for magnification in BITDEPTH_MAGNIFICATIONS: 672 bitdepth_raw, bitdepth_labels = datasets.bitdepth_nucseg.get_bitdepth_nucseg_paths( 673 path=os.path.join(input_path, "bitdepth_nucseg"), magnification=magnification, 674 ) 675 (train_r, val_r, _), (train_l, val_l, _) = _train_val_test_split(bitdepth_raw, bitdepth_labels) 676 bd_train_r.extend(train_r) 677 bd_val_r.extend(val_r) 678 bd_train_l.extend(train_l) 679 bd_val_l.extend(val_l) 680 for raws, labs, ds_list, n_samples in [ 681 (bd_train_r, bd_train_l, train_ds, 200), (bd_val_r, bd_val_l, val_ds, 50), 682 ]: 683 ds_list.append( 684 UniDataWrapper( 685 torch_em.default_segmentation_dataset( 686 raw_paths=raws, raw_key=None, label_paths=labs, label_key=None, 687 is_seg_dataset=False, ndim=2, n_samples=n_samples, **bitdepth_kwargs, 688 ), source_ndim=2, 689 ) 690 ) 691 692 # 18. BMGD (nucleus segmentation in DAPI fluorescence images on four substrate stiffnesses) 693 # NOTE: Native images are only 345x382, so they are randomly upscaled and padded to the patch shape. The 819 694 # crops are split 80 / 10 / 10 at random (seed 42); the test crops are blind. 695 bmgd_paths = datasets.bmgd.get_bmgd_paths(path=os.path.join(input_path, "bmgd")) 696 ((bmgd_train, bmgd_val, _),) = _train_val_test_split(bmgd_paths) 697 bmgd_kwargs = { 698 "patch_shape": (345, 382), "with_channels": False, "ndim": 2, 699 **{**kwargs, "transform": _with_flips(_random_resize_and_pad_trafo, patch_shape)}, 700 } 701 for paths, ds_list, n_samples in [(bmgd_train, train_ds, 300), (bmgd_val, val_ds, 50)]: 702 ds_list.append( 703 UniDataWrapper( 704 torch_em.default_segmentation_dataset( 705 raw_paths=paths, raw_key="raw", label_paths=paths, label_key="labels/instances", 706 n_samples=n_samples, **bmgd_kwargs, 707 ), source_ndim=2, 708 ) 709 ) 710 711 # 20. Cell-ACDC (yeast cell segmentation in phase contrast time-lapse) 712 # NOTE: Native fields are only ~200x300, so they are randomly upscaled and padded to the patch shape. The seven 713 # movies are split by movie: one control position validates, one treated position is blind. 714 acdc_raw, acdc_labels = datasets.cell_acdc.get_cell_acdc_paths(os.path.join(input_path, "cell_acdc")) 715 acdc_movies = [cell_acdc_movie(p) for p in acdc_raw] 716 cell_acdc_kwargs = { 717 "patch_shape": (1, 200, 200), "raw_key": None, "label_key": None, "is_seg_dataset": True, "ndim": 2, 718 **{**kwargs, "transform": _with_flips(_random_resize_and_pad_trafo, patch_shape)}, 719 } 720 for keep, n_samples, ds_list in [ 721 ([m not in CELL_ACDC_VAL_MOVIES and m not in CELL_ACDC_TEST_MOVIES for m in acdc_movies], 200, train_ds), 722 ([m in CELL_ACDC_VAL_MOVIES for m in acdc_movies], 50, val_ds), 723 ]: 724 ds_list.append( 725 UniDataWrapper( 726 torch_em.default_segmentation_dataset( 727 raw_paths=[p for p, k in zip(acdc_raw, keep) if k], 728 label_paths=[p for p, k in zip(acdc_labels, keep) if k], 729 n_samples=n_samples, **cell_acdc_kwargs, 730 ), source_ndim=2, 731 ) 732 ) 733 734 # 22. CellBinDB (nucleus segmentation in DAPI, ssDNA and mIF images; the H&E tiles train with histopathology) 735 # NOTE: The tiles are 256x256, so they are randomly upscaled and padded to the patch shape. Each stain is split 736 # 80 / 10 / 10 at random (seed 42); the test tiles are blind. 737 cellbindb_kwargs = { 738 "patch_shape": (256, 256), "is_seg_dataset": False, "ndim": 2, 739 **{**kwargs, "transform": _with_flips(_pannuke_random_resize_and_pad_trafo, patch_shape)}, 740 } 741 for stain in CELLBINDB_STAINS: 742 cellbindb_raw, cellbindb_labels = datasets.cellbindb.get_cellbindb_paths( 743 path=os.path.join(input_path, "cellbindb"), data_choice=stain, 744 ) 745 (cb_train_r, cb_val_r, _), (cb_train_l, cb_val_l, _) = _train_val_test_split(cellbindb_raw, cellbindb_labels) 746 for raws, labs, ds_list, n_samples in [ 747 (cb_train_r, cb_train_l, train_ds, 150), (cb_val_r, cb_val_l, val_ds, 30), 748 ]: 749 ds_list.append( 750 UniDataWrapper( 751 torch_em.default_segmentation_dataset( 752 raw_paths=raws, raw_key=None, label_paths=labs, label_key=None, 753 n_samples=n_samples, **cellbindb_kwargs, 754 ), source_ndim=2, 755 ) 756 ) 757 758 # 23. CELLULAR (cell segmentation in Drosophila cells) 759 # NOTE: Only the brightfield channel is used. The two fluorescence channels light up a few strongly 760 # expressing cells, while the labels cover every cell in the field, which only brightfield resolves. 761 # The 53 fields come from six wells and are split by well: I04 validates, C06 is blind. 762 cellular_paths = datasets.cellular.get_cellular_paths(path=os.path.join(input_path, "cellular")) 763 cellular_wells = [os.path.basename(p).split("_")[3] for p in cellular_paths] 764 cellular_train = [p for p, w in zip(cellular_paths, cellular_wells) if w in CELLULAR_TRAIN_WELLS] 765 cellular_val = [p for p, w in zip(cellular_paths, cellular_wells) if w in CELLULAR_VAL_WELLS] 766 cellular_kwargs = {"patch_shape": patch_shape, "ndim": 2, **kwargs} 767 for paths, ds_list, n_samples in [(cellular_train, train_ds, 400), (cellular_val, val_ds, 50)]: 768 ds_list.append( 769 UniDataWrapper( 770 torch_em.default_segmentation_dataset( 771 raw_paths=paths, raw_key="raw/brightfield", label_paths=paths, 772 label_key="labels/instances", n_samples=n_samples, **cellular_kwargs, 773 ), source_ndim=2, 774 ) 775 ) 776 777 # 24. CISD (urothelial cell segmentation in brightfield urine cytology) 778 # NOTE: Only 2-3 cells per image, so the shared 3-instance sampler would reject nearly every patch. The 3911 779 # crops come from 30 slides and are split by slide (see CISD_VAL_SLIDES, CISD_TEST_SLIDES); the test slides 780 # are blind. 781 cisd_raw, cisd_labels = datasets.cisd.get_cisd_paths(os.path.join(input_path, "cisd"), mode="center_slice") 782 cisd_slides = [os.path.basename(p).split("_")[0] for p in cisd_raw] 783 cisd_kwargs = { 784 "patch_shape": patch_shape, "raw_key": None, "label_key": None, "is_seg_dataset": False, "ndim": 2, 785 **{**kwargs, "sampler": MinInstanceSampler(min_num_instances=1, exclude_ids=[0])}, 786 } 787 for keep, n_samples, ds_list in [ 788 ([sl not in CISD_VAL_SLIDES and sl not in CISD_TEST_SLIDES for sl in cisd_slides], 200, train_ds), 789 ([sl in CISD_VAL_SLIDES for sl in cisd_slides], 50, val_ds), 790 ]: 791 ds_list.append( 792 UniDataWrapper( 793 torch_em.default_segmentation_dataset( 794 raw_paths=[p for p, k in zip(cisd_raw, keep) if k], 795 label_paths=[p for p, k in zip(cisd_labels, keep) if k], 796 n_samples=n_samples, **cisd_kwargs, 797 ), source_ndim=2, 798 ) 799 ) 800 801 # 26. DeMemSeg (prospore membrane segmentation in fluorescence yeast crops) 802 # NOTE: Native crops are 200x200, so they are randomly upscaled and padded to the patch shape. 803 # NOTE: Each 200x200 crop holds a single yeast cell with only a handful of prospore membranes, so the 804 # shared 3-instance sampler rejects many patches outright. 805 dememseg_kwargs = { 806 "path": os.path.join(input_path, "dememseg"), "patch_shape": (200, 200), 807 **{ 808 **kwargs, 809 "transform": _with_flips(_pannuke_random_resize_and_pad_trafo, patch_shape), 810 "sampler": MinInstanceSampler(min_num_instances=1, exclude_ids=[0]), 811 }, 812 } 813 train_ds.append( 814 UniDataWrapper(datasets.get_dememseg_dataset(split="train", n_samples=200, **dememseg_kwargs), source_ndim=2) 815 ) 816 val_ds.append( 817 UniDataWrapper(datasets.get_dememseg_dataset(split="val", n_samples=50, **dememseg_kwargs), source_ndim=2) 818 ) 819 820 # 28. DynamicNuclearNet (nucleus segmentation in fluorescence time-lapse frames) 821 dnn_kwargs = {"path": os.path.join(input_path, "dynamicnuclearnet"), "patch_shape": patch_shape, **kwargs} 822 train_ds.append( 823 UniDataWrapper( 824 datasets.get_dynamicnuclearnet_dataset(split="train", n_samples=600, **dnn_kwargs), source_ndim=2 825 ) 826 ) 827 val_ds.append( 828 UniDataWrapper(datasets.get_dynamicnuclearnet_dataset(split="val", n_samples=50, **dnn_kwargs), source_ndim=2) 829 ) 830 831 # 29. FlyWing (epithelial cell segmentation in fluorescence membrane images) 832 # NOTE: The train and val splits are native 128x128 tiles, so they are randomly upscaled and padded. 833 flywing_kwargs = { 834 "path": os.path.join(input_path, "flywing"), "patch_shape": (128, 128), 835 **{**kwargs, "transform": _with_flips(_pannuke_random_resize_and_pad_trafo, patch_shape)}, 836 } 837 train_ds.append( 838 UniDataWrapper(datasets.get_flywing_dataset(split="train", n_samples=400, **flywing_kwargs), source_ndim=2) 839 ) 840 val_ds.append( 841 UniDataWrapper(datasets.get_flywing_dataset(split="val", n_samples=50, **flywing_kwargs), source_ndim=2) 842 ) 843 844 # 30. PNAS Arabidopsis (3D cell segmentation in confocal shoot apical meristem, acyl-YFP membranes) 845 # NOTE: The labels have no id 0. Background is numbered 1 and covers about three quarters of a slice, so it 846 # is mapped to 0 first, exactly as for PlantSeg root. 847 for z in z_slices: 848 pnas_trafo = partial( 849 _background_id_label_trafo, background_id=1, 850 label_trafo=label_trafo() if label_trafo is not None else kwargs.get("label_transform2"), 851 ) 852 pnas_kwargs = { 853 "path": os.path.join(input_path, "pnas_arabidopsis"), 854 "patch_shape": (z, *patch_shape), 855 "label_transform2": pnas_trafo, 856 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0, 1]), 857 "n_samples": max(1, 400 // n_z), 858 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 859 } 860 train_ds.append( 861 UniDataWrapper( 862 datasets.get_pnas_arabidopsis_dataset(plants=PNAS_TRAIN_PLANTS, **pnas_kwargs), 863 source_ndim=3, group_key=(3, z), 864 ) 865 ) 866 val_ds.append( 867 UniDataWrapper( 868 datasets.get_pnas_arabidopsis_dataset(plants=PNAS_VAL_PLANTS, **pnas_kwargs), 869 source_ndim=3, group_key=(3, z), 870 ) 871 ) 872 873 # 31. EpiCure (epithelial cell segmentation in fluorescence membrane movies) 874 # NOTE: Four model systems (Drosophila notum and histoblasts, zebrafish telencephalon, quail gastrula). 875 # The frames are exhaustively labelled and very dense, 250-370 cells per patch. Patch shape is 876 # (1, 512, 512) because the movies are stored as time series, so one frame is drawn per sample. The quail 877 # frame labels an unannotated corner as one cell, 54x the median cell, which the oversized-label rule drops. 878 epicure_kwargs = { 879 "path": os.path.join(input_path, "epicure"), "patch_shape": (1, *patch_shape), 880 "label_transform2": partial( 881 _drop_oversized_label_trafo, max_fraction=0.02, 882 label_trafo=label_trafo() if label_trafo is not None else kwargs.get("label_transform2"), 883 ), 884 **{k: v for k, v in kwargs.items() if k != "label_transform2"}, 885 } 886 train_ds.append( 887 UniDataWrapper(datasets.get_epicure_dataset(n_samples=500, **epicure_kwargs), source_ndim=2) 888 ) 889 890 # 32. CartoCell (3D cell segmentation in confocal epithelial cysts) 891 # NOTE: The on-disk layout is 'CartoCell/{train_M1,train_M2,validation,test}/{x,y}', which the torch-em loader 892 # does not expect, so the paths are given explicitly. The official folders are used: train_M1 and train_M2 893 # train, validation validates and test stays blind. Native volumes are only ~84-128 px in XY, so an 80x80 crop 894 # is always resized up to 512x512 rather than zero-padded. 895 cartocell_root = os.path.join(input_path, "cartocell", "CartoCell") 896 897 def _cartocell_paths(*folders): 898 raw = sorted(p for folder in folders for p in glob(os.path.join(cartocell_root, folder, "x", "*.tif"))) 899 labels = [p.replace(os.sep + "x" + os.sep, os.sep + "y" + os.sep) for p in raw] 900 assert raw and all(os.path.exists(p) for p in labels) 901 return raw, labels 902 903 cc_train_r, cc_train_l = _cartocell_paths(*CARTOCELL_TRAIN_FOLDERS) 904 cc_val_r, cc_val_l = _cartocell_paths(CARTOCELL_VAL_FOLDER) 905 906 for z in z_slices: 907 cartocell_kwargs = { 908 "patch_shape": (z, 80, 80), 909 "raw_transform": _resize_raw_to_512, 910 "label_transform2": ( 911 partial(_resize_then_em_label_trafo, em_trafo_fn=label_trafo(instances=True)) 912 if label_trafo is not None else kwargs.get("label_transform2") 913 ), 914 "sampler": MinInstanceSampler(min_num_instances=1, exclude_ids=[0]), 915 "n_samples": max(1, 400 // n_z), 916 **{k: v for k, v in kwargs.items() if k not in ["raw_transform", "label_transform2", "sampler"]}, 917 } 918 for raws, labs, ds_list in [(cc_train_r, cc_train_l, train_ds), (cc_val_r, cc_val_l, val_ds)]: 919 ds_list.append( 920 UniDataWrapper( 921 torch_em.default_segmentation_dataset( 922 raw_paths=raws, raw_key=None, label_paths=labs, label_key=None, 923 is_seg_dataset=True, **cartocell_kwargs, 924 ), source_ndim=3, group_key=(3, z), 925 ) 926 ) 927 928 # 33. C. elegans atlas (3D nucleus segmentation in confocal fluorescence) 929 for z in z_slices: 930 celegans_kwargs = { 931 "path": os.path.join(input_path, "celegans_atlas"), 932 "patch_shape": (z, 128, 128), 933 "raw_transform": _resize_raw_to_512, 934 "label_transform2": ( 935 partial(_resize_then_em_label_trafo, em_trafo_fn=label_trafo(instances=True)) 936 if label_trafo is not None else kwargs.get("label_transform2") 937 ), 938 "n_samples": max(1, 300 // n_z), 939 **{k: v for k, v in kwargs.items() if k not in ["raw_transform", "label_transform2"]}, 940 } 941 train_ds.append( 942 UniDataWrapper( 943 datasets.get_celegans_atlas_dataset(split="train", **celegans_kwargs), 944 source_ndim=3, group_key=(3, z), 945 ) 946 ) 947 val_ds.append( 948 UniDataWrapper( 949 datasets.get_celegans_atlas_dataset(split="val", **celegans_kwargs), 950 source_ndim=3, group_key=(3, z), 951 ) 952 ) 953 954 # 35. U2OS (nucleus segmentation in Hoechst fluorescence images) 955 # NOTE: 200 images without an official split, split 80 / 10 / 10 at random (seed 42); the test images are blind. 956 u20s_raw, u20s_labels = datasets.u20s.get_u20s_paths(os.path.join(input_path, "u20s")) 957 (u20s_train_r, u20s_val_r, _), (u20s_train_l, u20s_val_l, _) = _train_val_test_split(u20s_raw, u20s_labels) 958 u20s_kwargs = { 959 "patch_shape": patch_shape, "is_seg_dataset": False, "raw_key": None, "label_key": None, "ndim": 2, **kwargs 960 } 961 for raws, labs, n_samples, ds_list in [ 962 (u20s_train_r, u20s_train_l, 300, train_ds), (u20s_val_r, u20s_val_l, 50, val_ds), 963 ]: 964 ds_list.append( 965 UniDataWrapper( 966 torch_em.default_segmentation_dataset( 967 raw_paths=raws, label_paths=labs, n_samples=n_samples, **u20s_kwargs 968 ), source_ndim=2, 969 ) 970 ) 971 972 # 36. IFNuclei (nucleus segmentation in immunofluorescence images) 973 # NOTE: A random 10 % of the official train split (seed 42) validates; the official test split is blind. 974 ifnuclei_raw, ifnuclei_labels = datasets.ifnuclei.get_ifnuclei_paths( 975 os.path.join(input_path, "ifnuclei"), split="train", 976 ) 977 if_train_r, if_val_r, if_train_l, if_val_l = train_test_split( 978 ifnuclei_raw, ifnuclei_labels, test_size=0.1, random_state=42 979 ) 980 ifnuclei_kwargs = { 981 "patch_shape": patch_shape, "is_seg_dataset": False, "raw_key": None, "label_key": None, "ndim": 2, **kwargs 982 } 983 for raws, labs, n_samples, ds_list in [(if_train_r, if_train_l, 200, train_ds), (if_val_r, if_val_l, 50, val_ds)]: 984 ds_list.append( 985 UniDataWrapper( 986 torch_em.default_segmentation_dataset( 987 raw_paths=raws, label_paths=labs, n_samples=n_samples, **ifnuclei_kwargs 988 ), source_ndim=2, 989 ) 990 ) 991 992 # 37. VICAR (cell segmentation in quantitative phase imaging of five cell lines) 993 # NOTE: Each cell line is split 80 / 10 / 10 at random (seed 42); the test images are blind. 994 vicar_kwargs = { 995 "patch_shape": patch_shape, "raw_key": None, "label_key": None, "is_seg_dataset": False, "ndim": 2, **kwargs 996 } 997 vicar_train_r, vicar_val_r, vicar_train_l, vicar_val_l = [], [], [], [] 998 for cell_type in datasets.vicar.VALID_CELL_TYPES: 999 vicar_raw, vicar_labels = datasets.vicar.get_vicar_paths( 1000 os.path.join(input_path, "vicar"), cell_types=[cell_type] 1001 ) 1002 (train_r, val_r, _), (train_l, val_l, _) = _train_val_test_split(vicar_raw, vicar_labels) 1003 vicar_train_r.extend(train_r) 1004 vicar_val_r.extend(val_r) 1005 vicar_train_l.extend(train_l) 1006 vicar_val_l.extend(val_l) 1007 for raws, labs, n_samples, ds_list in [ 1008 (vicar_train_r, vicar_train_l, 300, train_ds), (vicar_val_r, vicar_val_l, 50, val_ds), 1009 ]: 1010 ds_list.append( 1011 UniDataWrapper( 1012 torch_em.default_segmentation_dataset( 1013 raw_paths=raws, label_paths=labs, n_samples=n_samples, **vicar_kwargs 1014 ), source_ndim=2, 1015 ) 1016 ) 1017 1018 # 39. microbeSEG (bacteria segmentation in phase contrast images) 1019 # NOTE: Native images are 320x320, so they are randomly upscaled and padded to the patch shape. 1020 microbeseg_kwargs = { 1021 "path": os.path.join(input_path, "microbeseg"), "patch_shape": (320, 320), 1022 **{**kwargs, "transform": _with_flips(_pannuke_random_resize_and_pad_trafo, patch_shape)}, 1023 } 1024 train_ds.append( 1025 UniDataWrapper( 1026 datasets.get_microbeseg_dataset(split="train", n_samples=150, **microbeseg_kwargs), source_ndim=2 1027 ) 1028 ) 1029 val_ds.append( 1030 UniDataWrapper(datasets.get_microbeseg_dataset(split="val", n_samples=50, **microbeseg_kwargs), source_ndim=2) 1031 ) 1032 1033 # 40. OrgLine (organoid segmentation in brightfield images across six organs) 1034 # NOTE: 59 % of the training images hold one or two organoids, which the default three-instance sampler can 1035 # never accept, so organoid images sample with a single-instance sampler (also OrganoID below). 1036 organoid_sampler = MinInstanceSampler(min_num_instances=1, exclude_ids=[0]) 1037 orgline_kwargs = { 1038 "path": os.path.join(input_path, "orgline"), "patch_shape": patch_shape, "sampler": organoid_sampler, 1039 **{k: v for k, v in kwargs.items() if k != "sampler"}, 1040 } 1041 train_ds.append( 1042 UniDataWrapper(datasets.get_orgline_dataset(split="train", n_samples=500, **orgline_kwargs), source_ndim=2) 1043 ) 1044 val_ds.append( 1045 UniDataWrapper(datasets.get_orgline_dataset(split="val", n_samples=50, **orgline_kwargs), source_ndim=2) 1046 ) 1047 1048 # 41. OrganoID (pancreatic organoid segmentation in brightfield culture wells) 1049 # NOTE: The 'original' (human) and 'mouse' subsets train on their official splits, their test splits are blind. 1050 # The 'gemcitabine' subset has no split and is left out. 1051 organoid_kwargs = { 1052 "path": os.path.join(input_path, "organoid"), "patch_shape": patch_shape, "sampler": organoid_sampler, 1053 **{k: v for k, v in kwargs.items() if k != "sampler"}, 1054 } 1055 for source, n_train in ORGANOID_SOURCES.items(): 1056 for split, n_samples, ds_list in [("train", n_train, train_ds), ("val", n_train // 4, val_ds)]: 1057 ds_list.append( 1058 UniDataWrapper( 1059 datasets.get_organoid_dataset(split=split, source=source, n_samples=n_samples, **organoid_kwargs), 1060 source_ndim=2, 1061 ) 1062 ) 1063 1064 # 42. EnSeg (enteric neuron segmentation in immunofluorescence whole-mount myenteric plexus) 1065 # NOTE: Stored RGB but only the green channel carries signal (maxima 41/251/43). 1066 enseg_kwargs = { 1067 "path": os.path.join(input_path, "enseg"), "patch_shape": patch_shape, 1068 "raw_transform": _enseg_green_channel, 1069 **{k: v for k, v in kwargs.items() if k != "raw_transform"}, 1070 } 1071 for animal_tags, n_samples, ds_list in [(ENSEG_TRAIN_ANIMALS, 200, train_ds), (ENSEG_VAL_ANIMALS, 50, val_ds)]: 1072 ds_list.append( 1073 UniDataWrapper( 1074 datasets.get_enseg_dataset(animal_tags=list(animal_tags), n_samples=n_samples, **enseg_kwargs), 1075 source_ndim=2, 1076 ) 1077 ) 1078 1079 # 43. LPC-NucSeg (nucleus segmentation in DNA fluorescence images) 1080 # NOTE: Two cell lines, U2OS (gnf) and NIH3T3 (ic100); a random 10 % of each (seed 42) validates, there is no 1081 # blind test. 1082 lpc_kwargs = {"patch_shape": patch_shape, "raw_key": "raw", "label_key": "labels", "ndim": 2, **kwargs} 1083 for source in LPC_NUCSEG_SOURCES: 1084 lpc_paths = datasets.lpc_nucseg.get_lpc_nucseg_paths(os.path.join(input_path, "lpc_nucseg"), source=source) 1085 lpc_train, lpc_val = train_test_split(lpc_paths, test_size=0.1, random_state=42) 1086 for paths, n_samples, ds_list in [(lpc_train, 100, train_ds), (lpc_val, 25, val_ds)]: 1087 ds_list.append( 1088 UniDataWrapper( 1089 torch_em.default_segmentation_dataset( 1090 raw_paths=paths, label_paths=paths, n_samples=n_samples, **lpc_kwargs 1091 ), source_ndim=2, 1092 ) 1093 ) 1094 1095 # 44. DCIS.COM nuclei (nucleus segmentation in spinning-disk confocal SiR-DNA images) 1096 # NOTE: The official train split trains and the two official test images validate; there is no blind test. 1097 dcis_train_r, dcis_train_l = datasets.dcis_com_nuclei.get_dcis_com_nuclei_paths( 1098 os.path.join(input_path, "dcis_com_nuclei"), split="train", 1099 ) 1100 dcis_val_r, dcis_val_l = datasets.dcis_com_nuclei.get_dcis_com_nuclei_paths( 1101 os.path.join(input_path, "dcis_com_nuclei"), split="test", 1102 ) 1103 dcis_kwargs = { 1104 "patch_shape": patch_shape, "is_seg_dataset": False, "raw_key": None, "label_key": None, "ndim": 2, **kwargs 1105 } 1106 for raws, labs, n_samples, ds_list in [ 1107 (dcis_train_r, dcis_train_l, 200, train_ds), (dcis_val_r, dcis_val_l, 50, val_ds), 1108 ]: 1109 ds_list.append( 1110 UniDataWrapper( 1111 torch_em.default_segmentation_dataset( 1112 raw_paths=raws, label_paths=labs, n_samples=n_samples, **dcis_kwargs 1113 ), source_ndim=2, 1114 ) 1115 ) 1116 1117 # 45. mCellSeg (cell segmentation in DIC and brightfield images of HEK-293T and HUVEC) 1118 # NOTE: The 200 images are split 80 / 10 / 10 at random (seed 42); the test images are blind. 1119 mcellseg_raw, mcellseg_labels = datasets.mcellseg.get_mcellseg_paths(os.path.join(input_path, "mcellseg")) 1120 (mc_train_r, mc_val_r, _), (mc_train_l, mc_val_l, _) = _train_val_test_split(mcellseg_raw, mcellseg_labels) 1121 mcellseg_kwargs = { 1122 "patch_shape": patch_shape, "raw_key": None, "label_key": None, "is_seg_dataset": False, "ndim": 2, **kwargs 1123 } 1124 for raws, labs, n_samples, ds_list in [(mc_train_r, mc_train_l, 200, train_ds), (mc_val_r, mc_val_l, 50, val_ds)]: 1125 ds_list.append( 1126 UniDataWrapper( 1127 torch_em.default_segmentation_dataset( 1128 raw_paths=raws, label_paths=labs, n_samples=n_samples, **mcellseg_kwargs 1129 ), source_ndim=2, 1130 ) 1131 ) 1132 1133 # 46. TOIAM (bacteria segmentation in phase contrast time-lapse colonies) 1134 # NOTE: The colony grows over time, so density is bimodal: a 512 patch holds a median of 39 objects with 1135 # quartiles at 8 and 305. A 25-instance minimum keeps 56 % of patches and cuts the near-empty early frames. 1136 # The five movies are split by movie: 03 validates, 04 is blind. 1137 toiam_raw, toiam_labels = datasets.toiam.get_toiam_paths(os.path.join(input_path, "toiam")) 1138 toiam_movies = [os.path.basename(os.path.dirname(p)) for p in toiam_raw] 1139 toiam_kwargs = { 1140 "patch_shape": patch_shape, "raw_key": None, "label_key": None, "is_seg_dataset": False, "ndim": 2, 1141 **{**kwargs, "sampler": MinInstanceSampler(min_num_instances=25, exclude_ids=[0])}, 1142 } 1143 for keep, n_samples, ds_list in [ 1144 ([m in TOIAM_TRAIN_MOVIES for m in toiam_movies], 400, train_ds), 1145 ([m in TOIAM_VAL_MOVIES for m in toiam_movies], 50, val_ds), 1146 ]: 1147 ds_list.append( 1148 UniDataWrapper( 1149 torch_em.default_segmentation_dataset( 1150 raw_paths=[p for p, k in zip(toiam_raw, keep) if k], 1151 label_paths=[p for p, k in zip(toiam_labels, keep) if k], 1152 n_samples=n_samples, **toiam_kwargs, 1153 ), source_ndim=2, 1154 ) 1155 ) 1156 1157 # 47. Usiigaci (cell segmentation in phase contrast fibroblast images) 1158 usiigaci_kwargs = {"path": os.path.join(input_path, "usiigaci"), "patch_shape": patch_shape, **kwargs} 1159 train_ds.append( 1160 UniDataWrapper(datasets.get_usiigaci_dataset(split="train", n_samples=200, **usiigaci_kwargs), source_ndim=2) 1161 ) 1162 val_ds.append( 1163 UniDataWrapper(datasets.get_usiigaci_dataset(split="val", n_samples=50, **usiigaci_kwargs), source_ndim=2) 1164 ) 1165 1166 # 50. Pan-multiplex (cell segmentation in MIBI, CODEX and Vectra tissue imaging) 1167 # NOTE: The loader returns (nuclei, membrane); they are reordered into TissueNet's membrane, nucleus, zeros. 1168 pan_kwargs = { 1169 "path": os.path.join(input_path, "pan_multiplex"), "patch_shape": patch_shape, 1170 "raw_channel": "both", "raw_transform": _pan_multiplex_tissuenet_order, 1171 **{k: v for k, v in kwargs.items() if k != "raw_transform"}, 1172 } 1173 # The official train / val / test split is used per subset; the test split is blind. 1174 for subset in ["codex_colon", "mibi_breast", "mibi_decidua", "vectra_colon", "vectra_pancreas"]: 1175 for split, n_samples, ds_list in [("train", 150, train_ds), ("val", 30, val_ds)]: 1176 ds_list.append( 1177 UniDataWrapper( 1178 datasets.get_pan_multiplex_dataset(subset=subset, split=split, n_samples=n_samples, **pan_kwargs), 1179 source_ndim=2, 1180 ) 1181 ) 1182 1183 # 51. Xenium (nucleus and cell segmentation in whole-slide multi-tissue stain) 1184 # NOTE: XOA segmented nuclei on DAPI (channel 0) and grew cells from the three morphology stains (channels 1185 # 1-3), so each target gets the channels it was made from. Whole slides are largely empty, hence the sampler. 1186 xenium_sampler = MinInstanceSampler(min_num_instances=10, exclude_ids=[0]) 1187 xenium_nuclei_kwargs = { 1188 "path": os.path.join(input_path, "xenium"), "patch_shape": patch_shape, 1189 "raw_channel": "dapi", "label_channel": "nuclei", 1190 **{**kwargs, "sampler": xenium_sampler}, 1191 } 1192 xenium_cells_kwargs = { 1193 "path": os.path.join(input_path, "xenium"), "patch_shape": patch_shape, 1194 "raw_channel": "stack", "label_channel": "cells", "raw_transform": _xenium_cell_channels, 1195 **{k: v for k, v in kwargs.items() if k != "raw_transform"}, "sampler": xenium_sampler, 1196 } 1197 # The slides are split for both targets: four train, human_skin validates, human_breast is blind. 1198 for xenium_kwargs in (xenium_nuclei_kwargs, xenium_cells_kwargs): 1199 for samples, n_samples, ds_list in [(XENIUM_TRAIN_SAMPLES, 400, train_ds), (XENIUM_VAL_SAMPLES, 50, val_ds)]: 1200 ds_list.append( 1201 UniDataWrapper( 1202 datasets.get_xenium_dataset(sample=list(samples), n_samples=n_samples, **xenium_kwargs), 1203 source_ndim=2, 1204 ) 1205 ) 1206 1207 # 52. GoNuclear (3D nucleus segmentation in confocal Arabidopsis ovules) 1208 # NOTE: Volume 1170 is the blind test volume by convention, 1139 validates. 1209 for z in z_slices: 1210 gonuclear_kwargs = { 1211 "path": os.path.join(input_path, "gonuclear"), 1212 "patch_shape": (z, *patch_shape), 1213 "segmentation_task": "nuclei", 1214 "n_samples": max(1, 400 // n_z), 1215 **kwargs, 1216 } 1217 train_ds.append( 1218 UniDataWrapper( 1219 datasets.get_gonuclear_dataset(sample_ids=GONUCLEAR_TRAIN_SAMPLES, **gonuclear_kwargs), 1220 source_ndim=3, group_key=(3, z), 1221 ) 1222 ) 1223 val_ds.append( 1224 UniDataWrapper( 1225 datasets.get_gonuclear_dataset(sample_ids=GONUCLEAR_VAL_SAMPLES, **gonuclear_kwargs), 1226 source_ndim=3, group_key=(3, z), 1227 ) 1228 ) 1229 1230 # 53. NucVerse3D (3D nucleus segmentation in two-photon liver and confocal fly glia) 1231 # NOTE: Volumes are 320 px or smaller in plane, so a 256 crop is resized up rather than zero-padded. The official 1232 # test volumes are blind. Liver and liver_hcc give up one train volume for validation; drosophila_glia has only 1233 # three train volumes, so the first 20 % of slices of one test volume validate instead. 1234 nucverse_root = os.path.join(input_path, "nucverse3d") 1235 nucverse_train, nucverse_val, nucverse_val_rois = [], [], [] 1236 for name in ("liver", "liver_hcc", "drosophila_glia"): 1237 paths = datasets.nucverse3d.get_nucverse3d_paths(nucverse_root, dataset=name, split="train") 1238 val_volume = NUCVERSE_VAL_VOLUMES.get(name) 1239 nucverse_train.extend(p for p in paths if os.path.basename(p) != val_volume) 1240 if val_volume is not None: 1241 nucverse_val.extend(p for p in paths if os.path.basename(p) == val_volume) 1242 nucverse_val_rois.append((slice(None),)) 1243 glia_test = datasets.nucverse3d.get_nucverse3d_paths(nucverse_root, dataset="drosophila_glia", split="test") 1244 nucverse_val.extend(p for p in glia_test if os.path.basename(p) == NUCVERSE_GLIA_VAL_VOLUME) 1245 nucverse_val_rois.append((NUCVERSE_GLIA_VAL_Z,)) 1246 assert len(nucverse_val) == 3 and len(nucverse_train) == 15 1247 1248 for z in z_slices: 1249 nucverse_kwargs = { 1250 "patch_shape": (z, 256, 256), 1251 "raw_key": "raw", 1252 "label_key": "labels", 1253 "is_seg_dataset": True, 1254 "raw_transform": _resize_raw_to_512, 1255 "label_transform2": ( 1256 partial(_resize_then_em_label_trafo, em_trafo_fn=label_trafo(instances=True)) 1257 if label_trafo is not None else kwargs.get("label_transform2") 1258 ), 1259 "n_samples": max(1, 300 // n_z), 1260 **{k: v for k, v in kwargs.items() if k not in ["raw_transform", "label_transform2"]}, 1261 } 1262 train_ds.append( 1263 UniDataWrapper( 1264 torch_em.default_segmentation_dataset( 1265 raw_paths=nucverse_train, label_paths=nucverse_train, **nucverse_kwargs 1266 ), source_ndim=3, group_key=(3, z), 1267 ) 1268 ) 1269 val_ds.append( 1270 UniDataWrapper( 1271 torch_em.default_segmentation_dataset( 1272 raw_paths=nucverse_val, label_paths=nucverse_val, rois=nucverse_val_rois, **nucverse_kwargs 1273 ), source_ndim=3, group_key=(3, z), 1274 ) 1275 ) 1276 1277 # 54. PhMamm (3D cell segmentation in light-sheet Phallusia embryo membranes) 1278 # NOTE: Volumes are 256 cubed, so the patch is taken at the native in-plane size and resized up. 1279 for z in z_slices: 1280 phmamm_kwargs = { 1281 "path": os.path.join(input_path, "phmamm"), 1282 "patch_shape": (z, 256, 256), 1283 "raw_transform": _resize_raw_to_512, 1284 "label_transform2": ( 1285 partial(_resize_then_em_label_trafo, em_trafo_fn=label_trafo(instances=True)) 1286 if label_trafo is not None else kwargs.get("label_transform2") 1287 ), 1288 "n_samples": max(1, 400 // n_z), 1289 **{k: v for k, v in kwargs.items() if k not in ["raw_transform", "label_transform2"]}, 1290 } 1291 train_ds.append( 1292 UniDataWrapper( 1293 datasets.get_phmamm_dataset(timepoints=PHMAMM_TRAIN_TIMEPOINTS, **phmamm_kwargs), 1294 source_ndim=3, group_key=(3, z), 1295 ) 1296 ) 1297 val_ds.append( 1298 UniDataWrapper( 1299 datasets.get_phmamm_dataset(timepoints=PHMAMM_VAL_TIMEPOINTS, **phmamm_kwargs), 1300 source_ndim=3, group_key=(3, z), 1301 ) 1302 ) 1303 1304 # 56. BBBC030 (CHO cell segmentation in DIC images) 1305 # NOTE: 60 images of 1032x1376 with 1-3 cells per 512 crop, hence the 1-instance sampler. The background spans 1306 # about 4 % of the intensity range, so the raw is min-max normalized instead of percentile normalized. The 1307 # torch-em split (seed 42) gives 40 / 8 / 12 images; the test split is blind. 1308 bbbc030_kwargs = { 1309 "path": os.path.join(input_path, "bbbc030"), "patch_shape": patch_shape, "raw_transform": _minmax_raw_trafo, 1310 **{k: v for k, v in kwargs.items() if k not in ["raw_transform", "sampler"]}, 1311 "sampler": MinInstanceSampler(min_num_instances=1, exclude_ids=[0]), 1312 } 1313 for split, n_samples, ds_list in [("train", 100, train_ds), ("val", 25, val_ds)]: 1314 ds_list.append( 1315 UniDataWrapper( 1316 datasets.get_bbbc030_dataset(split=split, n_samples=n_samples, **bbbc030_kwargs), source_ndim=2, 1317 ) 1318 ) 1319 1320 # 57. Tsakiroglou (nucleus segmentation in the DAPI channel of multiplex IF lymphoma TMA cores) 1321 # NOTE: 41 grayscale crops smaller than 256 px on at least one side, so the whole image is drawn and randomly 1322 # upscaled and padded to the patch shape. A random 10 % of the official train split (seed 42) validates, the 1323 # three official test images are blind. 1324 tsakiroglou_raw, tsakiroglou_labels = datasets.histopathology.tsakiroglou.get_tsakiroglou_paths( 1325 os.path.join(input_path, "tsakiroglou"), split="train", 1326 ) 1327 ts_train_r, ts_val_r, ts_train_l, ts_val_l = train_test_split( 1328 tsakiroglou_raw, tsakiroglou_labels, test_size=0.1, random_state=42 1329 ) 1330 tsakiroglou_kwargs = { 1331 "patch_shape": None, "raw_key": None, "label_key": None, "is_seg_dataset": False, "ndim": 2, 1332 "raw_transform": _to_8bit, 1333 **{k: v for k, v in kwargs.items() if k != "raw_transform"}, 1334 "transform": _with_flips(_random_resize_and_pad_trafo, patch_shape), 1335 } 1336 for raws, labs, n_samples, ds_list in [(ts_train_r, ts_train_l, 100, train_ds), (ts_val_r, ts_val_l, 25, val_ds)]: 1337 ds_list.append( 1338 UniDataWrapper( 1339 torch_em.default_segmentation_dataset( 1340 raw_paths=raws, label_paths=labs, n_samples=n_samples, **tsakiroglou_kwargs 1341 ), source_ndim=2, 1342 ) 1343 ) 1344 1345 # 55. Wing disc (3D cell segmentation in confocal Drosophila wing epithelium) 1346 # NOTE: Native in-plane size is exactly 512, so no resize or padding is needed. 1347 for z in z_slices: 1348 wing_disc_kwargs = { 1349 "path": os.path.join(input_path, "wing_disc"), 1350 "patch_shape": (z, *patch_shape), 1351 "n_samples": max(1, 300 // n_z), 1352 **kwargs, 1353 } 1354 train_ds.append( 1355 UniDataWrapper( 1356 datasets.get_wing_disc_dataset(volumes=WING_DISC_TRAIN_VOLUMES, **wing_disc_kwargs), 1357 source_ndim=3, group_key=(3, z), 1358 ) 1359 ) 1360 val_ds.append( 1361 UniDataWrapper( 1362 datasets.get_wing_disc_dataset( 1363 volumes=WING_DISC_TEST_VOLUMES, rois=[(WING_DISC_VAL_Z,)] * len(WING_DISC_TEST_VOLUMES), 1364 **wing_disc_kwargs, 1365 ), source_ndim=3, group_key=(3, z), 1366 ) 1367 ) 1368 1369 # 58. CochleaNet SGN (3D soma segmentation of spiral ganglion neurons, PV stain, light-sheet mouse cochlea) 1370 # NOTE: Internal data with official train and val folders. The blocks are 256 px in plane and are resized up. The 1371 # module leaves out the empty blocks and the 'resized' ones, which were interpolated and are only partly labelled. 1372 cochleanet_root = os.path.join(input_path, "cochleanet_data") 1373 for z in z_slices: 1374 sgn_kwargs = { 1375 "patch_shape": (z, 256, 256), 1376 "raw_transform": _resize_raw_to_512, 1377 "label_transform2": ( 1378 partial(_resize_then_em_label_trafo, em_trafo_fn=label_trafo(instances=True)) 1379 if label_trafo is not None else kwargs.get("label_transform2") 1380 ), 1381 "sampler": MinInstanceSampler(min_num_instances=4, exclude_ids=[0]), 1382 "n_samples": max(1, 300 // n_z), 1383 **{k: v for k, v in kwargs.items() if k not in ["raw_transform", "label_transform2", "sampler"]}, 1384 } 1385 for split, ds_list in [("train", train_ds), ("val", val_ds)]: 1386 ds_list.append( 1387 UniDataWrapper( 1388 cochleanet_data.get_cochleanet_dataset(cochleanet_root, name="sgn", split=split, **sgn_kwargs), 1389 source_ndim=3, group_key=(3, z), 1390 ) 1391 ) 1392 1393 # 59. CochleaNet IHC (3D cell segmentation of inner hair cells, Vglut3 stain, light-sheet mouse cochlea) 1394 # NOTE: Internal data with official train and val folders. The hair cells form one row, so a block is 1-7 % 1395 # labelled, holds few cells per crop and gets a lower sampler minimum than the SGN blocks. The blocks come in 1396 # three in-plane sizes and get one leaf each: 256 and 392 are resized up, 512 is native. The module reorients the 1397 # 512x512x256 blocks so that their short axis is z and leaves out the 'G-LR' crops, which label a few hair cells 1398 # next to unlabelled rows of cells. 1399 for z in z_slices: 1400 for split, ds_list in [("train", train_ds), ("val", val_ds)]: 1401 paths = cochleanet_data.get_cochleanet_paths(cochleanet_root, name="ihc", split=split) 1402 groups = {} 1403 for path in paths: 1404 groups.setdefault(_ihc_patch_size(_in_plane_size(path)), []).append(path) 1405 for size, group_paths in sorted(groups.items()): 1406 resize = size < 512 1407 ihc_kwargs = { 1408 "patch_shape": (z, size, size), 1409 "raw_key": "raw", 1410 "label_key": "labels", 1411 "is_seg_dataset": True, 1412 "raw_transform": _resize_raw_to_512 if resize else kwargs["raw_transform"], 1413 "label_transform2": ( 1414 ( 1415 partial(_resize_then_em_label_trafo, em_trafo_fn=label_trafo(instances=True)) if resize 1416 else label_trafo() 1417 ) 1418 if label_trafo is not None else kwargs.get("label_transform2") 1419 ), 1420 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 1421 "n_samples": max(1, (200 // n_z) * len(group_paths) // len(paths)), 1422 **{k: v for k, v in kwargs.items() if k not in ["raw_transform", "label_transform2", "sampler"]}, 1423 } 1424 ds_list.append( 1425 UniDataWrapper( 1426 torch_em.default_segmentation_dataset( 1427 raw_paths=group_paths, label_paths=group_paths, **ihc_kwargs 1428 ), source_ndim=3, group_key=(3, z), 1429 ) 1430 ) 1431 1432 return train_ds, val_ds 1433 1434 1435def _in_plane_size(path): 1436 """The smaller in-plane extent of an h5 volume stored as (z, y, x).""" 1437 with open_file(path, "r") as f: 1438 return min(f["raw"].shape[1:]) 1439 1440 1441def _ihc_patch_size(size): 1442 """The in-plane patch size of a CochleaNet IHC block: 512 native, otherwise the largest of 256 and 392 it holds.""" 1443 return 512 if size >= 512 else 392 if size >= 392 else 256 1444 1445 1446def _get_em_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo, _em_label_trafo=None): 1447 """Get all electron microscopy (EM) datasets for generalist training. 1448 1449 Args: 1450 _em_label_trafo: EM cell label transform function to use. Defaults to 1451 :func:`_em_cell_label_trafo`. Pass :func:`_joint_em_cell_label_trafo` 1452 when building joint interactive+automatic datasets. 1453 1454 Returns: 1455 Tuple of (train_ds, val_ds) lists of UniDataWrapper instances. 1456 """ 1457 if _em_label_trafo is None: 1458 _em_label_trafo = _em_cell_label_trafo 1459 1460 # Connectomics ids exceed 2^24 and would merge in the float32 flip augmentation. 1461 kwargs = {**kwargs, "label_transform": partial(_compact_label_ids, keep=(PLATY_IGNORE_LABEL,))} 1462 1463 train_ds, val_ds = [], [] 1464 n_z = len(z_slices) 1465 1466 # 1. CREMI (neuron segmentation in vEM) 1467 # NOTE: Neurons are large - a patch typically contains only 1-2 of them, so min_num_instances=3 1468 # would reject nearly every sample. Use min_num_instances=1 to require just one foreground object. 1469 for z in z_slices: 1470 cremi_kwargs = { 1471 "path": os.path.join(input_path, "cremi"), 1472 "patch_shape": (z, *patch_shape), 1473 "label_transform2": ( 1474 partial(_em_label_trafo, label_trafo=label_trafo(instances=True, sampling=(10, 1, 1))) 1475 if label_trafo is not None else kwargs.get("label_transform2") 1476 ), 1477 "sampler": MinInstanceSampler(min_num_instances=1, exclude_ids=[0]), 1478 "defect_augmentation_kwargs": { 1479 "p_drop_slice": 0.025, 1480 "p_low_contrast": 0.0, 1481 "p_deform_slice": 0.0, 1482 "deformation_mode": "compress", 1483 }, 1484 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]} 1485 } 1486 1487 # Sample C is the blind in-domain test set (shared with NeuronSeg); the last 25 of the 125 sections of 1488 # A and B validate. 1489 for rois, ds_list, n_samples in [ 1490 ({"A": np.s_[:100, :, :], "B": np.s_[:100, :, :]}, train_ds, 500), 1491 ({"A": np.s_[100:, :, :], "B": np.s_[100:, :, :]}, val_ds, 50), 1492 ]: 1493 ds_list.append( 1494 UniDataWrapper( 1495 datasets.get_cremi_dataset( 1496 samples=("A", "B"), rois=rois, n_samples=max(1, n_samples // n_z), **cremi_kwargs 1497 ), 1498 source_ndim=3, group_key=(3, z), 1499 ) 1500 ) 1501 1502 # 2. EMNeuron (neuron segmentation in vEM) 1503 # NOTE: Large neurons - use min_num_instances=1 (same reasoning as CREMI). 1504 # J0126-sbem (train: 150×150 or 256×256 XY) and FIB25 (val: 250×250 XY) are too small 1505 # for the standard 512×512 patch shape - they get their own 128×128 patch group with a 1506 # resize-to-512 transform applied to both raw and label before the EM label transform. 1507 from torch_em.data.datasets.electron_microscopy.emneuron import get_emneuron_paths 1508 1509 emneuron_path = os.path.join(input_path, "emneuron") 1510 all_train_raw, all_train_lbl = get_emneuron_paths(emneuron_path, "train") 1511 # The AxonEM, CREMI and FIB-25 folders copy the public releases at full depth, including the sections and 1512 # volumes the direct loaders hold out for validation and testing, so they train through those loaders only. 1513 keep = [not any(f"{os.sep}{folder}{os.sep}" in p for folder in EMNEURON_EXCLUDED_FOLDERS) for p in all_train_raw] 1514 all_train_raw = [p for p, k in zip(all_train_raw, keep) if k] 1515 all_train_lbl = [p for p, k in zip(all_train_lbl, keep) if k] 1516 all_val_raw, all_val_lbl = get_emneuron_paths(emneuron_path, "val") 1517 # Only the in-distribution validation volumes validate. The out-of-distribution folder holds the Harris 1518 # hippocampus volume, the source of the SynapseWeb OOD test, next to Ionsem and Microns. 1519 keep = [os.sep + "InDistribution" + os.sep in p for p in all_val_raw] 1520 all_val_raw = [p for p, k in zip(all_val_raw, keep) if k] 1521 all_val_lbl = [p for p, k in zip(all_val_lbl, keep) if k] 1522 1523 def _split(raw_paths, label_paths, small_keys): 1524 small_r = [r for r in raw_paths if any(k in r for k in small_keys)] 1525 small_l = [l for r, l in zip(raw_paths, label_paths) if any(k in r for k in small_keys)] 1526 rest_r = [r for r in raw_paths if not any(k in r for k in small_keys)] 1527 rest_l = [l for r, l in zip(raw_paths, label_paths) if not any(k in r for k in small_keys)] 1528 return small_r, small_l, rest_r, rest_l 1529 1530 sm_train_r, sm_train_l, rest_train_r, rest_train_l = _split(all_train_raw, all_train_lbl, ["J0126"]) 1531 sm_val_r, sm_val_l, rest_val_r, rest_val_l = _split(all_val_raw, all_val_lbl, ["J0126", "FIB25"]) 1532 1533 base_sampler = MinInstanceSampler(min_num_instances=1, exclude_ids=[0]) 1534 base_kwargs = {k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]} 1535 base_kwargs["label_transform"] = partial(_compact_native_label_ids, keep=(PLATY_IGNORE_LABEL,)) 1536 1537 for z in z_slices: 1538 em_label_trafo_fn = ( 1539 partial(_em_label_trafo, label_trafo=label_trafo(instances=True)) 1540 if label_trafo is not None else kwargs.get("label_transform2") 1541 ) 1542 1543 # Normal volumes (XY >= 512) 1544 rest_kwargs = { 1545 "patch_shape": (z, *patch_shape), 1546 "label_transform2": em_label_trafo_fn, 1547 "sampler": base_sampler, 1548 **base_kwargs, 1549 } 1550 train_ds.append(UniDataWrapper( 1551 torch_em.default_segmentation_dataset( 1552 raw_paths=rest_train_r, raw_key=None, label_paths=rest_train_l, label_key=None, 1553 is_seg_dataset=True, n_samples=max(1, 500 // n_z), **rest_kwargs, 1554 ), source_ndim=3, group_key=(3, z), 1555 )) 1556 val_ds.append(UniDataWrapper( 1557 torch_em.default_segmentation_dataset( 1558 raw_paths=rest_val_r, raw_key=None, label_paths=rest_val_l, label_key=None, 1559 is_seg_dataset=True, n_samples=max(1, 450 // n_z), **rest_kwargs, 1560 ), source_ndim=3, group_key=(3, z), 1561 )) 1562 1563 # Small volumes (J0126 train; J0126+FIB25 val): 128×128 patches -> resize to 512×512 1564 small_kwargs = { 1565 "patch_shape": (z, 128, 128), 1566 "raw_transform": _resize_raw_to_512, 1567 "label_transform2": partial(_resize_then_em_label_trafo, em_trafo_fn=em_label_trafo_fn), 1568 "sampler": base_sampler, 1569 **{k: v for k, v in base_kwargs.items() if k != "raw_transform"}, 1570 } 1571 train_ds.append(UniDataWrapper( 1572 torch_em.default_segmentation_dataset( 1573 raw_paths=sm_train_r, raw_key=None, label_paths=sm_train_l, label_key=None, 1574 is_seg_dataset=True, n_samples=max(1, 500 // n_z), **small_kwargs, 1575 ), source_ndim=3, group_key=(3, z), 1576 )) 1577 val_ds.append(UniDataWrapper( 1578 torch_em.default_segmentation_dataset( 1579 raw_paths=sm_val_r, raw_key=None, label_paths=sm_val_l, label_key=None, 1580 is_seg_dataset=True, n_samples=max(1, 450 // n_z), **small_kwargs, 1581 ), source_ndim=3, group_key=(3, z), 1582 )) 1583 1584 # 3. Platynereis (cell segmentation in vEM) 1585 platy_root = os.path.join(input_path, "platynereis") 1586 platy_cell_template = "membrane/train_data_membrane_%02i.n5" 1587 label_key = "volumes/labels/segmentation/s1" 1588 1589 # Volume 9 is held out: its neuropil id covers 41% of the volume, the largest share of any volume. 1590 platy_train_ids, platy_val_ids = [1, 2, 3, 4, 5, 6], [7, 8] 1591 1592 train_rois = _compute_platy_rois( 1593 platy_root, platy_train_ids, ignore_label=0, file_template=platy_cell_template, label_key=label_key, 1594 ) 1595 val_rois = _compute_platy_rois( 1596 platy_root, platy_val_ids, ignore_label=0, file_template=platy_cell_template, label_key=label_key, 1597 ) 1598 1599 for z in z_slices: 1600 platynereis_kwargs = { 1601 "path": os.path.join(input_path, "platynereis"), 1602 "patch_shape": (z, *patch_shape), 1603 # sampling=None: ~20nm isotropic 1604 "label_transform2": ( 1605 partial( 1606 _em_label_trafo, label_trafo=label_trafo(instances=True), ignore_label=PLATY_IGNORE_LABEL 1607 ) 1608 if label_trafo is not None else partial( 1609 _ignore_label_trafo, ignore_label=PLATY_IGNORE_LABEL, label_trafo=kwargs.get("label_transform2") 1610 ) 1611 ), 1612 # The neuropil ignore label is not an instance, so the sampler must not count it. 1613 "sampler": MinInstanceSampler(min_num_instances=1, exclude_ids=[0, PLATY_IGNORE_LABEL]), 1614 # Volumes 7 and 8 hold an unannotated tissue band (12 % and 8 % of the roi) next to the labelled 1615 # cells; it maps to the ignore label instead of being trained as background. Volumes 1-6 are fully 1616 # labelled, so the transform leaves them unchanged. 1617 "transform": partial( 1618 _ignore_unlabelled_blobs_trafo, ignore_label=PLATY_IGNORE_LABEL, min_area=2000, 1619 transform=get_augmentations(ndim=3), 1620 ), 1621 # get_platynereis_cell_dataset concatenates one dataset per volume, so n_samples is per volume. 1622 "n_samples": max(1, 500 // (n_z * len(platy_train_ids))), 1623 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler", "transform"]} 1624 } 1625 1626 train_ds.append( 1627 UniDataWrapper( 1628 datasets.get_platynereis_cell_dataset( 1629 sample_ids=platy_train_ids, rois=train_rois, **platynereis_kwargs 1630 ), 1631 source_ndim=3, group_key=(3, z), 1632 ) 1633 ) 1634 val_ds.append( 1635 UniDataWrapper( 1636 datasets.get_platynereis_cell_dataset( 1637 sample_ids=platy_val_ids, rois=val_rois, **platynereis_kwargs 1638 ), 1639 source_ndim=3, group_key=(3, z), 1640 ) 1641 ) 1642 1643 # 4. SNEMI (neuron segmentation in vEM) 1644 # The official test volume has no public labels, so the 100 training sections split into train, val and a 1645 # blind test slab: z < 60, 60 <= z < 80, z >= 80. 1646 snemi_train_rois = np.s_[:60, :, :] 1647 snemi_val_rois = np.s_[60:80, :, :] 1648 1649 for z in z_slices: 1650 snemi_kwargs = { 1651 "path": os.path.join(input_path, "snemi"), 1652 "patch_shape": (z, *patch_shape), 1653 "n_samples": max(1, 500 // n_z), 1654 "label_transform2": ( 1655 partial(_em_label_trafo, label_trafo=label_trafo(instances=True, sampling=(5, 1, 1))) 1656 if label_trafo is not None else kwargs.get("label_transform2") 1657 ), 1658 "sampler": MinInstanceSampler(min_num_instances=1, exclude_ids=[0]), 1659 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 1660 } 1661 1662 train_ds.append( 1663 UniDataWrapper( 1664 datasets.get_snemi_dataset(rois=snemi_train_rois, **snemi_kwargs), source_ndim=3, group_key=(3, z), 1665 ) 1666 ) 1667 val_ds.append( 1668 UniDataWrapper( 1669 datasets.get_snemi_dataset(rois=snemi_val_rois, **snemi_kwargs), source_ndim=3, group_key=(3, z), 1670 ) 1671 ) 1672 1673 # 5. Igor cells (cell segmentation in vEM) 1674 # NOTE: This data is used for training only. No validation data is added for it. 1675 # The volumes are (16, 1024, 1024) uint8 blocks with dense uint32 instance labels. 1676 igor_cells_root = os.path.join(input_path, "igor_cells") 1677 all_igor_cells_paths = sorted(glob(os.path.join(igor_cells_root, "data_block_*.tif"))) 1678 igor_cells_raw_paths = [p for p in all_igor_cells_paths if not p.endswith("_seg.tif")] 1679 igor_cells_label_paths = [p.replace(".tif", "_seg.tif") for p in igor_cells_raw_paths] 1680 assert igor_cells_raw_paths, f"Did not find any volumes in '{igor_cells_root}'." 1681 assert all(os.path.exists(p) for p in igor_cells_label_paths) 1682 1683 for z in z_slices: 1684 igor_cells_kwargs = { 1685 "patch_shape": (z, *patch_shape), 1686 "n_samples": max(1, 500 // n_z), 1687 # sampling=None: the volumes are isotropic. 1688 "label_transform2": ( 1689 partial(_em_label_trafo, label_trafo=label_trafo(instances=True)) 1690 if label_trafo is not None else kwargs.get("label_transform2") 1691 ), 1692 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 1693 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]} 1694 } 1695 1696 train_ds.append( 1697 UniDataWrapper( 1698 torch_em.default_segmentation_dataset( 1699 raw_paths=igor_cells_raw_paths, raw_key=None, 1700 label_paths=igor_cells_label_paths, label_key=None, 1701 is_seg_dataset=True, **igor_cells_kwargs, 1702 ), source_ndim=3, group_key=(3, z), 1703 ) 1704 ) 1705 1706 # 6. AxonEM (axon segmentation in vEM of human and mouse cortex) 1707 # NOTE: Only a central 50x512x512 block per volume is annotated, so each is cropped to its label bounding 1708 # box. Three mouse blocks lie inside a soma (one or two ids, no neurite boundaries) and are dropped. 1709 axonem_raw_paths, axonem_label_paths = datasets.axonem.get_axonem_paths( 1710 path=os.path.join(input_path, "axonem"), samples=("human", "mouse"), download=True, 1711 ) 1712 axonem_rois = _compute_label_rois(axonem_label_paths, label_key="main", min_ids=AXONEM_MIN_IDS) 1713 axonem_raw_paths = [p for p, lp in zip(axonem_raw_paths, axonem_label_paths) if lp in axonem_rois] 1714 axonem_label_paths = [lp for lp in axonem_label_paths if lp in axonem_rois] 1715 axonem_val = [p for p in axonem_label_paths if os.path.basename(p) in AXONEM_VAL_VOLUMES] 1716 axonem_test = [p for p in axonem_label_paths if os.path.basename(p) in AXONEM_TEST_VOLUMES] 1717 axonem_train = [p for p in axonem_label_paths if p not in axonem_val + axonem_test] 1718 assert len(axonem_val) == len(AXONEM_VAL_VOLUMES) and len(axonem_test) == len(AXONEM_TEST_VOLUMES) 1719 1720 for z in z_slices: 1721 axonem_kwargs = { 1722 "patch_shape": (z, *patch_shape), 1723 # sampling=None: 30nm isotropic. 1724 "label_transform2": ( 1725 partial( 1726 _em_label_trafo, label_trafo=label_trafo(instances=True), ignore_label=MISSING_RAW_IGNORE_LABEL 1727 ) 1728 if label_trafo is not None else partial( 1729 _ignore_label_trafo, ignore_label=MISSING_RAW_IGNORE_LABEL, 1730 label_trafo=kwargs.get("label_transform2"), 1731 ) 1732 ), 1733 # Some slices hold missing tiles (exact-zero raw) that still carry labels; they become ignore. The test 1734 # needs the stored intensities, so the raw is only prepared here and normalized inside the transform. 1735 "raw_transform": _prepare_identity, 1736 "transform": partial( 1737 _ignore_missing_raw_trafo, ignore_label=MISSING_RAW_IGNORE_LABEL, transform=get_augmentations(ndim=3) 1738 ), 1739 # uint8 labels cannot hold the ignore label, and torch_em recasts to the loaded dtype. 1740 "pre_label_transform": _labels_to_uint32, 1741 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 1742 **{ 1743 k: v for k, v in kwargs.items() 1744 if k not in ["raw_transform", "label_transform2", "sampler", "transform", "pre_label_transform"] 1745 }, 1746 } 1747 for label_paths, ds_list, n_samples in [(axonem_train, train_ds, 500), (axonem_val, val_ds, 50)]: 1748 raw_paths = [p.replace("seg_", "im_") for p in label_paths] 1749 ds_list.append( 1750 UniDataWrapper( 1751 torch_em.default_segmentation_dataset( 1752 raw_paths=raw_paths, raw_key="main", label_paths=label_paths, label_key="main", 1753 rois=[axonem_rois[p] for p in label_paths], is_seg_dataset=True, 1754 n_samples=max(1, n_samples // n_z), **axonem_kwargs, 1755 ), source_ndim=3, group_key=(3, z), 1756 ) 1757 ) 1758 1759 # 7. FAFB (neuron segmentation in ssTEM of the full adult fly brain, FlyWire v783 labels) 1760 # NOTE: Streamed from GCS and cached per box at 16x16x40 nm, the finest level of the segmentation. torch_em's 1761 # default boxes are tissue-verified 1024x1024x410 crops; one is the validation set. 1762 for z in z_slices: 1763 fafb_kwargs = { 1764 "path": os.path.join(input_path, "fafb"), 1765 "patch_shape": (z, *patch_shape), 1766 "download": True, 1767 # sampling: z is 2.5x coarser than xy. 1768 "label_transform2": ( 1769 partial(_em_label_trafo, label_trafo=label_trafo(instances=True, sampling=(2.5, 1, 1))) 1770 if label_trafo is not None else kwargs.get("label_transform2") 1771 ), 1772 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 1773 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 1774 } 1775 for boxes, ds_list, n_samples in [(FAFB_TRAIN_BOXES, train_ds, 500), (FAFB_VAL_BOXES, val_ds, 50)]: 1776 ds_list.append( 1777 UniDataWrapper( 1778 datasets.get_fafb_dataset(bounding_boxes=boxes, n_samples=max(1, n_samples // n_z), **fafb_kwargs), 1779 source_ndim=3, group_key=(3, z), 1780 ) 1781 ) 1782 1783 # 8. ASTIH (myelinated axon segmentation in SEM and brightfield nerve) 1784 # NOTE: SEM1, BF1 and BF2 only; TEM is covered by AxonDeepSeg and TEM1 alone would dominate. Labels are 1785 # semantic (1=myelin, 2=axon): instances are components of the axon class, since touching sheaths would 1786 # bridge neighbouring fibres. The 22 train images split 80/20, the 4 test images stay blind. 1787 astih_paths = datasets.astih.get_astih_paths( 1788 path=os.path.join(input_path, "astih"), name=ASTIH_SUBSETS, split="train", download=True, 1789 ) 1790 astih_train, astih_val = train_test_split(astih_paths, test_size=0.2, random_state=42) 1791 astih_kwargs = { 1792 "patch_shape": patch_shape, 1793 "raw_transform": _to_8bit, 1794 "pre_label_transform": _astih_pre_label_transform, 1795 "label_transform2": ( 1796 partial(_em_label_trafo, label_trafo=label_trafo(instances=True)) 1797 if label_trafo is not None else kwargs.get("label_transform2") 1798 ), 1799 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 1800 "ndim": 2, 1801 **{k: v for k, v in kwargs.items() if k not in ["raw_transform", "label_transform2", "sampler"]}, 1802 } 1803 for paths, ds_list, n_samples in [(astih_train, train_ds, 300), (astih_val, val_ds, 50)]: 1804 ds_list.append( 1805 UniDataWrapper( 1806 torch_em.default_segmentation_dataset( 1807 raw_paths=paths, raw_key="raw", label_paths=paths, label_key="labels", 1808 is_seg_dataset=True, n_samples=n_samples, **astih_kwargs, 1809 ), source_ndim=2, 1810 ) 1811 ) 1812 1813 # 9. FIB-25 (neuron segmentation in FIB-SEM of the Drosophila medulla, 8 nm isotropic) 1814 # NOTE: training_sample2 and validation_sample train, tstvol-520-1 stays blind; FIB-25 adds no validation leaf. 1815 for z in z_slices: 1816 fib25_kwargs = { 1817 "path": os.path.join(input_path, "fib25"), 1818 "patch_shape": (z, *patch_shape), 1819 "download": True, 1820 "ndim": 3, 1821 # sampling=None: 8 nm isotropic. 1822 "label_transform2": ( 1823 partial(_em_label_trafo, label_trafo=label_trafo(instances=True)) 1824 if label_trafo is not None else kwargs.get("label_transform2") 1825 ), 1826 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 1827 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 1828 } 1829 train_ds.append( 1830 UniDataWrapper( 1831 datasets.get_fib25_dataset(samples=FIB25_TRAIN_SAMPLES, n_samples=max(1, 500 // n_z), **fib25_kwargs), 1832 source_ndim=3, group_key=(3, z), 1833 ) 1834 ) 1835 1836 # 10. Hemibrain (neuron segmentation in FIB-SEM of the Drosophila central brain, 8 nm isotropic) 1837 # NOTE: One cached 1024^3 crop (torch_em's default box), ~99% of voxels labelled, proofread. Same pipeline as 1838 # MANC and MaleCNS. 1839 for z in z_slices: 1840 hemibrain_kwargs = { 1841 "path": os.path.join(input_path, "hemibrain"), 1842 "patch_shape": (z, *patch_shape), 1843 "label_choice": "neurons", 1844 "download": True, 1845 "ndim": 3, 1846 "label_transform2": ( 1847 partial(_em_label_trafo, label_trafo=label_trafo(instances=True)) 1848 if label_trafo is not None else kwargs.get("label_transform2") 1849 ), 1850 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 1851 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 1852 } 1853 # Of the 1024 sections, z < 700 train, 700 <= z < 820 validate and z >= 820 stay blind. 1854 for roi, ds_list, n_samples in [(np.s_[:700, :, :], train_ds, 500), (np.s_[700:820, :, :], val_ds, 50)]: 1855 ds_list.append( 1856 UniDataWrapper( 1857 datasets.get_hemibrain_dataset(rois=[roi], n_samples=max(1, n_samples // n_z), **hemibrain_kwargs), 1858 source_ndim=3, group_key=(3, z), 1859 ) 1860 ) 1861 1862 # 11. MANC (neuron segmentation in FIB-SEM of the Drosophila male adult nerve cord, 8 nm isotropic) 1863 # NOTE: A separate specimen from MaleCNS (bucket flyem-vnc-2-26), so the two do not overlap. One cached 1864 # 1024^3 crop (torch_em's default box). 1865 for z in z_slices: 1866 manc_kwargs = { 1867 "path": os.path.join(input_path, "manc"), 1868 "patch_shape": (z, *patch_shape), 1869 "download": True, 1870 "ndim": 3, 1871 "label_transform2": ( 1872 partial(_em_label_trafo, label_trafo=label_trafo(instances=True)) 1873 if label_trafo is not None else kwargs.get("label_transform2") 1874 ), 1875 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 1876 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 1877 } 1878 # Of the 1024 sections, z < 700 train, 700 <= z < 820 validate and z >= 820 stay blind. 1879 for roi, ds_list, n_samples in [(np.s_[:700, :, :], train_ds, 500), (np.s_[700:820, :, :], val_ds, 50)]: 1880 ds_list.append( 1881 UniDataWrapper( 1882 datasets.get_manc_dataset(rois=[roi], n_samples=max(1, n_samples // n_z), **manc_kwargs), 1883 source_ndim=3, group_key=(3, z), 1884 ) 1885 ) 1886 1887 # 12. MaleCNS (neuron segmentation in FIB-SEM of the whole Drosophila male CNS, 8 nm isotropic) 1888 # NOTE: Six 1024^3 crops streamed from GCS, placed by probing the segmentation density along the 1889 # brain-neck-VNC axis; four train, one VNC crop validates and the neck connective crop stays blind. 1890 for z in z_slices: 1891 malecns_kwargs = { 1892 "path": os.path.join(input_path, "malecns"), 1893 "patch_shape": (z, *patch_shape), 1894 "download": True, 1895 "ndim": 3, 1896 "label_transform2": ( 1897 partial(_em_label_trafo, label_trafo=label_trafo(instances=True)) 1898 if label_trafo is not None else kwargs.get("label_transform2") 1899 ), 1900 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 1901 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 1902 } 1903 for boxes, ds_list, n_samples in [(MALECNS_TRAIN_BOXES, train_ds, 500), (MALECNS_VAL_BOXES, val_ds, 50)]: 1904 ds_list.append( 1905 UniDataWrapper( 1906 datasets.get_malecns_dataset( 1907 bounding_boxes=boxes, n_samples=max(1, n_samples // n_z), **malecns_kwargs 1908 ), source_ndim=3, group_key=(3, z), 1909 ) 1910 ) 1911 1912 # 13. Wafer4 (neuron segmentation in multi-beam SEM of mouse medial entorhinal cortex, layer 6) 1913 # NOTE: One 125x1250x1250 volume at 8x8x35 nm. The authors' split is z < 100 train, z >= 100 test; the test 1914 # sections stay blind and validation is the last fifth of the training sections. 1915 for z in z_slices: 1916 wafer4_kwargs = { 1917 "path": os.path.join(input_path, "wafer4"), 1918 "patch_shape": (z, *patch_shape), 1919 "split": "train", 1920 "download": True, 1921 "label_transform2": ( 1922 partial(_em_label_trafo, label_trafo=label_trafo(instances=True, sampling=(4.4, 1, 1))) 1923 if label_trafo is not None else kwargs.get("label_transform2") 1924 ), 1925 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 1926 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 1927 } 1928 for roi, ds_list, n_samples in [(np.s_[:80, :, :], train_ds, 300), (np.s_[80:, :, :], val_ds, 50)]: 1929 ds_list.append( 1930 UniDataWrapper( 1931 datasets.get_wafer4_dataset(rois=roi, n_samples=max(1, n_samples // n_z), **wafer4_kwargs), 1932 source_ndim=3, group_key=(3, z), 1933 ) 1934 ) 1935 1936 # 14. MICrONS minnie65 (neuron segmentation in the cubic-millimetre mouse visual cortex, 8x8x40 nm) 1937 # NOTE: torch_em's own split of 14 cached 512x4096x4096 boxes: 8 train, 2 val, 4 test kept blind. At 69 G 1938 # voxels the train split is the largest EM source by far; n_samples keeps its epoch share in line. 1939 for z in z_slices: 1940 minnie_kwargs = { 1941 "path": os.path.join(input_path, "microns-minnie65"), 1942 "patch_shape": (z, *patch_shape), 1943 "download": True, 1944 "ndim": 3, 1945 "label_transform2": ( 1946 partial(_em_label_trafo, label_trafo=label_trafo(instances=True, sampling=(5, 1, 1))) 1947 if label_trafo is not None else kwargs.get("label_transform2") 1948 ), 1949 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 1950 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 1951 } 1952 for split, ds_list, n_samples in [("train", train_ds, 800), ("val", val_ds, 50)]: 1953 ds_list.append( 1954 UniDataWrapper( 1955 datasets.get_microns_minnie65_dataset( 1956 split=split, n_samples=max(1, n_samples // n_z), **minnie_kwargs 1957 ), source_ndim=3, group_key=(3, z), 1958 ) 1959 ) 1960 1961 # 15. MICrONS pinky (hand-annotated neuron instances in ssEM of mouse visual cortex, 4x4x40 nm) 1962 # NOTE: Each file is cropped to the bounding box of 'volumes/mask', the annotated region inside padded 1963 # context. Only the neuropil blocks are used; basil splits nucleus and cytoplasm into separate ids. 1964 pinky_root = os.path.join(input_path, "microns", "pinky") 1965 for z in z_slices: 1966 pinky_kwargs = { 1967 "patch_shape": (z, *patch_shape), 1968 "ndim": 3, 1969 "label_transform2": ( 1970 partial(_em_label_trafo, label_trafo=label_trafo(instances=True, sampling=(10, 1, 1))) 1971 if label_trafo is not None else kwargs.get("label_transform2") 1972 ), 1973 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 1974 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 1975 } 1976 for files, ds_list, n_samples in [(PINKY_TRAIN_FILES, train_ds, 300), (PINKY_VAL_FILES, val_ds, 50)]: 1977 paths = [os.path.join(pinky_root, name) for name in files] 1978 ds_list.append( 1979 UniDataWrapper( 1980 torch_em.default_segmentation_dataset( 1981 raw_paths=paths, raw_key="volumes/image", label_paths=paths, label_key="volumes/segmentation", 1982 rois=[PINKY_MASK_ROIS[name] for name in files], is_seg_dataset=True, 1983 n_samples=max(1, n_samples // n_z), **pinky_kwargs, 1984 ), source_ndim=3, group_key=(3, z), 1985 ) 1986 ) 1987 1988 # 16. Zebrafinch j0126 (neuron segmentation in SBEM of zebra finch Area X, 10x10x20 nm, Kornfeld lab) 1989 # NOTE: Somata, vessels and missing tiles carry no id, so unlabelled blobs above 2 um^2 map to the ignore 1990 # label. The last fifth of z validates. j0251 (10x10x25 nm) uses boxes placed by a tissue scan, since 1991 # torch_em's cached boxes sit at the empty volume corner. 1992 for z in z_slices: 1993 zebrafinch_kwargs = { 1994 "path": os.path.join(input_path, "zebrafinch"), 1995 "patch_shape": (z, *patch_shape), 1996 "dataset": "j0126", 1997 "bounding_box": ZEBRAFINCH_J0126_BOX, 1998 "label_choice": "neurons", 1999 "download": True, 2000 "ndim": 3, 2001 "label_transform2": ( 2002 partial( 2003 _em_label_trafo, label_trafo=label_trafo(instances=True, sampling=(2, 1, 1)), 2004 ignore_label=MISSING_RAW_IGNORE_LABEL, 2005 ) 2006 if label_trafo is not None else partial( 2007 _ignore_label_trafo, ignore_label=MISSING_RAW_IGNORE_LABEL, 2008 label_trafo=kwargs.get("label_transform2"), 2009 ) 2010 ), 2011 "raw_transform": _prepare_identity, # the missing-tile test needs the stored intensities 2012 "transform": partial( 2013 _ignore_missing_raw_trafo, ignore_label=MISSING_RAW_IGNORE_LABEL, 2014 transform=partial( 2015 _ignore_unlabelled_blobs_trafo, ignore_label=MISSING_RAW_IGNORE_LABEL, min_area=20000, 2016 transform=get_augmentations(ndim=3), 2017 ), 2018 ), 2019 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0, MISSING_RAW_IGNORE_LABEL]), 2020 **{ 2021 k: v for k, v in kwargs.items() 2022 if k not in ["raw_transform", "label_transform2", "sampler", "transform"] 2023 }, 2024 } 2025 # Of the 640 cached sections, z < 448 train, 448 <= z < 512 validate and z >= 512 stay blind. 2026 for roi, ds_list, n_samples in [(np.s_[:448, :, :], train_ds, 500), (np.s_[448:512, :, :], val_ds, 50)]: 2027 ds_list.append( 2028 UniDataWrapper( 2029 datasets.get_zebrafinch_dataset( 2030 rois=roi, n_samples=max(1, n_samples // n_z), **zebrafinch_kwargs 2031 ), 2032 source_ndim=3, group_key=(3, z), 2033 ) 2034 ) 2035 j0251_kwargs = {**zebrafinch_kwargs, "dataset": "j0251"} 2036 j0251_kwargs["label_transform2"] = ( 2037 partial( 2038 _em_label_trafo, label_trafo=label_trafo(instances=True, sampling=(2.5, 1, 1)), 2039 ignore_label=MISSING_RAW_IGNORE_LABEL, 2040 ) 2041 if label_trafo is not None else partial( 2042 _ignore_label_trafo, ignore_label=MISSING_RAW_IGNORE_LABEL, label_trafo=kwargs.get("label_transform2") 2043 ) 2044 ) 2045 j0251_splits = [(ZEBRAFINCH_J0251_TRAIN_BOXES, train_ds, 500), (ZEBRAFINCH_J0251_VAL_BOXES, val_ds, 50)] 2046 for boxes, ds_list, n_samples in j0251_splits: 2047 for box in boxes: 2048 j0251_kwargs["bounding_box"] = tuple(v * r for v, r in zip(box, (10, 10, 10, 10, 25, 25))) 2049 ds_list.append( 2050 UniDataWrapper( 2051 datasets.get_zebrafinch_dataset( 2052 n_samples=max(1, n_samples // (n_z * len(boxes))), **j0251_kwargs 2053 ), 2054 source_ndim=3, group_key=(3, z), 2055 ) 2056 ) 2057 2058 # 17. Wildenberg 2023 (dense automated segmentation of all processes in FIB-SEM of mouse V1 layer 4, 12x12x40 nm) 2059 # NOTE: The 'saturated' channel labels every process and soma. The box must be given explicitly, the module 2060 # default would stream the full 120 x 136 x 36 um experiment. 2061 for z in z_slices: 2062 wildenberg_kwargs = { 2063 "path": os.path.join(input_path, "wildenberg2023"), 2064 "patch_shape": (z, *patch_shape), 2065 "experiments": ("p105",), 2066 "label_choice": "saturated", 2067 "bounding_box": WILDENBERG_P105_BOX, 2068 "download": True, 2069 "ndim": 3, 2070 "label_transform2": ( 2071 partial(_em_label_trafo, label_trafo=label_trafo(instances=True, sampling=(3.3, 1, 1))) 2072 if label_trafo is not None else kwargs.get("label_transform2") 2073 ), 2074 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 2075 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 2076 } 2077 # Of the 150 cached sections, z < 100 train, 100 <= z < 120 validate and z >= 120 stay blind. 2078 for roi, ds_list, n_samples in [(np.s_[:100, :, :], train_ds, 300), (np.s_[100:120, :, :], val_ds, 50)]: 2079 ds_list.append( 2080 UniDataWrapper( 2081 datasets.get_wildenberg_dataset( 2082 rois=[roi], n_samples=max(1, n_samples // n_z), **wildenberg_kwargs 2083 ), 2084 source_ndim=3, group_key=(3, z), 2085 ) 2086 ) 2087 2088 # 18. DenseCell (platelet cells in SBF-SEM of human platelet tissue, 10x10x50 nm) 2089 # NOTE: The source labels are a semantic mask; torch-em derives and caches 3D cell instances 2090 # (label_choice 'cell_instances'). The train volume splits into z < 35 for training and z >= 35 for validation; 2091 # the val volume is the blind in-domain test set. The test split is sparsely annotated and not used. 2092 for z in z_slices: 2093 densecell_kwargs = { 2094 "path": os.path.join(input_path, "densecell"), 2095 "patch_shape": (z, *patch_shape), 2096 "label_choice": "cell_instances", 2097 "download": True, 2098 "ndim": 3, 2099 "label_transform2": ( 2100 partial(_em_label_trafo, label_trafo=label_trafo(instances=True, sampling=(5, 1, 1))) 2101 if label_trafo is not None else kwargs.get("label_transform2") 2102 ), 2103 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 2104 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 2105 } 2106 for roi, ds_list, n_samples in [(np.s_[:35, :, :], train_ds, 200), (np.s_[35:, :, :], val_ds, 40)]: 2107 ds_list.append( 2108 UniDataWrapper( 2109 datasets.get_densecell_dataset( 2110 split="train", rois=roi, n_samples=max(1, n_samples // n_z), **densecell_kwargs 2111 ), 2112 source_ndim=3, group_key=(3, z), 2113 ) 2114 ) 2115 2116 # 19. Tumor spheroid EM (FaDu tumor spheroid cells in SBF-SEM, 20 manually annotated 2D slices at 50 nm) 2117 # NOTE: 2D data. The 100 nm set is the same 20 slices downsampled and is not used; the 3D zarr holds automated 2118 # segmentation only. Our split: 14 slices train, 2 z slices validate, 4 slices stay blind (see the constants). 2119 spheroid_paths, spheroid_raw_key, spheroid_label_key = datasets.tumor_spheroid_em.get_tumor_spheroid_paths( 2120 os.path.join(input_path, "tumor_spheroid_em"), source="2d_manual", resolution="50-50-50", target="cells", 2121 download=True, 2122 ) 2123 spheroid_val = [p for p in spheroid_paths if os.path.basename(p) in TUMOR_SPHEROID_VAL_SLICES] 2124 spheroid_test = [p for p in spheroid_paths if os.path.basename(p) in TUMOR_SPHEROID_TEST_SLICES] 2125 spheroid_train = [p for p in spheroid_paths if p not in spheroid_val + spheroid_test] 2126 assert len(spheroid_train) == 14 and len(spheroid_val) == 2 and len(spheroid_test) == 4 2127 spheroid_kwargs = { 2128 "patch_shape": patch_shape, 2129 "label_transform2": ( 2130 partial(_em_label_trafo, label_trafo=label_trafo(instances=True)) 2131 if label_trafo is not None else kwargs.get("label_transform2") 2132 ), 2133 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 2134 "ndim": 2, 2135 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 2136 } 2137 for paths, ds_list, n_samples in [(spheroid_train, train_ds, 300), (spheroid_val, val_ds, 40)]: 2138 ds_list.append( 2139 UniDataWrapper( 2140 torch_em.default_segmentation_dataset( 2141 raw_paths=paths, raw_key=spheroid_raw_key, label_paths=paths, label_key=spheroid_label_key, 2142 is_seg_dataset=True, n_samples=n_samples, **spheroid_kwargs, 2143 ), source_ndim=2, 2144 ) 2145 ) 2146 2147 # 21. LICONN (neurite segmentation in expansion microscopy of mouse CA1, 18x18x24 nm raw, ~16x expansion) 2148 # NOTE: Light-based connectomics, so it belongs to the EM neurite pool. The proofread segmentation covers 2149 # only z 64-640 and y < 4608 of the volume (LICONN_ROI); within it z < 512 trains, 512 <= z < 576 validates 2150 # and z >= 576 stays blind. 2151 for z in z_slices: 2152 liconn_kwargs = { 2153 "path": os.path.join(input_path, "liconn"), 2154 "patch_shape": (z, *patch_shape), 2155 "segmentation": "proofread", 2156 "label_transform2": ( 2157 partial(_em_label_trafo, label_trafo=label_trafo(instances=True, sampling=(1.33, 1, 1))) 2158 if label_trafo is not None else kwargs.get("label_transform2") 2159 ), 2160 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 2161 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 2162 } 2163 for z_range, ds_list, n_samples in [(slice(64, 512), train_ds, 300), (slice(512, 576), val_ds, 50)]: 2164 ds_list.append( 2165 UniDataWrapper( 2166 datasets.get_liconn_dataset( 2167 roi=(z_range, *LICONN_ROI[1:]), n_samples=max(1, n_samples // n_z), **liconn_kwargs 2168 ), 2169 source_ndim=3, group_key=(3, z), 2170 ) 2171 ) 2172 2173 # 22. XPRESS (myelinated axon segmentation in X-ray holographic nano-tomography of mouse white matter, 33 nm) 2174 # NOTE: One volume with voxel labels in a 200^3 core (XPRESS_CORE); like ASTIH the target class is myelinated 2175 # axons only. Patches are sampled at the native 200x200 and resized to 512 like the small EMNeuron volumes. 2176 # z 128-288 of the core trains, 288-308 validates, 308-328 stays blind. 2177 for z in z_slices: 2178 xpress_kwargs = { 2179 "path": os.path.join(input_path, "xpress"), 2180 "patch_shape": (z, 200, 200), 2181 "download": True, 2182 "ndim": 3, 2183 "raw_transform": _resize_raw_to_512, 2184 "label_transform2": ( 2185 partial( 2186 _resize_then_em_label_trafo, 2187 em_trafo_fn=partial(_em_label_trafo, label_trafo=label_trafo(instances=True)), 2188 ) 2189 if label_trafo is not None else kwargs.get("label_transform2") 2190 ), 2191 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 2192 **{k: v for k, v in kwargs.items() if k not in ["raw_transform", "label_transform2", "sampler"]}, 2193 } 2194 for z_range, ds_list, n_samples in [(slice(128, 288), train_ds, 100), (slice(288, 308), val_ds, 20)]: 2195 ds_list.append( 2196 UniDataWrapper( 2197 datasets.get_xpress_dataset( 2198 rois=[(z_range, *XPRESS_CORE[1:])], n_samples=max(1, n_samples // n_z), **xpress_kwargs 2199 ), 2200 source_ndim=3, group_key=(3, z), 2201 ) 2202 ) 2203 2204 # 23. SynapseNet compartments (compartment segmentation in electron tomograms of three synapse types) 2205 # NOTE: Internal data, 11 tomograms of 440-495 px in plane. One tomogram per type is the blind test set, the 2206 # other eight train on their first 80 % of sections and validate on the rest. Patches are drawn at 440 px and 2207 # resized to 512 like the small EMNeuron volumes; a patch holds one to four compartments, so the sampler asks 2208 # for one. Ids of a few voxels are annotation specks, which the minimum size drops. The unlabelled voxels are 2209 # membranes, gaps and a few unannotated processes, so id 0 is the ignore label and not the background. 2210 synapsenet_paths = [ 2211 p for p in synapsenet_tomograms(os.path.join(input_path, "synapsenet_compartments_data")) 2212 if os.path.basename(p) not in SYNAPSENET_TEST_TOMOGRAMS 2213 ] 2214 for z in z_slices: 2215 synapsenet_kwargs = { 2216 "patch_shape": (z, 440, 440), 2217 "raw_key": "raw", 2218 "label_key": "labels/compartments", 2219 "is_seg_dataset": True, 2220 "ndim": 3, 2221 "raw_transform": _resize_raw_to_512, 2222 "label_transform2": ( 2223 partial( 2224 _resize_then_em_label_trafo, 2225 em_trafo_fn=partial( 2226 _em_label_trafo, label_trafo=label_trafo(instances=True, min_size=200), ignore_label=0 2227 ), 2228 ) 2229 if label_trafo is not None else kwargs.get("label_transform2") 2230 ), 2231 "sampler": MinInstanceSampler(min_num_instances=1, exclude_ids=[0]), 2232 **{k: v for k, v in kwargs.items() if k not in ["raw_transform", "label_transform2", "sampler"]}, 2233 } 2234 for split, ds_list, n_samples in [("train", train_ds, 100), ("val", val_ds, 20)]: 2235 ds_list.append( 2236 UniDataWrapper( 2237 torch_em.default_segmentation_dataset( 2238 raw_paths=synapsenet_paths, label_paths=synapsenet_paths, 2239 rois=[synapsenet_roi(p, split) for p in synapsenet_paths], 2240 n_samples=max(1, n_samples // n_z), **synapsenet_kwargs, 2241 ), 2242 source_ndim=3, group_key=(3, z), 2243 ) 2244 ) 2245 2246 return train_ds, val_ds 2247 2248 2249# Cached boxes in nm; both modules would otherwise default to far larger regions. 2250ZEBRAFINCH_J0126_BOX = (0, 51200, 0, 51200, 0, 12800) 2251# j0251 boxes in mip-0 voxels (x0, x1, y0, y1, z0, z1) at 10x10x25 nm, converted to nm at use. 2252# Our 3 / 1 / 1 split of the five density-verified j0251 boxes; the mid-depth box (z 7500) is the blind test set. 2253ZEBRAFINCH_J0251_TRAIN_BOXES = [ 2254 (6656, 8704, 15360, 17408, 3000, 3256), 2255 (23040, 25088, 1792, 3840, 3000, 3256), 2256 (12544, 14592, 20992, 23040, 12000, 12256), 2257] 2258ZEBRAFINCH_J0251_VAL_BOXES = [(24576, 26624, 3072, 5120, 12000, 12256)] 2259ZEBRAFINCH_J0251_TEST_BOXES = [(9472, 11520, 15360, 17408, 7500, 7756)] 2260WILDENBERG_P105_BOX = (576, 24576, 576, 24576, 160, 6160) 2261 2262# Bounding boxes of 'volumes/mask' (the annotated region) as (z, y, x) slices. 2263PINKY_MASK_ROIS = { 2264 "pinky_stitched_vol19-vol34_realigned.h5": np.s_[16:116, 256:2176, 256:2176], 2265 "pinky_stitched_vol40-vol41.h5": np.s_[0:86, 256:1280, 256:768], 2266 "pinky_vol401.h5": np.s_[16:116, 256:768, 256:768], 2267} 2268PINKY_TRAIN_FILES = ["pinky_stitched_vol19-vol34_realigned.h5", "pinky_stitched_vol40-vol41.h5"] 2269PINKY_VAL_FILES = ["pinky_vol401.h5"] 2270 2271 2272# MaleCNS 1024^3 crops in 8 nm voxel coordinates. z runs from the brain through the neck connective into the VNC. 2273# Our 4 / 1 / 1 split of the six density-verified boxes; the neck connective box is the blind in-domain test set, 2274# a region no other dataset in the pool covers. 2275MALECNS_TRAIN_BOXES = [ 2276 (40000, 41024, 40000, 41024, 20000, 21024), # brain, torch_em default 2277 (38912, 39936, 19456, 20480, 15000, 16024), # brain 2278 (81920, 82944, 33792, 34816, 35000, 36024), # brain, far lateral 2279 (63488, 64512, 57344, 58368, 75000, 76024), # VNC 2280] 2281MALECNS_VAL_BOXES = [(40960, 41984, 50176, 51200, 95000, 96024)] # VNC 2282MALECNS_TEST_BOXES = [(49152, 50176, 51200, 52224, 55000, 56024)] # neck connective 2283 2284# EMNeuron's CREMI folder holds samples A (all 125 sections), B (sections 25-124) and C at 8 nm, its FIB-25 folder 2285# tstvol-520-1 and validation_sample, verified by cross-correlation against the cached source volumes. 2286EMNEURON_EXCLUDED_FOLDERS = ("AxonEM[H]-atum", "AxonEM[M]-sstem", "CREMI-sstem", "Fib-25-fib") 2287# training_sample2 and validation_sample train in full, tstvol-520-1 is the blind in-domain test set. All three are 2288# at 8 nm; the training sample is only a smaller cube (250^3), not a coarser one. 2289FIB25_TRAIN_SAMPLES = ("training_sample2", "validation_sample") 2290FIB25_TEST_SAMPLE = "tstvol-520-1" 2291 2292PLATY_IGNORE_LABEL = datasets.platynereis.CELL_IGNORE_LABEL 2293 2294# Mouse volumes 0-0-0, 0-0-3584 and 0-3584-3584 are soma blocks with 1, 10 and 4 ids; this threshold drops them. 2295AXONEM_MIN_IDS = 50 2296# Our split of the 15 usable blocks: human 6 / 1 / 2 and mouse 3 / 1 / 2 (train / val / blind test). 2297AXONEM_VAL_VOLUMES = ("seg_950-3584-3584_pad.h5", "seg_700-3584-3584_pad.h5") 2298AXONEM_TEST_VOLUMES = ( 2299 "seg_950-0-3584_pad.h5", "seg_950-3584-0_pad.h5", # human 2300 "seg_700-0-3584_pad.h5", "seg_700-3584-0_pad.h5", # mouse 2301) 2302 2303# Voxels of missing raw data are mapped to this label and excluded from the loss. 2304MISSING_RAW_IGNORE_LABEL = datasets.platynereis.CELL_IGNORE_LABEL 2305 2306# FAFB crops in 16 nm voxel coordinates, 1024x1024x410 voxels each, chosen inside brain tissue with dense 2307# segmentation at three depths (torch_em's DEFAULT_BOUNDING_BOXES). One mid-depth central crop is the validation set. 2308# Of torch-em's nine tissue-verified boxes, the left dorsal mid-depth box validates and the midline ventral anterior 2309# box is the blind in-domain test set (the only ventral-anterior fly brain region in the pool); the other seven train. 2310FAFB_VAL_BOXES = [(24576, 25600, 11776, 12800, 3500, 3910)] 2311FAFB_TEST_BOXES = [(32768, 33792, 18944, 19968, 1500, 1910)] 2312FAFB_TRAIN_BOXES = [ 2313 box for box in datasets.fafb.DEFAULT_BOUNDING_BOXES if box not in FAFB_VAL_BOXES + FAFB_TEST_BOXES 2314] 2315 2316ASTIH_SUBSETS = ["SEM1", "BF1", "BF2"] 2317 2318# Our 14 / 2 / 4 split of the 20 manually annotated tumor spheroid slices: the two z slices below validate, 2319# the deepest x, y and two z slices are the blind in-domain test set, the other 14 train. 2320TUMOR_SPHEROID_VAL_SLICES = ("Au_01-vol_01-z_0180.h5", "Au_01-vol_01-z_0192.h5") 2321TUMOR_SPHEROID_TEST_SLICES = ( 2322 "Au_01-vol_01-x_1300.h5", "Au_01-vol_01-y_1606.h5", "Au_01-vol_01-z_0212.h5", "Au_01-vol_01-z_0274.h5" 2323) 2324 2325 2326# The part of the LICONN volume the proofread segmentation covers; z 576-640 of it is the blind test slab. 2327LICONN_ROI = (slice(64, 640), slice(0, 4608), slice(None)) 2328 2329# The voxel-labelled core of the XPRESS volume; z 308-328 of it is the blind test slab. 2330XPRESS_CORE = (slice(128, 328), slice(128, 328), slice(128, 328)) 2331 2332# SynapseNet compartments: one tomogram per synapse type (MF, PS, SC) is the blind test set, the other eight train 2333# on their first 80 % of sections and validate on the rest. 2334SYNAPSENET_TEST_TOMOGRAMS = ( 2335 "36859_J1_66K_TS_CA3_MF_19_rec_2Kb1dawbp_crop.h5", "36859_J2_66K_TS_R04_PS11_rec_2Kb1dawbp_crop.h5", 2336 "36859_H2_SP_11_rec_2Kb1dawbp_crop.h5", 2337) 2338SYNAPSENET_TRAIN_FRACTION = 0.8 2339 2340 2341def synapsenet_tomograms(path): 2342 """The SynapseNet compartment tomograms, h5 files with 'raw' and 'labels/compartments'.""" 2343 paths = sorted(glob(os.path.join(path, "v3", "*", "*.h5"))) 2344 assert paths, f"Did not find any tomograms in '{path}'." 2345 return paths 2346 2347 2348def synapsenet_roi(path, split): 2349 """The z-slab of a training tomogram that trains ('train') or validates ('val'), as a (z, y, x) roi.""" 2350 with open_file(path, "r") as f: 2351 n_sections = f["raw"].shape[0] 2352 cut = int(SYNAPSENET_TRAIN_FRACTION * n_sections) 2353 return (slice(0, cut) if split == "train" else slice(cut, None), slice(None), slice(None)) 2354 2355 2356# PanNuke fold_2 holds 2523 tiles; the first 80 % train, the last 20 % validate. fold_3 is blind. 2357PANNUKE_FOLD2_TRAIN_TILES = slice(0, 2018) 2358PANNUKE_FOLD2_VAL_TILES = slice(2018, 2523) 2359 2360SPATCH_HE_SUBSETS = ["visium_hd_ov", "visium_hd_hcc", "visium_hd_coad", "stereoseq_ov"] 2361 2362# CartoCell uses the official folders; 'test' is the blind split. 2363CARTOCELL_TRAIN_FOLDERS = ("train_M1", "train_M2") 2364CARTOCELL_VAL_FOLDER = "validation" 2365CARTOCELL_TEST_FOLDER = "test" 2366 2367GONUCLEAR_TRAIN_SAMPLES = (1135, 1136, 1137) 2368GONUCLEAR_VAL_SAMPLES = (1139,) 2369GONUCLEAR_TEST_SAMPLES = (1170,) 2370 2371BITDEPTH_MAGNIFICATIONS = ("20x", "40x_air", "40x_oil", "63x_oil") 2372# CellBinDB fluorescence stains train with light microscopy, the H&E tiles with histopathology. 2373CELLBINDB_STAINS = ("DAPI", "ssDNA", "mIF") 2374CELLBINDB_HE_STAIN = "HE" 2375LPC_NUCSEG_SOURCES = ("gnf", "ic100") 2376 2377# Xenium is split by slide, shared by the nucleus and cell targets. 2378XENIUM_TRAIN_SAMPLES = ("human_pancreas", "human_lung_cancer", "mouse_colon", "human_prostate") 2379XENIUM_VAL_SAMPLES = ("human_skin",) 2380XENIUM_TEST_SAMPLES = ("human_breast",) 2381 2382# EnSeg is split by animal; the C and TW tags are the two experimental groups. 2383ENSEG_TRAIN_ANIMALS = ("2C", "4C", "22TW", "23TW") 2384ENSEG_VAL_ANIMALS = ("5C",) 2385ENSEG_TEST_ANIMALS = ("28TW",) 2386 2387# CTC datasets of the v1 generalist; Fluo-N2DH-GOWT1 and Fluo-N2DL-HeLa stay out. 2388CTC_DATASETS = ( 2389 "BF-C2DL-HSC", "BF-C2DL-MuSC", "DIC-C2DH-HeLa", "Fluo-C2DL-Huh7", "Fluo-C2DL-MSC", "Fluo-N2DH-SIM+", 2390 "PhC-C2DH-U373", "PhC-C2DL-PSC", 2391) 2392 2393# Omnipose subsets and their samples per epoch; a random 10 % of each official train subset validates. 2394OMNIPOSE_TRAIN_SAMPLES = {"bact_fluor": 150, "bact_phase": 250, "worm": 50, "worm_high_res": 50} 2395 2396# TOIAM is split by movie (the folder name). 2397TOIAM_TRAIN_MOVIES = ("00", "01", "02") 2398TOIAM_VAL_MOVIES = ("03",) 2399TOIAM_TEST_MOVIES = ("04",) 2400 2401# OrganoID subsets and their samples per epoch; both use the official splits. 2402ORGANOID_SOURCES = {"original": 200, "mouse": 60} 2403 2404# CISD is split by slide (the filename prefix); three slides validate, three are blind, drawn with seed 42. 2405CISD_VAL_SLIDES = ("0239", "0243", "0248") 2406CISD_TEST_SLIDES = ("0235", "0251", "0255") 2407 2408# CELLULAR is split by well. 2409CELLULAR_TRAIN_WELLS = ("C03", "C05", "I06", "K07") 2410CELLULAR_VAL_WELLS = ("I04",) 2411CELLULAR_TEST_WELLS = ("C06",) 2412 2413# Cell-ACDC is split by movie, named '<experiment folder>/Position_<n>'. 2414CELL_ACDC_VAL_MOVIES = ("MIA_KC_htb1_mCitrine_flu_control_labeled/Position_1",) 2415CELL_ACDC_TEST_MOVIES = ("MIA_KC_htb1_mCitrine_labeled/Position_8",) 2416 2417 2418def cell_acdc_movie(path): 2419 """The movie a Cell-ACDC frame stack belongs to, as '<experiment folder>/Position_<n>'.""" 2420 parts = os.path.normpath(path).split(os.sep) 2421 return "/".join(parts[parts.index("TimeLapse_2D") + 1:parts.index("TimeLapse_2D") + 3]) 2422 2423 2424# CVZ Fluo is split by Vectra patient or CODEX / Zeiss slide, shared by the cell and DAPI stains. 2425CVZ_VAL_GROUPS = ("Vectra:P07", "Vectra:P12", "Zeiss:ZP-10002") 2426CVZ_TEST_GROUPS = ("Vectra:P01", "Vectra:P11", "Zeiss:Spleen", "CODEX:CODEX_LN") 2427 2428 2429def cvz_group(path): 2430 """The patient (Vectra) or slide (CODEX, Zeiss) a CVZ crop belongs to, as 'instrument:name'.""" 2431 parts = os.path.normpath(path).split(os.sep) 2432 instrument = parts[parts.index("cvz") + 1] 2433 name = os.path.basename(path) 2434 match = re.match(r"(P\d+)-", name) 2435 return f"{instrument}:{match.group(1) if match else name.split('(')[0]}" 2436 2437 2438# NucVerse3D: one train volume per liver collection validates; the glia validation is a slab of a test volume. 2439NUCVERSE_VAL_VOLUMES = { 2440 "liver": "20221006_13_Control_8w_Periportal.h5", "liver_hcc": "20221014_6_control_16w_centro.h5", 2441} 2442NUCVERSE_GLIA_VAL_VOLUME = "C2_M01.h5" 2443NUCVERSE_GLIA_VAL_Z = slice(0, 12) # of 53; at least the deepest training patch 2444 2445# Where a blind test volume also validates, a 20 % slab of its slices is the validation region. 2446NIS3D_VAL_Z = slice(158, 198) # Drosophila_1, of 198; the first slices hold almost no nuclei in the centre 2447EMBEDSEG_VAL_Z = {"Mouse-Skull-Nuclei-CBG": slice(100, 125), "Platynereis-ISH-Nuclei-CBG": slice(0, 21)} # of 125 / 105 2448 2449# EmbedSeg Platynereis-Nuclei is one time-lapse of 9 volumes; timepoint 300 validates, 350 is blind. 2450EMBEDSEG_PLATY_NUCLEI_TRAIN_TIMEPOINTS = slice(0, 7) 2451EMBEDSEG_PLATY_NUCLEI_VAL_TIMEPOINTS = slice(7, 8) 2452EMBEDSEG_PLATY_NUCLEI_TEST_TIMEPOINTS = slice(8, 9) 2453 2454# EmbedSeg Mouse-Organoid-Cells is one time-lapse of 108 volumes and is split along time; the last block is blind. 2455EMBEDSEG_ORGANOID_TRAIN_TIMEPOINTS = slice(0, 86) 2456EMBEDSEG_ORGANOID_VAL_TIMEPOINTS = slice(86, 97) 2457EMBEDSEG_ORGANOID_TEST_TIMEPOINTS = slice(97, 108) 2458 2459# PhMamm is one time-lapse (t001-t101, t008 missing) and is split along time; the last block is blind. 2460PHMAMM_TRAIN_TIMEPOINTS = range(1, 82) 2461PHMAMM_VAL_TIMEPOINTS = range(82, 92) 2462PHMAMM_TEST_TIMEPOINTS = range(92, 102) 2463 2464# Wing disc has one confocal and one multiphoton volume for training; the other two are the blind test volumes, 2465# of which the first slices validate (20 % of the 60-slice volume; the 38-slice volume gives up 12 as well). 2466WING_DISC_TRAIN_VOLUMES = ("WD1_15-02_WT_confocalonly", "WD1.1_17-03_WT_MP") 2467WING_DISC_TEST_VOLUMES = ("WD2.1_21-02_WT_confocalonly", "WD3.2_21-03_WT_MP") 2468WING_DISC_VAL_Z = slice(0, 12) 2469 2470# PNAS Arabidopsis is split by plant, since the timepoints of one plant are near-duplicates. 2471PNAS_TRAIN_PLANTS = ("plant1", "plant2", "plant13", "plant15") 2472PNAS_VAL_PLANTS = ("plant4",) 2473PNAS_TEST_PLANTS = ("plant18",) 2474 2475 2476def dsb_fluorescence_training_paths(path): 2477 """The DSB fluorescence images of the 'full' source without the StarDist test images. 2478 2479 The StarDist test files are named by their Kaggle image id, which is the folder name in the 'full' source, so 2480 the blind test images are excluded by id. 2481 """ 2482 test_ids = { 2483 os.path.splitext(os.path.basename(p))[0] 2484 for p in datasets.dsb.get_dsb_paths(path, source="reduced", split="test")[0] 2485 } 2486 raw, labels = datasets.dsb.get_dsb_paths(path, source="full", domain="fluo") 2487 keep = [os.path.basename(os.path.dirname(os.path.dirname(p))) not in test_ids for p in raw] 2488 return [p for p, k in zip(raw, keep) if k], [p for p, k in zip(labels, keep) if k] 2489 2490 2491def _train_val_test_split(*lists, seed=42): 2492 """Split parallel path lists 80 / 10 / 10 with a fixed seed; returns (train, val, test) per list.""" 2493 rest_and_test = train_test_split(*lists, test_size=0.1, random_state=seed) 2494 rest, test = rest_and_test[0::2], rest_and_test[1::2] 2495 train_and_val = train_test_split(*rest, test_size=1 / 9, random_state=seed) 2496 train, val = train_and_val[0::2], train_and_val[1::2] 2497 return [(tr, va, te) for tr, va, te in zip(train, val, test)] 2498 2499 2500def _compute_label_rois(label_paths, label_key, min_ids=1): 2501 """Bounding box of the non-zero labels per volume, cached as json next to each file. 2502 2503 Volumes with fewer than *min_ids* ids inside that box are left out of the result. 2504 """ 2505 rois = {} 2506 for path in label_paths: 2507 cache_path = f"{os.path.splitext(path)[0]}_roi.json" 2508 if os.path.exists(cache_path): 2509 with open(cache_path) as f: 2510 cached = json.load(f) 2511 else: 2512 with open_file(path, "r") as f: 2513 labels = f[label_key][:] 2514 coords = np.where(labels != 0) 2515 n_ids = int(len(np.unique(labels)) - 1) 2516 roi = [[int(c.min()), int(c.max()) + 1] for c in coords] if n_ids else [] 2517 cached = {"roi": roi, "n_ids": n_ids} 2518 tmp_path = f"{cache_path}.tmp{os.getpid()}" 2519 with open(tmp_path, "w") as f: 2520 json.dump(cached, f) 2521 os.replace(tmp_path, cache_path) 2522 if cached["n_ids"] >= min_ids: 2523 rois[path] = tuple(slice(start, stop) for start, stop in cached["roi"]) 2524 return rois 2525 2526 2527def _resize_pad_then_flip(raw, labels, resize, patch_shape, flip): 2528 raw, labels = resize(raw, labels, patch_shape) 2529 return flip(raw, labels) 2530 2531 2532def _with_flips(resize, patch_shape): 2533 """Compose a resize-and-pad transform with the default 2d flips, which an explicit 'transform' replaces.""" 2534 return partial(_resize_pad_then_flip, resize=resize, patch_shape=patch_shape, flip=get_augmentations(ndim=2)) 2535 2536 2537def _pannuke_random_resize_and_pad_trafo(raw, labels, patch_shape): 2538 """Randomly upscale a PanNuke 256x256 tile (steps of 64) and zero-pad the rest to patch_shape. 2539 2540 Runs as the joint 'transform', after normalization, so percentile stats stay on real pixels. 2541 """ 2542 from skimage.transform import resize 2543 2544 native = raw.shape[-1] 2545 target = patch_shape[-1] 2546 size = random.choice(range(native, target + 1, 64)) 2547 2548 if size != native: 2549 raw = resize( 2550 raw, raw.shape[:-2] + (size, size), order=1, anti_aliasing=True, preserve_range=True, 2551 ).astype(raw.dtype) 2552 labels = resize( 2553 labels, labels.shape[:-2] + (size, size), order=0, anti_aliasing=False, preserve_range=True, 2554 ).astype(labels.dtype) 2555 2556 pad_total = target - size 2557 if pad_total <= 0: 2558 return raw, labels 2559 2560 pad_width = (0, pad_total) 2561 2562 def _pad(x): 2563 return np.pad(x, [(0, 0)] * (x.ndim - 2) + [pad_width, pad_width]) 2564 2565 return _pad(raw), _pad(labels) 2566 2567 2568def _random_resize_and_pad_trafo(raw, labels, patch_shape): 2569 """Randomly upscale a whole small image by a factor in [1, target/longest side] and zero-pad to patch_shape. 2570 2571 A generalization of :func:`_pannuke_random_resize_and_pad_trafo` for datasets whose native images are small 2572 and not square. Runs as the joint 'transform', after normalization, so percentile stats stay on real pixels. 2573 """ 2574 from skimage.transform import resize 2575 2576 target = patch_shape[-1] 2577 height, width = raw.shape[-2:] 2578 max_scale = target / max(height, width) 2579 if max_scale > 1: 2580 scale = random.uniform(1.0, max_scale) 2581 new_h, new_w = min(target, int(height * scale)), min(target, int(width * scale)) 2582 raw = resize( 2583 raw, raw.shape[:-2] + (new_h, new_w), order=1, anti_aliasing=True, preserve_range=True, 2584 ).astype(raw.dtype) 2585 labels = resize( 2586 labels, labels.shape[:-2] + (new_h, new_w), order=0, anti_aliasing=False, preserve_range=True, 2587 ).astype(labels.dtype) 2588 2589 def _pad(x): 2590 pad_h, pad_w = target - x.shape[-2], target - x.shape[-1] 2591 if pad_h <= 0 and pad_w <= 0: 2592 return x 2593 return np.pad(x, [(0, 0)] * (x.ndim - 2) + [(0, max(0, pad_h)), (0, max(0, pad_w))]) 2594 2595 return _pad(raw), _pad(labels) 2596 2597 2598def _get_hp_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo): 2599 """Get all histopathology (HP) datasets for generalist training. 2600 2601 Dataset composition mirrors patho-sam's generalist training set: 2602 https://github.com/computational-cell-analytics/patho-sam 2603 2604 Returns: 2605 Tuple of (train_ds, val_ds) lists of UniDataWrapper instances. 2606 """ 2607 train_ds, val_ds = [], [] 2608 2609 # 1. CPM15 (nucleus segmentation in H&E histopathology images) 2610 # NOTE: No official split, and torch-em's own one is an unseeded random pick. All 15 images are pooled and split 2611 # 80/20 here, so there is no blind set; CPM17's official test split covers that. 2612 cpm15_raw_paths, cpm15_label_paths = [], [] 2613 for split in ["train", "val", "test"]: 2614 raws, labels = datasets.cpm.get_cpm_paths( 2615 path=os.path.join(input_path, "cpm15"), data_choice="cpm15", split=split 2616 ) 2617 cpm15_raw_paths += raws 2618 cpm15_label_paths += labels 2619 cpm15_train_raw, cpm15_val_raw, cpm15_train_labels, cpm15_val_labels = train_test_split( 2620 cpm15_raw_paths, cpm15_label_paths, test_size=0.2, random_state=42, 2621 ) 2622 cpm15_kwargs = {"patch_shape": patch_shape, "with_channels": True, "ndim": 2, **kwargs} 2623 for raws, labels, ds_list in [ 2624 (cpm15_train_raw, cpm15_train_labels, train_ds), (cpm15_val_raw, cpm15_val_labels, val_ds) 2625 ]: 2626 ds_list.append( 2627 UniDataWrapper( 2628 torch_em.default_segmentation_dataset( 2629 raw_paths=raws, raw_key=None, label_paths=labels, label_key=None, is_seg_dataset=False, 2630 n_samples=50, **cpm15_kwargs, 2631 ), source_ndim=2, 2632 ) 2633 ) 2634 2635 # 2. CPM17 (nucleus segmentation in H&E histopathology images) 2636 # NOTE: No native val split. Split the train image/label paths so train and val get 2637 # independent dataset instances (a shared random_split Subset would alias raw_transform). 2638 cpm17_raw_paths, cpm17_label_paths = datasets.cpm.get_cpm_paths( 2639 path=os.path.join(input_path, "cpm17"), data_choice="cpm17", split="train", 2640 ) 2641 cpm17_train_raw, cpm17_val_raw, cpm17_train_labels, cpm17_val_labels = train_test_split( 2642 cpm17_raw_paths, cpm17_label_paths, test_size=0.2, random_state=42, 2643 ) 2644 cpm17_kwargs = {"patch_shape": patch_shape, "with_channels": True, "ndim": 2, **kwargs} 2645 train_ds.append( 2646 UniDataWrapper( 2647 torch_em.default_segmentation_dataset( 2648 raw_paths=cpm17_train_raw, raw_key=None, label_paths=cpm17_train_labels, label_key=None, 2649 is_seg_dataset=False, n_samples=50, **cpm17_kwargs, 2650 ), source_ndim=2, 2651 ) 2652 ) 2653 val_ds.append( 2654 UniDataWrapper( 2655 torch_em.default_segmentation_dataset( 2656 raw_paths=cpm17_val_raw, raw_key=None, label_paths=cpm17_val_labels, label_key=None, 2657 is_seg_dataset=False, n_samples=50, **cpm17_kwargs, 2658 ), source_ndim=2, 2659 ) 2660 ) 2661 2662 # 3. Lizard (nucleus segmentation in H&E colon, 238 images from six cohorts) 2663 # NOTE: The train and val splits hold only the crag, dpath and glas cohorts; every PanNuke and CoNSeP source 2664 # image sits in the test split, so training here never touches the blind PanNuke fold 3. CoNIC is the same 2665 # material re-tiled and is not used. 2666 lizard_kwargs = { 2667 "path": os.path.join(input_path, "lizard"), "patch_shape": patch_shape, "download": True, **kwargs 2668 } 2669 train_ds.append( 2670 UniDataWrapper(datasets.get_lizard_dataset(split="train", n_samples=700, **lizard_kwargs), source_ndim=2) 2671 ) 2672 val_ds.append( 2673 UniDataWrapper(datasets.get_lizard_dataset(split="val", n_samples=100, **lizard_kwargs), source_ndim=2) 2674 ) 2675 2676 # 4. Lizard-Mitosis (nucleus segmentation in H&E colon, the dedicated mitosis tile set) 2677 # NOTE: Only the 'mitosis' subset is used: its tiles are new material, while the 'lizard' subset is CoNIC 2678 # re-split. Tiles are 256x256 and are resized/padded to 512 like PanNuke. 2679 lizard_mitosis_kwargs = { 2680 "path": os.path.join(input_path, "lizard_mitosis"), "patch_shape": (1, 256, 256), "subset": "mitosis", 2681 "label_choice": "instances", "download": True, 2682 **{**kwargs, "transform": _with_flips(_pannuke_random_resize_and_pad_trafo, patch_shape)}, 2683 } 2684 for split, ds_list, n_samples in [("train", train_ds, 500), ("val", val_ds, 50)]: 2685 ds_list.append( 2686 UniDataWrapper( 2687 datasets.get_lizard_mitosis_dataset(split=split, n_samples=n_samples, **lizard_mitosis_kwargs), 2688 source_ndim=2, 2689 ) 2690 ) 2691 2692 # 5. MoNuSeg (nucleus segmentation in H&E histopathology images) 2693 # NOTE: No native val split. Split the train image/label paths so train and val get 2694 # independent dataset instances (a shared random_split Subset would alias raw_transform). 2695 monuseg_raw_paths, monuseg_label_paths = datasets.monuseg.get_monuseg_paths( 2696 path=os.path.join(input_path, "monuseg"), split="train", download=True, 2697 ) 2698 monuseg_train_raw, monuseg_val_raw, monuseg_train_labels, monuseg_val_labels = train_test_split( 2699 monuseg_raw_paths, monuseg_label_paths, test_size=0.2, random_state=42, 2700 ) 2701 monuseg_kwargs = {"patch_shape": patch_shape, "is_seg_dataset": False, **kwargs} 2702 train_ds.append( 2703 UniDataWrapper( 2704 torch_em.default_segmentation_dataset( 2705 raw_paths=monuseg_train_raw, raw_key=None, label_paths=monuseg_train_labels, label_key=None, 2706 n_samples=50, **monuseg_kwargs, 2707 ), source_ndim=2, 2708 ) 2709 ) 2710 val_ds.append( 2711 UniDataWrapper( 2712 torch_em.default_segmentation_dataset( 2713 raw_paths=monuseg_val_raw, raw_key=None, label_paths=monuseg_val_labels, label_key=None, 2714 n_samples=50, **monuseg_kwargs, 2715 ), source_ndim=2, 2716 ) 2717 ) 2718 2719 # 6. PanNuke (nucleus segmentation in H&E histopathology images) 2720 # NOTE: fold_1 and the first 80 % of the fold_2 tiles train, the last 20 % of the fold_2 tiles validate (a fixed 2721 # tile partition, see PANNUKE_FOLD2_TRAIN_TILES). fold_3 is the blind benchmark split. patch_shape is requested 2722 # at PanNuke's native 256x256, so torch_em's own padding is a no-op; _pannuke_random_resize_and_pad_trafo does 2723 # the resize+pad up to 512x512 instead. 2724 pannuke_kwargs = { 2725 "path": os.path.join(input_path, "pannuke"), "patch_shape": (1, 256, 256), "download": True, "ndim": 2, 2726 **{**kwargs, "transform": _with_flips(_pannuke_random_resize_and_pad_trafo, patch_shape)}, 2727 } 2728 train_ds.append( 2729 UniDataWrapper( 2730 datasets.get_pannuke_dataset( 2731 folds=["fold_1", "fold_2"], rois={"fold_2": (PANNUKE_FOLD2_TRAIN_TILES, slice(None), slice(None))}, 2732 **pannuke_kwargs, 2733 ), source_ndim=2, 2734 ) 2735 ) 2736 val_ds.append( 2737 UniDataWrapper( 2738 datasets.get_pannuke_dataset( 2739 folds=["fold_2"], rois={"fold_2": (PANNUKE_FOLD2_VAL_TILES, slice(None), slice(None))}, 2740 **pannuke_kwargs, 2741 ), source_ndim=2, 2742 ) 2743 ) 2744 2745 # 7. PUMA (nucleus segmentation in H&E histopathology images) 2746 puma_kwargs = {"path": os.path.join(input_path, "puma"), "patch_shape": patch_shape, "download": True, **kwargs} 2747 train_ds.append(UniDataWrapper(datasets.get_puma_dataset(split="train", **puma_kwargs), source_ndim=2)) 2748 val_ds.append(UniDataWrapper(datasets.get_puma_dataset(split="val", **puma_kwargs), source_ndim=2)) 2749 2750 # 8. TNBC CellType (nucleus segmentation in H&E triple-negative breast cancer plus TCGA brain sections) 2751 # NOTE: Replaces plain `tnbc`, which it contains with near-identical masks, and adds 18 TCGA brain sections. 2752 # ndim is explicit: the raw is channels-last (H, W, 3) and auto-detection reads the 3 as a depth axis. 2753 tnbc_kwargs = { 2754 "path": os.path.join(input_path, "tnbc_celltype"), "patch_shape": patch_shape, "download": True, 2755 "ndim": 2, "label_choice": "instances", **kwargs, 2756 } 2757 train_ds.append( 2758 UniDataWrapper(datasets.get_tnbc_celltype_dataset(split="train", n_samples=50, **tnbc_kwargs), source_ndim=2) 2759 ) 2760 val_ds.append( 2761 UniDataWrapper(datasets.get_tnbc_celltype_dataset(split="val", n_samples=50, **tnbc_kwargs), source_ndim=2) 2762 ) 2763 2764 # 9. NuInsSeg (nucleus segmentation in H&E histopathology images from 31 human and mouse organs) 2765 # NOTE: No native split. Split the image/label paths so train and val get independent dataset instances. 2766 # 'human_liver_31.png' is the one RGBA image of the collection; its constant alpha channel is dropped. 2767 nuinsseg_raw_paths, nuinsseg_label_paths = datasets.nuinsseg.get_nuinsseg_paths( 2768 path=os.path.join(input_path, "nuinsseg") 2769 ) 2770 nuinsseg_train_raw, nuinsseg_val_raw, nuinsseg_train_labels, nuinsseg_val_labels = train_test_split( 2771 nuinsseg_raw_paths, nuinsseg_label_paths, test_size=0.2, random_state=42, 2772 ) 2773 nuinsseg_kwargs = { 2774 "patch_shape": patch_shape, "is_seg_dataset": False, "ndim": 2, "with_channels": True, **kwargs, 2775 "raw_transform": Compose(_drop_alpha_channel, kwargs["raw_transform"], is_multi_tensor=False), 2776 } 2777 train_ds.append( 2778 UniDataWrapper( 2779 torch_em.default_segmentation_dataset( 2780 raw_paths=nuinsseg_train_raw, raw_key=None, label_paths=nuinsseg_train_labels, label_key=None, 2781 n_samples=300, **nuinsseg_kwargs, 2782 ), source_ndim=2, 2783 ) 2784 ) 2785 val_ds.append( 2786 UniDataWrapper( 2787 torch_em.default_segmentation_dataset( 2788 raw_paths=nuinsseg_val_raw, raw_key=None, label_paths=nuinsseg_val_labels, label_key=None, 2789 n_samples=50, **nuinsseg_kwargs, 2790 ), source_ndim=2, 2791 ) 2792 ) 2793 2794 # 10. LyNSeC (nucleus segmentation in IHC and H&E lymphoma images) 2795 # NOTE: Both stains are used ('choice' left unset). The raw images are stored as int32 RGB tifs with an 8-bit 2796 # value range and the labels as int32; the percentile normalization and the label dtype cast handle both. 2797 # The split files 'lynsec_{ihc,h&e}_split.csv' live with the data. 2798 lynsec_kwargs = {"path": os.path.join(input_path, "lynsec"), "patch_shape": patch_shape, **kwargs} 2799 train_ds.append( 2800 UniDataWrapper(datasets.get_lynsec_dataset(split="train", n_samples=300, **lynsec_kwargs), source_ndim=2) 2801 ) 2802 val_ds.append( 2803 UniDataWrapper(datasets.get_lynsec_dataset(split="val", n_samples=50, **lynsec_kwargs), source_ndim=2) 2804 ) 2805 2806 # 11. SRSA-Net / IHC TMA (nucleus segmentation in IHC tissue microarray images of non-small cell lung cancer) 2807 # NOTE: Native 256x256 tiles, handled like PanNuke: crop at native size, then randomly upscale and pad to the 2808 # patch shape in the joint transform. Labels are uint64 connected components of the positive and negative masks. 2809 # The 35-image test split (fold 3) is kept blind. 2810 srsanet_kwargs = { 2811 "path": os.path.join(input_path, "srsanet"), "patch_shape": (256, 256), 2812 **{**kwargs, "transform": _with_flips(_pannuke_random_resize_and_pad_trafo, patch_shape)}, 2813 } 2814 train_ds.append( 2815 UniDataWrapper(datasets.get_srsanet_dataset(split="train", n_samples=200, **srsanet_kwargs), source_ndim=2) 2816 ) 2817 val_ds.append( 2818 UniDataWrapper(datasets.get_srsanet_dataset(split="val", n_samples=50, **srsanet_kwargs), source_ndim=2) 2819 ) 2820 2821 # 12. CryoNuSeg (nucleus segmentation in H&E cryosection images from 10 organs) 2822 # NOTE: 30 images, rater 'b1'. No official split, and torch-em's own one is an unseeded random pick, so all 30 2823 # images are pooled and split 80/20 here; there is no blind set. 2824 cryonuseg_raw_paths, cryonuseg_label_paths = [], [] 2825 for split in ["train", "val", "test"]: 2826 raws, labels = datasets.cryonuseg.get_cryonuseg_paths( 2827 path=os.path.join(input_path, "cryonuseg"), split=split, rater_choice="b1" 2828 ) 2829 cryonuseg_raw_paths += raws 2830 cryonuseg_label_paths += labels 2831 cryonuseg_train_raw, cryonuseg_val_raw, cryonuseg_train_labels, cryonuseg_val_labels = train_test_split( 2832 cryonuseg_raw_paths, cryonuseg_label_paths, test_size=0.2, random_state=42, 2833 ) 2834 cryonuseg_kwargs = {"patch_shape": patch_shape, "with_channels": True, "ndim": 2, **kwargs} 2835 for raws, labels, ds_list, n_samples in [ 2836 (cryonuseg_train_raw, cryonuseg_train_labels, train_ds, 50), 2837 (cryonuseg_val_raw, cryonuseg_val_labels, val_ds, 20), 2838 ]: 2839 ds_list.append( 2840 UniDataWrapper( 2841 torch_em.default_segmentation_dataset( 2842 raw_paths=raws, raw_key=None, label_paths=labels, label_key=None, is_seg_dataset=False, 2843 n_samples=n_samples, **cryonuseg_kwargs, 2844 ), source_ndim=2, 2845 ) 2846 ) 2847 2848 # 13. GLySAC (nucleus segmentation in H&E gastric cancer histopathology images) 2849 # NOTE: Densely annotated (median 124 nuclei per 512x512 area, comparable to MoNuSeg), unlike MoNuSAC. 2850 # No native val split, so the 34 train tiles are split 80/20. The 25-image test split is kept blind. 2851 glysac_paths = datasets.glysac.get_glysac_paths(path=os.path.join(input_path, "glysac"), split="train") 2852 glysac_train, glysac_val = train_test_split(glysac_paths, test_size=0.2, random_state=42) 2853 glysac_kwargs = {"patch_shape": patch_shape, "with_channels": True, "ndim": 2, **kwargs} 2854 for paths, ds_list, n_samples in [(glysac_train, train_ds, 200), (glysac_val, val_ds, 50)]: 2855 ds_list.append( 2856 UniDataWrapper( 2857 torch_em.default_segmentation_dataset( 2858 raw_paths=paths, raw_key="raw", label_paths=paths, label_key="labels/instances", 2859 n_samples=n_samples, **glysac_kwargs, 2860 ), source_ndim=2, 2861 ) 2862 ) 2863 2864 # 14. Histo-Miner (nucleus segmentation in H&E cutaneous squamous cell carcinoma) 2865 # NOTE: Tiles are 256x256, so patches are sampled at 256 and resized/padded to 512 like PanNuke; asking 2866 # torch_em for 512 directly would give 75 % zero padding. Only train and val are public. 2867 histo_miner_kwargs = { 2868 "path": os.path.join(input_path, "histo_miner"), "patch_shape": (256, 256), "download": True, 2869 "task": "nuclei", "label_choice": "instances", 2870 **{**kwargs, "transform": _with_flips(_pannuke_random_resize_and_pad_trafo, patch_shape)}, 2871 } 2872 train_ds.append( 2873 UniDataWrapper( 2874 datasets.get_histo_miner_dataset(split="train", n_samples=400, **histo_miner_kwargs), source_ndim=2 2875 ) 2876 ) 2877 val_ds.append( 2878 UniDataWrapper( 2879 datasets.get_histo_miner_dataset(split="val", n_samples=50, **histo_miner_kwargs), source_ndim=2 2880 ) 2881 ) 2882 2883 # 15. sPATCH (nucleus segmentation in spatial-omics tissue: ovarian cancer, HCC and colon adenocarcinoma) 2884 # NOTE: The four H&E subsets only; the six DAPI subsets are a light-microscopy evaluation set. No native 2885 # split, so the 20 tiles are split 80/20 by path. 2886 spatch_paths = datasets.spatch.get_spatch_paths( 2887 path=os.path.join(input_path, "spatch"), subset=SPATCH_HE_SUBSETS, download=True, 2888 ) 2889 spatch_train, spatch_val = train_test_split(spatch_paths, test_size=0.2, random_state=42) 2890 spatch_kwargs = {"patch_shape": patch_shape, "with_channels": True, "ndim": 2, **kwargs} 2891 for paths, ds_list, n_samples in [(spatch_train, train_ds, 400), (spatch_val, val_ds, 50)]: 2892 ds_list.append( 2893 UniDataWrapper( 2894 torch_em.default_segmentation_dataset( 2895 raw_paths=paths, raw_key="raw/rgb", label_paths=paths, label_key="labels/nuclei", 2896 is_seg_dataset=True, n_samples=n_samples, **spatch_kwargs, 2897 ), source_ndim=2, 2898 ) 2899 ) 2900 2901 # 16. CoNSeP (nucleus segmentation in H&E colorectal adenocarcinoma, 1000x1000 images) 2902 # NOTE: CoNSeP is one of Lizard's source cohorts, so it can never serve as a test set; its test split validates. 2903 consep_kwargs = { 2904 "path": os.path.join(input_path, "consep"), "patch_shape": patch_shape, "download": True, **kwargs 2905 } 2906 for split, ds_list, n_samples in [("train", train_ds, 150), ("test", val_ds, 50)]: 2907 ds_list.append( 2908 UniDataWrapper( 2909 datasets.get_consep_dataset(split=split, n_samples=n_samples, **consep_kwargs), source_ndim=2 2910 ) 2911 ) 2912 2913 # 17. DSB histopathology (nucleus segmentation in the 107 H&E images of the Kaggle stage-1 training set) 2914 # NOTE: A random 10 % (seed 42) validates; there is no blind test. The fluorescence images train with light 2915 # microscopy, see dsb_fluorescence_training_paths. 2916 dsb_hp_raw, dsb_hp_labels = datasets.dsb.get_dsb_paths( 2917 os.path.join(input_path, "dsb"), source="full", domain="histopatho", 2918 ) 2919 dsb_hp_train_r, dsb_hp_val_r, dsb_hp_train_l, dsb_hp_val_l = train_test_split( 2920 dsb_hp_raw, dsb_hp_labels, test_size=0.1, random_state=42 2921 ) 2922 dsb_hp_kwargs = {"patch_shape": patch_shape, "is_seg_dataset": False, "raw_key": None, "label_key": None, **kwargs} 2923 for raws, labs, ds_list, n_samples in [ 2924 (dsb_hp_train_r, dsb_hp_train_l, train_ds, 100), (dsb_hp_val_r, dsb_hp_val_l, val_ds, 25), 2925 ]: 2926 ds_list.append( 2927 UniDataWrapper( 2928 torch_em.default_segmentation_dataset( 2929 raw_paths=raws, label_paths=labs, n_samples=n_samples, **dsb_hp_kwargs 2930 ), source_ndim=2, 2931 ) 2932 ) 2933 2934 # 18. CellBinDB H&E (nucleus segmentation in H&E tiles of 512x512) 2935 # NOTE: The H&E tiles of CellBinDB; split 80 / 10 / 10 at random (seed 42), the test tiles are blind. 2936 cb_he_raw, cb_he_labels = datasets.cellbindb.get_cellbindb_paths( 2937 path=os.path.join(input_path, "cellbindb"), data_choice=CELLBINDB_HE_STAIN, 2938 ) 2939 (cb_he_train_r, cb_he_val_r, _), (cb_he_train_l, cb_he_val_l, _) = _train_val_test_split(cb_he_raw, cb_he_labels) 2940 cb_he_kwargs = {"patch_shape": patch_shape, "is_seg_dataset": False, "ndim": 2, **kwargs} 2941 for raws, labs, ds_list, n_samples in [ 2942 (cb_he_train_r, cb_he_train_l, train_ds, 150), (cb_he_val_r, cb_he_val_l, val_ds, 30), 2943 ]: 2944 ds_list.append( 2945 UniDataWrapper( 2946 torch_em.default_segmentation_dataset( 2947 raw_paths=raws, raw_key=None, label_paths=labs, label_key=None, n_samples=n_samples, **cb_he_kwargs, 2948 ), source_ndim=2, 2949 ) 2950 ) 2951 2952 return train_ds, val_ds 2953 2954 2955# The datasets of the mitochondria EM generalist ('em_mito'). Each name enables one block in 2956# _get_em_mito_datasets. 2957EM_MITO_DATASETS = ( 2958 "mitolab", "densecell_mito", "lucchi", "microns_pinky_mito", "mitoem", "mitoemv2", "mitoemv2_mossy", "probtem", 2959 "uro_cell", "vnc", "mitoverse_xiao18", "mitoverse_haberl18", "mitoverse_microns1", 2960 "cellmap_mito", "human_organoids_mito", "asem_mito", "brain_pfibsem_mito", "snemi_mito", "u2os_fibsem_mito", 2961 "hela_stard3_mito", "parlakgul_fasting_liver_mito", "aive_mito", "mito_segem", 2962) 2963 2964# Objects below this size (in pixels / voxels of the training patch) are dropped from the mitochondria targets. 2965EM_MITO_MIN_SIZE = 25 2966EM_MITO_MIN_SIZE_3D = 50 2967 2968# Training samples per epoch and source: 3D 200 x sqrt(voxels / 250M) in [200, 600], tiny sources ~7 passes; 2969# the large, diverse sources get more. 2970EM_MITO_TRAIN_SAMPLES = { 2971 "densecell_mito": 50, "lucchi": 200, "microns_pinky_mito": 240, "mitoem_human": 700, "mitoem_rat": 700, 2972 "mitoemv2_beta": 515, "mitoemv2_jurkat": 200, "mitoemv2_macro": 207, "mitoemv2_podo": 207, "mitoemv2_sperm": 254, 2973 "mitoemv2_stem": 200, "mitoemv2_mossy": 478, "probtem": 2800, "uro_cell": 200, "vnc": 450, 2974 "mitoverse_xiao18": 200, "mitoverse_haberl18": 14, "mitoverse_microns1": 200, "cellmap_mito": 900, 2975 "human_organoids_mito": 700, "asem_mito": 225, "asem_mito_small": 50, "brain_pfibsem_reference": 150, 2976 "brain_pfibsem_noisy": 50, "snemi_mito": 200, "u2os_fibsem_mito": 1260, "hela_stard3_mito": 446, 2977 "parlakgul_fasting_liver_mito": 205, "aive_mito": 700, "mito_segem": 200, 2978} 2979# One CEM-MitoLab group holds 720 of the 1264 validation tiles, so each group is capped. 2980MITOLAB_VAL_IMAGES_PER_GROUP = 50 2981 2982# The mitochondria that a patch needs; CEM-MitoLab and CellMap need one. 2983EM_MITO_MIN_INSTANCES = 3 2984# These volumes hold fewer mitochondria per patch, so they need fewer (measured on 40 random patches). 2985EM_MITO_SPARSE_VOLUMES = { 2986 "me2-macro_train01.n5": 1, "me2-jurkat_train01.n5": 2, "pos0.zarr": 2, "fib1-1-0-3.h5": 2, 2987 "x_0.h5": 2, "x_7.h5": 2, "x_9.h5": 2, "x_13.h5": 2, "x_17.h5": 2, 2988 "stard3.h5": 1, "1858_mito_80954b8a9027.zarr": 1, "8970_mito_b68e28ee1a3e.zarr": 1, 2989 "aive_dataset1.h5": 1, "aive_dataset2.h5": 1, "aive_dataset3.h5": 1, 2990} 2991 2992# The 3D validation regions hold at least 14 slices, because torch-em pads shallower regions with blank planes. 2993 2994DENSECELL_TRAIN_ROI = np.s_[:35, :, :] 2995DENSECELL_VAL_ROI = np.s_[35:, :, :] 2996 2997# The CEM-Mito-Benchmark volume 'lucchi_pp' is the Lucchi train volume. 2998LUCCHI_TRAIN_ROI = np.s_[:140, :, :] 2999LUCCHI_VAL_ROI = np.s_[140:, :, :] 3000 3001# Only this stitched volume is densely annotated for mitochondria. 3002MICRONS_PINKY_MITO_FILE = "pinky_stitched_vol19-vol34.h5" 3003MICRONS_PINKY_MITO_TRAIN_ROI = np.s_[:86, :, :] 3004MICRONS_PINKY_MITO_VAL_ROI = np.s_[86:, :, :] 3005 3006# The MitoEM val volumes are evaluation volumes, so only the train volumes train and validate. 3007MITOEM_SAMPLES = ("human", "rat") 3008MITOEM_TRAIN_ROI = np.s_[:360, :, :] 3009MITOEM_VAL_ROI = np.s_[360:, :, :] 3010 3011# The z / xy anisotropy per MitoEM v2 dataset; pyra repeats MitoEM-H, so it is left out. 3012MITOEMV2_DATASETS = {"beta": 1, "jurkat": 1, "macro": 1, "podo": 1, "sperm": 1, "stem": 30 / 8} 3013# The labels of the jurkat val volume do not match its raw, so jurkat validates on the end of its train volume. 3014MITOEMV2_JURKAT_TRAIN_ROI = np.s_[:230, :, :] 3015MITOEMV2_JURKAT_VAL_ROI = np.s_[230:, :, :] 3016 3017# The MitoVerse copies of the mossy volumes have the bouton masks; outside the boutons the loss is ignored. 3018MITOEMV2_MOSSY_TRAIN_VOLUMES = {"me2-mossy_train01": "neg0", "me2-mossy_train02": "pos0"} 3019MITOEMV2_MOSSY_VAL_VOLUMES = {"me2-mossy_train03": "pos2"} 3020MITOEMV2_MOSSY_IGNORE_LABEL = np.iinfo("uint32").max 3021 3022# The <data>/probtem copy is incomplete, so the processed files are read. 3023PROBTEM_ROOT = os.path.join("probtem_full", "processed") 3024PROBTEM_N_VAL = 3 3025 3026# The other 3 UroCell volumes have no mitochondria labels. 3027UROCELL_MITO_VOLUMES = ["fib1-0-0-0.h5", "fib1-1-0-3.h5", "fib1-3-2-1.h5", "fib1-3-3-0.h5", "fib1-4-3-0.h5"] 3028UROCELL_TRAIN_ROI = np.s_[:224, :, :] 3029UROCELL_VAL_ROI = np.s_[224:, :, :] 3030 3031# The 4-slice validation slab does not fit a 3D patch, so VNC trains on single slices. 3032VNC_TRAIN_ROI = np.s_[:16, :, :] 3033VNC_VAL_ROI = np.s_[16:, :, :] 3034 3035# Section 14 of xiao18 is torn, so no patch crosses it. 3036MITOVERSE_XIAO18_TRAIN_ROI = np.s_[15:, :, :] 3037MITOVERSE_XIAO18_VAL_ROI = np.s_[:14, :, :] 3038MITOVERSE_MICRONS1_VOLUMES = [f"microns1_vol{i}" for i in range(5)] 3039# The validation slab of these volumes holds a missing section, so they train whole. 3040MITOVERSE_MICRONS1_TRAIN_ONLY_VOLUMES = ("microns1_vol1", "microns1_vol2") 3041MITOVERSE_MICRONS1_TRAIN_ROI = np.s_[:36, :, :] 3042MITOVERSE_MICRONS1_VAL_ROI = np.s_[36:, :, :] 3043# Regions of raw == 0 above this area (in pixels) are missing data, not dark membranes. 3044MITOVERSE_MISSING_DATA_MIN_AREA = 2000 3045MITOVERSE_IGNORE_LABEL = np.iinfo("uint32").max 3046 3047HUMAN_ORGANOIDS_VOLUMES = ["F059_bin2.h5", "F107_A1_bin2.h5", "F107_A2_bin2.h5", "F107_A3_bin2.h5"] 3048HUMAN_ORGANOIDS_VAL_FRACTION = 0.1 3049# The neck watershed instances of finetuning/v2/generalist/em_organelles/preprocess_mito_dataset.py. 3050HUMAN_ORGANOIDS_MITO_ROOT = "human_organoids_mito" 3051 3052# The ASEM boxes (z0, z1, y0, y1, x0, x1) in raw voxels, cached by torch-em; 61 and 64 are evaluation volumes. 3053ASEM_MITO_BOXES = { 3054 "46": (640, 896, 0, 1024, 1112, 2136), "58": (152, 408, 0, 1000, 1480, 2504), 3055 "61": (0, 700, 190, 730, 2630, 3380), "64": (400, 641, 326, 802, 2212, 2740), 3056 "2E": (1015, 1215, 316, 516, 294, 494), 3057} 3058ASEM_MITO_TRAIN_VOLUMES = ("46", "58") 3059ASEM_MITO_SMALL_VOLUMES = ("2E",) 3060ASEM_MITO_TRAIN_ROI = np.s_[:224, :, :] 3061ASEM_MITO_VAL_ROI = np.s_[224:, :, :] 3062ASEM_MITO_SMALL_SIDE = 192 3063 3064# The noisy stack is registered to the reference stack, so it trains with the same labels. 3065BRAIN_PFIBSEM_PATH = os.path.join("brain_pfibsem", "brain_pfibsem.h5") 3066BRAIN_PFIBSEM_TRAIN_ROI = np.s_[:144, :, :] 3067BRAIN_PFIBSEM_VAL_ROI = np.s_[144:, :, :] 3068 3069U2OS_FIBSEM_MITO_ROOT = os.path.join("u2os_fibsem", "1_Mitochondria", "1_Train_Mito") 3070U2OS_FIBSEM_MITO_VAL_STEP = 9 3071 3072HELA_STARD3_VOLUMES = ("ctrl", "stard3", "stard3_fa_ya") 3073HELA_STARD3_VAL_VOLUME = "ctrl" 3074HELA_STARD3_VAL_START = 404 3075 3076# These samples differ from the Parlakgul liver samples of the evaluation. 3077PARLAKGUL_FASTING_ROOT = "parlakgul_fasting_liver" 3078PARLAKGUL_FASTING_TRAIN_ROI = np.s_[:50, :, :] 3079PARLAKGUL_FASTING_VAL_ROI = np.s_[50:, :, :] 3080 3081AIVE_MITO_CLASS = 1 3082AIVE_MITO_VAL_STARTS = { 3083 "aive_dataset1.h5": 652, "aive_dataset2.h5": 772, "aive_dataset3.h5": 556, "aive_dataset4.h5": 280, 3084} 3085 3086 3087# The intestine box of MitoSegEM is an out-of-domain evaluation set. 3088MITO_SEGEM_TRAIN_BOXES = { 3089 "testis": (1268, 1332, 1792, 2816, 7680, 8704), 3090 "brainstem": (1868, 1932, 7936, 8960, 7168, 8192), 3091} 3092MITO_SEGEM_TRAIN_ROI = np.s_[:50, :, :] 3093MITO_SEGEM_VAL_ROI = np.s_[50:, :, :] 3094 3095 3096# The crops of one cell can be nested, so whole cells validate. 3097CELLMAP_MITO_PATCH_SIDES = (128, 192, 256, 384, 512) 3098CELLMAP_MITO_VAL_FRACTION = 0.1 3099 3100 3101def probtem_split_paths(input_path, split): 3102 """The ProbTEM train images of the 'train' or 'val' part.""" 3103 paths = sorted(glob(os.path.join(input_path, PROBTEM_ROOT, "train", "*.h5"))) 3104 train_paths, val_paths = train_test_split(paths, test_size=PROBTEM_N_VAL, random_state=42) 3105 return sorted(train_paths if split == "train" else val_paths) 3106 3107 3108def cellmap_mito_split_crops(input_path, split): 3109 """The CellMap mito crops of the 'train' or 'val' volumes, as {patch side: crop paths}.""" 3110 root = os.path.join(input_path, "cellmap_mito_crops") 3111 with open(os.path.join(root, "index.json")) as f: 3112 crops = [ 3113 crop for crop in json.load(f) if crop["n_ids"] > 0 and min(crop["shape"][1:]) >= CELLMAP_MITO_PATCH_SIDES[0] 3114 ] 3115 volumes = sorted({crop["volume"] for crop in crops}) 3116 train_volumes, val_volumes = train_test_split(volumes, test_size=CELLMAP_MITO_VAL_FRACTION, random_state=42) 3117 keep = set(train_volumes if split == "train" else val_volumes) 3118 groups = {} 3119 for crop in crops: 3120 if crop["volume"] in keep: 3121 side = max(s for s in CELLMAP_MITO_PATCH_SIDES if s <= min(crop["shape"][1:])) 3122 groups.setdefault(side, []).append(os.path.join(root, f"{crop['name']}.zarr")) 3123 return {side: sorted(paths) for side, paths in sorted(groups.items())} 3124 3125 3126# The datasets of the nucleus EM generalist ('em_nucleus'). Each name enables one block in _get_em_nucleus_datasets. 3127EM_NUCLEUS_DATASETS = ( 3128 "betaseg_nucleus", "cellmap_nucleus", "human_organoids_nucleus", "sxt_nucleus", "fafb_nuclei", "janelia_nucleus", 3129 "microns_nuclei", "waenet_fibsem_nucleus", "waenet_sstem_nucleus", "waenet_tem_nucleus", "platynereis_nuclei", 3130 "tumor_spheroid_nuclei", "openorganelle_nucleus", "cardiomyocyte_tem_nucleus", "microsam_em_nuclei", 3131 "perez_nucleus", "vem_nuclei", "cerebellum_nucleus", "macrophage_a431_nucleus", 3132) 3133 3134# Objects below this size (in voxels of the training patch) are dropped from the nucleus targets. 3135EM_NUCLEUS_MIN_SIZE_3D = 50 3136 3137# Training samples per epoch and source, by the rules of EM_MITO_TRAIN_SAMPLES; large, diverse sources get more. 3138EM_NUCLEUS_TRAIN_SAMPLES = { 3139 "betaseg_nucleus": 400, "cellmap_nucleus": 900, "human_organoids_nucleus": 900, "sxt_nucleus": 800, 3140 "fafb_nuclei": 293, "janelia_nucleus": 900, "microns_nuclei": 414, "waenet_fibsem_nucleus": 200, 3141 "waenet_sstem_nucleus": 510, "waenet_tem_nucleus": 2500, "platynereis_nuclei": 200, "tumor_spheroid_nuclei": 1400, 3142 "openorganelle_nucleus": 1100, "cardiomyocyte_tem_nucleus": 575, "microsam_em_nuclei": 200, "perez_nucleus": 350, 3143 "vem_nuclei_2d": 2800, "vem_nuclei_3d": 200, "cerebellum_nucleus": 175, 3144 "macrophage_a431_nucleus": 424, 3145} 3146# The nuclei that a patch needs per dataset (measured on 40 random patches); the other datasets need one. 3147EM_NUCLEUS_MIN_INSTANCES = { 3148 "fafb_nuclei": 3, "microns_nuclei": 3, "platynereis_nuclei": 3, "microsam_em_nuclei": 3, "janelia_nucleus": 3, 3149 "tumor_spheroid_nuclei": 2, "human_organoids_nucleus": 2, "cellmap_nucleus": 2, "vem_nuclei": 2, 3150 "openorganelle_nucleus": 2, 3151} 3152# These volumes never held that many nuclei in a patch, so they need one. 3153EM_NUCLEUS_SPARSE_VOLUMES = { 3154 "cellmap_nucleus_crops/jrc_mus-liver-zon-2_crop367.zarr": 1, "janelia_nucleus/jrc_mus-nacc-2.zarr": 1, 3155 "janelia_nucleus/jrc_mus-nacc-4.zarr": 1, "openorganelle_nucleus/jrc_cos7-11_64nm.zarr": 1, 3156 "openorganelle_nucleus/jrc_hela-21.zarr": 1, "openorganelle_nucleus/aic_desmosome-3.zarr": 1, 3157 "vem_nuclei_nucleus/id_12.h5": 1, 3158} 3159 3160# A volume uses the largest side that fits in-plane; patches below 512 px are resized to 512 x 512. 3161EM_NUCLEUS_PATCH_SIDES = (128, 192, 256, 320, 384, 512) 3162 3163# Only the target cell is labeled, so the loss ignores the voxels outside it. 3164BETASEG_NUCLEUS_TRAIN_VOLUMES = ("high_c1", "high_c2", "high_c3", "high_c4", "low_c1", "low_c2") 3165BETASEG_NUCLEUS_VAL_VOLUMES = ("low_c3",) 3166BETASEG_NUCLEUS_IGNORE_LABEL = np.iinfo("uint32").max 3167 3168# The CellMap crop357 of jrc_mus-liver-zon-2 is the in-domain evaluation crop. 3169CELLMAP_NUCLEUS_VAL_CROPS = ("jrc_zf-cardiac-1_crop379",) 3170 3171# Label fragments and the entotic cell of F107_A1 carry this label. 3172HUMAN_ORGANOIDS_NUCLEUS_IGNORE_LABEL = np.iinfo("uint32").max 3173 3174# SXT is soft X-ray tomography; the loss ignores the exterior of the target cell. 3175SXT_NUCLEUS_CLASS = 2 3176SXT_EXTERIOR_CLASS = 0 3177SXT_NUCLEUS_IGNORE_LABEL = np.iinfo("uint16").max 3178SXT_NUCLEUS_N_VAL = 5 3179 3180# The FAFB test blocks are the in-domain evaluation blocks. 3181FAFB_NUCLEI_Z_SCALE = 40 / 32 3182 3183# jrc_mus-granule-neurons-1 is only 85 px wide in y. 3184JANELIA_NUCLEUS_EXCLUDED_VOLUMES = ("jrc_mus-granule-neurons-1",) 3185JANELIA_NUCLEUS_VAL_VOLUMES = ("jrc_mus-meissner-corpuscle-2",) 3186 3187# The MICrONS test blocks are the in-domain evaluation blocks. 3188MICRONS_NUCLEI_Z_SCALE = 40 / 64 3189 3190# Only the valid ROI of each volume trains; volume 03 is the in-domain evaluation volume. 3191PLATYNEREIS_NUCLEI_TRAIN_IDS = (1, 2, 4, 5, 6, 7, 8, 9, 10, 11) 3192PLATYNEREIS_NUCLEI_VAL_IDS = (12,) 3193PLATYNEREIS_NUCLEI_TEST_IDS = (3,) 3194PLATYNEREIS_NUCLEI_IGNORE_LABEL = -1 3195PLATYNEREIS_NUCLEI_Z_SCALE = 100 / 80 3196 3197# The validation slices have no close neighbour; cells without a nucleus label carry the ignore label. 3198TUMOR_SPHEROID_NUCLEI_VAL_SLICES = ("Au_01-vol_01-x_1300.h5", "Au_01-vol_01-z_0274.h5") 3199TUMOR_SPHEROID_NUCLEI_IGNORE_LABEL = np.iinfo("uint32").max 3200 3201# finetuning/v2/generalist/em_organelles/preprocess_nucleus_dataset.py writes the derived data of these datasets. 3202CARDIOMYOCYTE_NUCLEUS_ROOT = "cardiomyocyte_tem_nucleus" 3203CARDIOMYOCYTE_NUCLEUS_N_VAL = 2 3204# Only the 'train' crop has reference labels, so the 'annotation' crop is not used. 3205MICROSAM_EM_NUCLEI_PATH = os.path.join("microsam_em_nuclei", "data", "train_data.h5") 3206PEREZ_NUCLEUS_ROOT = "perez_nucleus" 3207VEM_NUCLEI_ROOT = "vem_nuclei_nucleus" 3208VEM_NUCLEI_3D_IDS = (11, 12) 3209# The nucleus of id_12 ends at z 399 of 463, so this slab holds its end. 3210VEM_NUCLEI_VAL_SLICES = 100 3211VEM_NUCLEI_IGNORE_LABEL = np.iinfo("uint32").max 3212CEREBELLUM_NUCLEUS_PATH = os.path.join("cerebellum_fibsem_nucleus", "cerebellum_fibsem.h5") 3213# This slab holds the end of one large nucleus. 3214CEREBELLUM_NUCLEUS_VAL_Z = 200 3215CEREBELLUM_NUCLEUS_IGNORE_LABEL = np.iinfo("uint32").max 3216MACROPHAGE_NUCLEUS_ROOT = "macrophage_a431_nucleus" 3217MACROPHAGE_NUCLEUS_Z_SCALE = 2.5 3218MACROPHAGE_NUCLEUS_VAL_VOLUME = "sbf_a431" 3219# The nucleus of sbf_a431 ends at z 134 of 162, so this slab holds its end. 3220MACROPHAGE_NUCLEUS_VAL_Z = 115 3221 3222# In the WAE-Net TEM images only the central cell is labeled, so the loss ignores the other pixels. 3223WAENET_VAL_FRACTION = 0.1 3224WAENET_NUCLEUS_IGNORE_LABEL = np.iinfo("uint32").max 3225 3226# The OpenOrganelle nucleus volumes with the voxel size (nm) of their full torch-em arrays; None is the default cache. 3227OPENORGANELLE_NUCLEUS_VOLUMES = { 3228 "jrc_mus-pancreas-4": 128.0, "jrc_mus-skin-1": 128.0, "jrc_mus-hippocampus-1": 128.0, "jrc_mus-sc-zp104a": 96.0, 3229 "jrc_mus-sc-zp105a": 96.0, "jrc_choroid-plexus-2": 64.0, "jrc_cos7-11": 64.0, "jrc_ctl-id8-3": 128.0, 3230 "jrc_ctl-id8-4": 128.0, "jrc_ctl-id8-5": 128.0, "jrc_ccl81-covid-1": 64.0, "jrc_hela-21": None, 3231 "aic_desmosome-3": None, "jrc_mus-thymus-1": None, "jrc_hum-airway-14953vc": None, "jrc_fly-acc-calyx-1": None, 3232 "jrc_fly-fsb-1": None, 3233} 3234OPENORGANELLE_NUCLEUS_VAL_VOLUMES = ("jrc_mus-sc-zp105a",) 3235 3236 3237def em_nucleus_patch_side(shape): 3238 """The largest patch side of EM_NUCLEUS_PATCH_SIDES that fits in-plane into a volume of *shape*.""" 3239 return max(side for side in EM_NUCLEUS_PATCH_SIDES if side <= min(shape[-2:])) 3240 3241 3242def betaseg_nucleus_split_boxes(input_path, split): 3243 """The BetaSeg nucleus boxes of the 'train' or 'val' volumes, as {patch side: box paths}.""" 3244 groups = {} 3245 for volume in BETASEG_NUCLEUS_TRAIN_VOLUMES if split == "train" else BETASEG_NUCLEUS_VAL_VOLUMES: 3246 path = os.path.join(input_path, "betaseg_nucleus_boxes", f"{volume}.h5") 3247 with open_file(path, "r") as f: 3248 groups.setdefault(em_nucleus_patch_side(f["raw"].shape), []).append(path) 3249 return {side: sorted(paths) for side, paths in sorted(groups.items())} 3250 3251 3252def sxt_nucleus_labels(labels): 3253 """The nucleus mask of the SXT INS-1E class labels, with SXT_NUCLEUS_IGNORE_LABEL outside the cell.""" 3254 labels = np.asarray(labels) 3255 nucleus = (labels == SXT_NUCLEUS_CLASS).astype("uint16") 3256 nucleus[labels == SXT_EXTERIOR_CLASS] = SXT_NUCLEUS_IGNORE_LABEL 3257 return nucleus 3258 3259 3260def sxt_nucleus_instances(labels): 3261 """The connected components of the SXT INS-1E nucleus mask, as the pre_label_transform (before the sampler).""" 3262 return _connected_components_pre_label_trafo(sxt_nucleus_labels(labels), ignore_label=SXT_NUCLEUS_IGNORE_LABEL) 3263 3264 3265def sxt_nucleus_split_paths(input_path, split): 3266 """The SXT INS-1E cells of the 'train' or 'val' part, as {patch side: zarr paths}.""" 3267 paths = sorted(glob(os.path.join(input_path, "sxt_ins1e_mito", "*.zarr"))) 3268 train_paths, val_paths = train_test_split(paths, test_size=SXT_NUCLEUS_N_VAL, random_state=42) 3269 groups = {} 3270 for path in train_paths if split == "train" else val_paths: 3271 with open_file(path, "r") as f: 3272 groups.setdefault(em_nucleus_patch_side(f["labels"].shape), []).append(path) 3273 return {side: sorted(paths) for side, paths in sorted(groups.items())} 3274 3275 3276def platynereis_nuclei_split_rois(input_path, split): 3277 """The Platynereis nucleus volumes of the 'train' or 'val' part, as {patch side: (paths, valid rois)}.""" 3278 root = os.path.join(input_path, "platynereis") 3279 template = "nuclei/train_data_nuclei_%02i.h5" 3280 sample_ids = PLATYNEREIS_NUCLEI_TRAIN_IDS if split == "train" else PLATYNEREIS_NUCLEI_VAL_IDS 3281 valid_rois = _compute_platy_rois( 3282 root, sample_ids, ignore_label=PLATYNEREIS_NUCLEI_IGNORE_LABEL, file_template=template, 3283 label_key="volumes/labels/nucleus_instance_labels", cache_prefix="_nuclei_roi_cache", 3284 ) 3285 groups = {} 3286 for sample_id in sample_ids: 3287 roi = valid_rois[sample_id] 3288 side = em_nucleus_patch_side((roi[1].stop - roi[1].start, roi[2].stop - roi[2].start)) 3289 paths, rois = groups.setdefault(side, ([], [])) 3290 paths.append(os.path.join(root, template % sample_id)) 3291 rois.append(roi) 3292 return dict(sorted(groups.items())) 3293 3294 3295def janelia_nucleus_split_paths(input_path, split): 3296 """The Janelia nucleus volumes of the split, as {patch side: zarr paths}, and their voxel counts. 3297 3298 The voxel counts weight the samples, so that the large tissue volumes are not outweighed by the small volumes with 3299 one to three nuclei. 3300 """ 3301 groups, voxels = {}, {} 3302 for path in sorted(glob(os.path.join(input_path, "janelia_nucleus", "*.zarr"))): 3303 name = os.path.basename(path)[:-len(".zarr")] 3304 if name in JANELIA_NUCLEUS_EXCLUDED_VOLUMES or (name in JANELIA_NUCLEUS_VAL_VOLUMES) != (split == "val"): 3305 continue 3306 with open_file(path, "r") as f: 3307 shape = f["labels"].shape 3308 groups.setdefault(em_nucleus_patch_side(shape), []).append(path) 3309 voxels[path] = int(np.prod(shape)) 3310 return {side: sorted(paths) for side, paths in sorted(groups.items())}, voxels 3311 3312 3313def openorganelle_nucleus_split_paths(input_path, split): 3314 """The OpenOrganelle nucleus volumes of the split, as {patch side: zarr paths}, and their voxel counts. 3315 3316 The voxel counts weight the samples, so that the large tissue volumes are not outweighed by the many single-cell 3317 volumes with one to three nuclei. 3318 """ 3319 root = os.path.join(input_path, "openorganelle_nucleus") 3320 groups, voxels = {}, {} 3321 for name, voxel_size in OPENORGANELLE_NUCLEUS_VOLUMES.items(): 3322 if (name in OPENORGANELLE_NUCLEUS_VAL_VOLUMES) != (split == "val"): 3323 continue 3324 path = datasets.openorganelle_nucleus.get_openorganelle_nucleus_paths(root, [name], voxel_size=voxel_size)[0] 3325 with open_file(path, "r") as f: 3326 shape = f["labels"].shape 3327 groups.setdefault(em_nucleus_patch_side(shape), []).append(path) 3328 voxels[path] = int(np.prod(shape)) 3329 return {side: sorted(paths) for side, paths in sorted(groups.items())}, voxels 3330 3331 3332def cellmap_nucleus_split_crops(input_path, split): 3333 """The CellMap nucleus crops of the 'train' or 'val' part, as {patch side: crop paths}.""" 3334 root = os.path.join(input_path, "cellmap_nucleus_crops") 3335 with open(os.path.join(root, "index.json")) as f: 3336 crops = [crop for crop in json.load(f) if crop["split"] == "train"] 3337 groups = {} 3338 for crop in crops: 3339 if (crop["name"] in CELLMAP_NUCLEUS_VAL_CROPS) == (split == "val"): 3340 groups.setdefault(em_nucleus_patch_side(crop["shape"]), []).append( 3341 os.path.join(root, f"{crop['name']}.zarr") 3342 ) 3343 return {side: sorted(paths) for side, paths in sorted(groups.items())} 3344 3345 3346# The CEM-MitoLab groups whose names match a mitochondria evaluation dataset never train. 3347MITOLAB_EXCLUDED_GROUPS = ( 3348 "Wei2020_MitoEM-H", "Wei2020_MitoEM-R", "jrc_jurkat-1_openorganelle", "jrc_macrophage-2_openorganelle", 3349 "Guay2020_patient1", "kasthuri2011", "segem2015", "Hennies2020_AMST_HeLaBV2", "jrc_hela-1_openorganelle", 3350 "jrc_hela-2_openorganelle", "jrc_hela-3_openorganelle", "jrc_hela-4_openorganelle", "jrc_hela-21_openorganelle", 3351 "jrc_hela-22_openorganelle", "jrc_hela-bfa_openorganelle", "jrc_hela-h89-1_openorganelle", 3352 "jrc_hela-h89-2_openorganelle", "Parlakgul2020_file03_video", "Parlakgul2020_file04_video", 3353 "perez2014", 3354) 3355 3356# Fraction of the CEM-MitoLab groups that validate. The split is by group, so the tiles of one source volume never 3357# land in both splits. 3358MITOLAB_VAL_FRACTION = 0.1 3359 3360 3361def mitolab_group(path, root): 3362 """The CEM-MitoLab group (source folder) of an image path: '<root>/<group>/images/<name>.tiff'.""" 3363 return os.path.relpath(path, root).split(os.sep)[0] 3364 3365 3366def mitolab_split_paths(path, split): 3367 """The non-empty CEM-MitoLab images and masks of the 'train' or 'val' groups, without the excluded groups.""" 3368 root = datasets.cem.get_mitolab_data(path, download=False) 3369 raw_paths, label_paths = datasets.cem.get_mitolab_paths(path, split=None, download=False) 3370 groups = sorted({mitolab_group(p, root) for p in raw_paths} - set(MITOLAB_EXCLUDED_GROUPS)) 3371 train_groups, val_groups = train_test_split(groups, test_size=MITOLAB_VAL_FRACTION, random_state=42) 3372 keep = set(train_groups if split == "train" else val_groups) 3373 pairs = [(r, lab) for r, lab in zip(raw_paths, label_paths) if mitolab_group(r, root) in keep] 3374 if split == "val": 3375 # A seeded MITOLAB_VAL_IMAGES_PER_GROUP images per group, so that no group dominates the validation. 3376 by_group = {} 3377 for pair in pairs: 3378 by_group.setdefault(mitolab_group(pair[0], root), []).append(pair) 3379 rng = np.random.default_rng(42) 3380 pairs = [] 3381 for group in sorted(by_group): 3382 members = by_group[group] 3383 if len(members) > MITOLAB_VAL_IMAGES_PER_GROUP: 3384 members = [members[i] for i in sorted(rng.choice(len(members), MITOLAB_VAL_IMAGES_PER_GROUP, False))] 3385 pairs.extend(members) 3386 return [r for r, _ in pairs], [lab for _, lab in pairs] 3387 3388 3389def mitoemv2_mossy_label_path(input_path, volume): 3390 """The labels of one MitoVerse han24 volume with MITOEMV2_MOSSY_IGNORE_LABEL outside the annotated boutons. 3391 3392 They are written once to <input_path>/mitoverse_derived, slab by slab, under a temporary name that is moved in 3393 place when complete, so that interrupted writes and concurrent ranks never leave a partial array behind. 3394 """ 3395 import zarr 3396 3397 out_path = os.path.join(input_path, "mitoverse_derived", f"han24_{volume}_bouton_labels.zarr") 3398 if os.path.exists(out_path): 3399 return out_path 3400 3401 source = zarr.open_group(os.path.join(input_path, "mitoverse", "data", "han24", f"{volume}.zarr"), mode="r") 3402 tmp_path = f"{out_path}.{os.getpid()}.incomplete" 3403 labels = zarr.open_group(tmp_path, mode="w").create_array( 3404 "labels", shape=source["mito"].shape, chunks=(32, 256, 256), dtype="uint32" 3405 ) 3406 for z in range(0, labels.shape[0], 32): 3407 slab = source["mito"][z:z + 32].astype("uint32") 3408 slab[source["mask"][z:z + 32] == 0] = MITOEMV2_MOSSY_IGNORE_LABEL 3409 labels[z:z + 32] = slab 3410 try: 3411 os.replace(tmp_path, out_path) 3412 except OSError: 3413 # Another rank moved its copy in place first. 3414 shutil.rmtree(tmp_path) 3415 return out_path 3416 3417 3418def mitoverse_missing_data_label_path(input_path, dataset, volume): 3419 """The labels of one MitoVerse volume with MITOVERSE_IGNORE_LABEL inside the regions without image data. 3420 3421 A region without image data is a connected raw == 0 region of a slice above MITOVERSE_MISSING_DATA_MIN_AREA. 3422 The labels are written once to <input_path>/mitoverse_derived, slice by slice, under a temporary name that is 3423 moved in place when complete, as in mitoemv2_mossy_label_path. 3424 """ 3425 import zarr 3426 from scipy import ndimage 3427 3428 out_path = os.path.join(input_path, "mitoverse_derived", f"{dataset}_{volume}_missing_data_labels.zarr") 3429 if os.path.exists(out_path): 3430 return out_path 3431 3432 source = zarr.open_group(os.path.join(input_path, "mitoverse", "data", dataset, f"{volume}.zarr"), mode="r") 3433 tmp_path = f"{out_path}.{os.getpid()}.incomplete" 3434 labels = zarr.open_group(tmp_path, mode="w").create_array( 3435 "labels", shape=source["mito"].shape, chunks=(32, 256, 256), dtype="uint32" 3436 ) 3437 for z in range(labels.shape[0]): 3438 slice_labels = source["mito"][z].astype("uint32") 3439 empty, _ = ndimage.label(source["img"][z] == 0) 3440 areas = np.bincount(empty.ravel()) 3441 missing = np.isin(empty, np.where(areas > MITOVERSE_MISSING_DATA_MIN_AREA)[0]) & (empty > 0) 3442 slice_labels[missing] = MITOVERSE_IGNORE_LABEL 3443 labels[z] = slice_labels 3444 try: 3445 os.replace(tmp_path, out_path) 3446 except OSError: 3447 # Another rank moved its copy in place first. 3448 shutil.rmtree(tmp_path) 3449 return out_path 3450 3451 3452def _set_volume_min_instances(dataset, min_instances, depth=1): 3453 """Set min_num_instances of the leaves whose raw path ends in a key of *min_instances* ({path end: minimum}). 3454 3455 The key is the last *depth* components of the raw path. 3456 """ 3457 if isinstance(dataset, (list, tuple)): 3458 for ds in dataset: 3459 _set_volume_min_instances(ds, min_instances, depth) 3460 elif isinstance(dataset, UniDataWrapper): 3461 _set_volume_min_instances(dataset.ds, min_instances, depth) 3462 elif getattr(dataset, "datasets", None) is not None: 3463 for ds in dataset.datasets: 3464 _set_volume_min_instances(ds, min_instances, depth) 3465 elif getattr(dataset, "raw_path", None) is not None: 3466 key = "/".join(str(dataset.raw_path).split(os.sep)[-depth:]) 3467 if key in min_instances: 3468 sampler = dataset.sampler 3469 dataset.sampler = MinInstanceSampler( 3470 min_num_instances=min_instances[key], min_size=sampler.min_size, exclude_ids=sampler.exclude_ids, 3471 ) 3472 3473 3474def _get_em_mito_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo): 3475 """Get the mitochondria EM datasets for the mitochondria generalist. 3476 3477 Only the mitochondria labels of a dataset are used, all other structures are background. Mitochondria are not dense 3478 cells, so the targets come from the plain label transform (no outer boundary erosion as in the EM cell datasets). 3479 The distance transform relabels every extracted patch with connected components (``apply_label=True``): semantic 3480 labels become instances, and the disconnected pieces of one id inside a patch become separate instances. Objects 3481 that touch, such as thin bridges across sections, stay merged. 3482 3483 Returns: 3484 Tuple of (train_ds, val_ds) lists of UniDataWrapper instances. 3485 """ 3486 train_ds, val_ds = [], [] 3487 n_z = len(z_slices) 3488 3489 def mito_label_trafo(min_size=EM_MITO_MIN_SIZE, sampling=None, ignore_label=None): 3490 trafo = kwargs.get("label_transform2") if label_trafo is None else label_trafo( 3491 min_size=min_size, sampling=sampling 3492 ) 3493 if ignore_label is None: 3494 return trafo 3495 return partial(_ignore_label_trafo, ignore_label=ignore_label, label_trafo=trafo) 3496 3497 # 1. CEM-MitoLab (2D mitochondria instance segmentation in EM tiles from about 600 source volumes and images) 3498 # NOTE: The tiles are 63-512 px, so the whole tile is drawn and randomly upscaled and padded to the patch shape. 3499 # Only the non-empty tiles are used, split by source group (see mitolab_split_paths). 3500 if "mitolab" in EM_MITO_DATASETS: 3501 mitolab_kwargs = { 3502 "patch_shape": None, "raw_key": None, "label_key": None, "is_seg_dataset": False, "ndim": 2, 3503 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 3504 "label_transform2": mito_label_trafo(), 3505 "pre_label_transform": _connected_components_pre_label_trafo, 3506 "sampler": MinInstanceSampler(min_num_instances=1, min_size=EM_MITO_MIN_SIZE, exclude_ids=[0]), 3507 "transform": _with_flips(_random_resize_and_pad_trafo, patch_shape), 3508 } 3509 for split, ds_list in [("train", train_ds), ("val", val_ds)]: 3510 raws, labs = mitolab_split_paths(os.path.join(input_path, "mitolab"), split) 3511 ds_list.append( 3512 UniDataWrapper( 3513 torch_em.default_segmentation_dataset( 3514 raw_paths=raws, label_paths=labs, n_samples=len(raws) if split == "train" else 50, 3515 **mitolab_kwargs, 3516 ), source_ndim=2, 3517 ) 3518 ) 3519 3520 # 2. DenseCell mitochondria (3D, class 2 of the semantic map in SBF-SEM of human platelets, 10x10x50 nm) 3521 # NOTE: The mitochondria are small and sparse (13-36 per volume), so one object per patch is enough. 3522 if "densecell_mito" in EM_MITO_DATASETS: 3523 for z in z_slices: 3524 densecell_kwargs = { 3525 "path": os.path.join(input_path, "densecell"), 3526 "patch_shape": (z, *patch_shape), 3527 "label_choice": "mitochondrion", 3528 "download": True, 3529 "ndim": 3, 3530 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 3531 "label_transform2": mito_label_trafo(EM_MITO_MIN_SIZE_3D, sampling=(5, 1, 1)), 3532 "pre_label_transform": _connected_components_pre_label_trafo, 3533 "sampler": MinInstanceSampler( 3534 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 3535 ), 3536 } 3537 for roi, ds_list, n_samples in [ 3538 (DENSECELL_TRAIN_ROI, train_ds, EM_MITO_TRAIN_SAMPLES["densecell_mito"]), 3539 (DENSECELL_VAL_ROI, val_ds, 40), 3540 ]: 3541 ds_list.append( 3542 UniDataWrapper( 3543 datasets.get_densecell_dataset( 3544 split="train", rois=roi, n_samples=max(1, n_samples // n_z), **densecell_kwargs 3545 ), 3546 source_ndim=3, group_key=(3, z), 3547 ) 3548 ) 3549 3550 # 3. Lucchi (3D mitochondria in FIB-SEM of the mouse hippocampus, 5 nm isotropic, manual semantic labels) 3551 if "lucchi" in EM_MITO_DATASETS: 3552 for z in z_slices: 3553 lucchi_kwargs = { 3554 "path": os.path.join(input_path, "lucchi"), 3555 "patch_shape": (z, *patch_shape), 3556 "download": True, 3557 "ndim": 3, 3558 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 3559 "label_transform2": mito_label_trafo(EM_MITO_MIN_SIZE_3D), 3560 "pre_label_transform": _connected_components_pre_label_trafo, 3561 "sampler": MinInstanceSampler( 3562 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 3563 ), 3564 } 3565 for roi, ds_list, n_samples in [ 3566 (LUCCHI_TRAIN_ROI, train_ds, EM_MITO_TRAIN_SAMPLES["lucchi"]), (LUCCHI_VAL_ROI, val_ds, 40), 3567 ]: 3568 ds_list.append( 3569 UniDataWrapper( 3570 datasets.get_lucchi_dataset( 3571 split="train", rois=roi, n_samples=max(1, n_samples // n_z), **lucchi_kwargs 3572 ), 3573 source_ndim=3, group_key=(3, z), 3574 ) 3575 ) 3576 3577 # 4. MICrONS pinky mitochondria (3D, ssTEM of the mouse visual cortex, 4x4x40 nm, manual instance labels) 3578 # NOTE: The uint8 ids wrap at 255; the connected components split the ids that are not connected. 3579 if "microns_pinky_mito" in EM_MITO_DATASETS: 3580 pinky_path = os.path.join(input_path, "microns", "pinky", MICRONS_PINKY_MITO_FILE) 3581 for z in z_slices: 3582 pinky_kwargs = { 3583 "raw_paths": pinky_path, "raw_key": "volumes/image", 3584 "label_paths": pinky_path, "label_key": "volumes/mitochondria", 3585 "patch_shape": (z, *patch_shape), "ndim": 3, 3586 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 3587 "label_transform2": mito_label_trafo(EM_MITO_MIN_SIZE_3D, sampling=(10, 1, 1)), 3588 "pre_label_transform": _connected_components_pre_label_trafo, 3589 "sampler": MinInstanceSampler( 3590 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 3591 ), 3592 } 3593 for roi, ds_list, n_samples in [ 3594 (MICRONS_PINKY_MITO_TRAIN_ROI, train_ds, EM_MITO_TRAIN_SAMPLES["microns_pinky_mito"]), 3595 (MICRONS_PINKY_MITO_VAL_ROI, val_ds, 40), 3596 ]: 3597 ds_list.append( 3598 UniDataWrapper( 3599 torch_em.default_segmentation_dataset( 3600 rois=roi, n_samples=max(1, n_samples // n_z), **pinky_kwargs 3601 ), 3602 source_ndim=3, group_key=(3, z), 3603 ) 3604 ) 3605 3606 # 5. MitoEM (3D mitochondria in ssTEM of the human and rat cortex, 8x8x30 nm, manual proofread instance labels) 3607 # NOTE: Reads the train volumes directly; torch-em's mitoem dataset adds its own instance label transform. 3608 if "mitoem" in EM_MITO_DATASETS: 3609 for sample in MITOEM_SAMPLES: 3610 mitoem_path = datasets.mitoem.get_mitoem_paths( 3611 os.path.join(input_path, "mitoem"), splits="train", samples=sample, download=False 3612 )[0] 3613 for z in z_slices: 3614 mitoem_kwargs = { 3615 "raw_paths": mitoem_path, "raw_key": "raw", "label_paths": mitoem_path, "label_key": "labels", 3616 "patch_shape": (z, *patch_shape), "ndim": 3, 3617 **{ 3618 k: v for k, v in kwargs.items() 3619 if k not in ["raw_transform", "label_transform2", "sampler", "transform"] 3620 }, 3621 "label_transform2": mito_label_trafo( 3622 EM_MITO_MIN_SIZE_3D, sampling=(3.75, 1, 1), ignore_label=MISSING_RAW_IGNORE_LABEL 3623 ), 3624 # Labels on constant raw (saturated 254 in human z = 190) become ignore; the transform normalizes. 3625 "raw_transform": _prepare_identity, 3626 "transform": partial( 3627 _ignore_missing_raw_trafo, ignore_label=MISSING_RAW_IGNORE_LABEL, any_constant=True, 3628 transform=get_augmentations(ndim=3), 3629 ), 3630 "pre_label_transform": _connected_components_pre_label_trafo, 3631 "sampler": MinInstanceSampler( 3632 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 3633 ), 3634 } 3635 for roi, ds_list, n_samples in [ 3636 (MITOEM_TRAIN_ROI, train_ds, EM_MITO_TRAIN_SAMPLES[f"mitoem_{sample}"]), 3637 (MITOEM_VAL_ROI, val_ds, 40), 3638 ]: 3639 ds_list.append( 3640 UniDataWrapper( 3641 torch_em.default_segmentation_dataset( 3642 rois=roi, n_samples=max(1, n_samples // n_z), **mitoem_kwargs 3643 ), 3644 source_ndim=3, group_key=(3, z), 3645 ) 3646 ) 3647 3648 # 6. MitoEM v2 (3D mitochondria, expert-verified instances; FIB-SEM at 16 nm and SBF-SEM at 8 x 8 x 30 nm) 3649 # NOTE: The official train / val volumes, see MITOEMV2_DATASETS. jurkat validates on the end of its train volume. 3650 if "mitoemv2" in EM_MITO_DATASETS: 3651 mitoemv2_path = os.path.join(input_path, "mitoemv2") 3652 for name, z_scale in MITOEMV2_DATASETS.items(): 3653 train_paths = datasets.mitoemv2.get_mitoemv2_paths(mitoemv2_path, name, split="train", download=False) 3654 if name == "jurkat": 3655 splits = [ 3656 (train_paths, MITOEMV2_JURKAT_TRAIN_ROI, train_ds, EM_MITO_TRAIN_SAMPLES["mitoemv2_jurkat"]), 3657 (train_paths, MITOEMV2_JURKAT_VAL_ROI, val_ds, 40), 3658 ] 3659 else: 3660 val_paths = datasets.mitoemv2.get_mitoemv2_paths(mitoemv2_path, name, split="val", download=False) 3661 splits = [ 3662 (train_paths, None, train_ds, EM_MITO_TRAIN_SAMPLES[f"mitoemv2_{name}"]), 3663 (val_paths, None, val_ds, 40), 3664 ] 3665 for z in z_slices: 3666 mitoemv2_kwargs = { 3667 "raw_key": "raw", "label_key": "labels", "patch_shape": (z, *patch_shape), "ndim": 3, 3668 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 3669 "label_transform2": mito_label_trafo(EM_MITO_MIN_SIZE_3D, sampling=(z_scale, 1, 1)), 3670 "pre_label_transform": _connected_components_pre_label_trafo, 3671 "sampler": MinInstanceSampler( 3672 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 3673 ), 3674 } 3675 for paths, roi, ds_list, n_samples in splits: 3676 ds_list.append( 3677 UniDataWrapper( 3678 torch_em.default_segmentation_dataset( 3679 raw_paths=paths, label_paths=paths, rois=None if roi is None else [roi] * len(paths), 3680 n_samples=max(1, n_samples // n_z), **mitoemv2_kwargs, 3681 ), 3682 source_ndim=3, group_key=(3, z), 3683 ) 3684 ) 3685 3686 # 7. MitoEM v2 mossy (3D mitochondria in ssSEM of mossy fiber boutons in the mouse cerebellum, 8 x 8 x 30 nm) 3687 # NOTE: Only the boutons are annotated, so the loss ignores the voxels outside them. 3688 if "mitoemv2_mossy" in EM_MITO_DATASETS: 3689 han24_root = os.path.join(input_path, "mitoverse", "data", "han24") 3690 for volumes, ds_list, n_samples in [ 3691 (MITOEMV2_MOSSY_TRAIN_VOLUMES, train_ds, EM_MITO_TRAIN_SAMPLES["mitoemv2_mossy"]), 3692 (MITOEMV2_MOSSY_VAL_VOLUMES, val_ds, 40), 3693 ]: 3694 raw_paths = [os.path.join(han24_root, f"{volume}.zarr") for volume in volumes.values()] 3695 label_paths = [mitoemv2_mossy_label_path(input_path, volume) for volume in volumes.values()] 3696 for z in z_slices: 3697 mossy_kwargs = { 3698 "raw_key": "img", "label_key": "labels", "patch_shape": (z, *patch_shape), "ndim": 3, 3699 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 3700 "label_transform2": mito_label_trafo( 3701 EM_MITO_MIN_SIZE_3D, sampling=(30 / 8, 1, 1), ignore_label=MITOEMV2_MOSSY_IGNORE_LABEL 3702 ), 3703 "pre_label_transform": partial( 3704 _connected_components_pre_label_trafo, ignore_label=MITOEMV2_MOSSY_IGNORE_LABEL 3705 ), 3706 "sampler": MinInstanceSampler( 3707 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, 3708 exclude_ids=[0, MITOEMV2_MOSSY_IGNORE_LABEL], 3709 ), 3710 } 3711 ds_list.append( 3712 UniDataWrapper( 3713 torch_em.default_segmentation_dataset( 3714 raw_paths=raw_paths, label_paths=label_paths, n_samples=max(1, n_samples // n_z), 3715 **mossy_kwargs, 3716 ), 3717 source_ndim=3, group_key=(3, z), 3718 ) 3719 ) 3720 3721 # 8. ProbTEM (2D mitochondria in TEM of mouse skeletal muscle, 2560 x 2560, manual semantic labels) 3722 if "probtem" in EM_MITO_DATASETS: 3723 probtem_kwargs = { 3724 "raw_key": "raw", "label_key": "labels", "patch_shape": patch_shape, "ndim": 2, "is_seg_dataset": True, 3725 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 3726 "label_transform2": mito_label_trafo(), 3727 "pre_label_transform": _connected_components_pre_label_trafo, 3728 "sampler": MinInstanceSampler( 3729 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE, exclude_ids=[0] 3730 ), 3731 } 3732 for split, ds_list, n_samples in [("train", train_ds, EM_MITO_TRAIN_SAMPLES["probtem"]), ("val", val_ds, 40)]: 3733 paths = probtem_split_paths(input_path, split) 3734 ds_list.append( 3735 UniDataWrapper( 3736 torch_em.default_segmentation_dataset( 3737 raw_paths=paths, label_paths=paths, n_samples=n_samples, **probtem_kwargs 3738 ), source_ndim=2, 3739 ) 3740 ) 3741 3742 # 9. UroCell (3D mitochondria in FIB-SEM of the mouse urinary bladder, 16 nm isotropic, manual instance labels) 3743 # NOTE: The volumes are 256 px in plane, so the patches are resized to 512 x 512. 3744 if "uro_cell" in EM_MITO_DATASETS: 3745 urocell_paths = [os.path.join(input_path, "uro_cell", name) for name in UROCELL_MITO_VOLUMES] 3746 for z in z_slices: 3747 urocell_kwargs = { 3748 "raw_key": "raw", "label_key": "labels/mito", "patch_shape": (z, 256, 256), "ndim": 3, 3749 **{k: v for k, v in kwargs.items() if k not in ["raw_transform", "label_transform2", "sampler"]}, 3750 "raw_transform": _resize_raw_to_512, 3751 "label_transform2": partial( 3752 _resize_then_em_label_trafo, 3753 em_trafo_fn=mito_label_trafo(EM_MITO_MIN_SIZE_3D, sampling=(2, 1, 1)), 3754 ), 3755 "pre_label_transform": _connected_components_pre_label_trafo, 3756 "sampler": MinInstanceSampler( 3757 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 3758 ), 3759 } 3760 for roi, ds_list, n_samples in [ 3761 (UROCELL_TRAIN_ROI, train_ds, EM_MITO_TRAIN_SAMPLES["uro_cell"]), (UROCELL_VAL_ROI, val_ds, 40), 3762 ]: 3763 ds_list.append( 3764 UniDataWrapper( 3765 torch_em.default_segmentation_dataset( 3766 raw_paths=urocell_paths, label_paths=urocell_paths, rois=[roi] * len(urocell_paths), 3767 n_samples=max(1, n_samples // n_z), **urocell_kwargs, 3768 ), 3769 source_ndim=3, group_key=(3, z), 3770 ) 3771 ) 3772 3773 # 10. VNC (mitochondria in ssTEM of the Drosophila ventral nerve cord, 4.6 x 4.6 x 45 nm, manual labels) 3774 # NOTE: Single slices of the 20-slice train stack (see VNC_TRAIN_ROI), drawn as (1, 512, 512) patches. 3775 if "vnc" in EM_MITO_DATASETS: 3776 vnc_path = os.path.join(input_path, "vnc", "vnc_train.h5") 3777 vnc_kwargs = { 3778 "raw_key": "raw", "label_key": "labels/mitochondria", "patch_shape": (1, *patch_shape), 3779 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 3780 "label_transform2": mito_label_trafo(), 3781 "pre_label_transform": _connected_components_pre_label_trafo, 3782 "sampler": MinInstanceSampler( 3783 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE, exclude_ids=[0] 3784 ), 3785 } 3786 for roi, ds_list, n_samples in [ 3787 (VNC_TRAIN_ROI, train_ds, EM_MITO_TRAIN_SAMPLES["vnc"]), (VNC_VAL_ROI, val_ds, 20), 3788 ]: 3789 ds_list.append( 3790 UniDataWrapper( 3791 torch_em.default_segmentation_dataset( 3792 raw_paths=vnc_path, label_paths=vnc_path, rois=roi, n_samples=n_samples, **vnc_kwargs 3793 ), 3794 source_ndim=2, 3795 ) 3796 ) 3797 3798 # 11. MitoVerse xiao18 (3D mitochondria in ssSEM of the mouse auditory cortex, 8 x 8 x 50 nm, instance labels) 3799 if "mitoverse_xiao18" in EM_MITO_DATASETS: 3800 xiao18_path = os.path.join(input_path, "mitoverse", "data", "xiao18", "vol0.zarr") 3801 for z in z_slices: 3802 xiao18_kwargs = { 3803 "raw_paths": xiao18_path, "raw_key": "img", "label_paths": xiao18_path, "label_key": "mito", 3804 "patch_shape": (z, *patch_shape), "ndim": 3, 3805 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 3806 "label_transform2": mito_label_trafo(EM_MITO_MIN_SIZE_3D, sampling=(6.25, 1, 1)), 3807 "pre_label_transform": _connected_components_pre_label_trafo, 3808 "sampler": MinInstanceSampler( 3809 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 3810 ), 3811 } 3812 for roi, ds_list, n_samples in [ 3813 (MITOVERSE_XIAO18_TRAIN_ROI, train_ds, EM_MITO_TRAIN_SAMPLES["mitoverse_xiao18"]), 3814 (MITOVERSE_XIAO18_VAL_ROI, val_ds, 40), 3815 ]: 3816 ds_list.append( 3817 UniDataWrapper( 3818 torch_em.default_segmentation_dataset( 3819 rois=roi, n_samples=max(1, n_samples // n_z), **xiao18_kwargs 3820 ), 3821 source_ndim=3, group_key=(3, z), 3822 ) 3823 ) 3824 3825 # 12. MitoVerse haberl18 (3D mitochondria in SBF-SEM of the mouse brain, CDeep3M, 10 x 10 x 24 nm, instance labels) 3826 # NOTE: The volumes are 256 px in plane, so the patches are resized to 512 x 512. 3827 if "mitoverse_haberl18" in EM_MITO_DATASETS: 3828 haberl18_root = os.path.join(input_path, "mitoverse", "data", "haberl18") 3829 for z in z_slices: 3830 haberl18_kwargs = { 3831 "raw_key": "img", "label_key": "mito", "patch_shape": (z, 256, 256), "ndim": 3, 3832 **{k: v for k, v in kwargs.items() if k not in ["raw_transform", "label_transform2", "sampler"]}, 3833 "raw_transform": _resize_raw_to_512, 3834 "label_transform2": partial( 3835 _resize_then_em_label_trafo, 3836 em_trafo_fn=mito_label_trafo(EM_MITO_MIN_SIZE_3D, sampling=(4.8, 1, 1)), 3837 ), 3838 "pre_label_transform": _connected_components_pre_label_trafo, 3839 "sampler": MinInstanceSampler( 3840 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 3841 ), 3842 } 3843 for volume, ds_list, n_samples in [("vol0", train_ds, EM_MITO_TRAIN_SAMPLES["mitoverse_haberl18"])]: 3844 haberl18_path = os.path.join(haberl18_root, f"{volume}.zarr") 3845 ds_list.append( 3846 UniDataWrapper( 3847 torch_em.default_segmentation_dataset( 3848 raw_paths=haberl18_path, label_paths=haberl18_path, n_samples=max(1, n_samples // n_z), 3849 **haberl18_kwargs, 3850 ), 3851 source_ndim=3, group_key=(3, z), 3852 ) 3853 ) 3854 3855 # 13. MitoVerse MICrONS phase 1 (3D mitochondria in ssTEM of the mouse visual cortex, 8 x 8 x 40 nm, proofread) 3856 # NOTE: The loss ignores the regions without image data. 3857 if "mitoverse_microns1" in EM_MITO_DATASETS: 3858 microns1_root = os.path.join(input_path, "mitoverse", "data", "turner22") 3859 raw_paths = [os.path.join(microns1_root, f"{volume}.zarr") for volume in MITOVERSE_MICRONS1_VOLUMES] 3860 label_paths = [ 3861 mitoverse_missing_data_label_path(input_path, "turner22", volume) for volume in MITOVERSE_MICRONS1_VOLUMES 3862 ] 3863 for z in z_slices: 3864 microns1_kwargs = { 3865 "raw_key": "img", "label_key": "labels", "patch_shape": (z, *patch_shape), "ndim": 3, 3866 **{ 3867 k: v for k, v in kwargs.items() 3868 if k not in ["raw_transform", "label_transform2", "sampler", "transform"] 3869 }, 3870 "label_transform2": mito_label_trafo( 3871 EM_MITO_MIN_SIZE_3D, sampling=(5, 1, 1), ignore_label=MITOVERSE_IGNORE_LABEL 3872 ), 3873 # Missing sections and tiles are also filled with the constant 128, which the raw == 0 test of the 3874 # derived labels misses; those regions become ignore here. The raw is normalized inside the transform. 3875 "raw_transform": _prepare_identity, 3876 "transform": partial( 3877 _ignore_missing_raw_trafo, ignore_label=MITOVERSE_IGNORE_LABEL, any_constant=True, 3878 transform=get_augmentations(ndim=3), 3879 ), 3880 "pre_label_transform": partial( 3881 _connected_components_pre_label_trafo, ignore_label=MITOVERSE_IGNORE_LABEL 3882 ), 3883 "sampler": MinInstanceSampler( 3884 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, 3885 exclude_ids=[0, MITOVERSE_IGNORE_LABEL], 3886 ), 3887 } 3888 train_only = [volume in MITOVERSE_MICRONS1_TRAIN_ONLY_VOLUMES for volume in MITOVERSE_MICRONS1_VOLUMES] 3889 train_rois = [np.s_[:, :, :] if only else MITOVERSE_MICRONS1_TRAIN_ROI for only in train_only] 3890 val_volumes = [i for i, only in enumerate(train_only) if not only] 3891 for paths, rois, ds_list, n_samples in [ 3892 ((raw_paths, label_paths), train_rois, train_ds, EM_MITO_TRAIN_SAMPLES["mitoverse_microns1"]), 3893 ( 3894 ([raw_paths[i] for i in val_volumes], [label_paths[i] for i in val_volumes]), 3895 [MITOVERSE_MICRONS1_VAL_ROI] * len(val_volumes), val_ds, 40, 3896 ), 3897 ]: 3898 ds_list.append( 3899 UniDataWrapper( 3900 torch_em.default_segmentation_dataset( 3901 raw_paths=paths[0], label_paths=paths[1], rois=rois, 3902 n_samples=max(1, n_samples // n_z), **microns1_kwargs, 3903 ), 3904 source_ndim=3, group_key=(3, z), 3905 ) 3906 ) 3907 3908 # 14. CellMap mitochondria (3D mitochondria in FIB-SEM crops of cells and tissues, 2-32 nm, manual labels) 3909 # NOTE: Each patch side group is one dataset; patches below 512 px are resized to 512 x 512. 3910 if "cellmap_mito" in EM_MITO_DATASETS: 3911 cellmap_groups = {split: cellmap_mito_split_crops(input_path, split) for split in ("train", "val")} 3912 for z in z_slices: 3913 for split, ds_list, n_samples in [ 3914 ("train", train_ds, EM_MITO_TRAIN_SAMPLES["cellmap_mito"]), ("val", val_ds, 40), 3915 ]: 3916 n_crops = sum(len(paths) for paths in cellmap_groups[split].values()) 3917 for side, paths in cellmap_groups[split].items(): 3918 resize = side < 512 3919 em_trafo_fn = mito_label_trafo( 3920 EM_MITO_MIN_SIZE_3D, sampling=(512 / side, 1, 1) if resize else None 3921 ) 3922 excluded = ["raw_transform", "label_transform2", "sampler"] 3923 cellmap_kwargs = { 3924 "raw_key": "raw", "label_key": "labels", "patch_shape": (z, side, side), "ndim": 3, 3925 **{k: v for k, v in kwargs.items() if k not in excluded}, 3926 "raw_transform": _resize_raw_to_512 if resize else kwargs["raw_transform"], 3927 "label_transform2": ( 3928 partial(_resize_then_em_label_trafo, em_trafo_fn=em_trafo_fn) if resize else em_trafo_fn 3929 ), 3930 "pre_label_transform": _connected_components_pre_label_trafo, 3931 "sampler": MinInstanceSampler( 3932 min_num_instances=1, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 3933 ), 3934 } 3935 ds_list.append( 3936 UniDataWrapper( 3937 torch_em.default_segmentation_dataset( 3938 raw_paths=paths, label_paths=paths, 3939 n_samples=max(1, round(n_samples * len(paths) / n_crops) // n_z), **cellmap_kwargs, 3940 ), 3941 source_ndim=3, group_key=(3, z), 3942 ) 3943 ) 3944 3945 # 15. Human organoids mitochondria (3D, FIB-SEM of patient-derived colorectal cancer organoids, manual labels) 3946 # NOTE: The labels are the precomputed neck watershed instances (HUMAN_ORGANOIDS_MITO_ROOT). 3947 if "human_organoids_mito" in EM_MITO_DATASETS: 3948 organoid_paths = [ 3949 os.path.join(input_path, "human_organoids", "11380", "data", name) for name in HUMAN_ORGANOIDS_VOLUMES 3950 ] 3951 mito_label_paths = [ 3952 os.path.join(input_path, HUMAN_ORGANOIDS_MITO_ROOT, name.replace("_bin2.h5", "_mito_labels.zarr")) 3953 for name in HUMAN_ORGANOIDS_VOLUMES 3954 ] 3955 organoid_rois = {"train": [], "val": []} 3956 for path in organoid_paths: 3957 with open_file(path, "r") as f: 3958 n_train = int(f["mitos"].shape[0] * (1 - HUMAN_ORGANOIDS_VAL_FRACTION)) 3959 organoid_rois["train"].append(np.s_[:n_train, :, :]) 3960 organoid_rois["val"].append(np.s_[n_train:, :, :]) 3961 for z in z_slices: 3962 organoid_kwargs = { 3963 "raw_key": "raw", "label_key": "labels", "patch_shape": (z, *patch_shape), "ndim": 3, 3964 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 3965 "label_transform2": mito_label_trafo(EM_MITO_MIN_SIZE_3D), 3966 "pre_label_transform": _connected_components_pre_label_trafo, 3967 "sampler": MinInstanceSampler( 3968 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 3969 ), 3970 } 3971 for split, ds_list, n_samples in [ 3972 ("train", train_ds, EM_MITO_TRAIN_SAMPLES["human_organoids_mito"]), ("val", val_ds, 40), 3973 ]: 3974 ds_list.append( 3975 UniDataWrapper( 3976 torch_em.default_segmentation_dataset( 3977 raw_paths=organoid_paths, label_paths=mito_label_paths, rois=organoid_rois[split], 3978 n_samples=max(1, n_samples // n_z), **organoid_kwargs, 3979 ), 3980 source_ndim=3, group_key=(3, z), 3981 ) 3982 ) 3983 3984 # 16. ASEM mitochondria (3D mitochondria in FIB-SEM of cultured cells, 4-5 nm isotropic, manual semantic labels) 3985 if "asem_mito" in EM_MITO_DATASETS: 3986 asem_paths, small_paths = [ 3987 datasets.asem.get_asem_paths( 3988 os.path.join(input_path, "asem"), list(volumes), organelles="mito", 3989 bounding_boxes={volume: ASEM_MITO_BOXES[volume] for volume in volumes}, 3990 ) 3991 for volumes in (ASEM_MITO_TRAIN_VOLUMES, ASEM_MITO_SMALL_VOLUMES) 3992 ] 3993 resize = 512 / ASEM_MITO_SMALL_SIDE 3994 excluded = ["raw_transform", "label_transform2", "sampler"] 3995 for z in z_slices: 3996 asem_kwargs = { 3997 "raw_key": "volumes/raw", "label_key": "volumes/labels/mito", "patch_shape": (z, *patch_shape), 3998 "ndim": 3, 3999 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 4000 "label_transform2": mito_label_trafo(EM_MITO_MIN_SIZE_3D), 4001 "pre_label_transform": _connected_components_pre_label_trafo, 4002 "sampler": MinInstanceSampler( 4003 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 4004 ), 4005 } 4006 for roi, ds_list, n_samples in [ 4007 (ASEM_MITO_TRAIN_ROI, train_ds, EM_MITO_TRAIN_SAMPLES["asem_mito"]), (ASEM_MITO_VAL_ROI, val_ds, 40), 4008 ]: 4009 ds_list.append( 4010 UniDataWrapper( 4011 torch_em.default_segmentation_dataset( 4012 raw_paths=asem_paths, label_paths=asem_paths, rois=[roi] * len(asem_paths), 4013 n_samples=max(1, n_samples // n_z), **asem_kwargs, 4014 ), 4015 source_ndim=3, group_key=(3, z), 4016 ) 4017 ) 4018 small_kwargs = { 4019 "raw_key": "volumes/raw", "label_key": "volumes/labels/mito", "ndim": 3, 4020 "patch_shape": (z, ASEM_MITO_SMALL_SIDE, ASEM_MITO_SMALL_SIDE), 4021 **{k: v for k, v in kwargs.items() if k not in excluded}, 4022 "raw_transform": _resize_raw_to_512, 4023 "label_transform2": partial( 4024 _resize_then_em_label_trafo, 4025 em_trafo_fn=mito_label_trafo(EM_MITO_MIN_SIZE_3D, sampling=(resize, 1, 1)), 4026 ), 4027 "pre_label_transform": _connected_components_pre_label_trafo, 4028 "sampler": MinInstanceSampler( 4029 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 4030 ), 4031 } 4032 train_ds.append( 4033 UniDataWrapper( 4034 torch_em.default_segmentation_dataset( 4035 raw_paths=small_paths, label_paths=small_paths, 4036 n_samples=max(1, EM_MITO_TRAIN_SAMPLES["asem_mito_small"] // n_z), **small_kwargs, 4037 ), 4038 source_ndim=3, group_key=(3, z), 4039 ) 4040 ) 4041 4042 # 17. Brain PFIB-SEM mitochondria (3D mitochondria in PFIB-SEM of the mouse brain, 5 nm isotropic, expert labels) 4043 # NOTE: Both stacks train with the same labels; only the reference stack validates. 4044 if "brain_pfibsem_mito" in EM_MITO_DATASETS: 4045 brain_path = os.path.join(input_path, BRAIN_PFIBSEM_PATH) 4046 for z in z_slices: 4047 for raw_key, roi, ds_list, n_samples in [ 4048 ("raw/reference", BRAIN_PFIBSEM_TRAIN_ROI, train_ds, EM_MITO_TRAIN_SAMPLES["brain_pfibsem_reference"]), 4049 ("raw/noisy", BRAIN_PFIBSEM_TRAIN_ROI, train_ds, EM_MITO_TRAIN_SAMPLES["brain_pfibsem_noisy"]), 4050 ("raw/reference", BRAIN_PFIBSEM_VAL_ROI, val_ds, 40), 4051 ]: 4052 brain_kwargs = { 4053 "raw_key": raw_key, "label_key": "labels/mitochondria", "patch_shape": (z, *patch_shape), 4054 "ndim": 3, **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 4055 "label_transform2": mito_label_trafo(EM_MITO_MIN_SIZE_3D), 4056 "pre_label_transform": _connected_components_pre_label_trafo, 4057 "sampler": MinInstanceSampler( 4058 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 4059 ), 4060 } 4061 ds_list.append( 4062 UniDataWrapper( 4063 torch_em.default_segmentation_dataset( 4064 raw_paths=brain_path, label_paths=brain_path, rois=roi, 4065 n_samples=max(1, n_samples // n_z), **brain_kwargs, 4066 ), 4067 source_ndim=3, group_key=(3, z), 4068 ) 4069 ) 4070 4071 # 18. SNEMI Mito (3D mitochondria in ssSEM of the mouse neocortex, SNEMI3D, 6 x 6 x 30 nm, manual binary masks) 4072 if "snemi_mito" in EM_MITO_DATASETS: 4073 snemi_path = datasets.snemi_mito.get_snemi_mito_data(os.path.join(input_path, "snemi_mito"), as_volume=True) 4074 for z in z_slices: 4075 snemi_kwargs = { 4076 "raw_key": "raw", "label_key": "labels", "patch_shape": (z, *patch_shape), "ndim": 3, 4077 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 4078 "label_transform2": mito_label_trafo(EM_MITO_MIN_SIZE_3D, sampling=(30 / 6, 1, 1)), 4079 "pre_label_transform": _connected_components_pre_label_trafo, 4080 "sampler": MinInstanceSampler( 4081 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 4082 ), 4083 } 4084 for roi, ds_list, n_samples in [ 4085 (datasets.snemi_mito.VOLUME_ROIS["train"], train_ds, EM_MITO_TRAIN_SAMPLES["snemi_mito"]), 4086 (datasets.snemi_mito.VOLUME_ROIS["val"], val_ds, 40), 4087 ]: 4088 ds_list.append( 4089 UniDataWrapper( 4090 torch_em.default_segmentation_dataset( 4091 raw_paths=snemi_path, label_paths=snemi_path, rois=roi, 4092 n_samples=max(1, n_samples // n_z), **snemi_kwargs, 4093 ), 4094 source_ndim=3, group_key=(3, z), 4095 ) 4096 ) 4097 4098 # 19. U2OS FIB-SEM mitochondria (2D mitochondria in single FIB-SEM slices of a U2-OS cell, manual binary masks) 4099 if "u2os_fibsem_mito" in EM_MITO_DATASETS: 4100 u2os_images = sorted(glob(os.path.join(input_path, U2OS_FIBSEM_MITO_ROOT, "images_tif", "*.tif"))) 4101 u2os_labels = sorted(glob(os.path.join(input_path, U2OS_FIBSEM_MITO_ROOT, "labels_tif", "*.tif"))) 4102 u2os_kwargs = { 4103 "raw_key": None, "label_key": None, "patch_shape": patch_shape, "ndim": 2, "is_seg_dataset": False, 4104 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 4105 "label_transform2": mito_label_trafo(), 4106 "pre_label_transform": _connected_components_pre_label_trafo, 4107 "sampler": MinInstanceSampler( 4108 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE, exclude_ids=[0] 4109 ), 4110 } 4111 for split, ds_list, n_samples in [ 4112 ("train", train_ds, EM_MITO_TRAIN_SAMPLES["u2os_fibsem_mito"]), ("val", val_ds, 40), 4113 ]: 4114 keep = [ 4115 (i % U2OS_FIBSEM_MITO_VAL_STEP == U2OS_FIBSEM_MITO_VAL_STEP // 2) == (split == "val") 4116 for i in range(len(u2os_images)) 4117 ] 4118 ds_list.append( 4119 UniDataWrapper( 4120 torch_em.default_segmentation_dataset( 4121 raw_paths=[p for p, k in zip(u2os_images, keep) if k], 4122 label_paths=[p for p, k in zip(u2os_labels, keep) if k], n_samples=n_samples, **u2os_kwargs, 4123 ), source_ndim=2, 4124 ) 4125 ) 4126 4127 # 20. HeLa STARD3 mitochondria (3D mitochondria in FIB-SEM of HeLa cells, 5-8 nm, manual binary masks in the ROI) 4128 if "hela_stard3_mito" in EM_MITO_DATASETS: 4129 hela_paths = [os.path.join(input_path, "hela_stard3", f"{volume}.h5") for volume in HELA_STARD3_VOLUMES] 4130 train_rois = [ 4131 np.s_[:HELA_STARD3_VAL_START, :, :] if volume == HELA_STARD3_VAL_VOLUME else np.s_[:, :, :] 4132 for volume in HELA_STARD3_VOLUMES 4133 ] 4134 val_path = hela_paths[HELA_STARD3_VOLUMES.index(HELA_STARD3_VAL_VOLUME)] 4135 for z in z_slices: 4136 hela_kwargs = { 4137 "raw_key": "raw", "label_key": "labels/mitochondria", "patch_shape": (z, *patch_shape), "ndim": 3, 4138 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 4139 "label_transform2": mito_label_trafo(EM_MITO_MIN_SIZE_3D), 4140 "pre_label_transform": _connected_components_pre_label_trafo, 4141 "sampler": MinInstanceSampler( 4142 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 4143 ), 4144 } 4145 for paths, rois, ds_list, n_samples in [ 4146 (hela_paths, train_rois, train_ds, EM_MITO_TRAIN_SAMPLES["hela_stard3_mito"]), 4147 ([val_path], [np.s_[HELA_STARD3_VAL_START:, :, :]], val_ds, 40), 4148 ]: 4149 ds_list.append( 4150 UniDataWrapper( 4151 torch_em.default_segmentation_dataset( 4152 raw_paths=paths, label_paths=paths, rois=rois, n_samples=max(1, n_samples // n_z), 4153 **hela_kwargs, 4154 ), 4155 source_ndim=3, group_key=(3, z), 4156 ) 4157 ) 4158 4159 # 21. Parlakgul fasting liver mitochondria (3D mitochondria in FIB-SEM of the mouse liver, 8 nm, instance labels) 4160 if "parlakgul_fasting_liver_mito" in EM_MITO_DATASETS: 4161 fasting_paths = sorted(glob(os.path.join(input_path, PARLAKGUL_FASTING_ROOT, "*_mito_*.zarr"))) 4162 for z in z_slices: 4163 fasting_kwargs = { 4164 "raw_key": "raw", "label_key": "labels", "patch_shape": (z, *patch_shape), "ndim": 3, 4165 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 4166 "label_transform2": mito_label_trafo(EM_MITO_MIN_SIZE_3D), 4167 "pre_label_transform": _connected_components_pre_label_trafo, 4168 "sampler": MinInstanceSampler( 4169 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 4170 ), 4171 } 4172 for roi, ds_list, n_samples in [ 4173 (PARLAKGUL_FASTING_TRAIN_ROI, train_ds, EM_MITO_TRAIN_SAMPLES["parlakgul_fasting_liver_mito"]), 4174 (PARLAKGUL_FASTING_VAL_ROI, val_ds, 40), 4175 ]: 4176 ds_list.append( 4177 UniDataWrapper( 4178 torch_em.default_segmentation_dataset( 4179 raw_paths=fasting_paths, label_paths=fasting_paths, rois=[roi] * len(fasting_paths), 4180 n_samples=max(1, n_samples // n_z), **fasting_kwargs, 4181 ), 4182 source_ndim=3, group_key=(3, z), 4183 ) 4184 ) 4185 4186 # 22. AIVE mitochondria (3D mitochondria in FIB-SEM of cells and muscle tissue, 6.5 x 6.5 x 10 nm, semantic labels) 4187 # NOTE: The mitochondria class is taken before the connected components. 4188 if "aive_mito" in EM_MITO_DATASETS: 4189 aive_paths = [os.path.join(input_path, "aive", name) for name in AIVE_MITO_VAL_STARTS] 4190 for z in z_slices: 4191 aive_kwargs = { 4192 "raw_key": "raw", "label_key": "labels", "patch_shape": (z, *patch_shape), "ndim": 3, 4193 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler", "pre_label_transform"]}, 4194 "pre_label_transform": partial( 4195 _connected_components_pre_label_trafo, foreground_class=AIVE_MITO_CLASS 4196 ), 4197 "label_transform2": mito_label_trafo(EM_MITO_MIN_SIZE_3D, sampling=(10 / 6.5, 1, 1)), 4198 "sampler": MinInstanceSampler( 4199 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 4200 ), 4201 } 4202 for rois, ds_list, n_samples in [ 4203 ( 4204 [np.s_[:start, :, :] for start in AIVE_MITO_VAL_STARTS.values()], train_ds, 4205 EM_MITO_TRAIN_SAMPLES["aive_mito"], 4206 ), 4207 ([np.s_[start:, :, :] for start in AIVE_MITO_VAL_STARTS.values()], val_ds, 40), 4208 ]: 4209 ds_list.append( 4210 UniDataWrapper( 4211 torch_em.default_segmentation_dataset( 4212 raw_paths=aive_paths, label_paths=aive_paths, rois=rois, 4213 n_samples=max(1, n_samples // n_z), **aive_kwargs, 4214 ), 4215 source_ndim=3, group_key=(3, z), 4216 ) 4217 ) 4218 4219 # 23. MitoSegEM (3D mitochondria in SBF-SEM of the mouse testis and brainstem, 15 x 15 x 50 nm, instance labels) 4220 if "mito_segem" in EM_MITO_DATASETS: 4221 from torch_em.data.datasets.electron_microscopy.mito_segem import get_mito_segem_paths 4222 segem_paths = [ 4223 path for tissue, box in MITO_SEGEM_TRAIN_BOXES.items() 4224 for path in get_mito_segem_paths(os.path.join(input_path, "mito_segem"), [box], tissue, download=True) 4225 ] 4226 for z in z_slices: 4227 segem_kwargs = { 4228 "raw_key": "raw", "label_key": "labels", "patch_shape": (z, *patch_shape), "ndim": 3, 4229 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 4230 "label_transform2": mito_label_trafo(EM_MITO_MIN_SIZE_3D, sampling=(50 / 15, 1, 1)), 4231 "pre_label_transform": _connected_components_pre_label_trafo, 4232 "sampler": MinInstanceSampler( 4233 min_num_instances=EM_MITO_MIN_INSTANCES, min_size=EM_MITO_MIN_SIZE_3D, exclude_ids=[0] 4234 ), 4235 } 4236 for roi, ds_list, n_samples in [ 4237 (MITO_SEGEM_TRAIN_ROI, train_ds, EM_MITO_TRAIN_SAMPLES["mito_segem"]), (MITO_SEGEM_VAL_ROI, val_ds, 40), 4238 ]: 4239 ds_list.append( 4240 UniDataWrapper( 4241 torch_em.default_segmentation_dataset( 4242 raw_paths=segem_paths, label_paths=segem_paths, rois=[roi] * len(segem_paths), 4243 n_samples=max(1, n_samples // n_z), **segem_kwargs, 4244 ), 4245 source_ndim=3, group_key=(3, z), 4246 ) 4247 ) 4248 4249 _set_volume_min_instances([train_ds, val_ds], EM_MITO_SPARSE_VOLUMES) 4250 return train_ds, val_ds 4251 4252 4253def _get_em_nucleus_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo): 4254 """Get the nucleus EM datasets for the nucleus generalist. 4255 4256 The targets come from the plain label transform, as for the mitochondria generalist, and the distance transform 4257 relabels every extracted patch with connected components (``apply_label=True``). Each patch side group of a dataset 4258 (see EM_NUCLEUS_PATCH_SIDES) is one dataset, and patches below 512 px are resized to 512 x 512, which gives the 4259 isotropic volumes a z / xy anisotropy of 512 / side. 4260 4261 Returns: 4262 Tuple of (train_ds, val_ds) lists of UniDataWrapper instances. 4263 """ 4264 train_ds, val_ds = [], [] 4265 n_z = len(z_slices) 4266 4267 def nucleus_label_trafo(side, ignore_label=None, z_scale=1): 4268 resize = side < 512 4269 z_factor = z_scale * 512 / side 4270 sampling = None if z_factor == 1 else (z_factor, 1, 1) 4271 trafo = kwargs.get("label_transform2") if label_trafo is None else label_trafo( 4272 min_size=EM_NUCLEUS_MIN_SIZE_3D, sampling=sampling 4273 ) 4274 if ignore_label is not None: 4275 trafo = partial(_ignore_label_trafo, ignore_label=ignore_label, label_trafo=trafo) 4276 return partial(_resize_then_em_label_trafo, em_trafo_fn=trafo) if resize else trafo 4277 4278 def connected_components(ignore_label=None): 4279 if ignore_label is None: 4280 return _connected_components_pre_label_trafo 4281 return partial(_connected_components_pre_label_trafo, ignore_label=ignore_label) 4282 4283 def nucleus_sampler(ignore_label=None, min_num_instances=1): 4284 exclude_ids = [0] if ignore_label is None else [0, ignore_label] 4285 return MinInstanceSampler( 4286 min_num_instances=min_num_instances, min_size=EM_NUCLEUS_MIN_SIZE_3D, exclude_ids=exclude_ids 4287 ) 4288 4289 def add_grouped_datasets( 4290 groups, label_key, train_samples, ignore_label=None, pre_label_transform=None, weights=None, 4291 min_num_instances=1, 4292 ): 4293 # The samples are divided across the side groups by the weights of their volumes ({path: weight}). 4294 excluded = ["raw_transform", "label_transform2", "sampler", "pre_label_transform"] 4295 if pre_label_transform is None: 4296 pre_label_transform = connected_components(ignore_label) 4297 for z in z_slices: 4298 for split, ds_list, n_samples in [("train", train_ds, train_samples), ("val", val_ds, 40)]: 4299 group_weights = { 4300 side: sum(1 if weights is None else weights[path] for path in paths) 4301 for side, paths in groups[split].items() 4302 } 4303 total_weight = sum(group_weights.values()) 4304 for side, paths in groups[split].items(): 4305 nucleus_kwargs = { 4306 "raw_key": "raw", "label_key": label_key, "patch_shape": (z, side, side), "ndim": 3, 4307 **{k: v for k, v in kwargs.items() if k not in excluded}, 4308 "raw_transform": _resize_raw_to_512 if side < 512 else kwargs["raw_transform"], 4309 "label_transform2": nucleus_label_trafo(side, ignore_label), 4310 "pre_label_transform": pre_label_transform, 4311 "sampler": nucleus_sampler(ignore_label, min_num_instances), 4312 } 4313 ds_list.append( 4314 UniDataWrapper( 4315 torch_em.default_segmentation_dataset( 4316 raw_paths=paths, label_paths=paths, 4317 n_samples=max(len(paths), round(n_samples * group_weights[side] / total_weight) // n_z), 4318 **nucleus_kwargs, 4319 ), 4320 source_ndim=3, group_key=(3, z), 4321 ) 4322 ) 4323 4324 def add_volume_datasets(volumes, train_samples, ignore_label=None, min_num_instances=1): 4325 # *volumes* are (split, path, raw_key, label_key, roi, z_scale) tuples. 4326 excluded = ["raw_transform", "label_transform2", "sampler", "pre_label_transform"] 4327 groups = {} 4328 for split, path, raw_key, label_key, roi, z_scale in volumes: 4329 with open_file(path, "r") as f: 4330 shape = f[label_key].shape 4331 in_plane = [len(range(*sl.indices(n))) for sl, n in zip(roi[1:], shape[1:])] 4332 key = (split, em_nucleus_patch_side(in_plane), raw_key, label_key, z_scale) 4333 groups.setdefault(key, []).append((path, roi)) 4334 for z in z_slices: 4335 for split, ds_list, n_samples in [("train", train_ds, train_samples), ("val", val_ds, 40)]: 4336 n_volumes = sum(len(entries) for key, entries in groups.items() if key[0] == split) 4337 for (group_split, side, raw_key, label_key, z_scale), entries in groups.items(): 4338 if group_split != split: 4339 continue 4340 volume_kwargs = { 4341 "raw_key": raw_key, "label_key": label_key, "patch_shape": (z, side, side), "ndim": 3, 4342 **{k: v for k, v in kwargs.items() if k not in excluded}, 4343 "raw_transform": _resize_raw_to_512 if side < 512 else kwargs["raw_transform"], 4344 "label_transform2": nucleus_label_trafo(side, ignore_label, z_scale=z_scale), 4345 "pre_label_transform": connected_components(ignore_label), 4346 "sampler": nucleus_sampler(ignore_label, min_num_instances), 4347 } 4348 ds_list.append( 4349 UniDataWrapper( 4350 torch_em.default_segmentation_dataset( 4351 raw_paths=[path for path, _ in entries], label_paths=[path for path, _ in entries], 4352 rois=[roi for _, roi in entries], 4353 n_samples=max(len(entries), round(n_samples * len(entries) / n_volumes) // n_z), 4354 **volume_kwargs, 4355 ), 4356 source_ndim=3, group_key=(3, z), 4357 ) 4358 ) 4359 4360 def add_image_datasets(train_paths, val_paths, train_samples, ignore_label=None, min_num_instances=1): 4361 # 2D images (h5 files with 'raw' and 'labels') of at least 512 px, drawn as 512 x 512 patches. 4362 image_kwargs = { 4363 "raw_key": "raw", "label_key": "labels", "patch_shape": patch_shape, "ndim": 2, 4364 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 4365 "label_transform2": nucleus_label_trafo(512, ignore_label=ignore_label), 4366 "pre_label_transform": connected_components(ignore_label), 4367 "sampler": nucleus_sampler(ignore_label, min_num_instances), 4368 } 4369 for paths, ds_list, n_samples in [(train_paths, train_ds, train_samples), (val_paths, val_ds, 40)]: 4370 if not paths: 4371 continue 4372 ds_list.append( 4373 UniDataWrapper( 4374 torch_em.default_segmentation_dataset( 4375 raw_paths=paths, label_paths=paths, n_samples=n_samples, **image_kwargs 4376 ), 4377 source_ndim=2, 4378 ) 4379 ) 4380 4381 # 1. BetaSeg nuclei (3D nucleus of one target cell per volume in FIB-SEM of mouse beta cells, 4 nm, manual labels) 4382 # NOTE: The loss ignores the voxels outside the target cell and on blank raw (BETASEG_NUCLEUS_IGNORE_LABEL). 4383 if "betaseg_nucleus" in EM_NUCLEUS_DATASETS: 4384 betaseg_groups = {split: betaseg_nucleus_split_boxes(input_path, split) for split in ("train", "val")} 4385 add_grouped_datasets( 4386 betaseg_groups, "labels/nucleus", EM_NUCLEUS_TRAIN_SAMPLES["betaseg_nucleus"], 4387 ignore_label=BETASEG_NUCLEUS_IGNORE_LABEL, 4388 ) 4389 4390 # 2. CellMap nuclei (3D nuclei in FIB-SEM crops of mouse liver, kidney and heart and zebrafish heart, 32-64 nm, 4391 # manual instance labels) 4392 if "cellmap_nucleus" in EM_NUCLEUS_DATASETS: 4393 cellmap_groups = {split: cellmap_nucleus_split_crops(input_path, split) for split in ("train", "val")} 4394 add_grouped_datasets( 4395 cellmap_groups, "labels", EM_NUCLEUS_TRAIN_SAMPLES["cellmap_nucleus"], 4396 min_num_instances=EM_NUCLEUS_MIN_INSTANCES["cellmap_nucleus"], 4397 ) 4398 4399 # 3. Human organoids nuclei (3D nuclei in FIB-SEM of a spheroid and colorectal cancer organoids, manual labels) 4400 # NOTE: The loss ignores label fragments and the entotic cell. 4401 if "human_organoids_nucleus" in EM_NUCLEUS_DATASETS: 4402 names = [name.replace("_bin2.h5", "") for name in HUMAN_ORGANOIDS_VOLUMES] 4403 raw_paths = [os.path.join(input_path, "human_organoids", "11380", "data", f"{name}_bin2.h5") for name in names] 4404 label_paths = [ 4405 os.path.join(input_path, "human_organoids_nucleus", f"{name}_nucleus_labels.zarr") for name in names 4406 ] 4407 organoid_rois = {"train": [], "val": []} 4408 for path in raw_paths: 4409 with open_file(path, "r") as f: 4410 n_train = int(f["nuclei"].shape[0] * (1 - HUMAN_ORGANOIDS_VAL_FRACTION)) 4411 organoid_rois["train"].append(np.s_[:n_train, :, :]) 4412 organoid_rois["val"].append(np.s_[n_train:, :, :]) 4413 for z in z_slices: 4414 organoid_kwargs = { 4415 "raw_key": "raw", "label_key": "labels", "patch_shape": (z, *patch_shape), "ndim": 3, 4416 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 4417 "label_transform2": nucleus_label_trafo(512, ignore_label=HUMAN_ORGANOIDS_NUCLEUS_IGNORE_LABEL), 4418 "pre_label_transform": connected_components(HUMAN_ORGANOIDS_NUCLEUS_IGNORE_LABEL), 4419 "sampler": nucleus_sampler( 4420 HUMAN_ORGANOIDS_NUCLEUS_IGNORE_LABEL, EM_NUCLEUS_MIN_INSTANCES["human_organoids_nucleus"] 4421 ), 4422 } 4423 for split, ds_list, n_samples in [ 4424 ("train", train_ds, EM_NUCLEUS_TRAIN_SAMPLES["human_organoids_nucleus"]), ("val", val_ds, 40), 4425 ]: 4426 ds_list.append( 4427 UniDataWrapper( 4428 torch_em.default_segmentation_dataset( 4429 raw_paths=raw_paths, label_paths=label_paths, rois=organoid_rois[split], 4430 n_samples=max(1, n_samples // n_z), **organoid_kwargs, 4431 ), 4432 source_ndim=3, group_key=(3, z), 4433 ) 4434 ) 4435 4436 # 4. SXT INS-1E nuclei (3D nucleus of one cell per soft X-ray tomogram, 36.8-45.5 nm, semi-automatic labels) 4437 # NOTE: The pre_label_transform maps the classes to the nucleus before the connected components. 4438 if "sxt_nucleus" in EM_NUCLEUS_DATASETS: 4439 sxt_groups = {split: sxt_nucleus_split_paths(input_path, split) for split in ("train", "val")} 4440 add_grouped_datasets( 4441 sxt_groups, "labels", EM_NUCLEUS_TRAIN_SAMPLES["sxt_nucleus"], ignore_label=SXT_NUCLEUS_IGNORE_LABEL, 4442 pre_label_transform=sxt_nucleus_instances, 4443 ) 4444 4445 # 5. FAFB nuclei (3D nuclei in ssTEM of the adult fly brain, 32 x 32 x 40 nm, automatic FlyWire segmentation) 4446 if "fafb_nuclei" in EM_NUCLEUS_DATASETS: 4447 for z in z_slices: 4448 fafb_kwargs = { 4449 "raw_key": "raw", "label_key": "labels/nuclei", "patch_shape": (z, *patch_shape), "ndim": 3, 4450 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 4451 "label_transform2": nucleus_label_trafo(512, z_scale=FAFB_NUCLEI_Z_SCALE), 4452 "pre_label_transform": connected_components(), 4453 "sampler": nucleus_sampler(min_num_instances=EM_NUCLEUS_MIN_INSTANCES["fafb_nuclei"]), 4454 } 4455 for split, ds_list, n_samples in [ 4456 ("train", train_ds, EM_NUCLEUS_TRAIN_SAMPLES["fafb_nuclei"]), ("val", val_ds, 40), 4457 ]: 4458 paths = sorted(glob(os.path.join(input_path, "fafb_nuclei", split, "*.h5"))) 4459 ds_list.append( 4460 UniDataWrapper( 4461 torch_em.default_segmentation_dataset( 4462 raw_paths=paths, label_paths=paths, n_samples=max(1, n_samples // n_z), **fafb_kwargs, 4463 ), 4464 source_ndim=3, group_key=(3, z), 4465 ) 4466 ) 4467 4468 # 6. Janelia nuclei (3D nuclei in FIB-SEM of 15 OpenOrganelle volumes of mouse and fly tissues, 32-128 nm, 4469 # Cellpose pseudo-labels and 3 manual volumes) 4470 if "janelia_nucleus" in EM_NUCLEUS_DATASETS: 4471 janelia_groups, janelia_voxels = {}, {} 4472 for split in ("train", "val"): 4473 janelia_groups[split], split_voxels = janelia_nucleus_split_paths(input_path, split) 4474 janelia_voxels.update(split_voxels) 4475 add_grouped_datasets( 4476 janelia_groups, "labels", EM_NUCLEUS_TRAIN_SAMPLES["janelia_nucleus"], weights=janelia_voxels, 4477 min_num_instances=EM_NUCLEUS_MIN_INSTANCES["janelia_nucleus"], 4478 ) 4479 4480 # 7. MICrONS nuclei (3D nuclei in ssTEM of the mouse visual cortex, 64 x 64 x 40 nm, automatic minnie65 labels) 4481 if "microns_nuclei" in EM_NUCLEUS_DATASETS: 4482 for z in z_slices: 4483 microns_kwargs = { 4484 "raw_key": "raw", "label_key": "labels/nuclei", "patch_shape": (z, *patch_shape), "ndim": 3, 4485 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 4486 "label_transform2": nucleus_label_trafo(512, z_scale=MICRONS_NUCLEI_Z_SCALE), 4487 "pre_label_transform": connected_components(), 4488 "sampler": nucleus_sampler(min_num_instances=EM_NUCLEUS_MIN_INSTANCES["microns_nuclei"]), 4489 } 4490 for split, ds_list, n_samples in [ 4491 ("train", train_ds, EM_NUCLEUS_TRAIN_SAMPLES["microns_nuclei"]), ("val", val_ds, 40), 4492 ]: 4493 paths = sorted(glob(os.path.join(input_path, "microns_nuclei", split, "*.h5"))) 4494 ds_list.append( 4495 UniDataWrapper( 4496 torch_em.default_segmentation_dataset( 4497 raw_paths=paths, label_paths=paths, n_samples=max(1, n_samples // n_z), **microns_kwargs, 4498 ), 4499 source_ndim=3, group_key=(3, z), 4500 ) 4501 ) 4502 4503 waenet_root = os.path.join(input_path, "waenet_nucleus") 4504 4505 # 8. WAE-Net dataset 1 nuclei (3D nuclei in FIB-SEM of pancreatic carcinoid cells, manual labels) 4506 if "waenet_fibsem_nucleus" in EM_NUCLEUS_DATASETS: 4507 waenet_path = os.path.join(waenet_root, "dataset_1.h5") 4508 with open_file(waenet_path, "r") as f: 4509 n_train = int(f["raw"].shape[0] * (1 - WAENET_VAL_FRACTION)) 4510 waenet_rois = {"train": np.s_[:n_train, :, :], "val": np.s_[n_train:, :, :]} 4511 for z in z_slices: 4512 waenet_kwargs = { 4513 "raw_key": "raw", "label_key": "labels", "patch_shape": (z, *patch_shape), "ndim": 3, 4514 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 4515 "label_transform2": nucleus_label_trafo(512), 4516 "pre_label_transform": connected_components(), 4517 "sampler": nucleus_sampler(), 4518 } 4519 for split, ds_list, n_samples in [ 4520 ("train", train_ds, EM_NUCLEUS_TRAIN_SAMPLES["waenet_fibsem_nucleus"]), ("val", val_ds, 40), 4521 ]: 4522 ds_list.append( 4523 UniDataWrapper( 4524 torch_em.default_segmentation_dataset( 4525 raw_paths=waenet_path, label_paths=waenet_path, rois=waenet_rois[split], 4526 n_samples=max(1, n_samples // n_z), **waenet_kwargs, 4527 ), 4528 source_ndim=3, group_key=(3, z), 4529 ) 4530 ) 4531 4532 # 9. WAE-Net dataset 3 nuclei (2D, serial ssTEM sections of one cell) and 4533 # 10. WAE-Net datasets 4-7 nuclei (2D, TEM images of lymphocytes and B cells; only the central cell is labeled) 4534 for name, prefix in [("waenet_sstem_nucleus", "dataset_3"), ("waenet_tem_nucleus", "tem")]: 4535 if name not in EM_NUCLEUS_DATASETS: 4536 continue 4537 waenet_kwargs = { 4538 "raw_key": "raw", "label_key": "labels", "patch_shape": (1, *patch_shape), 4539 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 4540 "label_transform2": nucleus_label_trafo(512, ignore_label=WAENET_NUCLEUS_IGNORE_LABEL), 4541 "pre_label_transform": connected_components(WAENET_NUCLEUS_IGNORE_LABEL), 4542 "sampler": nucleus_sampler(WAENET_NUCLEUS_IGNORE_LABEL), 4543 } 4544 for split, ds_list, n_samples in [("train", train_ds, EM_NUCLEUS_TRAIN_SAMPLES[name]), ("val", val_ds, 40)]: 4545 waenet_path = os.path.join(waenet_root, f"{prefix}_{split}.h5") 4546 ds_list.append( 4547 UniDataWrapper( 4548 torch_em.default_segmentation_dataset( 4549 raw_paths=waenet_path, label_paths=waenet_path, n_samples=n_samples, **waenet_kwargs 4550 ), 4551 source_ndim=2, 4552 ) 4553 ) 4554 4555 # 11. Platynereis nuclei (3D nuclei in SBEM of a Platynereis larva, about 80 x 80 x 100 nm, manual instance labels) 4556 # NOTE: Only the valid ROI of each volume trains, which removes the halo of unlabeled voxels. 4557 if "platynereis_nuclei" in EM_NUCLEUS_DATASETS: 4558 platy_groups = {split: platynereis_nuclei_split_rois(input_path, split) for split in ("train", "val")} 4559 excluded = ["raw_transform", "label_transform2", "sampler"] 4560 for z in z_slices: 4561 for split, ds_list, n_samples in [ 4562 ("train", train_ds, EM_NUCLEUS_TRAIN_SAMPLES["platynereis_nuclei"]), ("val", val_ds, 40), 4563 ]: 4564 n_volumes = sum(len(paths) for paths, _ in platy_groups[split].values()) 4565 for side, (paths, rois) in platy_groups[split].items(): 4566 platy_kwargs = { 4567 "raw_key": "volumes/raw", "label_key": "volumes/labels/nucleus_instance_labels", 4568 "patch_shape": (z, side, side), "ndim": 3, 4569 **{k: v for k, v in kwargs.items() if k not in excluded}, 4570 "raw_transform": _resize_raw_to_512 if side < 512 else kwargs["raw_transform"], 4571 "label_transform2": nucleus_label_trafo(side, z_scale=PLATYNEREIS_NUCLEI_Z_SCALE), 4572 "pre_label_transform": connected_components(), 4573 "sampler": nucleus_sampler(min_num_instances=EM_NUCLEUS_MIN_INSTANCES["platynereis_nuclei"]), 4574 } 4575 ds_list.append( 4576 UniDataWrapper( 4577 torch_em.default_segmentation_dataset( 4578 raw_paths=paths, label_paths=paths, rois=rois, 4579 n_samples=max(len(paths), round(n_samples * len(paths) / n_volumes) // n_z), 4580 **platy_kwargs, 4581 ), 4582 source_ndim=3, group_key=(3, z), 4583 ) 4584 ) 4585 4586 # 12. Tumor spheroid nuclei (2D nuclei in single SBF-SEM slices of a tumor spheroid, 50 nm, manual instance labels) 4587 # NOTE: The loss ignores the annotated cells without a nucleus label (TUMOR_SPHEROID_NUCLEI_IGNORE_LABEL). 4588 if "tumor_spheroid_nuclei" in EM_NUCLEUS_DATASETS: 4589 spheroid_paths = sorted(glob(os.path.join(input_path, "tumor_spheroid_nucleus", "*.h5"))) 4590 spheroid_kwargs = { 4591 "raw_key": "raw", "label_key": "labels", "patch_shape": patch_shape, "ndim": 2, 4592 **{k: v for k, v in kwargs.items() if k not in ["label_transform2", "sampler"]}, 4593 "label_transform2": nucleus_label_trafo(512, ignore_label=TUMOR_SPHEROID_NUCLEI_IGNORE_LABEL), 4594 "pre_label_transform": connected_components(TUMOR_SPHEROID_NUCLEI_IGNORE_LABEL), 4595 "sampler": nucleus_sampler( 4596 TUMOR_SPHEROID_NUCLEI_IGNORE_LABEL, EM_NUCLEUS_MIN_INSTANCES["tumor_spheroid_nuclei"] 4597 ), 4598 } 4599 for split, ds_list, n_samples in [ 4600 ("train", train_ds, EM_NUCLEUS_TRAIN_SAMPLES["tumor_spheroid_nuclei"]), ("val", val_ds, 40), 4601 ]: 4602 paths = [ 4603 path for path in spheroid_paths 4604 if (os.path.basename(path) in TUMOR_SPHEROID_NUCLEI_VAL_SLICES) == (split == "val") 4605 ] 4606 ds_list.append( 4607 UniDataWrapper( 4608 torch_em.default_segmentation_dataset( 4609 raw_paths=paths, label_paths=paths, n_samples=n_samples, **spheroid_kwargs 4610 ), 4611 source_ndim=2, 4612 ) 4613 ) 4614 4615 # 13. OpenOrganelle nuclei (3D nuclei in FIB-SEM of 17 OpenOrganelle tissue and single-cell volumes, 32-128 nm, 4616 # automatic labels) 4617 if "openorganelle_nucleus" in EM_NUCLEUS_DATASETS: 4618 openorganelle_groups, openorganelle_voxels = {}, {} 4619 for split in ("train", "val"): 4620 openorganelle_groups[split], split_voxels = openorganelle_nucleus_split_paths(input_path, split) 4621 openorganelle_voxels.update(split_voxels) 4622 add_grouped_datasets( 4623 openorganelle_groups, "labels", EM_NUCLEUS_TRAIN_SAMPLES["openorganelle_nucleus"], 4624 weights=openorganelle_voxels, min_num_instances=EM_NUCLEUS_MIN_INSTANCES["openorganelle_nucleus"], 4625 ) 4626 4627 full = np.s_[:, :, :] 4628 4629 # 14. Cardiomyocyte TEM nuclei (2D nucleus in TEM micrographs of isolated cardiomyocytes, manual masks, downscaled) 4630 if "cardiomyocyte_tem_nucleus" in EM_NUCLEUS_DATASETS: 4631 cardio_paths = sorted(glob(os.path.join(input_path, CARDIOMYOCYTE_NUCLEUS_ROOT, "*.h5"))) 4632 cardio_train, cardio_val = train_test_split( 4633 cardio_paths, test_size=CARDIOMYOCYTE_NUCLEUS_N_VAL, random_state=42 4634 ) 4635 add_image_datasets( 4636 sorted(cardio_train), sorted(cardio_val), EM_NUCLEUS_TRAIN_SAMPLES["cardiomyocyte_tem_nucleus"] 4637 ) 4638 4639 # 15. microSAM EM nuclei (3D nuclei in the 32 x 512 x 512 train crop of the microSAM user study, manual labels) 4640 # NOTE: The whole crop trains (no validation leaf), and the user-study 'annotation' crop is not used. 4641 if "microsam_em_nuclei" in EM_NUCLEUS_DATASETS: 4642 microsam_path = os.path.join(input_path, MICROSAM_EM_NUCLEI_PATH) 4643 add_volume_datasets( 4644 [("train", microsam_path, "raw", "labels/nuclei", full, 1)], EM_NUCLEUS_TRAIN_SAMPLES["microsam_em_nuclei"], 4645 min_num_instances=EM_NUCLEUS_MIN_INSTANCES["microsam_em_nuclei"], 4646 ) 4647 4648 # 16. Perez nuclei (2D nuclei in SBF-SEM tiles of the mouse suprachiasmatic nucleus, manual masks) 4649 if "perez_nucleus" in EM_NUCLEUS_DATASETS: 4650 add_image_datasets( 4651 sorted(glob(os.path.join(input_path, PEREZ_NUCLEUS_ROOT, "train", "*.h5"))), 4652 sorted(glob(os.path.join(input_path, PEREZ_NUCLEUS_ROOT, "test", "*.h5"))), 4653 EM_NUCLEUS_TRAIN_SAMPLES["perez_nucleus"], 4654 ) 4655 4656 # 17. vEM nuclei (2D array tomography SEM and 3D FIB-SEM of cancer cells, proofread NucleoNet predictions) 4657 # NOTE: The loss ignores the unlabeled border band of the 2D images. 4658 if "vem_nuclei" in EM_NUCLEUS_DATASETS: 4659 vem_root = os.path.join(input_path, VEM_NUCLEI_ROOT) 4660 vem_3d = [os.path.join(vem_root, f"id_{i}.h5") for i in VEM_NUCLEI_3D_IDS] 4661 vem_2d = sorted(p for p in glob(os.path.join(vem_root, "id_*.h5")) if p not in vem_3d) 4662 vem_train, vem_val = train_test_split(vem_2d, test_size=1, random_state=42) 4663 add_image_datasets( 4664 sorted(vem_train), vem_val, EM_NUCLEUS_TRAIN_SAMPLES["vem_nuclei_2d"], ignore_label=VEM_NUCLEI_IGNORE_LABEL, 4665 min_num_instances=EM_NUCLEUS_MIN_INSTANCES["vem_nuclei"], 4666 ) 4667 val_slab = np.s_[-VEM_NUCLEI_VAL_SLICES:, :, :] 4668 train_slab = np.s_[:-VEM_NUCLEI_VAL_SLICES, :, :] 4669 add_volume_datasets([ 4670 ("train", vem_3d[0], "raw", "labels", full, 1), ("train", vem_3d[1], "raw", "labels", train_slab, 1), 4671 ("val", vem_3d[1], "raw", "labels", val_slab, 1), 4672 ], EM_NUCLEUS_TRAIN_SAMPLES["vem_nuclei_3d"], min_num_instances=EM_NUCLEUS_MIN_INSTANCES["vem_nuclei"]) 4673 4674 # 18. Cerebellum nuclei (3D nuclei in FIB-SEM of the mouse cerebellum, downscaled to 20 nm, student labels) 4675 if "cerebellum_nucleus" in EM_NUCLEUS_DATASETS: 4676 cerebellum_path = os.path.join(input_path, CEREBELLUM_NUCLEUS_PATH) 4677 add_volume_datasets([ 4678 ("train", cerebellum_path, "raw", "labels", np.s_[:CEREBELLUM_NUCLEUS_VAL_Z, :, :], 1), 4679 ("val", cerebellum_path, "raw", "labels", np.s_[CEREBELLUM_NUCLEUS_VAL_Z:, :, :], 1), 4680 ], EM_NUCLEUS_TRAIN_SAMPLES["cerebellum_nucleus"], ignore_label=CEREBELLUM_NUCLEUS_IGNORE_LABEL) 4681 4682 # 19. Macrophage / A431 nuclei (3D nucleus in SBF-SEM of macrophages and an A431 cell, quick semantic annotations) 4683 if "macrophage_a431_nucleus" in EM_NUCLEUS_DATASETS: 4684 macrophage_volumes = [] 4685 for path in sorted(glob(os.path.join(input_path, MACROPHAGE_NUCLEUS_ROOT, "*.h5"))): 4686 z_scale = MACROPHAGE_NUCLEUS_Z_SCALE 4687 if os.path.basename(path) == f"{MACROPHAGE_NUCLEUS_VAL_VOLUME}.h5": 4688 macrophage_volumes += [ 4689 ("train", path, "raw", "labels", np.s_[:MACROPHAGE_NUCLEUS_VAL_Z, :, :], z_scale), 4690 ("val", path, "raw", "labels", np.s_[MACROPHAGE_NUCLEUS_VAL_Z:, :, :], z_scale), 4691 ] 4692 else: 4693 macrophage_volumes.append(("train", path, "raw", "labels", full, z_scale)) 4694 add_volume_datasets(macrophage_volumes, EM_NUCLEUS_TRAIN_SAMPLES["macrophage_a431_nucleus"]) 4695 4696 _set_volume_min_instances([train_ds, val_ds], EM_NUCLEUS_SPARSE_VOLUMES, depth=2) 4697 return train_ds, val_ds 4698 4699 4700def get_dataloaders( 4701 input_path, 4702 label_trafo=None, 4703 batch_size=1, 4704 batch_size_2d=None, 4705 z_slices=None, 4706 dataset_choice="all", 4707 n_workers=32, 4708 with_boundaries=False, 4709): 4710 """Get generalist dataloaders for training UniSAM2. 4711 4712 Args: 4713 input_path: Root path to the data. 4714 label_trafo: Label transform class (instantiated internally). 4715 batch_size: Default batch size (used for 3D groups). 4716 batch_size_2d: Optional larger batch size for 2D groups. 4717 Falls back to *batch_size* when not provided. 4718 z_slices: List of z-slice counts to use for 3D data (e.g. [2, 4, 6, 8]). 4719 Each value creates a separate dataset group so that batches have uniform z. 4720 Defaults to [8] (original behavior). 4721 dataset_choice: Which dataset domain to include. One of: 4722 - ``"lm"``: Light microscopy datasets only (2D + 3D LM). 4723 - ``"em"``: Electron microscopy datasets only. 4724 - ``"hp"``: Histopathology datasets only. 4725 - ``"em_mito"``: Mitochondria EM datasets only (not part of ``"all"``). 4726 - ``"em_nucleus"``: Nucleus EM datasets only (not part of ``"all"``). 4727 - ``"all"``: LM, EM and HP datasets (default). 4728 with_boundaries: The flag to append the full object-boundary channel to the automatic targets. 4729 """ 4730 if dataset_choice not in DATASET_CHOICES: 4731 raise ValueError(f"Invalid dataset_choice: {dataset_choice!r}. Expected one of {DATASET_CHOICES}.") 4732 4733 if label_trafo is None: 4734 from micro_sam.v2.transforms.labels import GeodesicHybridDistanceTransform 4735 label_trafo = GeodesicHybridDistanceTransform 4736 if with_boundaries: 4737 label_trafo = partial(label_trafo, with_boundaries=True) 4738 4739 if z_slices is None: 4740 z_slices = [8] 4741 if batch_size_2d is None: 4742 batch_size_2d = batch_size 4743 4744 # Some common elements for all datasets. 4745 patch_shape = (512, 512) 4746 4747 kwargs = { 4748 "raw_transform": _identity, 4749 "label_transform2": label_trafo(), 4750 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 4751 "label_dtype": torch.float32, 4752 } 4753 4754 train_ds, val_ds = [], [] 4755 4756 if dataset_choice in ("lm", "all"): 4757 lm_train, lm_val = _get_lm_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 4758 train_ds.extend(lm_train) 4759 val_ds.extend(lm_val) 4760 4761 if dataset_choice in ("em", "all"): 4762 em_train, em_val = _get_em_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 4763 train_ds.extend(em_train) 4764 val_ds.extend(em_val) 4765 4766 if dataset_choice in ("hp", "all"): 4767 hp_train, hp_val = _get_hp_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 4768 train_ds.extend(hp_train) 4769 val_ds.extend(hp_val) 4770 4771 if dataset_choice == "em_mito": 4772 mito_train, mito_val = _get_em_mito_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 4773 train_ds.extend(mito_train) 4774 val_ds.extend(mito_val) 4775 4776 if dataset_choice == "em_nucleus": 4777 nuc_train, nuc_val = _get_em_nucleus_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 4778 train_ds.extend(nuc_train) 4779 val_ds.extend(nuc_val) 4780 4781 _configure_training_normalization(train_ds, val_ds) 4782 4783 # Finally, we prepare a 'ConcatDataset' for all the available datasets. 4784 train_ds = ConcatDataset(*train_ds) 4785 val_ds = ConcatDataset(*val_ds) 4786 4787 # Determine per-group batch sizes for the sampler. 4788 batch_size_per_group = None 4789 if batch_size_2d != batch_size: 4790 batch_size_per_group = {2: batch_size_2d} 4791 4792 # And prepare the dataloaders for them. 4793 train_loader = _prepare_data_loader( 4794 train_ds, batch_size=batch_size, shuffle=True, 4795 batch_size_per_group=batch_size_per_group, num_workers=n_workers, 4796 ) 4797 val_loader = _prepare_data_loader( 4798 val_ds, batch_size=batch_size, shuffle=False, 4799 batch_size_per_group=batch_size_per_group, num_workers=n_workers, deterministic=True, 4800 ) 4801 4802 return train_loader, val_loader 4803 4804 4805def get_interactive_dataloaders( 4806 input_path, 4807 batch_size=1, 4808 batch_size_2d=None, 4809 z_slices=None, 4810 dataset_choice="all", 4811 n_workers=32, 4812): 4813 """Get generalist dataloaders for SAM2 interactive segmentation training. 4814 4815 Identical dataset composition to :func:`get_dataloaders` but returns raw 4816 integer instance labels (``label_dtype=torch.int64``) instead of distance 4817 transforms. Used with :class:`micro_sam.v2.training.ConvertToSam2VideoBatch`. 4818 4819 Args: 4820 input_path: Root path to the generalist training data. 4821 batch_size: Default batch size (used for 3D groups). 4822 batch_size_2d: Optional larger batch size for 2D groups. 4823 Falls back to *batch_size* when not provided. 4824 z_slices: List of z-slice counts for 3D data (e.g. [8]). 4825 Defaults to [8]. 4826 dataset_choice: Which dataset domain to include - ``"lm"``, ``"em"``, 4827 ``"hp"``, ``"em_mito"``, ``"em_nucleus"``, or ``"all"`` (default). 4828 n_workers: Number of DataLoader worker processes. 4829 4830 Returns: 4831 Tuple of (train_loader, val_loader). 4832 """ 4833 if dataset_choice not in DATASET_CHOICES: 4834 raise ValueError(f"Invalid dataset_choice: {dataset_choice!r}. Expected one of {DATASET_CHOICES}.") 4835 4836 if z_slices is None: 4837 z_slices = [8] 4838 if batch_size_2d is None: 4839 batch_size_2d = batch_size 4840 4841 train_ds, val_ds = _build_interactive_datasets(input_path, z_slices, dataset_choice) 4842 4843 batch_size_per_group = None 4844 if batch_size_2d != batch_size: 4845 batch_size_per_group = {2: batch_size_2d} 4846 4847 train_loader = _prepare_data_loader( 4848 train_ds, batch_size=batch_size, shuffle=True, 4849 batch_size_per_group=batch_size_per_group, num_workers=n_workers, 4850 ) 4851 val_loader = _prepare_data_loader( 4852 val_ds, batch_size=batch_size, shuffle=False, 4853 batch_size_per_group=batch_size_per_group, num_workers=n_workers, deterministic=True, 4854 ) 4855 4856 return train_loader, val_loader 4857 4858 4859def _build_automatic_datasets(input_path, z_slices, dataset_choice, with_boundaries=False): 4860 """Build train/val ConcatDatasets for automatic UniSAM2 training. 4861 4862 Separated from :func:`get_dataloaders` so that each DDP rank can 4863 independently construct its own dataset (required by 4864 :class:`DistributedUniBatchSampler`). 4865 4866 Returns: 4867 Tuple of (train_ds, val_ds) as :class:`ConcatDataset` instances. 4868 """ 4869 from micro_sam.v2.transforms.labels import GeodesicHybridDistanceTransform 4870 4871 patch_shape = (512, 512) 4872 label_trafo = GeodesicHybridDistanceTransform 4873 if with_boundaries: 4874 label_trafo = partial(label_trafo, with_boundaries=True) 4875 4876 kwargs = { 4877 "raw_transform": _identity, 4878 "label_transform2": label_trafo(), 4879 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 4880 "label_dtype": torch.float32, 4881 } 4882 4883 train_ds, val_ds = [], [] 4884 4885 if dataset_choice in ("lm", "all"): 4886 lm_train, lm_val = _get_lm_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 4887 train_ds.extend(lm_train) 4888 val_ds.extend(lm_val) 4889 4890 if dataset_choice in ("em", "all"): 4891 em_train, em_val = _get_em_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 4892 train_ds.extend(em_train) 4893 val_ds.extend(em_val) 4894 4895 if dataset_choice in ("hp", "all"): 4896 hp_train, hp_val = _get_hp_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 4897 train_ds.extend(hp_train) 4898 val_ds.extend(hp_val) 4899 4900 if dataset_choice == "em_mito": 4901 mito_train, mito_val = _get_em_mito_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 4902 train_ds.extend(mito_train) 4903 val_ds.extend(mito_val) 4904 4905 if dataset_choice == "em_nucleus": 4906 nuc_train, nuc_val = _get_em_nucleus_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 4907 train_ds.extend(nuc_train) 4908 val_ds.extend(nuc_val) 4909 4910 _configure_training_normalization(train_ds, val_ds) 4911 return ConcatDataset(*train_ds), ConcatDataset(*val_ds) 4912 4913 4914def _build_interactive_datasets(input_path, z_slices, dataset_choice): 4915 """Build train/val ConcatDatasets for interactive SAM2 training. 4916 4917 Separated from :func:`get_interactive_dataloaders` so that each DDP rank 4918 can independently construct its own dataset (required by 4919 :class:`DistributedUniBatchSampler`). 4920 4921 Returns: 4922 Tuple of (train_ds, val_ds) as :class:`ConcatDataset` instances. 4923 """ 4924 patch_shape = (512, 512) 4925 4926 kwargs = { 4927 "raw_transform": _identity, 4928 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 4929 "label_dtype": torch.int64, 4930 "label_transform2": _instance_labels, 4931 } 4932 4933 train_ds, val_ds = [], [] 4934 4935 if dataset_choice in ("lm", "all"): 4936 lm_train, lm_val = _get_lm_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo=None) 4937 train_ds.extend(lm_train) 4938 val_ds.extend(lm_val) 4939 4940 if dataset_choice in ("em", "all"): 4941 em_train, em_val = _get_em_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo=None) 4942 train_ds.extend(em_train) 4943 val_ds.extend(em_val) 4944 4945 if dataset_choice in ("hp", "all"): 4946 hp_train, hp_val = _get_hp_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo=None) 4947 train_ds.extend(hp_train) 4948 val_ds.extend(hp_val) 4949 4950 if dataset_choice == "em_mito": 4951 mito_train, mito_val = _get_em_mito_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo=None) 4952 train_ds.extend(mito_train) 4953 val_ds.extend(mito_val) 4954 4955 if dataset_choice == "em_nucleus": 4956 nuc_train, nuc_val = _get_em_nucleus_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo=None) 4957 train_ds.extend(nuc_train) 4958 val_ds.extend(nuc_val) 4959 4960 _configure_training_normalization(train_ds, val_ds) 4961 4962 # Cap each validation dataset to N_SAMPLES_VAL random samples so the per-epoch 4963 # validation pass stays cheap (train datasets are left at full size). 4964 for w in val_ds: 4965 w.max_samples = N_SAMPLES_VAL 4966 4967 return ConcatDataset(*train_ds), ConcatDataset(*val_ds) 4968 4969 4970def _build_joint_datasets( 4971 input_path, z_slices, dataset_choice, distance_type="geodesic", with_boundaries=False, label_trafo_threads=1, 4972): 4973 """Build train/val datasets for joint interactive + automatic SAM2 training. 4974 4975 Labels have ``[instance_ids, fg, d_z, d_y, d_x, boundaries?]`` channels. 4976 4977 - Channel 0 (int64): instance IDs -> interactive branch via ``ConvertToSam2VideoBatch``. 4978 - Channels 1 onward (float32): foreground + directed distances and optional boundary -> automatic branch via 4979 ``DirectedDistanceLoss``. 4980 4981 Unlike building two separate datasets, this shares a single data pipeline so both 4982 branches always see the same image patch. 4983 4984 Args: 4985 input_path: Root path to the generalist training data. 4986 z_slices: Z-slice counts for 3D groups. 4987 dataset_choice: ``"lm"``, ``"em"``, ``"hp"``, ``"em_mito"``, ``"em_nucleus"``, or ``"all"``. 4988 distance_type: Which directed distance target the automatic branch regresses. 4989 ``"geodesic"`` uses :class:`_JointGeodesicLabelTransform`, ``"directed"`` uses 4990 :class:`_JointLabelTransform`. 4991 with_boundaries: The flag to append the full object-boundary target for the automatic branch. 4992 label_trafo_threads: Threads per loader worker that process the objects of one patch in parallel 4993 in the distance transform. Only pays off when the node has more cores than loader workers. 4994 4995 Returns: 4996 Tuple of (train_ds, val_ds) as :class:`ConcatDataset` instances. 4997 """ 4998 if distance_type not in ("geodesic", "directed"): 4999 raise ValueError(f"Invalid distance_type: {distance_type!r}. Expected 'geodesic' or 'directed'.") 5000 5001 patch_shape = (512, 512) 5002 # The boundary target adds a sixth channel after the instance IDs, foreground, and distances. 5003 label_trafo = partial( 5004 _JointGeodesicLabelTransform if distance_type == "geodesic" else _JointLabelTransform, 5005 with_boundaries=with_boundaries, 5006 n_threads=label_trafo_threads, 5007 ) 5008 5009 kwargs = { 5010 "raw_transform": _identity, 5011 "label_transform2": label_trafo(), 5012 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 5013 "label_dtype": torch.float32, 5014 } 5015 5016 train_ds, val_ds = [], [] 5017 5018 if dataset_choice in ("lm", "all"): 5019 lm_train, lm_val = _get_lm_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 5020 train_ds.extend(lm_train) 5021 val_ds.extend(lm_val) 5022 5023 if dataset_choice in ("em", "all"): 5024 em_train, em_val = _get_em_datasets( 5025 input_path, patch_shape, z_slices, kwargs, label_trafo, 5026 _em_label_trafo=_joint_em_cell_label_trafo, 5027 ) 5028 train_ds.extend(em_train) 5029 val_ds.extend(em_val) 5030 5031 if dataset_choice in ("hp", "all"): 5032 hp_train, hp_val = _get_hp_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 5033 train_ds.extend(hp_train) 5034 val_ds.extend(hp_val) 5035 5036 if dataset_choice == "em_mito": 5037 mito_train, mito_val = _get_em_mito_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 5038 train_ds.extend(mito_train) 5039 val_ds.extend(mito_val) 5040 5041 if dataset_choice == "em_nucleus": 5042 nuc_train, nuc_val = _get_em_nucleus_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 5043 train_ds.extend(nuc_train) 5044 val_ds.extend(nuc_val) 5045 5046 _configure_training_normalization(train_ds, val_ds) 5047 5048 # Cap each validation dataset to N_SAMPLES_VAL random samples so the per-epoch 5049 # validation pass stays cheap (matches the interactive builder; train datasets are full size). 5050 for w in val_ds: 5051 w.max_samples = N_SAMPLES_VAL 5052 5053 return ConcatDataset(*train_ds), ConcatDataset(*val_ds)
64def seed_worker(worker_id): 65 """DataLoader worker_init_fn that pins per-worker RNG for deterministic validation crops. 66 67 The torch_em datasets draw a fresh random crop and random object subset on every 68 __getitem__ inside the worker process. Seeding each worker deterministically (and using 69 non-persistent workers so this runs every epoch) makes those crops identical across epochs. 70 """ 71 seed = VALIDATION_SEED + worker_id 72 random.seed(seed) 73 np.random.seed(seed) 74 torch.manual_seed(seed)
DataLoader worker_init_fn that pins per-worker RNG for deterministic validation crops.
The torch_em datasets draw a fresh random crop and random object subset on every __getitem__ inside the worker process. Seeding each worker deterministically (and using non-persistent workers so this runs every epoch) makes those crops identical across epochs.
2342def synapsenet_tomograms(path): 2343 """The SynapseNet compartment tomograms, h5 files with 'raw' and 'labels/compartments'.""" 2344 paths = sorted(glob(os.path.join(path, "v3", "*", "*.h5"))) 2345 assert paths, f"Did not find any tomograms in '{path}'." 2346 return paths
The SynapseNet compartment tomograms, h5 files with 'raw' and 'labels/compartments'.
2349def synapsenet_roi(path, split): 2350 """The z-slab of a training tomogram that trains ('train') or validates ('val'), as a (z, y, x) roi.""" 2351 with open_file(path, "r") as f: 2352 n_sections = f["raw"].shape[0] 2353 cut = int(SYNAPSENET_TRAIN_FRACTION * n_sections) 2354 return (slice(0, cut) if split == "train" else slice(cut, None), slice(None), slice(None))
The z-slab of a training tomogram that trains ('train') or validates ('val'), as a (z, y, x) roi.
2419def cell_acdc_movie(path): 2420 """The movie a Cell-ACDC frame stack belongs to, as '<experiment folder>/Position_<n>'.""" 2421 parts = os.path.normpath(path).split(os.sep) 2422 return "/".join(parts[parts.index("TimeLapse_2D") + 1:parts.index("TimeLapse_2D") + 3])
The movie a Cell-ACDC frame stack belongs to, as '
2430def cvz_group(path): 2431 """The patient (Vectra) or slide (CODEX, Zeiss) a CVZ crop belongs to, as 'instrument:name'.""" 2432 parts = os.path.normpath(path).split(os.sep) 2433 instrument = parts[parts.index("cvz") + 1] 2434 name = os.path.basename(path) 2435 match = re.match(r"(P\d+)-", name) 2436 return f"{instrument}:{match.group(1) if match else name.split('(')[0]}"
The patient (Vectra) or slide (CODEX, Zeiss) a CVZ crop belongs to, as 'instrument:name'.
2477def dsb_fluorescence_training_paths(path): 2478 """The DSB fluorescence images of the 'full' source without the StarDist test images. 2479 2480 The StarDist test files are named by their Kaggle image id, which is the folder name in the 'full' source, so 2481 the blind test images are excluded by id. 2482 """ 2483 test_ids = { 2484 os.path.splitext(os.path.basename(p))[0] 2485 for p in datasets.dsb.get_dsb_paths(path, source="reduced", split="test")[0] 2486 } 2487 raw, labels = datasets.dsb.get_dsb_paths(path, source="full", domain="fluo") 2488 keep = [os.path.basename(os.path.dirname(os.path.dirname(p))) not in test_ids for p in raw] 2489 return [p for p, k in zip(raw, keep) if k], [p for p, k in zip(labels, keep) if k]
The DSB fluorescence images of the 'full' source without the StarDist test images.
The StarDist test files are named by their Kaggle image id, which is the folder name in the 'full' source, so the blind test images are excluded by id.
3102def probtem_split_paths(input_path, split): 3103 """The ProbTEM train images of the 'train' or 'val' part.""" 3104 paths = sorted(glob(os.path.join(input_path, PROBTEM_ROOT, "train", "*.h5"))) 3105 train_paths, val_paths = train_test_split(paths, test_size=PROBTEM_N_VAL, random_state=42) 3106 return sorted(train_paths if split == "train" else val_paths)
The ProbTEM train images of the 'train' or 'val' part.
3109def cellmap_mito_split_crops(input_path, split): 3110 """The CellMap mito crops of the 'train' or 'val' volumes, as {patch side: crop paths}.""" 3111 root = os.path.join(input_path, "cellmap_mito_crops") 3112 with open(os.path.join(root, "index.json")) as f: 3113 crops = [ 3114 crop for crop in json.load(f) if crop["n_ids"] > 0 and min(crop["shape"][1:]) >= CELLMAP_MITO_PATCH_SIDES[0] 3115 ] 3116 volumes = sorted({crop["volume"] for crop in crops}) 3117 train_volumes, val_volumes = train_test_split(volumes, test_size=CELLMAP_MITO_VAL_FRACTION, random_state=42) 3118 keep = set(train_volumes if split == "train" else val_volumes) 3119 groups = {} 3120 for crop in crops: 3121 if crop["volume"] in keep: 3122 side = max(s for s in CELLMAP_MITO_PATCH_SIDES if s <= min(crop["shape"][1:])) 3123 groups.setdefault(side, []).append(os.path.join(root, f"{crop['name']}.zarr")) 3124 return {side: sorted(paths) for side, paths in sorted(groups.items())}
The CellMap mito crops of the 'train' or 'val' volumes, as {patch side: crop paths}.
3238def em_nucleus_patch_side(shape): 3239 """The largest patch side of EM_NUCLEUS_PATCH_SIDES that fits in-plane into a volume of *shape*.""" 3240 return max(side for side in EM_NUCLEUS_PATCH_SIDES if side <= min(shape[-2:]))
The largest patch side of EM_NUCLEUS_PATCH_SIDES that fits in-plane into a volume of shape.
3243def betaseg_nucleus_split_boxes(input_path, split): 3244 """The BetaSeg nucleus boxes of the 'train' or 'val' volumes, as {patch side: box paths}.""" 3245 groups = {} 3246 for volume in BETASEG_NUCLEUS_TRAIN_VOLUMES if split == "train" else BETASEG_NUCLEUS_VAL_VOLUMES: 3247 path = os.path.join(input_path, "betaseg_nucleus_boxes", f"{volume}.h5") 3248 with open_file(path, "r") as f: 3249 groups.setdefault(em_nucleus_patch_side(f["raw"].shape), []).append(path) 3250 return {side: sorted(paths) for side, paths in sorted(groups.items())}
The BetaSeg nucleus boxes of the 'train' or 'val' volumes, as {patch side: box paths}.
3253def sxt_nucleus_labels(labels): 3254 """The nucleus mask of the SXT INS-1E class labels, with SXT_NUCLEUS_IGNORE_LABEL outside the cell.""" 3255 labels = np.asarray(labels) 3256 nucleus = (labels == SXT_NUCLEUS_CLASS).astype("uint16") 3257 nucleus[labels == SXT_EXTERIOR_CLASS] = SXT_NUCLEUS_IGNORE_LABEL 3258 return nucleus
The nucleus mask of the SXT INS-1E class labels, with SXT_NUCLEUS_IGNORE_LABEL outside the cell.
3261def sxt_nucleus_instances(labels): 3262 """The connected components of the SXT INS-1E nucleus mask, as the pre_label_transform (before the sampler).""" 3263 return _connected_components_pre_label_trafo(sxt_nucleus_labels(labels), ignore_label=SXT_NUCLEUS_IGNORE_LABEL)
The connected components of the SXT INS-1E nucleus mask, as the pre_label_transform (before the sampler).
3266def sxt_nucleus_split_paths(input_path, split): 3267 """The SXT INS-1E cells of the 'train' or 'val' part, as {patch side: zarr paths}.""" 3268 paths = sorted(glob(os.path.join(input_path, "sxt_ins1e_mito", "*.zarr"))) 3269 train_paths, val_paths = train_test_split(paths, test_size=SXT_NUCLEUS_N_VAL, random_state=42) 3270 groups = {} 3271 for path in train_paths if split == "train" else val_paths: 3272 with open_file(path, "r") as f: 3273 groups.setdefault(em_nucleus_patch_side(f["labels"].shape), []).append(path) 3274 return {side: sorted(paths) for side, paths in sorted(groups.items())}
The SXT INS-1E cells of the 'train' or 'val' part, as {patch side: zarr paths}.
3277def platynereis_nuclei_split_rois(input_path, split): 3278 """The Platynereis nucleus volumes of the 'train' or 'val' part, as {patch side: (paths, valid rois)}.""" 3279 root = os.path.join(input_path, "platynereis") 3280 template = "nuclei/train_data_nuclei_%02i.h5" 3281 sample_ids = PLATYNEREIS_NUCLEI_TRAIN_IDS if split == "train" else PLATYNEREIS_NUCLEI_VAL_IDS 3282 valid_rois = _compute_platy_rois( 3283 root, sample_ids, ignore_label=PLATYNEREIS_NUCLEI_IGNORE_LABEL, file_template=template, 3284 label_key="volumes/labels/nucleus_instance_labels", cache_prefix="_nuclei_roi_cache", 3285 ) 3286 groups = {} 3287 for sample_id in sample_ids: 3288 roi = valid_rois[sample_id] 3289 side = em_nucleus_patch_side((roi[1].stop - roi[1].start, roi[2].stop - roi[2].start)) 3290 paths, rois = groups.setdefault(side, ([], [])) 3291 paths.append(os.path.join(root, template % sample_id)) 3292 rois.append(roi) 3293 return dict(sorted(groups.items()))
The Platynereis nucleus volumes of the 'train' or 'val' part, as {patch side: (paths, valid rois)}.
3296def janelia_nucleus_split_paths(input_path, split): 3297 """The Janelia nucleus volumes of the split, as {patch side: zarr paths}, and their voxel counts. 3298 3299 The voxel counts weight the samples, so that the large tissue volumes are not outweighed by the small volumes with 3300 one to three nuclei. 3301 """ 3302 groups, voxels = {}, {} 3303 for path in sorted(glob(os.path.join(input_path, "janelia_nucleus", "*.zarr"))): 3304 name = os.path.basename(path)[:-len(".zarr")] 3305 if name in JANELIA_NUCLEUS_EXCLUDED_VOLUMES or (name in JANELIA_NUCLEUS_VAL_VOLUMES) != (split == "val"): 3306 continue 3307 with open_file(path, "r") as f: 3308 shape = f["labels"].shape 3309 groups.setdefault(em_nucleus_patch_side(shape), []).append(path) 3310 voxels[path] = int(np.prod(shape)) 3311 return {side: sorted(paths) for side, paths in sorted(groups.items())}, voxels
The Janelia nucleus volumes of the split, as {patch side: zarr paths}, and their voxel counts.
The voxel counts weight the samples, so that the large tissue volumes are not outweighed by the small volumes with one to three nuclei.
3314def openorganelle_nucleus_split_paths(input_path, split): 3315 """The OpenOrganelle nucleus volumes of the split, as {patch side: zarr paths}, and their voxel counts. 3316 3317 The voxel counts weight the samples, so that the large tissue volumes are not outweighed by the many single-cell 3318 volumes with one to three nuclei. 3319 """ 3320 root = os.path.join(input_path, "openorganelle_nucleus") 3321 groups, voxels = {}, {} 3322 for name, voxel_size in OPENORGANELLE_NUCLEUS_VOLUMES.items(): 3323 if (name in OPENORGANELLE_NUCLEUS_VAL_VOLUMES) != (split == "val"): 3324 continue 3325 path = datasets.openorganelle_nucleus.get_openorganelle_nucleus_paths(root, [name], voxel_size=voxel_size)[0] 3326 with open_file(path, "r") as f: 3327 shape = f["labels"].shape 3328 groups.setdefault(em_nucleus_patch_side(shape), []).append(path) 3329 voxels[path] = int(np.prod(shape)) 3330 return {side: sorted(paths) for side, paths in sorted(groups.items())}, voxels
The OpenOrganelle nucleus volumes of the split, as {patch side: zarr paths}, and their voxel counts.
The voxel counts weight the samples, so that the large tissue volumes are not outweighed by the many single-cell volumes with one to three nuclei.
3333def cellmap_nucleus_split_crops(input_path, split): 3334 """The CellMap nucleus crops of the 'train' or 'val' part, as {patch side: crop paths}.""" 3335 root = os.path.join(input_path, "cellmap_nucleus_crops") 3336 with open(os.path.join(root, "index.json")) as f: 3337 crops = [crop for crop in json.load(f) if crop["split"] == "train"] 3338 groups = {} 3339 for crop in crops: 3340 if (crop["name"] in CELLMAP_NUCLEUS_VAL_CROPS) == (split == "val"): 3341 groups.setdefault(em_nucleus_patch_side(crop["shape"]), []).append( 3342 os.path.join(root, f"{crop['name']}.zarr") 3343 ) 3344 return {side: sorted(paths) for side, paths in sorted(groups.items())}
The CellMap nucleus crops of the 'train' or 'val' part, as {patch side: crop paths}.
3362def mitolab_group(path, root): 3363 """The CEM-MitoLab group (source folder) of an image path: '<root>/<group>/images/<name>.tiff'.""" 3364 return os.path.relpath(path, root).split(os.sep)[0]
The CEM-MitoLab group (source folder) of an image path: '
3367def mitolab_split_paths(path, split): 3368 """The non-empty CEM-MitoLab images and masks of the 'train' or 'val' groups, without the excluded groups.""" 3369 root = datasets.cem.get_mitolab_data(path, download=False) 3370 raw_paths, label_paths = datasets.cem.get_mitolab_paths(path, split=None, download=False) 3371 groups = sorted({mitolab_group(p, root) for p in raw_paths} - set(MITOLAB_EXCLUDED_GROUPS)) 3372 train_groups, val_groups = train_test_split(groups, test_size=MITOLAB_VAL_FRACTION, random_state=42) 3373 keep = set(train_groups if split == "train" else val_groups) 3374 pairs = [(r, lab) for r, lab in zip(raw_paths, label_paths) if mitolab_group(r, root) in keep] 3375 if split == "val": 3376 # A seeded MITOLAB_VAL_IMAGES_PER_GROUP images per group, so that no group dominates the validation. 3377 by_group = {} 3378 for pair in pairs: 3379 by_group.setdefault(mitolab_group(pair[0], root), []).append(pair) 3380 rng = np.random.default_rng(42) 3381 pairs = [] 3382 for group in sorted(by_group): 3383 members = by_group[group] 3384 if len(members) > MITOLAB_VAL_IMAGES_PER_GROUP: 3385 members = [members[i] for i in sorted(rng.choice(len(members), MITOLAB_VAL_IMAGES_PER_GROUP, False))] 3386 pairs.extend(members) 3387 return [r for r, _ in pairs], [lab for _, lab in pairs]
The non-empty CEM-MitoLab images and masks of the 'train' or 'val' groups, without the excluded groups.
3390def mitoemv2_mossy_label_path(input_path, volume): 3391 """The labels of one MitoVerse han24 volume with MITOEMV2_MOSSY_IGNORE_LABEL outside the annotated boutons. 3392 3393 They are written once to <input_path>/mitoverse_derived, slab by slab, under a temporary name that is moved in 3394 place when complete, so that interrupted writes and concurrent ranks never leave a partial array behind. 3395 """ 3396 import zarr 3397 3398 out_path = os.path.join(input_path, "mitoverse_derived", f"han24_{volume}_bouton_labels.zarr") 3399 if os.path.exists(out_path): 3400 return out_path 3401 3402 source = zarr.open_group(os.path.join(input_path, "mitoverse", "data", "han24", f"{volume}.zarr"), mode="r") 3403 tmp_path = f"{out_path}.{os.getpid()}.incomplete" 3404 labels = zarr.open_group(tmp_path, mode="w").create_array( 3405 "labels", shape=source["mito"].shape, chunks=(32, 256, 256), dtype="uint32" 3406 ) 3407 for z in range(0, labels.shape[0], 32): 3408 slab = source["mito"][z:z + 32].astype("uint32") 3409 slab[source["mask"][z:z + 32] == 0] = MITOEMV2_MOSSY_IGNORE_LABEL 3410 labels[z:z + 32] = slab 3411 try: 3412 os.replace(tmp_path, out_path) 3413 except OSError: 3414 # Another rank moved its copy in place first. 3415 shutil.rmtree(tmp_path) 3416 return out_path
The labels of one MitoVerse han24 volume with MITOEMV2_MOSSY_IGNORE_LABEL outside the annotated boutons.
They are written once to
3419def mitoverse_missing_data_label_path(input_path, dataset, volume): 3420 """The labels of one MitoVerse volume with MITOVERSE_IGNORE_LABEL inside the regions without image data. 3421 3422 A region without image data is a connected raw == 0 region of a slice above MITOVERSE_MISSING_DATA_MIN_AREA. 3423 The labels are written once to <input_path>/mitoverse_derived, slice by slice, under a temporary name that is 3424 moved in place when complete, as in mitoemv2_mossy_label_path. 3425 """ 3426 import zarr 3427 from scipy import ndimage 3428 3429 out_path = os.path.join(input_path, "mitoverse_derived", f"{dataset}_{volume}_missing_data_labels.zarr") 3430 if os.path.exists(out_path): 3431 return out_path 3432 3433 source = zarr.open_group(os.path.join(input_path, "mitoverse", "data", dataset, f"{volume}.zarr"), mode="r") 3434 tmp_path = f"{out_path}.{os.getpid()}.incomplete" 3435 labels = zarr.open_group(tmp_path, mode="w").create_array( 3436 "labels", shape=source["mito"].shape, chunks=(32, 256, 256), dtype="uint32" 3437 ) 3438 for z in range(labels.shape[0]): 3439 slice_labels = source["mito"][z].astype("uint32") 3440 empty, _ = ndimage.label(source["img"][z] == 0) 3441 areas = np.bincount(empty.ravel()) 3442 missing = np.isin(empty, np.where(areas > MITOVERSE_MISSING_DATA_MIN_AREA)[0]) & (empty > 0) 3443 slice_labels[missing] = MITOVERSE_IGNORE_LABEL 3444 labels[z] = slice_labels 3445 try: 3446 os.replace(tmp_path, out_path) 3447 except OSError: 3448 # Another rank moved its copy in place first. 3449 shutil.rmtree(tmp_path) 3450 return out_path
The labels of one MitoVerse volume with MITOVERSE_IGNORE_LABEL inside the regions without image data.
A region without image data is a connected raw == 0 region of a slice above MITOVERSE_MISSING_DATA_MIN_AREA.
The labels are written once to
4701def get_dataloaders( 4702 input_path, 4703 label_trafo=None, 4704 batch_size=1, 4705 batch_size_2d=None, 4706 z_slices=None, 4707 dataset_choice="all", 4708 n_workers=32, 4709 with_boundaries=False, 4710): 4711 """Get generalist dataloaders for training UniSAM2. 4712 4713 Args: 4714 input_path: Root path to the data. 4715 label_trafo: Label transform class (instantiated internally). 4716 batch_size: Default batch size (used for 3D groups). 4717 batch_size_2d: Optional larger batch size for 2D groups. 4718 Falls back to *batch_size* when not provided. 4719 z_slices: List of z-slice counts to use for 3D data (e.g. [2, 4, 6, 8]). 4720 Each value creates a separate dataset group so that batches have uniform z. 4721 Defaults to [8] (original behavior). 4722 dataset_choice: Which dataset domain to include. One of: 4723 - ``"lm"``: Light microscopy datasets only (2D + 3D LM). 4724 - ``"em"``: Electron microscopy datasets only. 4725 - ``"hp"``: Histopathology datasets only. 4726 - ``"em_mito"``: Mitochondria EM datasets only (not part of ``"all"``). 4727 - ``"em_nucleus"``: Nucleus EM datasets only (not part of ``"all"``). 4728 - ``"all"``: LM, EM and HP datasets (default). 4729 with_boundaries: The flag to append the full object-boundary channel to the automatic targets. 4730 """ 4731 if dataset_choice not in DATASET_CHOICES: 4732 raise ValueError(f"Invalid dataset_choice: {dataset_choice!r}. Expected one of {DATASET_CHOICES}.") 4733 4734 if label_trafo is None: 4735 from micro_sam.v2.transforms.labels import GeodesicHybridDistanceTransform 4736 label_trafo = GeodesicHybridDistanceTransform 4737 if with_boundaries: 4738 label_trafo = partial(label_trafo, with_boundaries=True) 4739 4740 if z_slices is None: 4741 z_slices = [8] 4742 if batch_size_2d is None: 4743 batch_size_2d = batch_size 4744 4745 # Some common elements for all datasets. 4746 patch_shape = (512, 512) 4747 4748 kwargs = { 4749 "raw_transform": _identity, 4750 "label_transform2": label_trafo(), 4751 "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]), 4752 "label_dtype": torch.float32, 4753 } 4754 4755 train_ds, val_ds = [], [] 4756 4757 if dataset_choice in ("lm", "all"): 4758 lm_train, lm_val = _get_lm_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 4759 train_ds.extend(lm_train) 4760 val_ds.extend(lm_val) 4761 4762 if dataset_choice in ("em", "all"): 4763 em_train, em_val = _get_em_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 4764 train_ds.extend(em_train) 4765 val_ds.extend(em_val) 4766 4767 if dataset_choice in ("hp", "all"): 4768 hp_train, hp_val = _get_hp_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 4769 train_ds.extend(hp_train) 4770 val_ds.extend(hp_val) 4771 4772 if dataset_choice == "em_mito": 4773 mito_train, mito_val = _get_em_mito_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 4774 train_ds.extend(mito_train) 4775 val_ds.extend(mito_val) 4776 4777 if dataset_choice == "em_nucleus": 4778 nuc_train, nuc_val = _get_em_nucleus_datasets(input_path, patch_shape, z_slices, kwargs, label_trafo) 4779 train_ds.extend(nuc_train) 4780 val_ds.extend(nuc_val) 4781 4782 _configure_training_normalization(train_ds, val_ds) 4783 4784 # Finally, we prepare a 'ConcatDataset' for all the available datasets. 4785 train_ds = ConcatDataset(*train_ds) 4786 val_ds = ConcatDataset(*val_ds) 4787 4788 # Determine per-group batch sizes for the sampler. 4789 batch_size_per_group = None 4790 if batch_size_2d != batch_size: 4791 batch_size_per_group = {2: batch_size_2d} 4792 4793 # And prepare the dataloaders for them. 4794 train_loader = _prepare_data_loader( 4795 train_ds, batch_size=batch_size, shuffle=True, 4796 batch_size_per_group=batch_size_per_group, num_workers=n_workers, 4797 ) 4798 val_loader = _prepare_data_loader( 4799 val_ds, batch_size=batch_size, shuffle=False, 4800 batch_size_per_group=batch_size_per_group, num_workers=n_workers, deterministic=True, 4801 ) 4802 4803 return train_loader, val_loader
Get generalist dataloaders for training UniSAM2.
Arguments:
- input_path: Root path to the data.
- label_trafo: Label transform class (instantiated internally).
- batch_size: Default batch size (used for 3D groups).
- batch_size_2d: Optional larger batch size for 2D groups. Falls back to batch_size when not provided.
- z_slices: List of z-slice counts to use for 3D data (e.g. [2, 4, 6, 8]). Each value creates a separate dataset group so that batches have uniform z. Defaults to [8] (original behavior).
- dataset_choice: Which dataset domain to include. One of:
"lm": Light microscopy datasets only (2D + 3D LM)."em": Electron microscopy datasets only."hp": Histopathology datasets only."em_mito": Mitochondria EM datasets only (not part of"all")."em_nucleus": Nucleus EM datasets only (not part of"all")."all": LM, EM and HP datasets (default).
- with_boundaries: The flag to append the full object-boundary channel to the automatic targets.
4806def get_interactive_dataloaders( 4807 input_path, 4808 batch_size=1, 4809 batch_size_2d=None, 4810 z_slices=None, 4811 dataset_choice="all", 4812 n_workers=32, 4813): 4814 """Get generalist dataloaders for SAM2 interactive segmentation training. 4815 4816 Identical dataset composition to :func:`get_dataloaders` but returns raw 4817 integer instance labels (``label_dtype=torch.int64``) instead of distance 4818 transforms. Used with :class:`micro_sam.v2.training.ConvertToSam2VideoBatch`. 4819 4820 Args: 4821 input_path: Root path to the generalist training data. 4822 batch_size: Default batch size (used for 3D groups). 4823 batch_size_2d: Optional larger batch size for 2D groups. 4824 Falls back to *batch_size* when not provided. 4825 z_slices: List of z-slice counts for 3D data (e.g. [8]). 4826 Defaults to [8]. 4827 dataset_choice: Which dataset domain to include - ``"lm"``, ``"em"``, 4828 ``"hp"``, ``"em_mito"``, ``"em_nucleus"``, or ``"all"`` (default). 4829 n_workers: Number of DataLoader worker processes. 4830 4831 Returns: 4832 Tuple of (train_loader, val_loader). 4833 """ 4834 if dataset_choice not in DATASET_CHOICES: 4835 raise ValueError(f"Invalid dataset_choice: {dataset_choice!r}. Expected one of {DATASET_CHOICES}.") 4836 4837 if z_slices is None: 4838 z_slices = [8] 4839 if batch_size_2d is None: 4840 batch_size_2d = batch_size 4841 4842 train_ds, val_ds = _build_interactive_datasets(input_path, z_slices, dataset_choice) 4843 4844 batch_size_per_group = None 4845 if batch_size_2d != batch_size: 4846 batch_size_per_group = {2: batch_size_2d} 4847 4848 train_loader = _prepare_data_loader( 4849 train_ds, batch_size=batch_size, shuffle=True, 4850 batch_size_per_group=batch_size_per_group, num_workers=n_workers, 4851 ) 4852 val_loader = _prepare_data_loader( 4853 val_ds, batch_size=batch_size, shuffle=False, 4854 batch_size_per_group=batch_size_per_group, num_workers=n_workers, deterministic=True, 4855 ) 4856 4857 return train_loader, val_loader
Get generalist dataloaders for SAM2 interactive segmentation training.
Identical dataset composition to get_dataloaders() but returns raw
integer instance labels (label_dtype=torch.int64) instead of distance
transforms. Used with micro_sam.v2.training.ConvertToSam2VideoBatch.
Arguments:
- input_path: Root path to the generalist training data.
- batch_size: Default batch size (used for 3D groups).
- batch_size_2d: Optional larger batch size for 2D groups. Falls back to batch_size when not provided.
- z_slices: List of z-slice counts for 3D data (e.g. [8]). Defaults to [8].
- dataset_choice: Which dataset domain to include -
"lm","em","hp","em_mito","em_nucleus", or"all"(default). - n_workers: Number of DataLoader worker processes.
Returns:
Tuple of (train_loader, val_loader).