dosma.utils package

Submodules

dosma.utils.cmd_line_utils module

class dosma.utils.cmd_line_utils.ActionWrapper(name, **kwargs)[source]

Bases: object

Wrapper for actions (methods) that can be executed via command-line.

Examples include segment scans, interregister scans, etc.

Actions are instance methods of classes that can be executed via the command line. They are typically associated with different scans.

To expose these methods to the command-line interface, we wrap these actions as subparsers.

Parameters for the method are arguments of the subparser.

property aliases

Aliases (other names) for this action.

Type

list[str]

get_alternative_param_names(param: str)[source]

Get aliases (alternate names) for a parameter.

Parameters

param (str) – Action parameter name.

Returns

If aliases exist for parameter. None, otherwise.

Return type

Optional[list[str]]

get_param_help(param: str)[source]

Get help menu for a parameter.

Parameters

param (str) – Action parameter name.

Returns

Help menu for parameter, if initialized. “”, otherwise.

Return type

str

property help

Help menu for this action.

Type

str

property name

Action name.

Type

str

dosma.utils.fits module

class dosma.utils.fits.MonoExponentialFit(ts: Sequence[float], subvolumes: List[dosma.data_io.med_volume.MedicalVolume], mask: Optional[dosma.data_io.med_volume.MedicalVolume] = None, bounds: Tuple[float] = (0, 100.0), tc0: float = 30.0, decimal_precision: int = 1, verbose: bool = False, num_workers: int = 0)[source]

Bases: dosma.utils.fits._Fit

Fit quantitative values using mono-exponential fit of model \(a*exp(t/tc)\).

Parameters
  • ts (array-like) – 1D array of times in milliseconds (typically echo times) corresponding to different volumes.

  • subvolumes (list[MedicalVolumes]) – Volumes (in order) corresponding to times in ts.

  • mask (MedicalVolume, optional) – Mask of pixels to fit. If specified, pixels outside of mask region are ignored and set to np.nan. Speeds fitting time as fewer fits are required.

  • bounds (tuple[float, float], optional) – Upper and lower bound for quantitative values. Values outside those bounds will be set to np.nan.

  • tc0 (float, optional) – Initial time constant guess (in milliseconds).

  • decimal_precision (int, optional) – Rounding precision after the decimal point.

fit()[source]

Fit quantitative values per pixel across multiple volumes.

Pixels with errors in fitting are set to np.nan.

Returns

Quantitative value volume and

r-squared goodness of fit volume.

Return type

tuple[MedicalVolume, MedicalVolume]

dosma.utils.fits.biexponential(x, a1, b1, a2, b2)[source]

Function: \(f(x) = a1*e^{b1*x} + a2*e^{b2*x}\).

dosma.utils.fits.curve_fit(func, x, y, y_bounds=None, p0=None, maxfev=100, ftol=1e-05, eps=1e-08, show_pbar=False, num_workers=0, **kwargs)[source]

Use non-linear least squares to fit a function func to data.

Uses scipy.optimize.curve_fit() backbone.

Parameters
  • func (callable) – The model function, f(x, …). It must take the independent variable as the first argument and the parameters to fit as separate remaining arguments.

  • x (ndarray) – The independent variable(s) where the data is measured. Should usually be an M-length sequence or an (k,M)-shaped array for functions with k predictors, but can actually be any object.

  • y (ndarray) – The dependent data, a length M array - nominally func(xdata, …) - or an (M,N)-shaped array for N different sequences.

  • y_bounds (tuple, optional) – Lower and upper bound on y values. Defaults to no bounds. Sequences with observations out of this range will not be processed.

  • p0 (Sequence, optional) – Initial guess for the parameters (length N). If None, then the initial values will all be 1 (if the number of parameters for the function can be determined using introspection, otherwise a ValueError is raised).

  • maxfev (int, optional) – Maximum number of function evaluations before the termination. If bounds argument for scipy.optimize.curve_fit is specified, this corresponds to the max_nfev in the least squares algorithm

  • ftol (float) – Tolerance for termination by the change of the cost function. See scipy.optimize.least_squares for more details.

  • eps (float, optional) – Epsilon for computing r-squared.

  • show_pbar (bool, optional) – If True, show progress bar. Note this can increase runtime slightly when using multiple workers.

  • kwargs – Keyword args for scipy.optimize.curve_fit.

dosma.utils.fits.monoexponential(x, a, b)[source]

Function: \(f(x) = a * e^{b*x}\).

dosma.utils.geometry_utils module

dosma.utils.geometry_utils.cart2pol(x, y)[source]

