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 |
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. |
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 theroot_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 toFalse
. -
The
absolute_paths_in_index
parameter controls whether the paths in the index file are absolute or relative to theroot_directory
, withFalse
being the default.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
pathlib.Path
|
The file path being saved. |
required |
|
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
|
True
|
|
str
|
The name of the column to store the file path. Defaults to "path". |
"path"
|
|
bool
|
If True, checks if the file path already exists in the index and replaces it. |
False
|
|
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
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 |
|
clear_context
#
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
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 toSKIP
. - Raises a
FileExistsError
if the mode is set toFAIL
. - An added benefit of using
preview_path
is that it automatically caches the context variables for future use, andsave()
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 |
---|---|---|---|
|
typing.Any
|
Parameters for resolving the filename and validating existence. |
{}
|
Returns:
Type | Description |
---|---|
pathlib.Path | None
|
If the file exists and the mode is |
Source code in src/imgtools/io/writers/abstract_base_writer.py
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 |
|
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 toFAIL
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
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
save
#
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 |
---|---|---|---|
|
SimpleITK.Image | numpy.ndarray
|
The SimpleITK image or numpy array to save |
required |
|
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
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 |
|
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.