micro_sam.v2.datasets.data_counter

Count the generalist training data (train + val) per domain and dimensionality.

The counter builds the datasets in the same way as generalist_loader.py. Then it reads the label sources (file, internal key and region of interest) from the torch-em leaf datasets. These leaves hold the outputs of the torch-em get_*_paths functions after every split rule of the loader. So the counter does not re-implement any split.

Each label source is one counting unit:

  • An image file of an ImageCollectionDataset is one 2D image.
  • A SegmentationDataset of a 3D source is one volume. A time point of a 3D time-lapse is one volume. A volume that train and val share through different regions of interest is one volume, and its objects are the union of the ids in these regions.
  • A SegmentationDataset of a 2D source over a stacked file (movie frames, tile stacks) is one image per entry of the first axis.
  • An image with several label targets, such as the Xenium nuclei and cells of one slide, is one image. The objects of both targets add up.

The objects of a unit are its unique non-zero label ids after the label pre-processing of the loader. This maps background ids to zero, converts semantic masks to instances and drops oversized annotation artefacts. The ignore label of the EM cell datasets is not an object. The counter does not run connected components. So an id with several disconnected parts is one object, and the counts describe the labels as annotated.

The counter writes generalist_data_counts.csv to the current directory with the columns domain, ndim, n_datasets (top-level data folders), n_images_or_volumes, n_objects and datasets. With --per_dataset it also writes one row per dataset. A JSON cache in the current directory holds the counts per label source, so a rerun after a loader change only counts new sources. Delete the cache after you regenerate labels on disk.

Each domain builds its datasets first, which takes about ten minutes. The EM volumes dominate the counting time (about half an hour with 6 workers). Use 6 to 8 workers on a 64 GB allocation. More workers ran out of memory.

Run python -m micro_sam.v2.datasets.data_counter --help for the options.

  1"""Count the generalist training data (train + val) per domain and dimensionality.
  2
  3The counter builds the datasets in the same way as ``generalist_loader.py``. Then it reads the label sources (file,
  4internal key and region of interest) from the torch-em leaf datasets. These leaves hold the outputs of the torch-em
  5``get_*_paths`` functions after every split rule of the loader. So the counter does not re-implement any split.
  6
  7Each label source is one counting unit:
  8
  9- An image file of an ``ImageCollectionDataset`` is one 2D image.
 10- A ``SegmentationDataset`` of a 3D source is one volume. A time point of a 3D time-lapse is one volume. A volume
 11  that train and val share through different regions of interest is one volume, and its objects are the union of
 12  the ids in these regions.
 13- A ``SegmentationDataset`` of a 2D source over a stacked file (movie frames, tile stacks) is one image per entry of
 14  the first axis.
 15- An image with several label targets, such as the Xenium nuclei and cells of one slide, is one image. The objects
 16  of both targets add up.
 17
 18The objects of a unit are its unique non-zero label ids after the label pre-processing of the loader. This maps
 19background ids to zero, converts semantic masks to instances and drops oversized annotation artefacts. The ignore
 20label of the EM cell datasets is not an object. The counter does not run connected components. So an id with
 21several disconnected parts is one object, and the counts describe the labels as annotated.
 22
 23The counter writes ``generalist_data_counts.csv`` to the current directory with the columns ``domain``, ``ndim``,
 24``n_datasets`` (top-level data folders), ``n_images_or_volumes``, ``n_objects`` and ``datasets``. With
 25``--per_dataset`` it also writes one row per dataset. A JSON cache in the current directory holds the counts per
 26label source, so a rerun after a loader change only counts new sources. Delete the cache after you regenerate
 27labels on disk.
 28
 29Each domain builds its datasets first, which takes about ten minutes. The EM volumes dominate the counting time
 30(about half an hour with 6 workers). Use 6 to 8 workers on a 64 GB allocation. More workers ran out of memory.
 31
 32Run ``python -m micro_sam.v2.datasets.data_counter --help`` for the options.
 33"""
 34
 35import os
 36import csv
 37import json
 38import argparse
 39import warnings
 40from functools import partial
 41from collections import defaultdict
 42from dataclasses import asdict, dataclass
 43from typing import Callable, Dict, List, Optional, Tuple
 44from concurrent.futures import ProcessPoolExecutor, as_completed
 45
 46import numpy as np
 47from tqdm import tqdm
 48
 49import torch
 50
 51from torch_em.util.image import load_data
 52from torch_em.data import MinInstanceSampler
 53from torch_em.data.datasets.electron_microscopy.platynereis import CELL_IGNORE_LABEL
 54
 55from .wrapper import _leaves
 56from ..transforms.raw import _identity
 57from .generalist_loader import (
 58    _get_em_datasets, _get_em_mito_datasets, _get_em_nucleus_datasets, _get_hp_datasets, _get_lm_datasets,
 59    _resize_then_em_label_trafo,
 60)
 61
 62DEFAULT_INPUT_PATH = "/mnt/vast-nhr/projects/cidas/cca/data"
 63DOMAIN_BUILDERS = {
 64    "lm": _get_lm_datasets, "em": _get_em_datasets, "hp": _get_hp_datasets,
 65    "em_mito": _get_em_mito_datasets, "em_nucleus": _get_em_nucleus_datasets,
 66}
 67DOMAIN_NAMES = {
 68    "lm": "light microscopy", "em": "electron microscopy", "hp": "histopathology",
 69    "em_mito": "electron microscopy mitochondria", "em_nucleus": "electron microscopy nuclei",
 70}
 71# The domains of the 'all' generalist, counted by default.
 72DEFAULT_DOMAINS = ["lm", "em", "hp"]
 73# The background and the ignore label of the EM cell datasets are never objects.
 74NON_OBJECT_IDS = (0, CELL_IGNORE_LABEL)
 75# The largest number of label elements that one slab of a streamed unit holds.
 76MAX_SLAB_ELEMENTS = 2 ** 26
 77
 78
 79@dataclass(frozen=True)
 80class Unit:
 81    """One label source of the training data."""
 82    domain: str
 83    dataset: str
 84    ndim: int
 85    label_path: str
 86    label_key: Optional[str]
 87    roi: Optional[Tuple[Tuple[Optional[int], Optional[int]], ...]]
 88    # A 2D source with the patch shape (1, H, W) is a stack. Its first axis holds the frames or tiles.
 89    stacked: bool
 90    splits: Tuple[str, ...]
 91
 92    @property
 93    def key(self):
 94        return (self.label_path, self.label_key, self.roi, self.stacked)
 95
 96
 97@dataclass
 98class UnitCount:
 99    """The counting result of one unit. ``ids`` holds the object ids of a unit that shares its file with others."""