Convert cartesian coordinates to polar coordinates.

Parameters
  • x – x-coordinate.

  • y – y-coordinate.

Returns

radius (rho) and angle (phi).

Return type

tuple[float, float]

dosma.utils.geometry_utils.circle_fit(x: numpy.ndarray, y: numpy.ndarray)[source]

Fit a circle given (x, y) scatter points in a plane.

Parameters
  • x (np.ndarray) – x-coordinates of scatter points.

  • y (np.ndarray) – y-coordinates of scatter points.

Returns

Coordinates and radius of circle (center x, center y, radius).

Return type

tuple[float]

dosma.utils.img_utils module

dosma.utils.img_utils.downsample_slice(img_array, ds_factor, is_mask=False)[source]

Takes in a 3D array and then downsamples in the z-direction by a user-specified downsampling factor.

Parameters
  • img_array (np.ndarray) – 3D numpy array for now (xres x yres x zres)

  • ds_factor (int) – Downsampling factor

  • is_mask (bool, optional) – If True, img_array is a mask and will be binarized after downsampling. Defaults to False.

Returns

3D numpy array of dimensions (xres x yres x zres//ds_factor)

Return type

np.ndarray

Examples

>>> input_image  = numpy.random.rand(4,4,4)
>>> input_mask   = (a > 0.5) * 1.0
>>> output_image = downsample_slice(input_mask, ds_factor = 2, is_mask = False)
>>> output_mask  = downsample_slice(input_mask, ds_factor = 2, is_mask = True)
dosma.utils.img_utils.write_regions(file_path, arr, plt_dict=None)[source]

Write 2D array to region image where colors correspond to the region.

All finite values should be >= 1. nan/inf value are ignored - written as white.

Parameters
  • file_path (str) – File path to save image.

  • arr (np.ndarray) – The 2D numpy array to convert to region image. Unique non-zero values correspond to different regions. Values that are 0 or np.nan will be written as white pixels.

  • plt_dict (dict, optional) – Dictionary of values to use when plotting with matplotlib.pyplot. Keys are strings like xlabel, ylabel, etc. Use Key labels to specify a mapping from unique non-zero values in the array to names for the legend.

dosma.utils.io_utils module

dosma.utils.io_utils.load_h5(file_path)[source]

Load data in H5DF format.

Parameters

file_path (str) – File path to save to.

Returns

Loaded data.

Return type

dict

Raises

FileNotFoundError – If file_path does not exist.

dosma.utils.io_utils.load_pik(file_path: str)[source]

Load data using pickle.

Should be used with save_pik.

Pickle is not be stable across Python 2/3.

Parameters

file_path (str) – File path to load from.

Returns

Loaded data.

Return type

Any

Raises

FileNotFoundError – If file_path does not exist.

dosma.utils.io_utils.mkdirs(dir_path: str)[source]

Make directory is directory does not exist.

Parameters

dir_path (str) – Directory path to make.

Returns

path to directory

Return type

str

dosma.utils.io_utils.save_h5(file_path: str, data_dict: dict)[source]

Save data in H5DF format.

Parameters
  • file_path (str) – File path to save to.

  • data_dict (dict) – Dictionary of data to store. Dictionary can only have depth of 1.

dosma.utils.io_utils.save_pik(file_path: str, data)[source]

Save data using pickle.

Pickle is not be stable across Python 2/3.

Parameters
  • file_path (str) – File path to save to.

  • data (Any) – Data to serialize.

dosma.utils.io_utils.save_tables(file_path: str, data_frames: Sequence[pandas.core.frame.DataFrame], sheet_names: Optional[Sequence[str]] = None)[source]

Save data in excel tables.

Parameters
  • file_path (str) – File path to excel file.

  • data_frames (Sequence[pd.DataFrame]) – Tables to store to excel file. One table stored per sheet.

  • sheet_names (Sequence[str], optional) – Sheet names for each data frame.

dosma.utils.registration module

dosma.utils.registration.apply_warp(moving: Union[dosma.data_io.med_volume.MedicalVolume, str], transform: Optional[Union[str, Sequence[str]]] = None, out_registration: Optional[nipype.interfaces.elastix.registration.RegistrationOutputSpec] = None, output_path: Optional[str] = None, rtype: type = <class 'dosma.data_io.med_volume.MedicalVolume'>, num_threads: int = 1, show_pbar: bool = False)Union[dosma.data_io.med_volume.MedicalVolume, str][source]

Apply transform(s) to moving image using transformix.

Use transformix to apply a transform on an input image. The transform(s) is/are specified in the transform-parameter file(s).

Parameters
  • moving (MedicalVolume(s) or str(s)) – The moving/source image to transform.

  • transform (str(s)) – Paths to transform files to be used by transformix. If multiple files provided, transforms will be applied sequentially. If None, will be determined by out_registration.transform.

  • out_registration (RegistrationOutputSpec(s)) – Outputs from elastix registration using nipype. Must be specified if transform is None.

  • output_path (str) – Output directory to store files.

  • rtype (type, optional) – Return type - either MedicalVolume or str. If str, output_path must be specified. Defaults to MedicalVolume.

  • num_threads (int, optional) – Number of threads to use for registration. If None, defaults to 1.

  • show_pbar (bool, optional) – If True, show progress bar when applying transforms.

Returns

The medical volume or nifti file corresponding to the volume.

See rtype for details.

Return type

MedVolOrPath

dosma.utils.registration.register(target: Union[dosma.data_io.med_volume.MedicalVolume, str], moving: Union[dosma.data_io.med_volume.MedicalVolume, str, Sequence[Union[dosma.data_io.med_volume.MedicalVolume, str]]], parameters: Union[str, Sequence[str]], output_path: str, target_mask: Optional[Union[dosma.data_io.med_volume.MedicalVolume, str]] = None, moving_masks: Optional[Union[dosma.data_io.med_volume.MedicalVolume, str, Sequence[Union[dosma.data_io.med_volume.MedicalVolume, str]]]] = None, sequential: bool = False, collate: bool = True, num_workers: int = 0, num_threads: int = 1, show_pbar: bool = False, return_volumes: bool = False, rtype: type = <class 'dict'>, **kwargs)[source]

Register moving image(s) to the target.

MedVolOrPath is a shorthand for MedicalVolume or str. It indicates the argument can be either a MedicalVolume or a str path to a nifti file.

Parameters
  • target (MedicalVolume or str) – The target/fixed image.

  • moving (`MedicalVolume`(s) or `str`(s)) – The moving/source image(s).

  • parameters (str(s)) – Elastix parameter files to use.

  • output_path (str) – Output directory to store files.

  • target_mask (MedicalVolume or str, optional) – The target/fixed mask.

  • moving_masks (`MedicalVolume`(s) or `str`(s), optional) – The moving mask(s). If only one specified, the mask will be used for all moving images.

  • sequential (bool, optional) – If True, apply parameter files sequentially.

  • collate (bool, optional) – If True, will collate outputs from sequential registration into single RegistrationOutputSpec instance. If sequential=False, this argument is ignored.

  • num_workers (int, optional) – Number of workers to use for reading/writing data and for registration.

  • num_threads (int, optional) – Number of threads to use for registration. Note total number of threads used will be num_workers * num_threads.

  • show_pbar (bool, optional) – If True, show progress bar during registration. Note the progress bar will not be shown for intermediate reading/writing.

  • return_volumes (bool, optional) – If True, registered volumes will also be returned. By default, only the output namespaces (RegistrationOutputSpec) of the registrations are returned.

  • rtype (type, optional) – The return type. Either dict or tuple.

  • kwargs – Keyword arguments used to initialize nipype.interfaces.elastix.Registration.

Returns

Type specified by rtype. If dict, with keys ‘outputs’

(registration outputs) and ‘volumes’ (final volumes) if return_volumes=True). If tuple, order is (outputs, volumes or None). Length of outputs and volumes depends on number of images specified in moving.

outputs (Sequence[RegistrationOutputSpec]): The output objects from

elastix registration, one for each moving image. Each object is effectively a namespace with four main attributes:

  • ’transform’ (List[str]): Paths to transform files produced using registration.

  • ’warped_file’ (str): Path to the final registered image.

  • ’warped_files’ (List[str]): Paths to all intermediate images created if

    multiple parameter files used.

volumes (Sequence[MedicalVolume]): Registered volumes.

Return type

Dict or Tuple

Symlinks elastix/transformix files to the dosma library.

Parameters
  • path (str, optional) – Path to elastix folder. This folder should contain two folders bin and lib. If None, determined using which elastix. This will overwrite existing linked files. path cannot be automatically determined on Windows.

  • lib_only (bool, optional) – If True, only links contents of lib folder.

  • force (bool, optional) – If True, unlinks existing files before relinking. Note this operation is not atomic.

Note

Setting elastix paths this way is not recommended unless you are using a MacOS (Darwin) platform, where there are known path issues with elastix (https://github.com/almarklein/pyelastix/issues/9). For linux and windows machines, using the setup described in the elastix guide is sufficient.

Unlinks all elastix/transformix files in the dosma library.

Module contents