API

The public functions and classes of monalisa, by subpackage, generated from their docstrings. Every one of them is also available from the top-level package: monalisa.recon.mathilda is also monalisa.mathilda (import monalisa as ml; ml.mathilda(...)). The arguments keep the names of the MATLAB functions; Renaming: MATLAB names → Python names gives the MATLAB name of each function.

MATLAB names

find_function(matlab_name)[source]

The Python function or class ported from the MATLAB function matlab_name.

Returns None when it is not ported. Example: find_function("bmMathilda") is monalisa.recon.mathilda.

monalisa.MATLAB_NAMES

Dictionary of the ported MATLAB functions: MATLAB name → Python name relative to the package ("bmMathilda" → "recon.mathilda"). The table is Renaming: MATLAB names → Python names.

recon

Reconstructions: gridded (mathilda, nasha), iterative (sensa, sleva, steva) and chain reconstructions with temporal regularization, optionally motion-compensated (teva_morphosia_chain, teva_duo_morphosia_chain, sensitiva_morphosia_chain).

mathilda(y, t, v, C=None, N_u=None, n_u=None, dK_u=None, kernelType=None, nWin=None, kernelParam=None, fft_lib_flag=None, leight_flag=None)[source]

Gridded reconstruction of non-Cartesian data.

Density-compensated gridding of y (trajectory t, volume elements v) on the grid N_u with step dK_u, centered inverse FFT, deapodization, cropping to n_u and, when coil sensitivities C are given, coil combination. Without C one image per channel is returned (block format [n_u, nCh]). Output is complex single.

nasha(y, G, n_u, C=None, K=None, fft_lib_flag=None)[source]

Gridded reconstruction with a precomputed gridding matrix G (Gn).

y is [nPt, nCh] single. Gridding, centered inverse FFT, deapodization K, cropping to n_u and, with C, coil combination.

sensa(x, y, ve, C, Gu, Gut, frSize, nCGD, ve_max, nIter, witnessInfo)[source]

SENSE reconstruction: nIter restarts of nCGD conjugate gradient steps on the density-weighted least squares data fidelity, from x.

sensitiva_morphosia_chain(x, y, ve, C, Gu, Gut, frSize, Tu, Tut, delta, regul_mode, nCGD, ve_max, nIter, witnessInfo)[source]

Chain reconstruction with a quadratic (L2) penalty on the differences between consecutive (optionally motion-compensated) frames, by restarted conjugate gradient; regul_mode 'normal' or 'adapt'.

sleva(x, y, ve, C, Gu, Gut, frSize, delta, regul_mode, nCGD, ve_max, nIter, witnessInfo)[source]

L2 (Tikhonov) regularized reconstruction by restarted conjugate gradient; regul_mode 'normal' (fixed delta) or 'adapt'.

steva(x, z, u, y, ve, C, Gu, Gut, frSize, delta, rho, nCGD, ve_max, nIter, witnessInfo)[source]

Total-variation regularized reconstruction (ADMM: nCGD conjugate gradient steps for x, soft thresholding for z, dual update u).

teva_duo_morphosia_chain(x, z1, z2, u1, u2, y, ve, C, Gu, Gut, frSize, Tu1, Tu1t, Tu2, Tu2t, delta, rho, regul_mode, nCGD, ve_max, nIter, witnessInfo, *, nargout=1)[source]

Chain reconstruction with temporal total variation toward both the previous (Tu1) and the next (Tu2) frame. Returns x or, with nargout, (x, z1, z2, u1, u2).

teva_morphosia_chain(x, z, u, y, ve, C, Gu, Gut, frSize, Tu, Tut, delta, rho, regul_mode, nCGD, ve_max, nIter, witnessInfo)[source]

Reconstruction of a chain of frames with temporal total variation between consecutive frames (optionally motion compensated by the deformation matrices Tu/Tut), by ADMM with nCGD conjugate gradient steps per iteration. x, y, ve, Gu, Gut (and Tu, Tut) are cells over frames.

io

Raw data readers (Siemens twix .dat, ISMRMRD .mrd), acquisition parameters, MATLAB v7.3 files and directories.

class IsmrmrdReader(filepath, autoFlag)[source]

Reader of ISMRMRD .mrd files.

read_meta_data()[source]
read_raw_data(flagSS=False, flagExcludeSI=False)[source]
class MriAcquisitionParam(arg_name=None)[source]

Acquisition parameters of a raw data set (number of points per line N, segments nSeg, shots nShot, FoV, trajectory type, …).

refresh()[source]

Fill the missing counts from the others (as single, like MATLAB).

parity_fields()[source]
classmethod from_matlab_fields(fields)[source]
class RawDataReader(filepath, autoFlag)[source]

