Skip to content

Nifti writer

nifti_writer #

NIFTIWriter dataclass #

NIFTIWriter(
    root_directory: pathlib.Path = dataclasses.field(),
    filename_format: str = dataclasses.field(),
    create_dirs: bool = True,
    existing_file_mode: imgtools.io.writers.abstract_base_writer.ExistingFileMode = imgtools.io.writers.abstract_base_writer.ExistingFileMode.FAIL,
    sanitize_filenames: bool = True,
    context: typing.Dict[str, typing.Any] = dict(),
    overwrite_index: bool = False,
    absolute_paths_in_index: bool = False,
    index_filename: typing.Optional[str] = None,
    compression_level: int = 9,
    truncate_uids_in_filename: int = 8,
)

Bases: imgtools.io.writers.abstract_base_writer.AbstractBaseWriter[SimpleITK.Image | numpy.ndarray]

Class for managing file writing with customizable paths and filenames for NIFTI files.

This class extends the AbstractBaseWriter to provide specialized functionality for writing NIFTI image files. It supports both SimpleITK Image objects and numpy arrays as input data types.

Attributes:

Name Type Description
compression_level int, default=9

Compression level (0-9). Higher means better compression but slower writing. Value must be between MIN_COMPRESSION_LEVEL (0) and MAX_COMPRESSION_LEVEL (9).

truncate_uids_in_filename int, default=8

Many DICOM files have long UIDs in the filename. If used in the filename format, this will truncate the UID to the last truncate_uids_in_filename characters. A value of 0 means no truncation.

VALID_EXTENSIONS typing.ClassVar[list[str]]

List of valid file extensions for NIFTI files (".nii", ".nii.gz").

MAX_COMPRESSION_LEVEL typing.ClassVar[int]

Maximum allowed compression level (9).

MIN_COMPRESSION_LEVEL typing.ClassVar[int]

Minimum allowed compression level (0).

Inherited Attributes

root_directory : Path Root directory where files will be saved. This directory will be created if it doesn't exist and create_dirs is True. filename_format : str Format string defining the directory and filename structure. Supports placeholders for context variables enclosed in curly braces. Example: '{subject_id}_{date}/{disease}.nii.gz' create_dirs : bool, default=True Creates necessary directories if they don't exist. existing_file_mode : ExistingFileMode, default=ExistingFileMode.FAIL Behavior when a file already exists. Options: OVERWRITE, SKIP, FAIL sanitize_filenames : bool, default=True Replaces illegal characters from filenames with underscores. context : Dict[str, Any], default={} Internal context storage for pre-checking. index_filename : Optional[str], default=None Name of the index file to track saved files. If an absolute path is provided, it will be used as is. If not provided, it will be saved in the root directory with the format of {root_directory.name}_index.csv. overwrite_index : bool, default=False Overwrites the index file if it already exists. absolute_paths_in_index : bool, default=False If True, saves absolute paths in the index file. If False, saves paths relative to the root directory. pattern_resolver : PatternResolver Instance used to handle filename formatting with placeholders.

Notes

When using this class, ensure your filename_format ends with one of the VALID_EXTENSIONS. The class validates the compression level and filename format during initialization.

Methods:

Name Description
add_to_index

Add or update an entry in the shared CSV index file using IndexWriter.

clear_context

Clear the context for the writer.

preview_path

Pre-checking file existence and setting up the writer context.

resolve_path

Generate a file path based on the filename format, subject ID, and

save

Abstract method for writing data. Must be implemented by subclasses.

set_context

Set the context for the writer.

index_file property #

index_file: pathlib.Path

Get the path to the index CSV file.

add_to_index #

add_to_index(
    path: pathlib.Path,
    include_all_context: bool = True,
    filepath_column: str = "path",
    replace_existing: bool = False,
    merge_columns: bool = True,
) -> None

Add or update an entry in the shared CSV index file using IndexWriter.

