Skip to content

Sample output

sample_output #

AnnotatedPathSequence #

AnnotatedPathSequence(
    paths: typing.List[pathlib.Path],
    errors: (
        typing.List[
            imgtools.io.sample_output.FailedToSaveSingleImageError
        ]
        | None
    ) = None,
)

Bases: list

Custom sequence of paths that behaves like a list but includes an errors attribute.

This class is returned by SampleOutput.call to allow access to any errors that occurred during the save process while still behaving like a regular sequence of paths.

Attributes:

Name Type Description
errors typing.List[imgtools.io.sample_output.FailedToSaveSingleImageError]

List of errors that occurred during the save process.

Parameters:

Name Type Description Default

paths #

typing.List[pathlib.Path]

List of paths to saved files.

required

errors #

typing.List[imgtools.io.sample_output.FailedToSaveSingleImageError]

List of errors that occurred during the save process.

None
Source code in src/imgtools/io/sample_output.py
def __init__(
    self,
    paths: List[Path],
    errors: List[FailedToSaveSingleImageError] | None = None,
) -> None:
    """
    Initialize the annotated path sequence.

    Parameters
    ----------
    paths : List[Path]
        List of paths to saved files.
    errors : List[FailedToSaveSingleImageError], optional
        List of errors that occurred during the save process.
    """
    super().__init__(paths)
    self.errors = errors or []

FailedToSaveSingleImageError #

FailedToSaveSingleImageError(
    message: str, image: imgtools.coretypes.MedImage
)

Bases: Exception

Exception raised when a single image fails to save.

Source code in src/imgtools/io/sample_output.py
def __init__(self, message: str, image: MedImage) -> None:
    super().__init__(message)
    self.image = image

SampleOutput #

Bases: pydantic.BaseModel

Configuration model for saving medical imaging outputs.

This class provides a standardized configuration for saving medical images, supporting various file formats and output organization strategies.

Attributes:

Name Type Description
directory pathlib.Path

Directory where output files will be saved. Must exist and be writable.

filename_format str

Format string for output filenames with placeholders for metadata values.

existing_file_mode imgtools.io.writers.ExistingFileMode

How to handle existing files (FAIL, SKIP, OVERWRITE).

extra_context typing.Dict[str, typing.Any]

Additional metadata to include when saving files.

Examples:

>>> from imgtools.io import SampleOutput
>>> from imgtools.io.writers import ExistingFileMode
>>> output = SampleOutput(
...     directory="results/patient_scans",
...     filename_format="{PatientID}/{Modality}/{ImageID}.nii.gz",
...     existing_file_mode=ExistingFileMode.SKIP,
... )
>>> output(scan_list)  # Save all scans in the list

Methods:

Name Description
default

Create a default instance of SampleOutput.

model_post_init

Initialize the writer after model initialization.

validate_directory

Validate that the output directory exists or can be created, and is writable.

writer property #

writer: imgtools.io.writers.AbstractBaseWriter

Get the writer instance.

default classmethod #

Create a default instance of SampleOutput.

Source code in src/imgtools/io/sample_output.py
@classmethod
def default(cls) -> SampleOutput:
    """Create a default instance of SampleOutput."""
    return cls(
        directory=Path("output"),
        filename_format=DEFAULT_FILENAME_FORMAT,
        existing_file_mode=ExistingFileMode.FAIL,
        extra_context={},
    )

model_post_init #

model_post_init(__context) -> None

Initialize the writer after model initialization.

Source code in src/imgtools/io/sample_output.py
def model_post_init(self, __context) -> None:  # type: ignore # noqa: ANN001
    """Initialize the writer after model initialization."""
    self._writer = NIFTIWriter(
        root_directory=self.directory,
        existing_file_mode=self.existing_file_mode,
        filename_format=self.filename_format,
        context=self.extra_context,
    )

validate_directory classmethod #

validate_directory(v: str | pathlib.Path) -> pathlib.Path

Validate that the output directory exists or can be created, and is writable.

Source code in src/imgtools/io/sample_output.py
@field_validator("directory")
@classmethod
def validate_directory(cls, v: str | Path) -> Path:
    """Validate that the output directory exists or can be created, and is writable."""
    return validate_directory(v, create=True)