Raw data reader: argFile, autoFlag (no user interaction when true) and the acquisitionParams read at construction.

read_meta_data()[source]
read_raw_data(flagSS=False, flagNoSI=False)[source]
classmethod from_matlab_fields(fields)[source]

Rebuild a reader recorded in MATLAB without reading the file again.

class SiemensReader(filepath, autoFlag)[source]

Reader of Siemens twix .dat files.

read_meta_data()[source]
read_raw_data(flagSS=False, flagExcludeSI=False)[source]

Readouts [nCh, N, nLine]; flagSS drops the non steady-state shots, flagExcludeSI the self-navigation (first) segment of each shot.

check_dir(argDir, dlgFlag=True)[source]

1 when argDir is an existing directory, else 0 (no dialog in Python).

check_metadata_interactive(mySI, s_mean, s_center_mass, myMriAcquisition_node, reconFoV)[source]

Plot the self-navigation magnitude of the first segment of every shot (with its mean and centre of mass), with a draggable line at the estimated steady-state shot nShot_off, above the editable parameter table of correct_metadata_interactive(). Waits until Confirm.

Without a window: autoFlag=True and set reader.acquisitionParams.nShot_off etc. Returns (myMriAcquisition_node, reconFoV).

correct_metadata_interactive(myMriAcquisition_node, reconFoV)[source]

Let the user correct the extracted acquisition parameters in a table (N, nLine, nShot, nSeg, nCh, nEcho, nShotOff, FoV, reconstruction FoV), the navigation type and the oversampling flag. Waits until Confirm; Cancel or closing keeps the extracted values.

Opened by the raw data readers when autoFlag is false or the FoV could not be read. Without a window: autoFlag=True and set reader.acquisitionParams fields in the code. Returns (myMriAcquisition_node, reconFoV).

create_dir(argDir, myErrorFlag=False)[source]

Create argDir; returns 1 when created, 0 when it already existed.

create_raw_data_reader(filepath, autoFlag)[source]

Reader for a raw data file, chosen by extension (.dat Siemens, .mrd ISMRMRD).

ismrmrd_read_meta_data(obj, nargout=1)[source]

Acquisition parameters of an ISMRMRD file (counts from the acquisition headers, FoV = 2 x encoded FoV of the XML header, nShot_off estimated from the self-navigation signal). Returns the parameters or (parameters, reconFoV). With obj.autoFlag false the parameters are shown for checking (check_metadata_interactive).

ismrmrd_read_raw_data(obj, flagSS, flagExcludeSI)[source]

Readouts [nCh, N, nSeg*nShot] (single) of an ISMRMRD file, optionally without the non steady-state shots and the self-navigation segment.

loadmat73(path, variable_names=None)[source]

Numeric, logical and cell variables of a MATLAB v7.3 MAT-file, with MATLAB shapes.

Older MAT-files (MATLAB save without -v7.3) are read with scipy.io.loadmat.

savemat73(path, variables)[source]

Save numeric/logical arrays as a MATLAB v7.3 MAT-file (MATLAB shapes kept).

The file is written next to path under a temporary name and renamed when complete, so that an interrupted run (killed kernel, full disk) never leaves a truncated file at path.

siemens_read_meta_data(obj, nargout=1)[source]

Acquisition parameters of a Siemens file.

The number of non steady-state shots nShot_off is estimated from the self-navigation signal. When obj.autoFlag is false, or the FoV is not in the header, the parameters are shown for correction (correct_metadata_interactive, then check_metadata_interactive with the self-navigation plot); with autoFlag=True set the fields of the returned object in the code instead. Returns the parameters, or (parameters, reconFoV) for nargout=2.

siemens_read_raw_data(obj, flagSS, flagExcludeSI)[source]

Readouts [nCh, N, nSeg*nShot] of a Siemens file (see SiemensReader.read_raw_data).

trajectory

Trajectories: generation from the acquisition parameters, grid size and step, line format, norms and the low-resolution part of the data.

low_res(c, t, ve, N_u, dK_u, nargout=3)[source]

Keep the samples whose trajectory lies in the box of N_u grid steps dK_u.

Returns (c, t, ve) restricted to these points (truncated to nargout).

phyllotaxis_angle3(nseg, nshot, flagSelfNav=0)[source]

Polar theta and azimuthal phi angles (rows of length nseg*nshot) of the 3D golden-angle phyllotaxis spiral; with flagSelfNav the first segment of each shot points along z (theta = phi = 0).

traj(mriAcquisition_node)[source]

Trajectory of an acquisition, dispatched on mriAcquisition_node.traj_type.

traj_format(argTraj, argData=None, nargout=1)[source]