What It Does:

  • Logs the file's path and associated context variables to a shared CSV index file.
  • Uses IndexWriter to safely handle concurrent writes and schema evolution.

When to Use It:

  • Use this method to maintain a centralized record of saved files for auditing or debugging.
Relevant Writer Parameters
  • The index_filename parameter allows you to specify a custom filename for the index file. By default, it will be named after the root_directory with _index.csv appended.

  • If the index file already exists in the root directory, it will overwrite it unless the overwrite_index parameter is set to False.

  • The absolute_paths_in_index parameter controls whether the paths in the index file are absolute or relative to the root_directory, with False being the default.

Parameters:

Name Type Description Default
path #
pathlib.Path

The file path being saved.

required
include_all_context #
bool

If True, write existing context variables passed into writer and the additional context to the CSV. If False, determines only the context keys parsed from the filename_format (excludes all other context variables, and unused context keys).

True
filepath_column #
str

The name of the column to store the file path. Defaults to "path".

"path"
replace_existing #
bool

If True, checks if the file path already exists in the index and replaces it.

False
merge_columns #
bool

If True, allows schema evolution by merging new columns with existing ones. Set to False for strict schema enforcement (will raise an error if schemas don't match).

True
Source code in src/imgtools/io/writers/abstract_base_writer.py
def add_to_index(
    self,
    path: Path,
    include_all_context: bool = True,
    filepath_column: str = "path",
    replace_existing: bool = False,
    merge_columns: bool = True,
) -> None:
    """
    Add or update an entry in the shared CSV index file using IndexWriter.

    **What It Does**:

    - Logs the file's path and associated context variables to a
        shared CSV index file.
    - Uses IndexWriter to safely handle concurrent writes and schema evolution.

    **When to Use It**:

    - Use this method to maintain a centralized record of saved
    files for auditing or debugging.

    **Relevant Writer Parameters**
    ------------------------------

    - The `index_filename` parameter allows you to specify a
    custom filename for the index file.
    By default, it will be named after the `root_directory`
    with `_index.csv` appended.

    - If the index file already exists in the root directory,
    it will overwrite it unless
    the `overwrite_index` parameter is set to `False`.

    - The `absolute_paths_in_index` parameter controls whether
    the paths in the index file are absolute or relative to the
    `root_directory`, with `False` being the default.

    Parameters
    ----------
    path : Path
        The file path being saved.
    include_all_context : bool, default=True
        If True, write existing context variables passed into writer and
        the additional context to the CSV.
        If False, determines only the context keys parsed from the
        `filename_format` (excludes all other context variables, and
        unused context keys).
    filepath_column : str, default="path"
        The name of the column to store the file path. Defaults to "path".
    replace_existing : bool, default=False
        If True, checks if the file path already exists in the index and
        replaces it.
    merge_columns : bool, default=True
        If True, allows schema evolution by merging new columns with existing ones.
        Set to False for strict schema enforcement (will raise an error if schemas don't match).
    """
    # Prepare context data
    context = {}

    # Determine which context to include
    if include_all_context:
        context = self.context
    else:
        # Only include keys from the pattern resolver
        context = {
            k: v
            for k, v in self.context.items()
            if k in self.pattern_resolver.keys
        }

    # Resolve the path according to configuration
    resolved_path = (
        path.resolve().absolute()
        if self.absolute_paths_in_index
        else path.relative_to(self.root_directory)
    )

    # Write the entry to the index file
    try:
        self._index_writer.write_entry(
            path=resolved_path,
            context=context,
            filepath_column=filepath_column,
            replace_existing=replace_existing,
            merge_columns=merge_columns,
        )
    except (
        IndexSchemaMismatchError,
        IndexReadError,
        IndexWriteError,
        IndexWriterError,
    ) as e:
        logger.exception(
            f"Error writing to index file {self.index_file}.", error=e
        )
        raise WriterIndexError(
            f"Error writing to index file {self.index_file}.",
            writer=self,
        ) from e
    except Exception as general_e:
        raise general_e

clear_context #

clear_context() -> None

Clear the context for the writer.

Useful for resetting the context after using preview_path or save and want to make sure that the context is empty for new operations.

Source code in src/imgtools/io/writers/abstract_base_writer.py
def clear_context(self) -> None:
    """
    Clear the context for the writer.

    Useful for resetting the context after using `preview_path` or `save`
    and want to make sure that the context is empty for new operations.
    """
    self.context.clear()

preview_path #

preview_path(
    **kwargs: object,
) -> typing.Optional[pathlib.Path]

Pre-checking file existence and setting up the writer context.

Meant to be used by users to skip expensive computations if a file already exists and you dont want to overwrite it. Only difference between this and resolve_path is that this method does not return the path if the file exists and the mode is set to SKIP.

This is because the .save() method should be able to return the path even if the file exists.

What It Does:

  • Pre-checks the file path based on context without writing the file.
  • Returns None if the file exists and the mode is set to SKIP.
  • Raises a FileExistsError if the mode is set to FAIL.
  • An added benefit of using preview_path is that it automatically caches the context variables for future use, and save() can be called without passing in the context variables again.

Examples:

Main idea here is to allow users to save computation if they choose to skip existing files.

i.e. if file exists and mode is SKIP, we return None, so the user can skip the computation.

>>> if nifti_writer.preview_path(subject="math", name="test") is None:
>>>     logger.info("File already exists. Skipping computation.")
>>>     continue # could be `break` or `return` depending on the use case

if the mode is FAIL, we raise an error if the file exists, so user doesnt have to perform expensive computation only to fail when saving.

Useful Feature

The context is saved in the instance, so running .save() after this will use the same context, and user can optionally update the context with new values passed to .save().

>>> if path := writer.preview_path(subject="math", name="test"):
>>>     ... # do some expensive computation to generate the data
>>>     writer.save(data)
.save() automatically uses the context for subject and name we passed to preview_path

Parameters:

Name Type Description Default
**kwargs #
typing.Any

Parameters for resolving the filename and validating existence.

{}

Returns:

Type Description
pathlib.Path | None

If the file exists and the mode is SKIP, returns None. if the file exists and the mode is FAIL, raises a FileExistsError. If the file exists and the mode is OVERWRITE, logs a debug message and returns the path.

Source code in src/imgtools/io/writers/abstract_base_writer.py
def preview_path(self, **kwargs: object) -> Optional[Path]:
    """
    Pre-checking file existence and setting up the writer context.

    Meant to be used by users to skip expensive computations if a file
    already exists and you dont want to overwrite it.
    Only difference between this and resolve_path is that this method
    does not return the path if the file exists and the mode is set to
    `SKIP`.

    This is because the `.save()` method should be able to return
    the path even if the file exists.

    **What It Does**:

    - Pre-checks the file path based on context without writing the file.
    - Returns `None` if the file exists and the mode is set to `SKIP`.
    - Raises a `FileExistsError` if the mode is set to `FAIL`.
    - An added benefit of using `preview_path` is that it automatically
    caches the context variables for future use, and `save()` can be called
    without passing in the context variables again.

    Examples
    --------

    Main idea here is to allow users to save computation if they choose to
    skip existing files.

    i.e. if file exists and mode is **`SKIP`**, we return
    `None`, so the user can skip the computation.
    >>> if nifti_writer.preview_path(subject="math", name="test") is None:
    >>>     logger.info("File already exists. Skipping computation.")
    >>>     continue # could be `break` or `return` depending on the use case

    if the mode is **`FAIL`**, we raise an error if the file exists, so user
    doesnt have to perform expensive computation only to fail when saving.

    **Useful Feature**
    ----------------------
    The context is saved in the instance, so running
    `.save()` after this will use the same context, and user can optionally
    update the context with new values passed to `.save()`.

    ```python
    >>> if path := writer.preview_path(subject="math", name="test"):
    >>>     ... # do some expensive computation to generate the data
    >>>     writer.save(data)
    ```
    `.save()` automatically uses the context for `subject` and `name` we
    passed to `preview_path`

    Parameters
    ----------
    **kwargs : Any
        Parameters for resolving the filename and validating existence.

    Returns
    ------
    Path | None
        If the file exists and the mode is `SKIP`, returns `None`. if the file
        exists and the mode is FAIL, raises a `FileExistsError`. If the file
        exists and the mode is OVERWRITE, logs a debug message and returns
        the path.

    Raises
    ------
    FileExistsError
        If the file exists and the mode is FAIL.
    """
    out_path = self._generate_path(**kwargs)

    if not out_path.exists():
        return out_path
    elif out_path.is_dir():
        msg = f"Path {out_path} is already a directory that exists."
        msg += " Use a different filename format or context to avoid this."
        raise IsADirectoryError(msg)

    match self.existing_file_mode:
        case ExistingFileMode.SKIP:
            return None
        case ExistingFileMode.FAIL:
            msg = f"File {out_path} already exists."
            raise FileExistsError(msg)
        case ExistingFileMode.OVERWRITE:
            logger.debug(
                f"File {out_path} exists. Deleting and overwriting."
            )
            out_path.unlink()

    return out_path

resolve_path #

resolve_path(**kwargs: object) -> pathlib.Path

Generate a file path based on the filename format, subject ID, and additional parameters.

Meant to be used by developers when creating a new writer class and used internally by the save method.

What It Does:

  • Dynamically generates a file path based on the provided context and filename format.

When to Use It:

  • This method is meant to be used in the save method to determine the file’s target location, but can also be used by external code to generate paths.
  • It ensures you’re working with a valid path and can handle file existence scenarios.
  • Only raises FileExistsError if the file already exists and the mode is set to FAIL.

Parameters:

Name Type Description Default
**kwargs #
typing.Any

Parameters for resolving the filename and validating existence.

{}

Returns:

Name Type Description
resolved_path pathlib.Path

The resolved path for the file.

Source code in src/imgtools/io/writers/abstract_base_writer.py
def resolve_path(self, **kwargs: object) -> Path:
    """
    Generate a file path based on the filename format, subject ID, and
    additional parameters.

    Meant to be used by developers when creating a new writer class
    and used internally by the `save` method.

    **What It Does**:

    - Dynamically generates a file path based on the provided context and
    filename format.

    **When to Use It**:

    - This method is meant to be used in the `save` method to determine the
    file’s target location, but can also be used by external code to
    generate paths.
    - It ensures you’re working with a valid path and can handle file
    existence scenarios.
    - Only raises `FileExistsError` if the file already exists and the mode
    is set to `FAIL`.

    Parameters
    ----------
    **kwargs : Any
        Parameters for resolving the filename and validating existence.

    Returns
    -------
    resolved_path: Path
        The resolved path for the file.

    Raises
    ------
    FileExistsError
        If the file already exists and the mode is set to FAIL.
    """
    out_path = self._generate_path(**kwargs)
    if not out_path.exists():
        if self.create_dirs:
            self._ensure_directory_exists(out_path.parent)
        # should we raise this error here?
        # elif not out_path.parent.exists():
        #     msg = f"Directory {out_path.parent} does not exist."
        #     raise DirectoryNotFoundError(msg)
        return out_path
    match self.existing_file_mode:
        case ExistingFileMode.SKIP:
            return out_path
        case ExistingFileMode.FAIL:
            msg = f"File {out_path} already exists."
            raise FileExistsError(msg)
        case ExistingFileMode.OVERWRITE:
            logger.debug(f"Deleting existing {out_path} and overwriting.")
            out_path.unlink()
            return out_path

save #

save(
    data: SimpleITK.Image | numpy.ndarray, **kwargs: object
) -> pathlib.Path

Abstract method for writing data. Must be implemented by subclasses.

Can use resolve_path() to get the output path and write the data to it.

For efficiency, use self.context to access the context variables, updating them with the kwargs passed from the save method.

This will help simplify repeated saves with similar context variables.

Write the SimpleITK image to a NIFTI file.

Parameters:

Name Type Description Default
data #
SimpleITK.Image | numpy.ndarray

The SimpleITK image or numpy array to save

required
**kwargs #
object

Additional formatting parameters for the output path

{}

Returns:

Type Description
pathlib.Path

Path to the saved file

Source code in src/imgtools/io/writers/nifti_writer.py
def save(self, data: sitk.Image | np.ndarray, **kwargs: object) -> Path:
    """Write the SimpleITK image to a NIFTI file.

    Parameters
    ----------
    data : sitk.Image | np.ndarray
        The SimpleITK image or numpy array to save
    **kwargs : object
        Additional formatting parameters for the output path

    Returns
    -------
    Path
        Path to the saved file

    Raises
    ------
    NiftiWriterIOError
        If writing fails
    NiftiWriterValidationError
        If the input data is invalid
    """
    match data:
        case sitk.Image():
            image = data
        case np.ndarray():
            image = sitk.GetImageFromArray(data)
        case _:
            msg = "Input must be a SimpleITK Image or a numpy array"
            raise NiftiWriterValidationError(msg)

    # if the object has the 'fingerprint' property, update the context
    if hasattr(data, "serialized_fingerprint"):
        self.set_context(**data.serialized_fingerprint)
    elif isinstance(data, MedImage):
        # if there is no fingerprint, this is unexpected
        # this is an issue now since we auto keep context between
        # saves, so this could lead to using the fingerprint
        # of the previous save
        logger.error(
            "No fingerprint found in the writer object. "
            "This is unexpected and may indicate a bug. "
            "The fingerprint fields in the index might be incorrect."
        )
        # TODO:: think of a better way to handle this
        self.clear_context()

    # TODO:: think of a better way to handle the truncate_uids_in_filename
    if self.truncate_uids_in_filename:
        truncated_kwargs = {
            k: truncate_uid(str(v), self.truncate_uids_in_filename)
            if k.lower().endswith("uid")
            else v
            for k, v in kwargs.items()
        }
        out_path = self.resolve_path(**truncated_kwargs)
        # need to update the context with the old kwargs
        # because it will be used in the index, and we dont want
        # to truncate the UIDs in the index
        self.set_context(**kwargs)
    else:
        out_path = self.resolve_path(**kwargs)

    if (
        out_path.exists()  # check if it exists
        # This will only be true if SKIP,
        # OVERWRITE would have deleted the file
        and self.existing_file_mode == ExistingFileMode.SKIP
    ):
        logger.debug("File exists, skipping.", out_path=out_path)
        return out_path

    try:
        sitk.WriteImage(
            image,
            out_path.as_posix(),
            useCompression=True,
            compressionLevel=self.compression_level,
        )
    except Exception as e:
        msg = f"Error writing image to file {out_path}: {e}"
        raise NiftiWriterIOError(msg) from e

    self.add_to_index(
        out_path,
        filepath_column="filepath",
        replace_existing=out_path.exists(),
    )

    return out_path

set_context #

set_context(**kwargs: object) -> None

Set the context for the writer.

Source code in src/imgtools/io/writers/abstract_base_writer.py
def set_context(self, **kwargs: object) -> None:
    """
    Set the context for the writer.
    """
    self.context.update(kwargs)

NiftiWriterError #

Bases: Exception

Base exception for NiftiWriter errors.

NiftiWriterIOError #

Bases: imgtools.io.writers.nifti_writer.NiftiWriterError

Raised when I/O operations fail.

NiftiWriterValidationError #

Bases: imgtools.io.writers.nifti_writer.NiftiWriterError

Raised when validation of writer configuration fails.