100    n_images: int
101    n_objects: int
102    shape: Tuple[int, ...]
103    ids: Optional[List[int]] = None
104
105
106def _roi_to_tuple(roi):
107    """Convert a region of interest of slices into a tuple of (start, stop) pairs, which is hashable."""
108    if roi is None:
109        return None
110    return tuple((s.start, s.stop) for s in roi)
111
112
113def _roi_to_slices(roi, shape):
114    """Convert a region of interest of (start, stop) pairs into full slices for an array of ``shape``."""
115    if roi is None:
116        return tuple(slice(0, s) for s in shape)
117    slices = tuple(
118        slice(0 if start is None else start, dim if stop is None else stop) for (start, stop), dim in zip(roi, shape)
119    )
120    return slices + tuple(slice(0, s) for s in shape[len(slices):])
121
122
123def _dataset_name(label_path, input_path):
124    """Return the top-level data folder of a label file. Files outside the data root use their parent folder."""
125    rel = os.path.relpath(os.path.abspath(label_path), os.path.abspath(input_path))
126    if rel.startswith(os.pardir):
127        return os.path.basename(os.path.dirname(label_path))
128    return rel.split(os.sep)[0]
129
130
131def _label_transform(leaf):
132    """Return the label transform of a leaf without the in-plane resize of the small-volume datasets.
133
134    The counter builds the datasets with ``label_transform2=None``. So the dataset-specific transforms of the loader
135    wrap ``None`` and return the mapped instance ids instead of distance targets.
136    """
137    trafo = getattr(leaf, "label_transform2", None)
138    if isinstance(trafo, partial) and trafo.func is _resize_then_em_label_trafo:
139        trafo = trafo.keywords.get("em_trafo_fn")
140    return trafo
141
142
143def build_units(domain, input_path):
144    """Build the datasets of one domain in the same way as the training and collect their label sources.
145
146    Args:
147        domain: The domain, one of ``"lm"``, ``"em"``, ``"hp"``, ``"em_mito"`` or ``"em_nucleus"``.
148        input_path: The root path of the training data.
149
150    Returns:
151        The units, deduplicated over train and val, and the label transforms of each unit
152        (``pre_label_transform``, ``label_transform2``) keyed by the unit key.
153    """
154    kwargs = {
155        "raw_transform": _identity,
156        "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]),
157        "label_dtype": torch.int64,
158        "label_transform2": None,
159    }
160    train_ds, val_ds = DOMAIN_BUILDERS[domain](input_path, (512, 512), [8], kwargs, None)
161
162    units: Dict[tuple, Unit] = {}
163    transforms: Dict[tuple, Tuple[Optional[Callable], Optional[Callable]]] = {}
164    for split, wrappers in [("train", train_ds), ("val", val_ds)]:
165        for wrapper in wrappers:
166            for leaf in _leaves(wrapper.ds):
167                if hasattr(leaf, "label_images"):
168                    sources = [(p, None, None) for p in leaf.label_images]
169                    stacked = False
170                else:
171                    sources = [(leaf.label_path, leaf.label_key, _roi_to_tuple(leaf.roi))]
172                    stacked = wrapper.source_ndim == 2 and len(leaf.patch_shape) == 3
173                for label_path, label_key, roi in sources:
174                    unit = Unit(
175                        domain=domain, dataset=_dataset_name(label_path, input_path), ndim=wrapper.source_ndim,
176                        label_path=label_path, label_key=label_key, roi=roi, stacked=stacked, splits=(split,),
177                    )
178                    if unit.key in units:
179                        previous = units[unit.key]
180                        if split not in previous.splits:
181                            warnings.warn(f"{label_path} ({label_key}, {roi}) is used for training and validation.")
182                            units[unit.key] = Unit(**{**asdict(previous), "splits": previous.splits + (split,)})
183                        continue
184                    units[unit.key] = unit
185                    transforms[unit.key] = (getattr(leaf, "pre_label_transform", None), _label_transform(leaf))
186    return list(units.values()), transforms
187
188
189def _object_ids(labels, pre_label_transform, label_transform):
190    """Return the object ids of a label array after the transforms of the loader."""
191    labels = np.asarray(labels)
192    if pre_label_transform is not None:
193        labels = pre_label_transform(labels)
194    if label_transform is not None:
195        labels = label_transform(labels)
196    ids = np.unique(labels)
197    return ids[(ids > 0) & ~np.isin(ids, NON_OBJECT_IDS)]
198
199
200def _iter_slabs(labels, slices):
201    """Yield the label data of ``slices`` in slabs along the first axis. Each slab fits ``MAX_SLAB_ELEMENTS``."""
202    per_slice = int(np.prod([s.stop - s.start for s in slices[1:]], dtype=np.int64)) if len(slices) > 1 else 1
203    step = max(1, MAX_SLAB_ELEMENTS // max(per_slice, 1))
204    for start in range(slices[0].start, slices[0].stop, step):
205        stop = min(start + step, slices[0].stop)
206        yield np.asarray(labels[(slice(start, stop),) + slices[1:]])
207
208
209def count_unit(unit: Unit, pre_label_transform, label_transform, keep_ids=False) -> UnitCount:
210    """Count the images or volumes and the objects of one unit.
211
212    Args:
213        unit: The label source.
214        pre_label_transform: The ``pre_label_transform`` of the leaf dataset, or None.
215        label_transform: The id-preserving label transform of the leaf dataset, or None.
216        keep_ids: Whether to return the object ids of a volume or image next to their number.
217
218    Returns:
219        The count of the unit.
220    """
221    labels = load_data(unit.label_path, unit.label_key)
222    slices = _roi_to_slices(unit.roi, labels.shape)
223    shape = tuple(s.stop - s.start for s in slices)
224    needs_transform = pre_label_transform is not None or label_transform is not None
225
226    if unit.ndim == 3 or not unit.stacked:
227        # A unit without a transform streams in slabs, so large files fit into memory.
228        if needs_transform:
229            ids = _object_ids(labels[slices], pre_label_transform, label_transform)
230        else:
231            ids = np.unique(np.concatenate([_object_ids(slab, None, None) for slab in _iter_slabs(labels, slices)]))
232        return UnitCount(n_images=1, n_objects=len(ids), shape=shape, ids=ids.tolist() if keep_ids else None)
233
234    if len(shape) != 3:
235        raise ValueError(
236            f"The stacked source {unit.label_path}, {unit.label_key} has the shape {shape}. "
237            "Expected the shape (frames, height, width)."
238        )
239
240    # Every entry of the first axis of a stack is one image.
241    n_objects = 0
242    for slab in _iter_slabs(labels, slices):
243        n_objects += sum(len(_object_ids(frame, pre_label_transform, label_transform)) for frame in slab)
244    return UnitCount(n_images=shape[0], n_objects=n_objects, shape=shape)
245
246
247def _file_key(unit):
248    """Return the key that the units of one label file and key share, such as the train and val slabs of a volume."""
249    return (unit.label_path, unit.label_key, unit.stacked)
250
251
252def _count_units(units, transforms, n_workers, cache):
253    """Count all units in parallel and reuse the cached results."""
254    units_per_file = defaultdict(int)
255    for unit in units:
256        units_per_file[_file_key(unit)] += 1
257
258    results = {}
259    pending = []
260    for unit in units:
261        keep_ids = not unit.stacked and units_per_file[_file_key(unit)] > 1
262        cache_key = json.dumps([unit.label_path, unit.label_key, unit.roi, unit.ndim, unit.stacked])
263        if cache_key in cache and (cache[cache_key].get("ids") is not None or not keep_ids):
264            results[unit.key] = UnitCount(**cache[cache_key])
265        else:
266            pending.append((unit, cache_key, keep_ids))
267
268    if pending:
269        with ProcessPoolExecutor(max_workers=n_workers) as pool:
270            futures = {
271                pool.submit(count_unit, unit, *transforms[unit.key], keep_ids=keep_ids): (unit, cache_key)
272                for unit, cache_key, keep_ids in pending
273            }
274            for future in tqdm(as_completed(futures), total=len(futures), desc="Count the label sources"):
275                unit, cache_key = futures[future]
276                count = future.result()
277                results[unit.key] = count
278                cache[cache_key] = asdict(count)
279    return results
280
281
282def _load_cache(path):
283    """Load the JSON cache of the counts per label source. A missing cache is empty."""
284    if path is None or not os.path.exists(path):
285        return {}
286    with open(path) as f:
287        return json.load(f)
288
289
290def _save_cache(path, cache):
291    """Write the cache to a temporary file, then move it into place, so an interrupted write leaves no partial cache."""
292    if path is None:
293        return
294    tmp_path = f"{path}.tmp{os.getpid()}"
295    with open(tmp_path, "w") as f:
296        json.dump(cache, f)
297    os.replace(tmp_path, path)
298
299
300def summarize(units: List[Unit], counts: Dict[tuple, UnitCount]):
301    """Sum the unit counts per (domain, ndim) and per (domain, ndim, dataset).
302
303    Args:
304        units: The label sources.
305        counts: The count of each unit, keyed by the unit key.
306
307    Returns:
308        The summary rows and the per-dataset rows. Each is a list of dicts.
309    """
310    per_dataset = defaultdict(
311        lambda: {"n_units": 0, "n_train_units": 0, "n_val_units": 0, "n_images": 0, "n_objects": 0}
312    )
313    # The units of one file and key are the regions of interest of one volume: their ids are joined.
314    ids_per_file = defaultdict(set)
315    for unit in units:
316        count = counts[unit.key]
317        if count.ids is not None:
318            ids_per_file[_file_key(unit)].update(count.ids)
319
320    # An image with several label targets, such as the Xenium nuclei and cells, is one image. Its objects add up.
321    seen_images, seen_files = set(), set()
322    for unit in units:
323        row = per_dataset[(unit.domain, unit.ndim, unit.dataset)]
324        count = counts[unit.key]
325        row["n_units"] += 1
326        row["n_train_units"] += "train" in unit.splits
327        row["n_val_units"] += "val" in unit.splits
328        file_key = _file_key(unit)
329        if file_key in ids_per_file:
330            if file_key not in seen_files:
331                seen_files.add(file_key)
332                row["n_objects"] += len(ids_per_file[file_key])
333        else:
334            row["n_objects"] += count.n_objects
335        image_key = (unit.label_path, unit.roi if unit.stacked else None)
336        if image_key not in seen_images:
337            seen_images.add(image_key)
338            row["n_images"] += count.n_images
339
340    dataset_rows = []
341    summary = defaultdict(lambda: {"datasets": [], "n_images": 0, "n_objects": 0})
342    for (domain, ndim, dataset), row in sorted(per_dataset.items()):
343        dataset_rows.append({"domain": domain, "ndim": ndim, "dataset": dataset, **row})
344        agg = summary[(domain, ndim)]
345        agg["datasets"].append(dataset)
346        agg["n_images"] += row["n_images"]
347        agg["n_objects"] += row["n_objects"]
348
349    summary_rows = []
350    for (domain, ndim), agg in sorted(summary.items()):
351        summary_rows.append({
352            "domain": domain, "ndim": ndim, "n_datasets": len(agg["datasets"]),
353            "n_images_or_volumes": agg["n_images"], "n_objects": agg["n_objects"],
354            "datasets": ";".join(agg["datasets"]),
355        })
356    return summary_rows, dataset_rows
357
358
359def _write_csv(path, rows):
360    """Write the rows to a CSV file with the keys of the first row as header."""
361    with open(path, "w", newline="") as f:
362        writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
363        writer.writeheader()
364        writer.writerows(rows)
365
366
367def _print_summary(summary_rows):
368    """Print one sentence per (domain, ndim) row."""
369    unit_name = {2: "images", 3: "volumes"}
370    for row in summary_rows:
371        print(
372            f"{row['n_objects']:,} objects in {row['n_images_or_volumes']:,} {DOMAIN_NAMES[row['domain']]} "
373            f"({row['ndim']}d) {unit_name[row['ndim']]} from {row['n_datasets']} datasets"
374        )
375
376
377def run(input_path, domains, n_workers, output_prefix, per_dataset, cache_path):
378    """Build, count and summarize the training data of the requested domains.
379
380    Args:
381        input_path: The root path of the training data.
382        domains: The domains to count, a subset of ``"lm"``, ``"em"`` and ``"hp"``.
383        n_workers: The number of processes that count label sources in parallel.
384        output_prefix: The prefix of the CSV files in the current directory.
385        per_dataset: Whether to also write the breakdown per dataset.
386        cache_path: The path of the JSON cache of the counts per label source, or None to disable the cache.
387    """
388    units, transforms = [], {}
389    for domain in domains:
390        domain_units, domain_transforms = build_units(domain, input_path)
391        print(f"{domain}: {len(domain_units)} label sources from {len({u.dataset for u in domain_units})} datasets")
392        units.extend(domain_units)
393        transforms.update(domain_transforms)
394
395    cache = _load_cache(cache_path)
396    try:
397        counts = _count_units(units, transforms, n_workers, cache)
398    finally:
399        _save_cache(cache_path, cache)
400
401    summary_rows, dataset_rows = summarize(units, counts)
402    _write_csv(f"{output_prefix}.csv", summary_rows)
403    print(f"Wrote {output_prefix}.csv")
404    if per_dataset:
405        _write_csv(f"{output_prefix}_per_dataset.csv", dataset_rows)
406        print(f"Wrote {output_prefix}_per_dataset.csv")
407    _print_summary(summary_rows)
408
409
410def main():
411    parser = argparse.ArgumentParser(description="Count the generalist training data (train + val).")
412    parser.add_argument("--input_path", default=DEFAULT_INPUT_PATH, help="The root path of the training data.")
413    parser.add_argument("--domains", nargs="+", default=DEFAULT_DOMAINS, choices=list(DOMAIN_BUILDERS))
414    parser.add_argument("--n_workers", type=int, default=len(os.sched_getaffinity(0)), help="The number of processes.")
415    parser.add_argument("--output_prefix", default="generalist_data_counts", help="The prefix of the CSV files.")
416    parser.add_argument("--per_dataset", action="store_true", help="Also write the breakdown per dataset.")
417    parser.add_argument(
418        "--cache_path", default="generalist_data_counts_cache.json",
419        help="The JSON cache of the counts per label source. Pass '' to disable it."
420    )
421    args = parser.parse_args()
422    run(
423        args.input_path, args.domains, args.n_workers, args.output_prefix, args.per_dataset,
424        args.cache_path or None,
425    )
426
427
428if __name__ == "__main__":
429    main()
DEFAULT_INPUT_PATH = '/mnt/vast-nhr/projects/cidas/cca/data'
DOMAIN_BUILDERS = {'lm': <function _get_lm_datasets>, 'em': <function _get_em_datasets>, 'hp': <function _get_hp_datasets>, 'em_mito': <function _get_em_mito_datasets>, 'em_nucleus': <function _get_em_nucleus_datasets>}
DOMAIN_NAMES = {'lm': 'light microscopy', 'em': 'electron microscopy', 'hp': 'histopathology', 'em_mito': 'electron microscopy mitochondria', 'em_nucleus': 'electron microscopy nuclei'}
DEFAULT_DOMAINS = ['lm', 'em', 'hp']
NON_OBJECT_IDS = (0, 16777215)
MAX_SLAB_ELEMENTS = 67108864
@dataclass(frozen=True)
class Unit:
80@dataclass(frozen=True)
81class Unit:
82    """One label source of the training data."""
83    domain: str
84    dataset: str
85    ndim: int
86    label_path: str
87    label_key: Optional[str]
88    roi: Optional[Tuple[Tuple[Optional[int], Optional[int]], ...]]
89    # A 2D source with the patch shape (1, H, W) is a stack. Its first axis holds the frames or tiles.
90    stacked: bool
91    splits: Tuple[str, ...]
92
93    @property
94    def key(self):
95        return (self.label_path, self.label_key, self.roi, self.stacked)

One label source of the training data.

Unit( domain: str, dataset: str, ndim: int, label_path: str, label_key: Optional[str], roi: Optional[Tuple[Tuple[Optional[int], Optional[int]], ...]], stacked: bool, splits: Tuple[str, ...])
domain: str
dataset: str
ndim: int
label_path: str
label_key: Optional[str]
roi: Optional[Tuple[Tuple[Optional[int], Optional[int]], ...]]
stacked: bool
splits: Tuple[str, ...]
key
93    @property
94    def key(self):
95        return (self.label_path, self.label_key, self.roi, self.stacked)
@dataclass
class UnitCount:
 98@dataclass
 99class UnitCount:
100    """The counting result of one unit. ``ids`` holds the object ids of a unit that shares its file with others."""
101    n_images: int
102    n_objects: int
103    shape: Tuple[int, ...]
104    ids: Optional[List[int]] = None

The counting result of one unit. ids holds the object ids of a unit that shares its file with others.

UnitCount( n_images: int, n_objects: int, shape: Tuple[int, ...], ids: Optional[List[int]] = None)
n_images: int
n_objects: int
shape: Tuple[int, ...]
ids: Optional[List[int]] = None
def build_units(domain, input_path):
144def build_units(domain, input_path):
145    """Build the datasets of one domain in the same way as the training and collect their label sources.
146
147    Args:
148        domain: The domain, one of ``"lm"``, ``"em"``, ``"hp"``, ``"em_mito"`` or ``"em_nucleus"``.
149        input_path: The root path of the training data.
150
151    Returns:
152        The units, deduplicated over train and val, and the label transforms of each unit
153        (``pre_label_transform``, ``label_transform2``) keyed by the unit key.
154    """
155    kwargs = {
156        "raw_transform": _identity,
157        "sampler": MinInstanceSampler(min_num_instances=3, exclude_ids=[0]),
158        "label_dtype": torch.int64,
159        "label_transform2": None,
160    }
161    train_ds, val_ds = DOMAIN_BUILDERS[domain](input_path, (512, 512), [8], kwargs, None)
162
163    units: Dict[tuple, Unit] = {}
164    transforms: Dict[tuple, Tuple[Optional[Callable], Optional[Callable]]] = {}
165    for split, wrappers in [("train", train_ds), ("val", val_ds)]:
166        for wrapper in wrappers:
167            for leaf in _leaves(wrapper.ds):
168                if hasattr(leaf, "label_images"):
169                    sources = [(p, None, None) for p in leaf.label_images]
170                    stacked = False
171                else:
172                    sources = [(leaf.label_path, leaf.label_key, _roi_to_tuple(leaf.roi))]
173                    stacked = wrapper.source_ndim == 2 and len(leaf.patch_shape) == 3
174                for label_path, label_key, roi in sources:
175                    unit = Unit(
176                        domain=domain, dataset=_dataset_name(label_path, input_path), ndim=wrapper.source_ndim,
177                        label_path=label_path, label_key=label_key, roi=roi, stacked=stacked, splits=(split,),
178                    )
179                    if unit.key in units:
180                        previous = units[unit.key]
181                        if split not in previous.splits:
182                            warnings.warn(f"{label_path} ({label_key}, {roi}) is used for training and validation.")
183                            units[unit.key] = Unit(**{**asdict(previous), "splits": previous.splits + (split,)})
184                        continue
185                    units[unit.key] = unit
186                    transforms[unit.key] = (getattr(leaf, "pre_label_transform", None), _label_transform(leaf))
187    return list(units.values()), transforms

Build the datasets of one domain in the same way as the training and collect their label sources.

Arguments:
  • domain: The domain, one of "lm", "em", "hp", "em_mito" or "em_nucleus".
  • input_path: The root path of the training data.
Returns:

The units, deduplicated over train and val, and the label transforms of each unit (pre_label_transform, label_transform2) keyed by the unit key.

def count_unit( unit: Unit, pre_label_transform, label_transform, keep_ids=False) -> UnitCount:
210def count_unit(unit: Unit, pre_label_transform, label_transform, keep_ids=False) -> UnitCount:
211    """Count the images or volumes and the objects of one unit.
212
213    Args:
214        unit: The label source.
215        pre_label_transform: The ``pre_label_transform`` of the leaf dataset, or None.
216        label_transform: The id-preserving label transform of the leaf dataset, or None.
217        keep_ids: Whether to return the object ids of a volume or image next to their number.
218
219    Returns:
220        The count of the unit.
221    """
222    labels = load_data(unit.label_path, unit.label_key)
223    slices = _roi_to_slices(unit.roi, labels.shape)
224    shape = tuple(s.stop - s.start for s in slices)
225    needs_transform = pre_label_transform is not None or label_transform is not None
226
227    if unit.ndim == 3 or not unit.stacked:
228        # A unit without a transform streams in slabs, so large files fit into memory.
229        if needs_transform:
230            ids = _object_ids(labels[slices], pre_label_transform, label_transform)
231        else:
232            ids = np.unique(np.concatenate([_object_ids(slab, None, None) for slab in _iter_slabs(labels, slices)]))
233        return UnitCount(n_images=1, n_objects=len(ids), shape=shape, ids=ids.tolist() if keep_ids else None)
234
235    if len(shape) != 3:
236        raise ValueError(
237            f"The stacked source {unit.label_path}, {unit.label_key} has the shape {shape}. "
238            "Expected the shape (frames, height, width)."
239        )
240
241    # Every entry of the first axis of a stack is one image.
242    n_objects = 0
243    for slab in _iter_slabs(labels, slices):
244        n_objects += sum(len(_object_ids(frame, pre_label_transform, label_transform)) for frame in slab)
245    return UnitCount(n_images=shape[0], n_objects=n_objects, shape=shape)

Count the images or volumes and the objects of one unit.

Arguments:
  • unit: The label source.
  • pre_label_transform: The pre_label_transform of the leaf dataset, or None.
  • label_transform: The id-preserving label transform of the leaf dataset, or None.
  • keep_ids: Whether to return the object ids of a volume or image next to their number.
Returns:

The count of the unit.

def summarize( units: List[Unit], counts: Dict[tuple, UnitCount]):
301def summarize(units: List[Unit], counts: Dict[tuple, UnitCount]):
302    """Sum the unit counts per (domain, ndim) and per (domain, ndim, dataset).
303
304    Args:
305        units: The label sources.
306        counts: The count of each unit, keyed by the unit key.
307
308    Returns:
309        The summary rows and the per-dataset rows. Each is a list of dicts.
310    """
311    per_dataset = defaultdict(
312        lambda: {"n_units": 0, "n_train_units": 0, "n_val_units": 0, "n_images": 0, "n_objects": 0}
313    )
314    # The units of one file and key are the regions of interest of one volume: their ids are joined.
315    ids_per_file = defaultdict(set)
316    for unit in units:
317        count = counts[unit.key]
318        if count.ids is not None:
319            ids_per_file[_file_key(unit)].update(count.ids)
320
321    # An image with several label targets, such as the Xenium nuclei and cells, is one image. Its objects add up.
322    seen_images, seen_files = set(), set()
323    for unit in units:
324        row = per_dataset[(unit.domain, unit.ndim, unit.dataset)]
325        count = counts[unit.key]
326        row["n_units"] += 1
327        row["n_train_units"] += "train" in unit.splits
328        row["n_val_units"] += "val" in unit.splits
329        file_key = _file_key(unit)
330        if file_key in ids_per_file:
331            if file_key not in seen_files:
332                seen_files.add(file_key)
333                row["n_objects"] += len(ids_per_file[file_key])
334        else:
335            row["n_objects"] += count.n_objects
336        image_key = (unit.label_path, unit.roi if unit.stacked else None)
337        if image_key not in seen_images:
338            seen_images.add(image_key)
339            row["n_images"] += count.n_images
340
341    dataset_rows = []
342    summary = defaultdict(lambda: {"datasets": [], "n_images": 0, "n_objects": 0})
343    for (domain, ndim, dataset), row in sorted(per_dataset.items()):
344        dataset_rows.append({"domain": domain, "ndim": ndim, "dataset": dataset, **row})
345        agg = summary[(domain, ndim)]
346        agg["datasets"].append(dataset)
347        agg["n_images"] += row["n_images"]
348        agg["n_objects"] += row["n_objects"]
349
350    summary_rows = []
351    for (domain, ndim), agg in sorted(summary.items()):
352        summary_rows.append({
353            "domain": domain, "ndim": ndim, "n_datasets": len(agg["datasets"]),
354            "n_images_or_volumes": agg["n_images"], "n_objects": agg["n_objects"],
355            "datasets": ";".join(agg["datasets"]),
356        })
357    return summary_rows, dataset_rows

Sum the unit counts per (domain, ndim) and per (domain, ndim, dataset).

Arguments:
  • units: The label sources.
  • counts: The count of each unit, keyed by the unit key.
Returns:

The summary rows and the per-dataset rows. Each is a list of dicts.

def run( input_path, domains, n_workers, output_prefix, per_dataset, cache_path):
378def run(input_path, domains, n_workers, output_prefix, per_dataset, cache_path):
379    """Build, count and summarize the training data of the requested domains.
380
381    Args:
382        input_path: The root path of the training data.
383        domains: The domains to count, a subset of ``"lm"``, ``"em"`` and ``"hp"``.
384        n_workers: The number of processes that count label sources in parallel.
385        output_prefix: The prefix of the CSV files in the current directory.
386        per_dataset: Whether to also write the breakdown per dataset.
387        cache_path: The path of the JSON cache of the counts per label source, or None to disable the cache.
388    """
389    units, transforms = [], {}
390    for domain in domains:
391        domain_units, domain_transforms = build_units(domain, input_path)
392        print(f"{domain}: {len(domain_units)} label sources from {len({u.dataset for u in domain_units})} datasets")
393        units.extend(domain_units)
394        transforms.update(domain_transforms)
395
396    cache = _load_cache(cache_path)
397    try:
398        counts = _count_units(units, transforms, n_workers, cache)
399    finally:
400        _save_cache(cache_path, cache)
401
402    summary_rows, dataset_rows = summarize(units, counts)
403    _write_csv(f"{output_prefix}.csv", summary_rows)
404    print(f"Wrote {output_prefix}.csv")
405    if per_dataset:
406        _write_csv(f"{output_prefix}_per_dataset.csv", dataset_rows)
407        print(f"Wrote {output_prefix}_per_dataset.csv")
408    _print_summary(summary_rows)

Build, count and summarize the training data of the requested domains.

Arguments:
  • input_path: The root path of the training data.
  • domains: The domains to count, a subset of "lm", "em" and "hp".
  • n_workers: The number of processes that count label sources in parallel.
  • output_prefix: The prefix of the CSV files in the current directory.
  • per_dataset: Whether to also write the breakdown per dataset.
  • cache_path: The path of the JSON cache of the counts per label source, or None to disable the cache.
def main():
411def main():
412    parser = argparse.ArgumentParser(description="Count the generalist training data (train + val).")
413    parser.add_argument("--input_path", default=DEFAULT_INPUT_PATH, help="The root path of the training data.")
414    parser.add_argument("--domains", nargs="+", default=DEFAULT_DOMAINS, choices=list(DOMAIN_BUILDERS))
415    parser.add_argument("--n_workers", type=int, default=len(os.sched_getaffinity(0)), help="The number of processes.")
416    parser.add_argument("--output_prefix", default="generalist_data_counts", help="The prefix of the CSV files.")
417    parser.add_argument("--per_dataset", action="store_true", help="Also write the breakdown per dataset.")
418    parser.add_argument(
419        "--cache_path", default="generalist_data_counts_cache.json",
420        help="The JSON cache of the counts per label source. Pass '' to disable it."
421    )
422    args = parser.parse_args()
423    run(
424        args.input_path, args.domains, args.n_workers, args.output_prefix, args.per_dataset,
425        args.cache_path or None,
426    )