Merge all k-space center points of a trajectory into a single point.

Returns formatedTraj or (formatedTraj, formatedData, formatedIndex, formatedWeight) truncated to nargout. formatedIndex holds 1-based MATLAB indices (as doubles) into formatedTraj.

traj_full_radial3_phyllotaxis_line_assym2(*varargin)[source]

3D full-radial phyllotaxis trajectory [3, N, nLine].

Called with an acquisition parameter object, or with (N_n, nSeg, nShot, dK_n, flagSelfNav, nShot_off). Self-navigation lines (first segment of each shot) and the first nShot_off shots are removed.

traj_grid(t, N_u=None, dK_u=None)[source]

Return (N_u, dK_u), guessing the ones not given from the trajectory.

traj_grid_size(t)[source]

Guess the Cartesian grid size N_u from the number of points per line.

traj_grid_step(t, N_u=None)[source]

Guess the Cartesian grid step dK_u from the trajectory extent.

traj_line_direction(t)[source]

Unit direction of each line of a trajectory in line format [imDim, N, nLine].

traj_line_reshape(t, data=None, nargout=1)[source]

Reshape a trajectory (and optionally its data) to line format [imDim, N, nLine].

traj_n_line(argTraj, nargout=1)[source]

Detect the number of straight lines of a trajectory.

Returns nLine or, for nargout > 1, (nLine, N, isN_integer, dK_list) truncated to nargout values, with N = nPt / nLine points per line.

traj_norm(t)[source]

Euclidean norm of each trajectory point, shaped like size(t)(2:end).

traj_squared_norm(t)[source]

Squared norm of each trajectory point, shaped [1, size(t)(2:end)].

geometry

Volume elements (density compensation weights) of trajectories, and Voronoi cells.

volume_element(argTraj, argType, *varargin)[source]

Volume elements (density compensation) of a trajectory, or of each trajectory of a cell. varargin is (N_u, dK_u) as in MATLAB.

volume_element1(x)[source]

1D Voronoi lengths of the samples x (columns sorted by the first column).

volume_element_cartesian2(t)[source]

Volume element of a (possibly rotated) 2D Cartesian grid: product of the grid steps along the grid axes, the same for all points.

volume_element_center_out_radial3(t)[source]

Volume elements of a 3D center-out radial trajectory (uniform solid angle).

volume_element_full_radial3(t)[source]

Volume elements of a 3D full-radial trajectory assuming uniformly spread lines.

volume_element_random_partial_cartesian2_x(t, N_u, dK_u)[source]

Volume elements of 2D Cartesian lines along x at random y positions.

volume_element_random_partial_cartesian3_x(t, N_u, dK_u)[source]

Volume elements of 3D Cartesian lines along x at random (y, z) positions.

volume_element_voronoi_box2(t, N_u, d_u)[source]

Voronoi areas of 2D points bounded by a frame of extra points around the grid N_u with step d_u.

volume_element_voronoi_center_out_radial2(t)[source]

Volume elements of a 2D center-out radial trajectory.

volume_element_voronoi_full_radial2(t)[source]

Volume elements of a 2D full-radial trajectory (radial x angular Voronoi).

volume_element_voronoi_full_radial3(t)[source]

Volume elements of a 3D full-radial trajectory (radial x spherical Voronoi).

voronoi(x, dispFlag=True)[source]

Voronoi cell volume of each point of x ([imDim, nPt]).

Unbounded cells get -1. For imDim == 1 the 1D lengths of volume_element1 are returned (as a column, like MATLAB).

gridding

Gridding of non-Cartesian data on a Cartesian grid, and the sparse gridding and deformation matrices.

gridder_n2u_leight(y, t, v, N_u, dK_u, kernelType=None, nWin=None, kernelParam=None)[source]

Grid non-uniform data y [nCh, nPt] onto the uniform grid N_u.

Density-compensated (v) Gaussian gridding with per-cell normalization. Returns [nCh, N_u] complex single. Like the MEX implementation, the kernel is Gaussian with width kernelParam[0] whatever kernelType is.

im_deform_field_to_sparse_mat(v, N_u, Dn=None, torus_flag=None, *, nargout=2)[source]

Sparse interpolation matrices of the deformation field v: Gn (nargout 1), (Gu, Gut) (2) or (Gn, Gu, Gut) (3). Gu warps an image (column format) by v; Gut is its transpose.

im_deform_field_to_sparse_mat_ind_weight(v, N_u, Dn, torus_flag)[source]

Grid indices (ind_1), point indices (ind_2, both 1-based doubles) and bump-kernel weights of the interpolation at the displaced pixel positions x + v; returns (ind_1, ind_2, myWeight, Dn) as columns.

