API Reference¶
The following section outlines the API of shimmingtoolbox.
unwrap¶
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)
coils¶
siemens_basis¶

shimmingtoolbox.coils.siemens_basis.
siemens_basis
(x, y, z)¶ The function first wraps
shimmingtoolbox.coils.spherical_harmonics
to generate 1st and 2nd order spherical harmonicbasis
fields at the grid positions given by arraysX,Y,Z
. Following Siemens convention,basis
is then:Reordered along the 4th dimension as X, Y, Z, Z2, ZX, ZY, X2Y2, XY
Rescaled to Hz/unitshim, where “unitshim” refers to the measure displayed in the Adjustments card of the Syngo console UI, namely:
1 microT/m for X,Y,Z gradients (= 0.042576 Hz/mm)
1 microT/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 nonnegative integers (
[0:1:n]
yields harmonics up to nth order)x (numpy.ndarray) – 3D arrays of grid coordinates, “Right>Left” grid coordinates in the patient coordinate system (i.e. DICOM reference, units of mm)
y (numpy.ndarray) – 3D 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) – 3D 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
4D 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 3rdorder 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.
spherical_harmonics¶

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 nonnegative integers (
np.array(range(0, 3))
yields harmonics up to (n1)th order). Must be non negative.x (numpy.ndarray) – 3D arrays of grid coordinates
y (numpy.ndarray) – 3D arrays of grid coordinates (same shape as x)
z (numpy.ndarray) – 3D 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')
0thto2nd order terms inclusive
>>> orders = np.array(range(0, 3)) >>> basis = spherical_harmonics(orders, x, y, z)
Notes
 basis[:, :, :,0] corresponds to the 0thorder constant term (globally=unity)
0: c
 basis[:, :, :, 1:3] to 1storder linear terms
1: y
2: z
3: x
 basis[:, :, :, 4:8] to 2ndorder terms
4: xy
5: zy
6: z2
7: zx
8: x2y2
 Based on
spherical_harmonics.m by topfer@ualberta.ca
calc_spherical_harmonics_arb_points_cz.m by jaystock@nmr.mgh.harvard.edu
numerical_model¶
Create numerical model data for multiecho B0 field mapping data
This module is for numerically simulating multiecho 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="shepplogan")
# 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)¶ Multiecho B0 field mapping data numerical simulator.
Simulate multiecho 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 crossproduct for the Larmor equation. The value of this attribute is MRI vendordependent.

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'
, thenparams
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 echotime 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 multiecho measurement for field mapping
Resets the measurement class attribute to zero before simulating. Simulates the signal for each echotime provided. If defined, adds noise to the complex simulated signal measurements using an SNR value.
 Parameters
FA – Flip angle in degrees.
TE – Echotimes in seconds. Can be either a single value, list, or array.
SNR – Signaltonoise ratio used to define noise. If not set, no noise is added to the measurements.

misc¶

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 indest_folder
. Parameters
compressed – the compressed
.zip
or.tar.gz
filedest_folder – the destination dir that expanded files are written to

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 B0maps, image contained in the nifti. Siemens phase images are rescaled between 0 and 2pi. For RFmaps, complex array of dimension (x, y, slice, coil) with phase between pi and pi.
 Return type
info (Nifti1Image)

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.
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 inputcmd
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).