"""Morfeus lab
The University of Texas
MD Anderson Cancer Center
Author - Caleb O'Connor
Email - csoconnor@mdanderson.org
Data Management Module for Medical Imaging and Transformations
==============================================================
Description:
This module provides a centralized, global state container for medical
imaging data, including volumetric images, dose distributions, and
spatial transformations (rigid and deformable).
`Data` holds the state (registries, id providers, counters) and
inherits its methods from one file per topic, so every method is
called as ``Data.<method>``. The file map is in the package docstring
(``data/__init__.py``).
Stored Data:
* Images (CT, MR, PT, US, XRay, MHD, NIfTI, ...)
* Rigid registrations
* Deformable registrations (DVFs)
* Dose distributions (RTDOSE)
* ROIs, POIs, markups, planes, models and groups (kept on their images)
Id Note:
Without help, new ids come from counters (1, 2, 3, ...) that only go
up, so a deleted ROI's number is not reused in the session.
The package doesn't know the application's database or numbering
convention, so the application decides ids in one of two ways:
* **Provider (recommended):** set `Data.roi_id_provider` (and
`volume_id_provider`, `poi_id_provider`, `rigid_id_provider`,
`deformable_id_provider`, `moi_id_provider`, `planeoi_id_provider`,
`model_id_provider`, `group_id_provider`) to a function `provider(name, item)` that
returns the database id: the existing one when the name / series is
already known, otherwise a newly created one. Returning None falls back
to the counter. Every new ROI anywhere (RTSTRUCT, mask, drawing,
match_rois) goes through it, once per name.
* **Re-key afterwards:** `Data.change_roi_id`, `change_poi_id` and
`change_volume_id` move an item to the database's id and update every
image, Rigid and Deformable that stores the old one.
Architecture Note:
The module utilizes a Singleton-style pattern via class-level attributes
in the `Data` class. Data loaded in one part of the application (e.g. a
reader) is immediately available to other components (e.g. a
visualization or registration module).
Warning:
Because this class uses global state, calling `Data.clear()` will affect
all modules currently importing this class.
Usage:
>>> import medicalimageanalysis as mia
>>> from medicalimageanalysis import Data
>>> # Load a patient
>>> mia.read_dicoms(folder_path='C:/Data/Patient01')
>>> # Inspect what was loaded
>>> Data.image_list()
Examples
--------
>>> import medicalimageanalysis as mia
>>> from medicalimageanalysis import Data
>>> Data.clear()
>>> Data.image_list()
[]
>>> mia.read_dicoms(folder_path='C:/Data/Patient01')
>>> Data.image_list()
['CT 01', 'MR 01']
>>> ct = Data.image['CT 01']
>>> list(ct.roi.keys())
['Liver', 'GTV']
>>> Data.get_roi_id('Liver')
1
>>> Data.rename_roi('Liver', 'Liver_Whole')
>>> ct.roi[1].name
'Liver_Whole'
"""
import weakref
from ..registry import Registry
from .annotations import AnnotationData
from .group_status import GroupStatusData
from .groups import GroupData
from .markups import MarkupData
from .registrations import RegistrationData
from .volumes import VolumeData
[docs]
class Data(VolumeData, AnnotationData, MarkupData, RegistrationData, GroupData, GroupStatusData):
"""
Global orchestrator for medical imaging data and transformations.
This class acts as a centralized, static repository (Singleton pattern)
for managing volumetric data, spatial transformations, and clinical
annotations. Because data is stored at the class level, all
modifications are reflected globally across the application.
Every attribute is a `Registry`: look entries up by permanent id (int)
or user name (str). Iterating and `keys()` give names, like the plain
dictionaries they replace; `ids()` gives the permanent ids.
Attributes
----------
image : Registry
Images; the name is mirrored onto `image.image_name`.
rigid : Registry
Rigid registration objects; the name is mirrored onto
`rigid.rigid_name`.
deformable : Registry
Deformable registration objects; the name is mirrored onto
`deformable.deformable_name`.
dose : Registry
Dose distribution objects; the name is mirrored onto
`dose.image_name`. Image and dose ids share one counter, so a
volume id is unique across both.
roi_next_id, poi_next_id : int
Fallback counters for new ROI / POI ids (no provider). ROIs and POIs
themselves live only on images (``image.roi`` / ``image.poi``).
moi_next_id, planeoi_next_id, model_next_id, group_next_id : int
Fallback counters for new markup / plane / model / group ids (no provider). They themselves live only on
images (``image.moi`` / ``image.planeoi`` / ``image.model`` / ``image.roi_group``, ...).
GROUP_KINDS : tuple of str
Kinds of item a group can hold; each image has a container ``image.<kind>_group`` for each.
Examples
--------
Access the registry from any module without passing objects around:
>>> import medicalimageanalysis as mia
>>> from medicalimageanalysis import Data
>>> mia.read_dicoms(folder_path='C:/Data/Patient01')
>>> Data.image_list()
['CT 01', 'MR 01']
Grab an image by name or by id (always z-y-x):
>>> ct = Data.image['CT 01']
>>> ct is Data.image[ct.id]
True
>>> ct.array.shape
(142, 512, 512)
The same ROI id on every image:
>>> Data.image['CT 01'].roi['GTV'].id == Data.image['MR 01'].roi['GTV'].id
True
"""
# Id providers: functions the application sets so new ids come from its database instead of the counters. Each
# is called as provider(name, item) and returns an int, or None to fall back to the counter. Not reset by clear().
volume_id_provider = None # images and doses; item is the Image / Dose (series_uid, mrn, frame_ref, ...)
roi_id_provider = None # item is None: an ROI's identity is its name
poi_id_provider = None # item is None
rigid_id_provider = None # item is the Rigid
deformable_id_provider = None # item is the Deformable
moi_id_provider = None # item is the Moi (its image, kind, ... are set)
planeoi_id_provider = None # item is the PlaneOI
model_id_provider = None # item is the Model (its image, roi_ids, recipe are set)
group_id_provider = None # item is the Group (its kind, name, parent_id are set); name is its path
# Kinds of item a group can hold: each image has a container '<kind>_group' for each
GROUP_KINDS = ('roi', 'poi', 'moi', 'planeoi', 'model')
# Fallback counters for new ROI / POI ids when there is no provider (or it returns None). They only go up, so a
# number is never handed out twice in a session. Reset by clear().
roi_next_id = 1
poi_next_id = 1
moi_next_id = 1
planeoi_next_id = 1
model_next_id = 1
group_next_id = 1
# Registries, built by clear() (run once at import, below the class). Images and doses draw ids from one counter,
# so a volume id is unique across both and Data.volume(id) is never ambiguous.
image = None
rigid = None
deformable = None
dose = None
# Fingerprints of item geometry / registrations for group_status, kept until the object they were taken from is
# replaced (contours, mesh, DVF, ...). Weak keys, so a deleted item drops its entry.
_key_cache = weakref.WeakKeyDictionary()
# ---- Registry ----
@staticmethod
def _provided_id(provider, name, item):
"""The provider's id for a new item, or None (counter) when there is no provider or it returns None.
Examples
--------
>>> from medicalimageanalysis import Data
>>> Data._provided_id(None, 'Liver', None) is None # no provider: the counter decides
True
>>> Data._provided_id(lambda name, item: 1042, 'Liver', None) # the database's id
1042
>>> Data._provided_id(lambda name, item: None, 'Kidney', None) is None # provider has none: the counter
True
"""
if provider is None:
return None
return provider(name, item)
[docs]
@classmethod
def clear(cls) -> None:
"""
Wipe all data from the global registry.
Performs a full reset of the class-level storage, clearing the
current session's images (with their groups), registrations, dose
objects and ROI/POI/MOI/PlaneOI/Model/group ids. Ids start again at 1. This action is
non-reversible and affects every module importing `Data`.
Returns
-------
None
Examples
--------
Reset the session before loading a new patient:
>>> import medicalimageanalysis as mia
>>> from medicalimageanalysis import Data
>>> mia.read_dicoms(folder_path='C:/Data/Patient01')
>>> Data.image_list()
['CT 01', 'MR 01']
>>> Data.clear()
>>> Data.image_list()
[]
Every registry is emptied, not just images:
>>> Data.clear()
>>> Data.rigid_list(), Data.deformable_list(), Data.dose_list(), Data.roi_list()
([], [], [], [])
"""
# Replace (not mutate) each registry so old references are released. The id providers are kept.
cls.image = Registry(name_attribute='image_name', id_source=cls.new_volume_id)
cls.dose = Registry(name_attribute='image_name', id_source=cls.new_volume_id)
cls.rigid = Registry(name_attribute='rigid_name',
id_source=lambda name, item: cls._provided_id(cls.rigid_id_provider, name, item))
cls.deformable = Registry(name_attribute='deformable_name',
id_source=lambda name, item: cls._provided_id(cls.deformable_id_provider, name, item))
cls.roi_next_id = 1
cls.poi_next_id = 1
cls.moi_next_id = 1
cls.planeoi_next_id = 1
cls.model_next_id = 1
cls.group_next_id = 1
cls._key_cache = weakref.WeakKeyDictionary()
[docs]
@classmethod
def delete(cls, name, registry: str | None = None) -> None:
"""
Remove an image, dose, rigid or deformable registration from the registry.
Registrations are not removed with their images: Rigid and Deformable keep their frames of reference (and
Deformable its meshes), so they keep working when the image is loaded again. Use `delete_roi` / `delete_poi`
for ROIs and POIs.
Parameters
----------
name : str | int
User name or permanent id of the entry to delete. An id needs `registry`, since ids are only unique
within one registry.
registry : {'image', 'dose', 'rigid', 'deformable'}, optional
Registry to delete from. None searches all four by name; the name must then be in exactly one.
Returns
-------
None
Raises
------
KeyError
If `name` is not in the registry (or in any registry when `registry` is None).
ValueError
If `registry` is not a known registry, `registry` is None and `name` is in more than one, or `name` is
an id and `registry` is None.
Examples
--------
Remove a dose, a rigid and a deformable registration:
>>> import medicalimageanalysis as mia
>>> from medicalimageanalysis import Data
>>> Data.delete('Dose_0')
>>> Data.delete('CT 01_MR 01', registry='rigid')
>>> Data.delete('DVF_CT 01_CBCT 01')
Remove an image by id while keeping the rest of the session:
>>> Data.delete(Data.image.get_id('MR 01'), registry='image')
>>> Data.image_list()
['CT 01']
"""
registries = {'image': cls.image, 'dose': cls.dose, 'rigid': cls.rigid, 'deformable': cls.deformable}
if registry is not None:
if registry not in registries:
raise ValueError(f"registry must be one of {list(registries)}; got {registry!r}")
del registries[registry][name]
return
if not isinstance(name, str):
raise ValueError(f"Deleting by id ({name!r}) needs registry=, ids are only unique within one registry.")
found = [key for key, entries in registries.items() if name in entries]
if not found:
raise KeyError(f"'{name}' is not in any registry.")
if len(found) > 1:
raise ValueError(f"'{name}' is in {found}; pass registry= to choose one.")
del registries[found[0]][name]
# Build the registries once at import
Data.clear()