traj_to_sparse_mat(t, v, N_u, dK_u, sparseType=None, kernelType=None, nWin=None, kernelParam=None, *, nargout=3)[source]

Gridding matrices of the trajectory t with volume elements v.

nargout selects the outputs as in MATLAB: Gn (1), (Gu, Gut) (2) or (Gn, Gu, Gut) (3). Gn ([prod(N_u), nPt]) grids density-compensated data onto the Cartesian grid, Gu ([nPt, prod(N_u)]) interpolates the grid at the trajectory points and Gut is its transpose. Cells of trajectories give cells of matrices.

sparse

Monalisa’s row-compressed sparse matrix (SparseMat) and its products with vectors.

class SparseMat[source]

Sparse matrix in Monalisa’s row-compressed format.

Rows are the left (l) side, columns the right (r) side. For each row r_nJump holds its number of non-zeros; their column indices are r_ind (1-based, type 'matlab_ind') or, once cpp_prepare has run, the jumps r_jump between consecutive non-zeros (absolute 0-based index at the start of each block). l_squeeze removes empty rows; their positions are then kept in l_ind / l_jump. Values m_val are single precision.

l_squeeze()[source]

Remove the empty rows (type 'matlab_ind' -> 'l_squeezed_matlab_ind').

cpp_prepare(argMode, nJumpPerBlock_factor=None, blockLengthMax_factor=None)[source]

Convert indices to jumps and partition the rows in blocks.

check()[source]

Consistency checks of the MATLAB class; raises when one fails.

csr()[source]

Decoded structure (row_of, row_start, cols, vals) of a cpp_prepared matrix: stored row i is output row row_of[i] with non-zeros row_start[i]:row_start[i+1] in cols (0-based) / vals.

parity_fields()[source]
classmethod from_matlab_fields(fields)[source]

Rebuild an object from the properties recorded in MATLAB.

sparse_mat_block_partition(r_nJump, nJumpPerBlock_factor, blockLengthMax_factor, mode=None)[source]

Partition the rows in blocks of bounded number of non-zeros.

Returns (l_block_start, block_length, nBlock, zero_block_flag); with mode == 'one' a single block holds all rows.

sparse_mat_complete_matlab_sparse(argSparse, mySize)[source]

Pad a sparse matrix with empty rows/columns up to mySize.

sparse_mat_from_matlab_sparse(a, N_u, d_u, kernelType, nWin, kernelParam)[source]

Convert a (scipy) sparse matrix to a SparseMat of type 'matlab_ind'.

sparse_mat_r_n_jump_to_index(r_nJump)[source]

1-based row index of every non-zero, given the number of non-zeros per row (int32 row).

sparse_mat_vec(s, v, *varargin)[source]

Product of the SparseMat s with the vectors v (single).

varargin: omp_flag ('omp' or bool), 'complex' / 'real', and the transpose flag T (vectors are the rows of v; by default guessed from the shape as in MATLAB). Returns [l_size, n_vec] (or [n_vec, l_size] in row mode), single.

fourier

Centered discrete Fourier transforms (dft1 … idf3 and their adjoints), the deapodization and scaling factors of the gridding (deapodization, kf, fc), and the non-Cartesian Fourier model: forward shanna, adjoint nakatsha.

deapodization(N_u, dK_u, nCh, kernelType=None, nWin=None, kernelParam=None)[source]

Deapodization kernel of the gridding kernel, in column format [prod(N_u), nCh] (single), clipped at K_max.

dft1(x, N_u, dK_u)[source]

Centered 1D Fourier transform scaled by 1/(prod(N_u)*prod(dK_u)).

dft1_conj_trans(x, N_u, dK_u)[source]

Adjoint of dft1 (centered inverse FFT and scaling).

dft2(x, N_u, dK_u)[source]

Centered 2D Fourier transform scaled by 1/(prod(N_u)*prod(dK_u)).

dft2_conj_trans(x, N_u, dK_u)[source]

Adjoint of dft2 (centered inverse FFT and scaling).

dft3(x, N_u, dK_u)[source]

Centered 3D Fourier transform scaled by 1/(prod(N_u)*prod(dK_u)).

dft3_conj_trans(x, N_u, dK_u)[source]

Adjoint of dft3 (centered inverse FFT and scaling).

fc(C, N_u, n_u, dK_u)[source]

Fourier scaling 1/prod(N_u)/prod(dK_u) times C, column format, single.

fc_conj(C_conj, N_u, n_u, dK_u)[source]

Fourier scaling 1/prod(dK_u) times C_conj, column format, single.

idf(f, k, nZero=None, nDim=None, gridType=None, nargout=1)[source]

