API Reference

The following section outlines the API of shimming-toolbox.

Fieldmapping

Wrapper to different unwrapping algorithms.

shimmingtoolbox.unwrap.unwrap_phase.unwrap_phase(phase, affine, unwrapper='prelude', mag=None, mask=None, threshold=None)

Calls different unwrapping algorithms according to the specified unwrapper parameter. The function also allows to call the different unwrappers with more flexibility regarding input shape.

Parameters
  • phase (numpy.ndarray) – 2D, 3D or 4D radian values [-pi to pi] to perform phase unwrapping. Supported shapes: [x, y], [x, y, z] or [x, y, z, t].

  • affine (numpy.ndarray) – 2D array (4x4) containing the transformation coefficients. Can be acquired by : nii = nib.load(“nii_path”) affine = nii.affine

  • unwrapper (str, optional) – Unwrapper algorithm name. Possible values: prelude.

  • mag (numpy.ndarray) – 2D, 3D or 4D magnitude data corresponding to phase data. Shape must be the same as phase.

  • mask (numpy.ndarray) – numpy array of booleans with shape of phase to mask during phase unwrapping.

  • threshold (float) – Prelude parameter, see prelude for more detail.

Returns

Unwrapped phase image.

Return type

numpy.ndarray

Wrapper to FSL Prelude (https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/FUGUE/Guide#PRELUDE_.28phase_unwrapping.29)

shimmingtoolbox.unwrap.prelude.prelude(wrapped_phase, affine, mag=None, mask=None, threshold=None, is_unwrapping_in_2d=False)

wrapper to FSL prelude

This function enables phase unwrapping by calling FSL prelude on the command line. A mask can be provided to mask the phase image provided. 2D unwrapping can be turned off. The output path can be specified. The temporary niis can optionally be saved.

Parameters
  • wrapped_phase (numpy.ndarray) – 2D or 3D radian numpy array to perform phase unwrapping. (2 pi interval)

  • affine (numpy.ndarray) – 2D array containing the transformation coefficients. Can be calculated by using: nii = nib.load(“nii_path”) affine = nii.affine

  • mag (numpy.ndarray) – 2D or 3D magnitude numpy array corresponding to the phase array

  • mask (numpy.ndarray, optional) – numpy array of booleans with shape of complex_array to mask during phase unwrapping

  • threshold – Threshold value for automatic mask generation (Use either mask or threshold, not both)

  • is_unwrapping_in_2d (bool, optional) – prelude parameter to unwrap slice by slice

Returns

3D array with the shape of complex_array of the unwrapped phase output from prelude

Return type

numpy.ndarray

Masking

Image mask with shape API

shimmingtoolbox.masking.shapes.shape_cube(data, len_dim1, len_dim2, len_dim3, center_dim1=None, center_dim2=None, center_dim3=None)

Creates a cube mask. Returns mask with the same shape as data.

Parameters
  • data (numpy.ndarray) – Data to mask, must be 3 dimensional array.

  • len_dim1 (int) – Length of the side of the square along first dimension (in pixels).

  • len_dim2 (int) – Length of the side of the square along second dimension (in pixels).

  • len_dim3 (int) – Length of the side of the square along third dimension (in pixels).

  • center_dim1 (int) – Center of the square along first dimension (in pixels). If no center is provided, the middle is used.

  • center_dim2 (int) – Center of the square along second dimension (in pixels). If no center is provided, the middle is used.

  • center_dim3 (int) – Center of the square along third dimension (in pixels). If no center is provided, the middle is used.

Returns

Mask with booleans. True where the cube is located and False in the background.

Return type

numpy.ndarray

shimmingtoolbox.masking.shapes.shape_square(data, len_dim1, len_dim2, center_dim1=None, center_dim2=None)

Creates a square mask. Returns mask with the same shape as data.

Parameters
  • data (numpy.ndarray) – Data to mask, must be 2 dimensional array.

  • len_dim1 (int) – Length of the side of the square along first dimension (in pixels).

  • len_dim2 (int) – Length of the side of the square along second dimension (in pixels).

  • center_dim1 (int) – Center of the square along first dimension (in pixels). If no center is provided, the middle is used.

  • center_dim2 (int) – Center of the square along second dimension (in pixels). If no center is provided, the middle is used.

Returns

Mask with booleans. True where the square is located and False in the background.

Return type

numpy.ndarray

shimmingtoolbox.masking.shapes.shapes(data, shape, **kargs)

Wrapper to different shape masking functions.

Parameters
  • data (numpy.ndarray) – Data to mask.

  • shape (str) – Shape to mask, implemented shapes include: {‘square’, ‘cube’}.

  • **kargs – Refer to the specific function in this file for the specific arguments for each shape. See example section for more details.

Returns

Mask with booleans. True where the shape is located and False in the background.

Return type

numpy.ndarray

Examples

>>> dummy_data = np.ones([4,3])
>>> dummy_mask = shapes(dummy_data, 'square', center_dim1=1, center_dim2=1, len_dim1=1, len_dim2=3)

Image thresholding API

shimmingtoolbox.masking.threshold.threshold(data, thr=30)

Threshold an image

Parameters
  • data (numpy.ndarray) – Data to be masked

  • thr – Value to threshold the data: voxels will be set to zero if their value is equal or less than this threshold

Returns

Boolean mask with same dimensions as data

Return type

numpy.ndarray

Coils

class shimmingtoolbox.coils.coil.Coil(profile, affine, constraints)

Coil profile object that stores coil profiles and there constraints

dim

Dimension along specific axis. dim: 0,1,2 are spatial axes, while dim: 3 corresponds to the coil channel.

Type

Tuple[int]

profile

(dim1, dim2, dim3, channels) 4d array of N 3d coil profiles

Type

np.ndarray

affine

4x4 array containing the affine transformation associated with the NIfTI file of the coil profile. This transformation relates to the physical coordinates of the scanner (qform).

Type

np.ndarray

required_constraints

List containing the required keys for constraints

Type

list

coef_sum_max

Contains the maximum value for the sum of the coefficients

Type

float

coef_channel_minmax

Contains the maximum coefficient for each channel

Type

list

__init__(profile, affine, constraints)

Initialize Coil

Parameters
  • profile (np.ndarray) – Coil profile (dim1, dim2, dim3, channels) 4d array of N 3d coil profiles

  • affine (np.ndarray) – 4x4 array containing the qform affine transformation for the coil profiles

  • constraints (dict) –

    dict containing the constraints for the coil profiles. Required keys:

    • coef_sum_max (float): Contains the maximum value for the sum of the coefficients. None is used to specify no bounds

    • coef_channel_max (list): List of (min, max) pairs for each coil channels. (None, None) is used to specify no bounds.

Examples

# Example of constraints
constraints = {
    'coef_sum_max': 40,
    # 8 channel coil
    'coef_channel_minmax': [(-2, 2), (-2, 2), (-2, 2), (-2, 2), (-3, 3), (-3, 3), (-3, 3), (-3, 3)]
}
load_constraints(constraints)

Loads the constraints named in required_constraints as attribute to this class

shimmingtoolbox.coils.spherical_harmonics.spherical_harmonics(orders, x, y, z)

Returns an array of spherical harmonic basis fields with the order/degree index along the 4th dimension.

Parameters
  • orders (numpy.ndarray) – Degrees of the desired terms in the series expansion, specified as a vector of non-negative integers (np.array(range(0, 3)) yields harmonics up to (n-1)-th order). Must be non negative.

  • x (numpy.ndarray) – 3-D arrays of grid coordinates

  • y (numpy.ndarray) – 3-D arrays of grid coordinates (same shape as x)

  • z (numpy.ndarray) – 3-D arrays of grid coordinates (same shape as x)

Returns

4d basis set of spherical harmonics with order/degree ordered along 4th dimension

Return type

numpy.ndarray

Examples

Initialize grid positions

>>> [x, y, z] = np.meshgrid(np.array(range(-10, 11)), np.array(range(-10, 11)), np.array(range(-10, 11)), indexing='ij')

0th-to-2nd order terms inclusive

>>> orders = np.array(range(0, 3))
>>> basis = spherical_harmonics(orders, x, y, z)

Notes

  • basis[:, :, :,0] corresponds to the 0th-order constant term (globally=unity)
    • 0: c

  • basis[:, :, :, 1:3] to 1st-order linear terms
    • 1: y

    • 2: z

    • 3: x

  • basis[:, :, :, 4:8] to 2nd-order terms
    • 4: xy

    • 5: zy

    • 6: z2

    • 7: zx

    • 8: x2y2

Based on
shimmingtoolbox.coils.siemens_basis.siemens_basis(x, y, z)

The function first wraps shimmingtoolbox.coils.spherical_harmonics to generate 1st and 2nd order spherical harmonic basis fields at the grid positions given by arrays X,Y,Z. Following Siemens convention, basis is then:

  • Reordered along the 4th dimension as X, Y, Z, Z2, ZX, ZY, X2-Y2, XY

  • Rescaled to Hz/unit-shim, where “unit-shim” refers to the measure displayed in the Adjustments card of the Syngo console UI, namely:

    • 1 micro-T/m for X,Y,Z gradients (= 0.042576 Hz/mm)

    • 1 micro-T/m^2 for 2nd order terms (= 0.000042576 Hz/mm^2)

The returned basis is thereby in the form of ideal “shim reference maps”, ready for optimization.

Parameters
  • orders (numpy.ndarray) – not yet implemented Degrees of the desired terms in the series expansion, specified as a vector of non-negative integers ([0:1:n] yields harmonics up to n-th order)

  • x (numpy.ndarray) – 3-D arrays of grid coordinates, “Right->Left” grid coordinates in the patient coordinate system (i.e. DICOM reference, units of mm)

  • y (numpy.ndarray) – 3-D arrays of grid coordinates (same shape as x). “Anterior->Posterior” grid coordinates in the patient coordinate system (i.e. DICOM reference, units of mm)

  • z (numpy.ndarray) – 3-D arrays of grid coordinates (same shape as x). “Inferior->Superior” grid coordinates in the patient coordinate system (i.e. DICOM reference, units of mm)

Returns

4-D array of spherical harmonic basis fields

Return type

numpy.ndarray

Notes

For now, orders is, in fact, ignored: fixed as [1:2]—which is suitable for the Prisma (presumably other Siemens systems as well) however, the 3rd-order shims of the Terra should ultimately be accommodated too. (Requires checking the Adjustments/Shim card to see what the corresponding terms and values actually are). So, for now, basis will always be returned with 8 terms along the 4th dim.

shimmingtoolbox.coils.coordinates.generate_meshgrid(dim, affine)

Generate meshgrid of size dim, with coordinate system defined by affine. :param dim: x, y and z dimensions. :type dim: tuple :param affine: 4x4 affine matrix :type affine: numpy.ndarray

Returns

List of numpy.ndarray containing meshgrid of coordinates

Return type

list

shimmingtoolbox.coils.coordinates.phys_gradient(data, affine)

Calculate the gradient of data along physical coordinates defined by affine

Parameters
  • data (numpy.ndarray) – 3d array containing data to apply gradient

  • affine (numpy.ndarray) – 4x4 array containing affine transformation

Returns

numpy.ndarray: 3D matrix containing the gradient along the x direction in the physical coordinate system numpy.ndarray: 3D matrix containing the gradient along the y direction in the physical coordinate system numpy.ndarray: 3D matrix containing the gradient along the z direction in the physical coordinate system

shimmingtoolbox.coils.coordinates.phys_to_vox_gradient(gx, gy, gz, affine)

Calculate the gradient along the voxel coordinates defined by affine with gradients in the physical coordinate system

Parameters
  • gx (numpy.ndarray) – 3D matrix containing the gradient along the x direction in the physical coordinate system

  • gy (numpy.ndarray) – 3D matrix containing the gradient along the y direction in the physical coordinate system

  • gz (numpy.ndarray) – 3D matrix containing the gradient along the z direction in the physical coordinate system

  • affine (numpy.ndarray) – 4x4 array containing affine transformation

Returns

3D matrix containing the gradient along the x direction in the voxel coordinate system numpy.ndarray: 3D matrix containing the gradient along the y direction in the voxel coordinate system numpy.ndarray: 3D matrix containing the gradient along the z direction in the voxel coordinate system

Return type

numpy.ndarray

shimmingtoolbox.coils.coordinates.resample_from_to(nii_from_img, nii_to_vox_map, order=2, mode='nearest', cval=0.0, out_class=nibabel.Nifti1Image)

Wrapper to nibabel’s resample_from_to function. Resample image from_img to mapped voxel space to_vox_map. The wrapper adds support for 2D input data (adds a singleton) and for 4D time series. For more info, refer to nibabel.processing.resample_from_to.

Parameters
  • nii_from_img (nibabel.Nifti1Image) – Nibabel object with 2D, 3D or 4D array. The 4d case will be treated as a timeseries.

  • nii_to_vox_map (nibabel.Nifti1Image) – Nibabel object with

  • order (int) – Refer to nibabel.processing.resample_from_to

  • mode (str) – Refer to nibabel.processing.resample_from_to

  • cval (scalar) – Refer to nibabel.processing.resample_from_to

  • out_class – Refer to nibabel.processing.resample_from_to

Returns

Return a Nibabel object with the resampled data. The 4d case will have an extra dimension

for the different time points.

Return type

nibabel.Nifti1Image

shimmingtoolbox.coils.biot_savart.biot_savart(centers, normals, radii, segment_numbers, fov_min, fov_max, fov_n)

Creates coil profiles for arbitrary loops, for use in multichannel shim examples that do not match spherical harmonics :param centers: List of 3D float center points for each loop in mm :type centers: list :param normals: List of 3D float normal vectors for each loop in mm :type normals: list :param radii: List of float radii for each loop in mm :type radii: list :param segment_numbers: List of integer number of segments for each loop approximation :type segment_numbers: list :param fov_min: Low 3D float corner of coil profile field of view (x, y, z) in mm :type fov_min: tuple :param fov_max: Inclusive high 3D float corner of coil profile field of view (x, y, z) in mm :type fov_max: tuple :param fov_n: Integer number of points for each dimension (x, y, z) in mm :type fov_n: tuple

Returns

(X, Y, Z, centers) coil profiles of magnetic field z-component in Hz/A – (X, Y, Z, Channel)

Return type

numpy.ndarray

Shim

shimmingtoolbox.optimizer.sequential.optimize_slicewise(optimizer: shimmingtoolbox.optimizer.basic_optimizer.Optimizer, mask, z_slices)

Shim slicewise in the specified ROI

Parameters
  • optimizer (Optimizer) – Initialized Optimizer object

  • mask (numpy.ndarray) – 3D mask used for the optimizer (only consider voxels with non-zero values).

  • z_slices (numpy.ndarray) – 1D array containing z slices to shim

Returns

Coefficients to shim (channels x z_slices.size)

Return type

numpy.ndarray

shimmingtoolbox.optimizer.sequential.select_optimizer(method, unshimmed, affine, coils: List[shimmingtoolbox.coils.coil.Coil])

Select and initialize the optimizer

Parameters
  • method (str) – Supported optimizer: ‘least_squares’, ‘pseudo_inverse’

  • unshimmed (numpy.ndarray) – 3D B0 map

  • affine (np.ndarray) – 4x4 array containing the affine transformation for the unshimmed array

  • coils (ListCoil) – List of Coils containing the coil profiles

Returns

Initialized Optimizer object

Return type

Optimizer

shimmingtoolbox.optimizer.sequential.sequential_zslice(unshimmed, affine, coils: List[shimmingtoolbox.coils.coil.Coil], mask, z_slices, method='least_squares')

Performs shimming slice by slice using one of the supported optimizers

Parameters
  • unshimmed (numpy.ndarray) – 3D B0 map

  • affine (np.ndarray) – 4x4 array containing the affine transformation for the unshimmed array

  • coils (ListCoil) – List of Coils containing the coil profiles

  • mask (numpy.ndarray) – 3D mask used for the optimizer (only consider voxels with non-zero values).

  • z_slices (numpy.ndarray) – 1D array containing z slices to shim

  • method (str) – Supported optimizer: ‘least_squares’, ‘pseudo_inverse’

Returns

Coefficients to shim (channels x z_slices.size)

Return type

numpy.ndarray

Optimizer

class shimmingtoolbox.optimizer.basic_optimizer.Optimizer(coils: List[shimmingtoolbox.coils.coil.Coil], unshimmed, affine)

Optimizer object that stores coil profiles and optimizes an unshimmed volume given a mask. Use optimize(args) to optimize a given mask. For basic optimizer, uses unbounded pseudo-inverse.

coils

List of Coil objects containing the coil profiles and related constraints

Type

ListCoil

unshimmed

3d array of unshimmed volume

Type

numpy.ndarray

unshimmed_affine

4x4 array containing the qform affine transformation for the unshimmed array

Type

numpy.ndarray

merged_coils

4d array containing all coil profiles resampled onto the target unshimmed array concatenated on the 4th dimension. See self.merge_coils() for more details

Type

numpy.ndarray

merged_bounds

list of bounds corresponding to each merged coils: merged_bounds[3] is the (min, max) bound for merged_coils[…, 3]

Type

list

__init__(coils: List[shimmingtoolbox.coils.coil.Coil], unshimmed, affine)

Initializes coils according to input list of Coil

Parameters
  • coils (ListCoil) – List of Coil objects containing the coil profiles and related constraints

  • unshimmed (numpy.ndarray) – 3d array of unshimmed volume

  • affine (numpy.ndarray) – 4x4 array containing the affine transformation for the unshimmed array

merge_coils(unshimmed, affine)

Uses the list of coil profiles to return a resampled concatenated list of coil profiles matching the unshimmed image. Bounds are also concatenated and returned.

Parameters
  • unshimmed (numpy.ndarray) – 3d array of unshimmed volume

  • affine (numpy.ndarray) – 4x4 array containing the affine transformation for the unshimmed array

optimize(mask)

Optimize unshimmed volume by varying current to each channel

Parameters

mask (numpy.ndarray) – 3d array of integers marking volume for optimization. Must be the same shape as unshimmed

Returns

Coefficients corresponding to the coil profiles that minimize the objective function.

The shape of the array returned has shape corresponding to the total number of channels

Return type

numpy.ndarray

class shimmingtoolbox.optimizer.lsq_optimizer.LsqOptimizer(coils: List[shimmingtoolbox.coils.coil.Coil], unshimmed, affine)

Bases: shimmingtoolbox.optimizer.basic_optimizer.Optimizer

__init__(coils: List[shimmingtoolbox.coils.coil.Coil], unshimmed, affine)

Initializes coils according to input list of Coil

Parameters
  • coils (ListCoil) – List of Coil objects containing the coil profiles and related constraints

  • unshimmed (numpy.ndarray) – 3d array of unshimmed volume

  • affine (numpy.ndarray) – 4x4 array containing the affine transformation for the unshimmed array

merge_coils(unshimmed, affine)

Uses the list of coil profiles to return a resampled concatenated list of coil profiles matching the unshimmed image. Bounds are also concatenated and returned.

Parameters
  • unshimmed (numpy.ndarray) – 3d array of unshimmed volume

  • affine (numpy.ndarray) – 4x4 array containing the affine transformation for the unshimmed array

optimize(mask)

Optimize unshimmed volume by varying current to each channel

Parameters

mask (numpy.ndarray) – 3D integer mask used for the optimizer (only consider voxels with non-zero values).

Returns

Coefficients corresponding to the coil profiles that minimize the objective function.

The shape of the array returned has shape corresponding to the total number of channels

Return type

numpy.ndarray

Image manipulation

shimmingtoolbox.image.concat_data(list_nii: List[nibabel.Nifti1Image], axis=3, pixdim=None)

Concatenate data

Parameters
  • list_nii – list of Nifti1Image

  • axis – axis: 0, 1, 2, 3, 4.

  • pixdim – pixel resolution to join to image header

Returns

concatenated image

Return type

ListNii

Numerical model

Create numerical model data for multi-echo B0 field mapping data

This module is for numerically simulating multi-echo B0 field mapping data. It considers features like: background B0 field, flip angle, echo time, and noise.

Typical usage example:

from shimmingtoolbox.simulate import *

b0_sim = NumericalModel(model="shepp-logan")

# Generate a background B0
b0_field = 13 # (Hz)
b0_sim.generate_deltaB0("linear", [0.0, b0_field])

# Simulate the signal data
FA = 15 # (degrees)
TE = [0.003, 0.015] # (seconds)
SNR = 50
b0_sim.simulate_measurement(FA, TE, SNR)

# Save simulation as NIfTI file (JSON sidecar also exported with parameters)
b0_sim.save('Phase', 'b0_mapping_data.nii', format='nifti')
class shimmingtoolbox.simulate.numerical_model.NumericalModel(model=None, num_vox=128)

Multi-echo B0 field mapping data numerical simulator.

Simulate multi-echo B0 field mapping data in the presence of a B0 field. Can simulate data under ideal conditions or with noise. Export simulations in a NIfTI or .mat file formats.

gamma

Gyromagnetic ratio in rad * Hz / Tesla.

Type

float

field_strength

Static field strength in Tesla.

Type

float

handedness

Orientation of the cross-product for the Larmor equation. The value of this attribute is MRI vendor-dependent.

measurement

Simulated measurement data array.

proton_density

Default assumed brain proton density in %.

T2_star

Default assumed brain T2* values in seconds at 3T.

generate_deltaB0(field_type, params)

Generates a background B0 field.

Defines the starting volume. Sets the background B0 field to zeros.

Parameters
  • field_type – Type of field to be generated. Available implementations are: 'linear'.

  • params – List of parameters defining the field for the selected field type. If field_type = 'linear', then params are [m b] where m (Hz/pixel) is the slope and b is the floor field (Hz).

save(data_type, file_name, format=None)

Exports simulated data to a file with a JSON sidecar.

Resets the measurement class attribute to zero before simulating. Simulates the signal for each echo-time provided. If defined, adds noise to the complex simulated signal measurements using an SNR value.

Parameters
  • data_type – Export data type. “Magnitude”, “Phase”, “Real”, or “Imaginary”.

  • file_name – Filename of exported file, with or without file extension.

  • format – File format for exported data. If no value given, will attempt to extract format from filename file extension, otherwise default to NIfTI.

simulate_measurement(FA, TE, SNR=None)

Simulates a multi-echo measurement for field mapping

Resets the measurement class attribute to zero before simulating. Simulates the signal for each echo-time provided. If defined, adds noise to the complex simulated signal measurements using an SNR value.

Parameters
  • FA – Flip angle in degrees.

  • TE – Echo-times in seconds. Can be either a single value, list, or array.

  • SNR – Signal-to-noise ratio used to define noise. If not set, no noise is added to the measurements.

Miscellaneous

shimmingtoolbox.dicom_to_nifti.dicom_to_nifti(path_dicom, path_nifti, subject_id='sub-01', path_config_dcm2bids='/home/docs/checkouts/readthedocs.org/user_builds/shimming-toolbox-py/checkouts/stable/config/dcm2bids.json', remove_tmp=False)

Converts dicom files into nifti files by calling dcm2bids

Parameters
  • path_dicom (str) – path to the input dicom folder

  • path_nifti (str) – path to the output nifti folder

shimmingtoolbox.load_nifti.get_acquisition_times(nii_data, json_data)

Return the acquisition timestamps from a json sidecar. This assumes BIDS convention.

Parameters
  • nii_data (nibabel.Nifti1Image) – Nibabel object containing the image timeseries.

  • json_data (dict) – Json dict corresponding to a nifti sidecar.

Returns

Acquisition timestamps in ms.

Return type

numpy.ndarray

shimmingtoolbox.load_nifti.load_nifti(path_data, modality='phase')

Load data from a directory containing NIFTI type file with nibabel. :param path_data: Path to the directory containing the file(s) to load :type path_data: str :param modality: Modality to read nifti (can be phase or magnitude) :type modality: str

Returns

List containing headers for every Nifti file dict: List containing all information in JSON format from every Nifti image numpy.ndarray: 5D array of all acquisition in time (x, y, z, echo, volume)

Return type

nibabel.Nifti1Image.Header

Note

If ‘path’ is a folder containing niftis, directly output niftis. It ‘path’ is a folder containing acquisitions, ask the user for which acquisition to use.

shimmingtoolbox.load_nifti.read_nii(fname_nifti, auto_scale=True)

Reads a nifti file and returns the corresponding image and info. Also returns the associated json data. :param fname_nifti: direct path to the .nii or .nii.gz file that is going to be read :type fname_nifti: str :param auto_scale: Tells if scaling is done before return :type auto_scale: bool, optional

Returns

Objet containing various data about the nifti file (returned by nibabel.load) json_data (dict): Contains the different fields present in the json file corresponding to the nifti file image (ndarray): For B0-maps, image contained in the nifti. Siemens phase images are rescaled between 0 and 2pi. For RF-maps, complex array of dimension (x, y, slice, coil) with phase between -pi and pi.

Return type

info (Nifti1Image)

shimmingtoolbox.download.download_data(urls)

Download the binaries from a URL and return the destination filename Retry downloading if either server or connection errors occur on a SSL connection

Parameters

urls – list of several urls (mirror servers) or single url (string)

shimmingtoolbox.download.install_data(url, dest_folder, keep=False)

Download a data bundle from a URL and install in the destination folder.

Parameters
  • url – URL or sequence thereof (if mirrors).

  • dest_folder – destination directory for the data (to be created).

  • keep – whether to keep existing data in the destination folder.

Returns

NoneType

Note

The function tries to be smart about the data contents.

Examples:

If the archive only contains a README.md, and the destination folder is ${dst}, ${dst}/README.md will be created. Note: an archive not containing a single folder is commonly known as a “tarbomb” because it puts files anywhere in the current working directory.

If the archive contains a ${dir}/README.md, and the destination folder is ${dst}, ${dst}/README.md will be created. Note: typically the package will be called ${basename}-${revision}.zip and contain a root folder named ${basename}-${revision}/ under which all the other files will be located. The right thing to do in this case is to take the files from there and install them in ${dst}.

  • Uses download_data() to retrieve the data.

  • Uses unzip() to extract the bundle.

shimmingtoolbox.download.unzip(compressed, dest_folder)

Extract compressed file to the dest_folder. Can handle .zip, .tar.gz. If none of this extension is found, simply copy the file in dest_folder.

Parameters
  • compressed – the compressed .zip or .tar.gz file

  • dest_folder – the destination dir that expanded files are written to

class shimmingtoolbox.pmu.PmuResp(fname_pmu)

PMU object containing the pressure values of a Siemens .resp file

fname

Filename of the Siemens .resp file

Type

str

data

Pressure values ranging from 0 to 4095

Type

numpy.ndarray

start_time_mdh

Start time in milliseconds past midnight (mdh clock is expected to be the closest to the image header)

Type

int

stop_time_mdh

Stop time in milliseconds past midnight (mdh clock is expected to be the closest to the image header)

Type

int

start_time_mpcu

Start time in milliseconds past midnight

Type

int

stop_time_mpcu

Stop time in milliseconds past midnight

Type

int

interp_resp_trace(acquisition_times)

Interpolates data to the specified acquisition_times

Parameters

acquisition_times (numpy.ndarray) – 1D array of the times in milliseconds past midnight of the desired times to interpolate the resp_trace. Times must be within self.start_time_mdh and self.stop_time_mdh

Returns

1D array with interpolated times

Return type

numpy.ndarray

read_resp(fname_pmu)

Read a Siemens Physiological Log file. Returns a tuple with the logging data as numpy integer array and times in the form of milliseconds past midnight.

Parameters

fname_pmu – Filename of the Siemens .resp file

Returns

A dict containing the fname_pmu infos. Contains the following keys:

  • fname

  • data

  • start_time_mdh

  • stop_time_mdh

  • start_time_mpcu

  • stop_time_mpcu

Return type

dict

shimmingtoolbox.utils.add_suffix(fname, suffix)

Add suffix between end of file name and extension.

Parameters
  • fname – absolute or relative file name. Example: t2.nii

  • suffix – suffix. Example: _mean

Return

file name string with suffix. Example: t2_mean.nii

Examples:

  • add_suffix(t2.nii, _mean) -> t2_mean.nii

  • add_suffix(t2.nii.gz, a) -> t2a.nii.gz

shimmingtoolbox.utils.create_output_dir(path_output, is_file=False, output_folder_name='output')

Given a path, create the directory if it doesn’t exist.

Parameters
  • path_output (str) – Full path to either a folder or a file.

  • is_file (bool) – True if the path_output is for a file, else False.

  • output_folder_name (str) – Name of sub-folder.

shimmingtoolbox.utils.iso_times_to_ms(iso_times)

Convert dicom acquisition times to ms

Parameters

iso_times (numpy.ndarray) – 1D array of time strings from dicoms. Suported formats: “HHMMSS.mmmmmm” or “HH:MM:SS.mmmmmm”

Returns

1D array of times in milliseconds

Return type

numpy.ndarray

shimmingtoolbox.utils.run_subprocess(cmd)

Wrapper for subprocess.run() that enables to input cmd as a full string (easier for debugging).

Parameters

cmd (string) – full command to be run on the command line

shimmingtoolbox.utils.st_progress_bar(*args, **kwargs)

Thin wrapper around tqdm.tqdm which checks SCT_PROGRESS_BAR muffling the progress bar if the user sets it to no, off, or false (case insensitive).