API

Base classes

The base classes of the formats in the package, which declare the hooks implemented in fileformats-medimage-extras (see Extras).

class fileformats.medimage.MedicalImagingData(*fspaths: Iterable[str | Path] | str | Path | fileformats.core.FileSet, metadata: Dict[str, Any] | None = None, **load_kwargs: Any)[source]

Bases: FileSet

Base class for all medical imaging data including pre-image raw data and associated data

contains_phi: bool | Literal['nested'] = True
deidentify(out_dir: PathLike[str], recipe: Annotated[Any, LoadedMarker(format=FileSet)] | None = None, **kwargs: Any) → Self[source]

Deidentifies the image by stripping any subject-identifying information from the image header. The exact implementation of this method will depend on the specific image format and the type of identifying information that is present. The output files should be named with a new file path(s) that is derived from the metadata, such that it doesn’t contain any subject-identifying information within it.

Implementations are passed a hidden staging directory as out_dir, the contents of which are only moved into the requested directory once they have returned, so they can copy files there and deidentify them in place without any risk of partially deidentified files being left in the output if they fail.

Implementations only need to strip the identifying data – they don’t need to track/report what was changed. Callers that need that (e.g. for re-identification audit trails) can diff metadata before and after calling this method instead, since that works uniformly across formats without extra bookkeeping in each implementation.

Parameters:
  • out_dir (PathLike[str]) – The directory where the deidentified image should be saved

  • recipe (Loaded[FileSet], optional) – A recipe for the deidentification process, loaded from a format that depends on the implementation (e.g. DeidRecipe for DICOM), which may include details on which fields to remove or how to handle certain types of data. Implementations annotate it with Loaded[<recipe format>], or a union of them in order of preference (e.g. Loaded[DeidRecipeX] | Loaded[DeidRecipe], for recipes with and without side-cars), or None if they don’t accept a recipe. Callers can find the formats to load the recipe from with LoadedMarker.all_from_hint(get_type_hints(find_extra_implementation( MedicalImagingData.deidentify, type(image)), include_extras=True)["recipe"]) Formats nested within one another are passed the same recipe, so they need to be able to read a common recipe format.

  • **kwargs (Any) – Additional format-specific keyword arguments (e.g. concurrency options), which implementations that don’t use them should accept and ignore

Returns:

  • Self – A new instance of the image with any subject-identifying information stripped from the image header.

  • Formats whose contains_phi is “nested” are deidentified by

  • deidentify_nested if no implementation is registered for them.

class fileformats.medimage.MedicalImage(*fspaths: Iterable[str | Path] | str | Path | fileformats.core.FileSet, metadata: Dict[str, Any] | None = None, **load_kwargs: Any)[source]

Bases: WithClassifiers, MedicalImagingData

data_array
dims() → Tuple[int, int, int][source]

The dimensions of the image

read_array() → Any[source]

Returns the binary data of the image in a numpy array

vox_sizes() → Tuple[float, float, float][source]

The length of the voxels along each dimension

class fileformats.medimage.DicomCollection(*fspaths: Iterable[str | Path] | str | Path | fileformats.core.FileSet, metadata: Dict[str, Any] | None = None, **load_kwargs: Any)[source]

Bases: MedicalImage, TypedCollection

Base class for collections of DICOM files, which can either be stored within a directory (DicomDir) or presented as a flat list (DicomSeries)

contents
series_number() → str[source]
class fileformats.medimage.DwiEncoding[source]

Bases: object

property b_values: Any

the b-value weighting

property directions: Any

gradient direction and weighting combined into a single Nx4 array

property encodings_array: Any
read_encodings() → Any[source]

Both the gradient direction and weighting combined into a single Nx4 array

Deidentification (extras)

The types that deidentification recipes are loaded into, from fileformats-medimage-extras (see Deidentification).

class fileformats.extras.medimage.deid_recipe.DeidRecipeWithTransforms(deid: str | None = None, transforms: DeidTransformsSpec | Mapping[str, Callable[[Dataset], Any]] | None = None, **kwargs: Any)[source]

Bases: DeidRecipe

A deid.config.DeidRecipe together with the transforms that define the values of the “var:” and “func:” references in the recipe

Parameters:
  • deid (str, optional) – path to the deid recipe file

  • transforms (DeidTransformsSpec or Mapping[str, VariableBuilder], optional) – the loaded transforms, or just the variable builders, keyed by the names of the variables they define

  • **kwargs – passed through to deid.config.DeidRecipe

Raises:

ValueError – if the recipe references variables or functions that aren’t defined

property function_names: set[str]

‘ values anywhere in the recipe (NB: not ‘deid_func:’, which are provided by deid)

Type:

Names of the functions referenced by ‘func

parser(dicom_file: PathLike[str] | str) → DicomParser[source]

Creates a parser to deidentify the given DICOM file with the recipe, with the variables defined by the transforms evaluated against the file

Parameters:

dicom_file (PathLike) – the DICOM file to deidentify

Returns:

the parser, ready to parse() and save()

Return type:

DicomParser

property variables: set[str]

‘ values anywhere in the recipe

Type:

Names of the variables referenced by ‘var

class fileformats.extras.medimage.deid_transforms.DeidTransformsSpec(variables: dict[str, ~typing.Callable[[~pydicom.dataset.Dataset], ~typing.Any]] = <factory>, functions: dict[str, ~typing.Callable[[...], ~typing.Any]] = <factory>, version: str = '0.1', description: str = '')[source]

Bases: object

The loaded transforms

variables

builders for the values of var: references, keyed by variable name, which take the dataset being deidentified

Type:

dict[str, VariableBuilder]

functions

callables for func: references, keyed by function name, with the signature deid calls them with, i.e. (item, value, field, dicom)

Type:

dict[str, DeidFunction]

version

the version of the spec the transforms were written against

Type:

str

description

the description given in the transforms, if any

Type:

str

fileformats.extras.medimage.deid_transforms.load_transforms(spec: Any, salt: bytes | None = None) → DeidTransformsSpec[source]

Compiles parsed YAML transforms into callables

Parameters:
  • spec (Any) – the parsed YAML document

  • salt (bytes, optional) – the key from the salt side-car of the recipe, used by salted hashes

Returns:

the compiled variables and functions

Return type:

DeidTransformsSpec

Raises:

DeidTransformsError – if the transforms aren’t valid, or they use a salted hash but there is no salt

class fileformats.extras.medimage.deid_transforms.DeidTransformsError[source]

Bases: ValueError

Raised when the transforms aren’t valid, with the location of the problem