Inverse discrete Fourier transform of f along dimension nDim (1-based) sampled on the frequency grid k (or with step k when scalar).

Returns iFf or (iFf, x, outGridType). Grid types follow upstream: 0 odd centered, 1/2 even shifted right/left, 3 even symmetric, 4 general.

idf1(x, N_u, dK_u)[source]

Centered 1D inverse Fourier transform scaled by prod(N_u)*prod(dK_u).

idf1_conj_trans(x, N_u, dK_u)[source]

Adjoint of idf1 (centered FFT and scaling).

idf2(x, N_u, dK_u)[source]

Centered 2D inverse Fourier transform scaled by prod(N_u)*prod(dK_u).

idf2_conj_trans(x, N_u, dK_u)[source]

Adjoint of idf2 (centered FFT and scaling).

idf3(x, N_u, dK_u)[source]

Centered 3D inverse Fourier transform scaled by prod(N_u)*prod(dK_u).

idf3_conj_trans(x, N_u, dK_u)[source]

Adjoint of idf3 (centered FFT and scaling).

kf(C, N_u, n_u, dK_u, nCh, kernelType=None, nWin=None, kernelParam=None)[source]

Deapodization times Fourier scaling 1/prod(N_u)/prod(dK_u) (times C when given), column format [prod(n_u), nCh], single.

kf_conj(C_conj, N_u, n_u, dK_u, nCh, kernelType=None, nWin=None, kernelParam=None)[source]

Deapodization times 1/prod(dK_u) (times C_conj when given), for the adjoint operator; column format [prod(n_u), nCh], single.

nakatsha(y, G, KFC_conj, C_flag, n_u, fft_lib_sFlag)[source]

Adjoint non-Cartesian Fourier model; only the 'MATLAB' FFT backend exists in Python.

nakatsha_matlab(y, G, KFC_conj, C_flag, n_u)[source]

Adjoint model: data y [nPt, nCh] -> image (column format).

Gridding G (normally Gut), centered inverse FFT, cropping to n_u, multiplication by KFC_conj and, if C_flag, sum over coils.

shanna(x, G, KFC, n_u, fft_lib_sFlag)[source]

Forward non-Cartesian Fourier model; only the 'MATLAB' FFT backend exists in Python.

shanna_matlab(x, G, KFC, n_u)[source]

Forward model: image x (column format) -> non-Cartesian data [nPt, nCh].

x .* KFC, zero filling to G.N_u, centered FFT, interpolation G.

coil

Coil sensitivity estimation from body and surface coil scans, and coil combination.

coil_sense_non_cart_data(reader, N_u, nargout=3)[source]

Low-resolution data y (column format), trajectory t and volume elements ve of a raw file, restricted to the box of N_u points at the raw resolution 1/FoV. Returns up to nargout of (y, t, ve).

coil_sense_non_cart_mask_automatic(y, Gn, autoFlag, th_RMS=None, th_MIP=None, borders=None, open_size=None, close_size=None)[source]

Mask of the object for coil sensitivity estimation, from thresholds of the RMS and MIP over channels of the gridded images, cut to a bounding box.

With autoFlag false the thresholds (threshold_rms_mip) and the bounding box (select_roi) are chosen in windows, starting from the automatic values, and the RMS, MIP and masked images are shown (show_image). The chosen values are printed; passing them as th_RMS, th_MIP and borders reproduces the mask without windows.

coil_sense_non_cart_primary(y, y_ref, C_ref, Gn, ve, m)[source]

First estimate of the coil sensitivities of the array y relative to the reference coil (y_ref, C_ref), smoothed in the mask m and harmonically extended outside.

coil_sense_non_cart_ref(y, Gn, m, nSmooth_phi=None)[source]

Reference coil (first channel of y) and its sensitivity: magnitude relative to the RMS image, smoothed in the mask and harmonically extended outside. Returns (y_ref, C_ref).

coil_sense_non_cart_secondary(y, C, y_ref, C_ref, Gn, Gu, Gut, ve, nIter, display_flag=False, nargout=1)[source]

Refine the coil sensitivities C jointly with the image by nIter alternating gradient steps on the data consistency of all coils (reference coil included and kept fixed). Returns C or (C, x).

coil_sense_pinv(C, x0, n_u)[source]

Coil combination sum(conj(C) .* x0, 2) ./ sum(abs(C).^2, 2) in single precision.

detect_roi(rawData, N_u)[source]

Bounding box [xMin, xW; yMin, yW; zMin, zW] (1-based) of the object in a 3D image, from Otsu-thresholded projections, padded by 3 voxels.

select_roi(dataRMS, dataMIP, N_u, autoFlag=None, boxPos=None)[source]

Bounding box of the region of interest, drawn on the RMS and MIP images summed along x, y and z (6 images; moving one rectangle updates the others, and the limits can be typed in). boxPos = [xMin, xWidth; yMin, yWidth; zMin, zWidth] is the initial box (default [2, min(N_u) - 4] on every axis). Waits until Confirm.

Returns [xMin, xMax; yMin, yMax; zMin, zMax] (1-based). Closing the window without confirming returns the initial box. Without a window: pass borders to coil_sense_non_cart_mask_automatic.

threshold_rms_mip(colorMax, dataRMS, dataMIP, N_u, autoFlag)[source]

Thresholds (thRMS, thMIP) separating background from object in the RMS and MIP images (crossing of a two-Gaussian fit of their histograms).

With autoFlag false a window shows the fraction of voxels above each value with the two thresholds as draggable lines, and a slice of the thresholded RMS and MIP images (scroll to change slice, menu for the view, “Contrast” for the binary mask). Confirm returns the chosen thresholds; closing the window returns the automatic ones.

binning

Binning of the acquired lines (mitosis) and binned data written to and read from disk (mitosius).

mitosis(*varargin, nargout=2)[source]

Split nargout tables (last dimension = samples) into bins.

The remaining arguments are 2D logical masks [nPhase, nSample] (or one cell of them); every combination of one phase per mask is a bin. Returns one [N_tot, 1] cell per table.

mitosius_create(mitosius_dir, *varargin)[source]

Write binned data to mitosius_dir/cell_<i>[_<j>...]/{y,t,ve}.mat (MATLAB v7.3) and mitosius_size.mat. Arguments: (y_cell, t_cell, ve_cell) or (mitosius_length,).

mitosius_load(mitosius_dir, arg_name, *edges)[source]

Load the variable arg_name of every cell (or of the cells selected by edges: 1-based indices or 'all' per mitosius dimension).

image

Image operations: cropping, zero filling, resizing, deformation, Laplace and diffusion smoothing, and projections over the channels (rms, mip).

im_crop(arg_im, N_u, n_u)[source]

Crop the centered region of size n_u from images of size N_u.

im_deform(Tu, x, n_u, K=None)[source]

Apply the deformation matrix Tu to the images x (identity when Tu is empty); with K the deformed images are filtered in k-space.

im_deform_field_hard_thresholding2(v, n_u, argTh)[source]

Clip the length of the 2D displacement vectors of v to argTh pixels.

im_deform_t(Tut, x, n_u, K=None)[source]

Adjoint of im_deform (Tut is the transposed deformation matrix).

im_dim(a, nargout=2)[source]

Image dimension n (vectors are 1D, empty is 0) and size s; with nargout up to 5 also sx, sy, sz (None when absent).

im_laplace_equation_solver(imStart, m, nIter, L_th, omp_flag=None, nBlockPerThread=None)[source]

Harmonic extension of imStart outside the mask m: blocks of nIter iterations until the relative Laplacian norm outside m is below L_th.

im_laplace_iterator(imStart, m, nIter, omp_flag=None, nBlockPerThread=None)[source]

nIter (rounded up to even) Jacobi iterations of the discrete Laplace equation, keeping the voxels where m is true at their initial value. Real and imaginary parts are solved separately, in single precision.

im_laplacian(argIm)[source]

Discrete Laplacian (linear-offset neighbours, see mex/_laplace), single precision.

im_pseudo_diffusion(argIm, nIter=None)[source]

Smoothing by repeated averaging over the cross neighbourhood (periodic), single precision.

im_pseudo_diffusion_in_mask(argIm, argMask, nIter=None)[source]

Smoothing restricted to the mask (averages of the masked cross neighbours); values outside the mask are kept.

im_reshape(argIm, nargout=3)[source]

Image as column (1D) or unchanged, with (imDim, imSize, sx, sy, sz).

im_resize(argIm, n_u, N_u, interp_option=None)[source]

Resample images of size n_u to size N_u on the periodic grid used by Monalisa (cubic interpolation by default). Returns double.

im_zero_fill(arg_im, N_u, n_u, argType)[source]

Embed images of size n_u at the center of zero images of size N_u.

mip(y, N_u)[source]

Maximum intensity projection over the channels.

rms(x, N_u)[source]

Root mean square over the channels.

registration

Deformation fields between frames by demons registration (SimpleITK), for motion-compensated reconstructions.

im_deform_field_chain_im_reg_demons23(x, n_u, chain_type, nIter, nSmooth, arg_name, myMask=None, maxPixDisplacement=None, *, nargout=1)[source]

Demons deformation fields between the frames of the chain x.

chain_type says which frame is registered to which ('curr_to_prev': the field warping frame i onto frame i-1, cyclically, etc.). Each frame is smoothed nSmooth times and rescaled to [0, 255] before a 3-level demons registration with [nIter, fix(nIter/2), fix(nIter/4)] iterations. The fields are masked by myMask, clipped to maxPixDisplacement pixels (2D) and returned in point format [imDim, nPt]. With nargout=2 the registered images are returned too. If arg_name is given, the fields are saved to arg_name and the images to arg_name + '_im_out' (v7.3 MAT-files).

im_deform_field_sheet_im_reg_demons23(x, n_u, sheet_type, nIter, nSmooth, arg_name, myMask=None, maxPixDisplacement=None, *, nargout=2)[source]

Demons deformation fields along both dimensions of the sheet x (nCell_1 x nCell_2 cell).

Like im_deform_field_chain_im_reg_demons23(), for the neighbours along the first (imDeformField_1, nIter[0] iterations) and the second dimension (imDeformField_2, nIter[1] iterations), cyclically. Returns (imDeformField_1, imDeformField_2) and, with nargout=4, the registered images (im_out_1, im_out_2) too. If arg_name is given, the four cells are saved to arg_name + '_1', '_2', '_im_out_1' and '_im_out_2' (v7.3 MAT-files).

optim

Building blocks of the iterative reconstructions: finite differences, inner products and norms, element-wise operations on cells, proximal operators and the convergence monitor (WitnessInfo).

class WitnessInfo(witness_name=None, witness_ind=None, save_witnessIm_flag=None)[source]

Monitor of an iterative reconstruction: parameters, per-iteration values and, at the iterations witness_ind, the current image saved to x_<name>.mat in out_dir (the working directory by default, like MATLAB).

watch(curr_ind, x, n_u, loop_or_final, z=None, u=None)[source]

Record the iteration curr_ind; save x (and z, u) when it is a witness index.

parity_fields()[source]
classmethod from_matlab_fields(fields)[source]
axpy(a, x, y)[source]

a .* x + y, also for cells (a scalar, array or cell).

back_gradient(x, n_u, dX_u)[source]

Backward-difference gradient [prod(n_u), imDim] (complex single).

back_gradient_n(x, n_u, dX_u, n)[source]

Backward finite difference along dimension n (1-based), zero on the first slice.

back_gradient_n_t(x, n_u, dX_u, n)[source]

Adjoint of back_gradient_n.

back_gradient_t(g, n_u, dX_u)[source]

Adjoint of back_gradient (complex single column).

euclidean_prod(x1, x2, H)[source]

Weighted inner product real(x1' * (H .* x2)), summed over cells.

initial_witness_info(witnessInfo, function_label=None, N_u=None, n_u=None, dK_u=None, ve_max=None, nIter_max=None, nCGD=None, delta=None, rho=None, regul_mode=None)[source]

Store the reconstruction parameters in witnessInfo.param (cells 1-13).

minus(x, y)[source]

x - y element-wise, also for cells of arrays.

mult(x, y)[source]

x .* y element-wise, also for cells of arrays.

plus(x, y)[source]

x + y element-wise, also for cells of arrays.

prox_one_norm(w, s)[source]

Proximal operator of s * ||.||_1: soft thresholding (real and imaginary parts separately for complex data), single precision.

squared_norm(x, H)[source]

Weighted squared norm real(x' * (H .* x)).

y_norm(y, d_n, collapse_flag=None)[source]

Norm of each channel of y weighted by the volume elements d_n; with collapse_flag the norm over all channels.

y_ve_reshape(ve, y_size)[source]

Expand volume elements ve to the size y_size of the data [nPt, nCh].

display

Image viewers (napari windows, sliders in Jupyter notebooks) and polygon masks.

The interactive dialogs of the MATLAB code (metadata check, coil-mask thresholds and bounding box) live next to the functions that open them and use the helpers of monalisa.display._qt. Every interactive step has a non-interactive equivalent (a parameter).

poly2mask(c, r, shape)[source]

Pixels of an image of size shape whose centre lies inside the polygon with vertices (c, r) (1-based column and row coordinates, as MATLAB poly2mask; edge pixels can differ from MATLAB’s sub-pixel rule).

roipoly(image, c=None, r=None)[source]

Binary mask of a polygon drawn on image (2D, shown with rows down and columns across, as MATLAB imagesc).

roipoly(image) opens a window: click the vertices, close the polygon on the first vertex (it can then be moved and edited), and press Confirm. The vertices are printed, so the same mask can be rebuilt without the window: roipoly(image, c, r) with the 1-based column and row coordinates of the vertices (MATLAB roipoly(I, c, r)).

show_image(argImage, view=None, *, name=None, contrast=None, block=False, viewer=None, **old_names)[source]

Show a 2D, 3D, 4D or 5D image (or a cell / list of equally sized frames).

Axes keep the MATLAB layout (x, y, z, t, ...): the slice x(:, :, k) is shown with x down the rows and y along the columns, as in MATLAB, and z, t have sliders. Complex images are shown as magnitudes.

Parameters:
  • argImage (the image, or a list / cell of frames of the same size (stacked along t).)

  • view (how to show it:) –

    • "inline": sliders and the slice below the cell (Jupyter only, no window);

    • "window": a napari window with one slice view (views along x, y or z, contrast, points; the cube button at its bottom left switches to 3D);

    • "3d": the same window, opened in 3D (volume rendering, rotate with the mouse);

    • "ortho": one window laid out like ITK-SNAP: the slices along z, x and y and a 3D view, linked by a cursor (click in a slice view to move it).

    Default: "inline" in Jupyter, "window" otherwise. Windows also open from Jupyter, next to the notebook (they need a display). In Jupyter without a display (Docker on macOS or Windows, a remote server), the window views fall back to "inline", with a warning.

  • name (title of the window and name of the image.)

  • contrast ((low, high) display range; default: the data range.)

  • block (in a script, wait until the window is closed. Windows opened from a script close when) – it ends: pass block=True on the last call (like plt.show()). Not needed in Jupyter.

  • viewer (add the image to this napari Viewer (returned by an earlier show_image call)) – instead of opening a new window, to compare reconstructions: the images are shown side by side in one row, in the order they were added, with shared sliders (napari grid mode; viewer.canvas.grid.shape = (2, 2) for another arrangement). The grid button at the bottom left of the window stacks them instead; hide the top one with the eye icon of the layer list to see the one below.

Returns:

  • The viewer, to keep working with it from code (a napari Viewer ("window", "3d";)

  • its layers hold the data and any points placed), an ``OrthoViewer`` (``”ortho”`` (.point,)

  • .set_point) or the notebook viewer ("inline").

array

Array formats of Monalisa: block [N_u, nCh], column [prod(N_u), nCh] and point [nCh, nPt] formats of images and data, and cells of arrays.

block_reshape(argIn, N_u)[source]

Reshape argIn (or each element of a cell) to block shape [N_u, nCh].

nCh = numel(argIn) / prod(N_u); MATLAB drops the trailing nCh when it equals 1. Returns None (MATLAB []) for empty input.

cell_to_array(c)[source]

Stack the equally sized arrays of a cell into one array [size(c{1}), size(c)].

col(a)[source]

MATLAB a(:).

col_reshape(argIn, argSize)[source]

Reshape argIn (or each element of a cell) to column shape [prod(argSize), nCh].

index_to_multi_index(argInd, argSize)[source]

1-based linear index -> 1-based multi-index (row of doubles), column-major.

is_block_shape(x, N_u)[source]

True when size(x) equals [N_u, nCh] exactly (MATLAB isequal).

is_col_shape(x, N_u)[source]

True when size(x) equals [prod(N_u), nCh] exactly (MATLAB isequal).

is_scalar(x)[source]

True for a single element that is not a cell.

permute_to_col(y, argSize=None)[source]

Reshape data [nCh, ...] to [nCh, nPt] and transpose to column format [nPt, nCh].

permute_to_point(y, argSize)[source]

Column format [nPt, nCh] -> point format [nCh, nPt], nPt = prod(argSize).

point_reshape(t, argSize=None)[source]

Reshape t to point format [nCh, nPt].

Vectors become row vectors. nCh is argSize[0] when given, else size(t, 1).

to_single(a)[source]

MATLAB single, applied to every element of a cell.

zero(argSize, argType, frame_size=None)[source]

Zero array of size argSize and type 'real_double', 'complex_double', 'real_single' or 'complex_single'; a cell of them if frame_size is given.

util

Argument defaults shared by the functions (MATLAB varargin handling) and the clock.

default_grid(t, N_u=None, dK_u=None)[source]

Return (N_u, dK_u) (guessed from t when missing), rounded through single.

default_kernel(kernelType=None, nWin=None, kernelParam=None)[source]

Fill in the default gridding kernel: 'gauss', nWin = 3, kernelParam = [0.61, 10] (gauss) or [1.95, 10, 10] (kaiser).

default_sparse_type(sparseType=None)[source]

Default sparse type 'SparseMat'.

time_in_second()[source]

Seconds elapsed since the start of the current month (MATLAB definition).

varargin(myCell=None, nargout=1)[source]

Unpack the cell myCell into nargout values, padding with None.

In the Python port optional arguments are keyword arguments; this function is kept for code that forwards MATLAB-style varargin cells.