seq package
Submodules
seq.B1calibration module
seq.FIDandNoise module
@author: José Miguel Algarín Guisado @modifield: T. Guallart Naval, february 28th 2022 MRILAB @ I3M
seq.autoTuning module
Created on Thu June 2 2022 @author: J.M. Algarín, MRILab, i3M, CSIC, Valencia @email: josalggui@i3m.upv.es @Summary: code to obtain a good combination of tuning/matching Specific hardware from MRILab @ i3M is required
- class AutoTuning[source]
Bases:
MRIBLANKSEQ
seq.cpmg module
@author: José Miguel Algarín Guisado @modifield: T. Guallart Naval, february 28th 2022 MRILAB @ I3M
seq.eddycurrents module
seq.fid module
@author: José Miguel Algarín Guisado MRILAB @ I3M
seq.fix_gain module
- class FixGain[source]
Bases:
Larmor
- sequenceAnalysis(mode=None, save=True)[source]
Analyzes the acquired data from the Larmor sequence to determine the Larmor frequency and compute the corresponding time-domain signal and frequency spectrum.
This method processes the acquired data by generating time and frequency vectors, performing a Fourier transform to obtain the signal spectrum, and determining the central frequency. It updates the Larmor frequency and provides the results in both time and frequency domains. The data is then optionally plotted, and the results are saved for further analysis.
- Parameters:
mode (str, optional) – The mode of execution. If set to ‘Standalone’, the results are plotted in a standalone manner. Defaults to None.
- Returns:
A list containing the time-domain signal and frequency spectrum for visualization.
- Return type:
list
Notes
The Larmor frequency is recalculated based on the signal’s central frequency from the spectrum.
The time-domain signal and frequency spectrum are both included in the output layout for visualization.
The results are saved as raw data and can be accessed later.
If the mode is not ‘Standalone’, the Larmor frequency is updated in all sequences in the sequence list.
- sequenceRun(plotSeq=0, demo=False, standalone=False)[source]
This method sets up the sequence parameters, including the RF pulse amplitudes, acquisition times, and echo times. It initializes the experiment, runs the scan, and processes the acquired data. The Larmor frequency is determined by the spin echo response.
- Parameters:
plotSeq (int, optional) – Flag to indicate if sequence plotting is required. Defaults to 0 (no plotting).
demo (bool, optional) – Flag to indicate if the sequence should run in demo mode (using simulated data). Defaults to False.
standalone (bool, optional) – Flag to indicate if the sequence is run in standalone mode (with plotting). Defaults to False.
- Returns:
True if the sequence ran successfully, False otherwise.
- Return type:
bool
Notes
The sequence assumes that hardware settings are configured correctly (e.g., B1 efficiency, bandwidth).
In demo mode, actual hardware is not used, and simulated data is generated for testing purposes.
seq.gre1d module
@author: José Miguel Algarín Guisado @modifield: T. Guallart Naval, february 28th 2022 MRILAB @ I3M
seq.gre3d module
Created on Sat Nov 13 13:45:05 2021
@author: José Miguel Algarín Guisado MRILAB @ I3M
- class GRE3D[source]
Bases:
MRIBLANKSEQ
- save_ismrmrd()[source]
Save the current instance’s data in ISMRMRD format.
This method saves the raw data, header information, and reconstructed images to an HDF5 file using the ISMRMRD (Image Storage and Reconstruction format for MR Data) format.
Steps performed: 1. Generate a timestamp-based filename and directory path for the output file. 2. Initialize the ISMRMRD dataset with the generated path. 3. Populate the header and write the XML header to the dataset. Informations can be added. 4. Reshape the raw data matrix and iterate over scans, slices, and phases to write each acquisition. 5. Set acquisition flags and properties. 6. Append the acquisition data to the dataset. 7. Reshape and save the reconstructed images. 8. Close the dataset.
Attribute: - self.data_full_mat (numpy.array): Full matrix of raw data to be reshaped and saved.
Returns: None. It creates an HDF5 file with the ISMRMRD format.
- sequenceAtributes()[source]
Add input parameters to the sequence object.
This method iterates over the input parameters and adds them as attributes to the sequence object (self). It multiplies each parameter by its corresponding unit if units are specified (e.g. key = ‘f0’, val = 3, units = 1e-6 will create self.f0 = 3e-6.
- Returns:
None
seq.inversionRecovery module
@author: T. Guallart Naval, november 2021 @modifield: J.M. Algarín, february 25th 2022 @modified: J.M. Algarín, june 8th 2022, adapted to new gui structure MRILAB @ I3M @summary: spin echo with inversion recovery where we sweep the time between the IR pulse and the excitation pulse.
seq.larmor module
@author: José Miguel Algarín Guisado @modifield: T. Guallart Naval, february 28th 2022 MRILAB @ I3M
- class Larmor[source]
Bases:
MRIBLANKSEQ
Runs the Larmor sequence, which uses a spin echo technique to estimate the Larmor frequency.
- sequenceAnalysis(mode=None)[source]
Analyzes the acquired data from the Larmor sequence to determine the Larmor frequency and compute the corresponding time-domain signal and frequency spectrum.
This method processes the acquired data by generating time and frequency vectors, performing a Fourier transform to obtain the signal spectrum, and determining the central frequency. It updates the Larmor frequency and provides the results in both time and frequency domains. The data is then optionally plotted, and the results are saved for further analysis.
- Parameters:
mode (str, optional) – The mode of execution. If set to ‘Standalone’, the results are plotted in a standalone manner. Defaults to None.
- Returns:
A list containing the time-domain signal and frequency spectrum for visualization.
- Return type:
list
Notes
The Larmor frequency is recalculated based on the signal’s central frequency from the spectrum.
The time-domain signal and frequency spectrum are both included in the output layout for visualization.
The results are saved as raw data and can be accessed later.
If the mode is not ‘Standalone’, the Larmor frequency is updated in all sequences in the sequence list.
- sequenceRun(plotSeq=0, demo=False, standalone=False)[source]
This method sets up the sequence parameters, including the RF pulse amplitudes, acquisition times, and echo times. It initializes the experiment, runs the scan, and processes the acquired data. The Larmor frequency is determined by the spin echo response.
- Parameters:
plotSeq (int, optional) – Flag to indicate if sequence plotting is required. Defaults to 0 (no plotting).
demo (bool, optional) – Flag to indicate if the sequence should run in demo mode (using simulated data). Defaults to False.
standalone (bool, optional) – Flag to indicate if the sequence is run in standalone mode (with plotting). Defaults to False.
- Returns:
True if the sequence ran successfully, False otherwise.
- Return type:
bool
Notes
The sequence assumes that hardware settings are configured correctly (e.g., B1 efficiency, bandwidth).
In demo mode, actual hardware is not used, and simulated data is generated for testing purposes.
seq.larmor_pypulseq module
@author: José Miguel Algarín Guisado @modifield: T. Guallart Naval, february 28th 2022 MRILAB @ I3M
seq.larmor_raw module
@author: José Miguel Algarín Guisado @modifield: T. Guallart Naval, february 28th 2022 MRILAB @ I3M
seq.localizer module
Created on Thu June 2 2022 @author: J.M. Algarín, MRILab, i3M, CSIC, Valencia @email: josalggui@i3m.upv.es @Summary: All sequences on the GUI must be here
seq.mriBlankSeq module
Created on Thu June 2 2022 @author: J.M. Algarín, MRILab, i3M, CSIC, Valencia @email: josalggui@i3m.upv.es @Summary: mri blank sequence with common methods that will be inherited by any sequence
- class MRIBLANKSEQ[source]
Bases:
object
Class for representing MRI sequences.
This class provides functionality for creating and managing MRI sequences. It includes methods for setting parameters, generating sequences, processing data, and plotting results.
- mapKeys
Keys for the maps.
- Type:
list
- mapNmspc
Name to show in the GUI.
- Type:
dict
- mapVals
Values to show in the GUI.
- Type:
dict
- mapFields
Fields to classify the input parameters.
- Type:
dict
- mapLen
Length of the input values.
- Type:
dict
- mapTips
Tips for the input parameters.
- Type:
dict
- map_units
Units for the input parameters.
- Type:
dict
- meta_data
Dictionary to save meta data for DICOM files.
- Type:
dict
- rotations
List of rotation matrices.
- Type:
list
- dfovs
List of displacement field of views.
- Type:
list
- fovs
List of field of views.
- Type:
list
- session
Session information.
- Type:
dict
- demo
Demo information.
- Type:
bool
- mode
Mode information for ‘Standalone’ execution.
- Type:
string
- flo_dict
Dictionary containing sequence waveforms.
- Type:
dict
- property IMproperties: dict
Retrieve IM-related properties.
Automatically selects the inputs related to IM fields and returns them along with their corresponding tips.
- Returns:
A dictionary containing IM-related properties. dict: A dictionary containing tips for IM-related properties.
- Return type:
dict
- property OTHproperties: dict
Retrieve OTH-related properties.
Automatically selects the inputs related to OTH fields and returns them along with their corresponding tips.
- Returns:
A dictionary containing OTH-related properties. dict: A dictionary containing tips for OTH-related properties.
- Return type:
dict
- property RFproperties
Retrieve RF-related properties.
Automatically selects the inputs related to RF fields and returns them along with their corresponding tips.
- Returns:
A dictionary containing RF-related properties. dict: A dictionary containing tips for RF-related properties.
- Return type:
dict
- property SEQproperties: dict
Retrieve SEQ-related properties.
Automatically selects the inputs related to SEQ fields and returns them along with their corresponding tips.
- Returns:
A dictionary containing SEQ-related properties. dict: A dictionary containing tips for SEQ-related properties.
- Return type:
dict
- addParameter(key='', string='', val=0, units=True, field='', tip=None)[source]
Add a parameter to the sequence.
This method adds a parameter to the sequence with the specified key, description string, value, units, field, and tip.
- Parameters:
key (str) – The key of the parameter.
string (str) – The description string of the parameter.
val (int/float/str/list) – The value of the parameter. It can be an integer, a float, a string, or a list.
units (bool) – Indicates the units of the parameter (e.g. cm -> 1e-2, or you can use the config/units.py module).
field (str) – The field of the parameter: ‘RF’, ‘IMG’, ‘SEQ’, ‘OTH’.
tip (str) – Additional information or tip about the parameter.
- Returns:
None
- autoProcessing(sampled, k_space)[source]
Perform automated processing on k-space data.
This method performs a series of processing steps on the k-space data to generate an image. The steps include inverse FFT, BM4D filtering, direct FFT, Cosbell filtering, zero-padding, and inverse FFT.
- Parameters:
sampled (ndarray) – The sampled k-space data.
k_space (ndarray) – The k-space data to be processed.
- Returns:
The processed image generated from the k-space data after automated processing.
- Return type:
ndarray
- decimate(data_over, n_adc, option='PETRA', remove=True)[source]
Decimates oversampled MRI data, with optional preprocessing to manage oscillations and postprocessing to remove extra points.
Parameters:
- data_overnumpy.ndarray
The oversampled data array to be decimated.
- n_adcint
The number of adc windows in the dataset, used to reshape and process the data appropriately.
- optionstr, optional
Preprocessing option to handle data before decimation: - ‘PETRA’: Adjusts initial points to avoid oscillations during decimation. - ‘Normal’: Applies no preprocessing (default is ‘PETRA’).
- removebool, optional
If True, removes addRdPoints from the start and end of each readout line after decimation. Defaults to True.
Returns:
- numpy.ndarray
The decimated data array, optionally adjusted to remove extra points.
Workflow:
- Preprocess data (optional):
For ‘PETRA’ mode, reshapes the data into adc windows and adjusts the first few points of each line to avoid oscillations caused by decimation.
For ‘Normal’ mode, no preprocessing is applied.
- Decimate the signal:
Applies a finite impulse response (FIR) filter and decimates the signal by the oversampling factor (hw.oversamplingFactor).
Starts decimation after skipping (oversamplingFactor - 1) / 2 points to minimize edge effects.
- Postprocess data (if `remove=True`):
Reshapes the decimated data into adc windows.
Removes hw.addRdPoints from the start and end of each line.
Reshapes the cleaned data back into a 1D array.
Notes:
This method uses the hardware-specific parameters: - hw.oversamplingFactor: The oversampling factor applied during data acquisition. - hw.addRdPoints: The number of additional readout points to include or remove.
The ‘PETRA’ preprocessing mode is tailored for specialized MRI acquisitions that require smoothing of initial points to prevent oscillations.
- endSequence(tEnd)[source]
Finalize the sequence by setting the gradients, RX, TX, and TTL signals to zero at the specified end time.
- Parameters:
tEnd (float) – End time of the sequence in microseconds.
- fixEchoPosition(echoes, data0)[source]
Adjust the position of k=0 in the echo data to the center of the acquisition window.
This method uses oversampled data obtained with a given echo train length and readout gradient to determine the true position of k=0. It then shifts the sampled data to place k=0 at the center of each acquisition window for each gradient-spin-echo.
- Parameters:
echoes (numpy.ndarray) – The echo data array with dimensions [etl, n], where etl is the echo train length and n is the number of samples per echo. This echo train is acquired in a dummy excitation before the sequence using only the readout gradient.
data0 (numpy.ndarray) – The original data array to be adjusted with dimensions [channels, etl, n].
- Returns:
The adjusted data array with k=0 positioned at the center of each acquisition window.
- Return type:
numpy.ndarray
- static fix_image_orientation(image, axes)[source]
Adjusts the orientation of a 3D image array to match standard anatomical planes (sagittal, coronal, or transversal) and returns the oriented image along with labeling and metadata for visualization.
- Parameters:
image (np.ndarray) – A 3D numpy array representing the image data to be reoriented.
axes (list[int]) – A list of three integers representing the current order of the axes in the image (e.g., [0, 1, 2] for x, y, z).
- Returns:
- A dictionary containing the following keys:
’widget’: A fixed string “image” or “curve” indicating the type of data for visualization.
’data’: The reoriented 3D image array (np.ndarray).
’xLabel’: A string representing the label for the x-axis in the visualization.
’yLabel’: A string representing the label for the y-axis in the visualization.
’title’: A string representing the title of the visualization (e.g., “Sagittal”).
- Return type:
dict
- floDict2Exp(rewrite=True, demo=False)[source]
Check for errors and add instructions to Red Pitaya if no errors are found.
- Parameters:
rewrite (bool, optional) – Whether to overwrite existing values. Defaults to True.
demo – If demo is True it just check for errors. Defaults to False.
- Returns:
True if no errors were found and instructions were successfully added to Red Pitaya; False otherwise.
- Return type:
bool
- getFovDisplacement()[source]
Get the displacement to apply in the FFT reconstruction.
- Returns:
The displacement vector.
- Return type:
np.ndarray
- getIndex(etl=1, nPH=1, sweepMode=1)[source]
Generate an array representing the order to sweep the k-space phase lines along an echo train length.
The method creates an ‘ind’ array based on the specified echo train length (ETL), number of phase encoding steps (nPH), and sweep mode. The sweep mode determines the order in which the k-space phase lines are traversed.
- Parameters:
etl (int) – Echo train length. Default is 1.
nPH (int) – Number of phase encoding steps. Default is 1.
sweepMode (int) – Sweep mode for k-space traversal. Default is 1. - 0: Sequential from -kMax to kMax (for T2 contrast). - 1: Center-out from 0 to kMax (for T1 or proton density contrast). - 2: Out-to-center from kMax to 0 (for T2 contrast). - 3: Niquist modulated method to reduce ghosting artifact (To be tested).
- Returns:
An array of indices representing the k-space phase line traversal order.
- Return type:
numpy.ndarray
- getParameter(key)[source]
Get the value of a parameter.
- Parameters:
key (str) – The key corresponding to the parameter.
- Returns:
The value of the parameter associated with the given key.
- Return type:
Any
- getRotationMatrix()[source]
Get the rotation matrix to rotate through an arbitrary axis.
- Returns:
The rotation matrix.
- Return type:
np.ndarray
- gradTrap(tStart, gRiseTime, gFlattopTime, gAmp, gSteps, gAxis, shimming)[source]
Generate a gradient pulse with trapezoidal shape.
This method generates a gradient pulse with a trapezoidal shape. One step is used to generate a rectangular pulse.
- Parameters:
tStart (float) – Start time of the gradient pulse.
gRiseTime (float) – Rise time of the gradient pulse in microseconds.
gFlattopTime (float) – Flattop time of the gradient pulse in microseconds.
gAmp (float) – Amplitude of the gradient pulse in T/m.
gSteps (int) – Number of steps for the gradient ramps.
gAxis (int) – Axis index for the gradient pulse.
shimming (list) – List of shimming values for each axis in arbitrary units from marcos.
Notes
Time inputs are in microseconds.
Amplitude inputs are in T/m.
shimming is in arbitrary units
- gradTrapAmplitude(tStart, gAmplitude, gTotalTime, gAxis, shimming, orders, rewrite=True)[source]
Generate a gradient pulse with trapezoidal shape according to slew rate and specified amplitude.
This method generates a gradient pulse with a trapezoidal shape according to the specified amplitude and slew rate.
- Parameters:
tStart (float) – Start time of the gradient pulse.
gAmplitude (float) – Amplitude of the gradient pulse in T/m.
gTotalTime (float) – Total duration of the gradient pulse in microseconds.
gAxis (int) – Axis index for the gradient pulse.
shimming (list) – List of shimming values for each axis.
orders (int) – Number of orders.
rewrite (bool, optional) – Whether to overwrite existing gradient data. Defaults to True.
Notes
Time inputs are in microseconds.
gAmplitude input is in T/m.
shimming is in arbitrary units
OUT OF DATE
- gradTrapMomentum(tStart, kMax, gTotalTime, gAxis, shimming, rewrite=True)[source]
Generate a gradient pulse with trapezoidal shape according to slew rate.
This method generates a gradient pulse with a trapezoidal shape based on the provided slew rate and maximum k-value.
- Parameters:
tStart (float) – Start time of the gradient pulse.
kMax (float) – Maximum k-value in 1/m.
gTotalTime (float) – Total time of the gradient pulse in microseconds including flattop and ramps.
gAxis (int) – Axis index for the gradient pulse.
shimming (list) – List of shimming values for each axis.
rewrite (bool, optional) – Whether to overwrite existing gradient data. Defaults to True.
Notes
Time inputs are in microseconds.
kMax inputs are in 1/m.
shimming is in arbitrary units
NOT FULLY TESTED
- image2Dicom(fileName)[source]
Save the DICOM image.
This method saves the DICOM image with the given filename.
- Parameters:
fileName (str) – The filename to save the DICOM image.
- Returns:
None
- iniSequence(t0, shimming)[source]
Initialize the sequence by setting the initial values for gradients, RX, TX, and TTL signals at the desired time.
- Parameters:
t0 (float) – Initial time of the sequence in microseconds.
shimming (list) – List of shimming values for each axis in arbitrary units.
- loadParams(directory='experiments/parameterization', file=None)[source]
Load parameter values from a CSV file.
This method loads parameter values into the mapVals attribute from a specified CSV file. The method first attempts to load the last saved parameters if no specific file is provided. If a file is provided, it loads parameters from the given file. The directory can be either ‘experiments/parameterization’ or ‘calibration’, or any other specified directory for protocol parameters.
- Parameters:
directory (str) – The directory where the CSV file is located. Defaults to ‘experiments/parameterization’.
file (str, optional) – The specific CSV file to load. If not provided, the method loads the last saved parameters based on seqName in mapVals.
- Raises:
KeyError – If ‘seqName’ is not found in mapVals when attempting to load the last parameters.
FileNotFoundError – If the specified file does not exist in the given directory.
Example
self.loadParams()
self.loadParams(directory=’calibration’, file=’calibration_parameters.csv’)
Notes
This method updates the mapVals attribute with the new parameter values from the CSV file.
The method handles different data types (str, int, float) for each parameter key and ensures the correct type is maintained.
If a key is missing in the new parameter values, the old value is retained.
- static move_batch_files(destination_folder, file_name)[source]
Move batch_X.seq files from the current working directory to the specified destination folder.
The method scans all files in the current directory and identifies files with the extension ‘.seq’. It extracts the batch number from the file name (in the format ‘batch_X.seq’, where ‘X’ is the batch number). Then, it moves these files to a subfolder ‘seq’ inside the specified destination folder, renaming them based on the provided file_name template.
Args: - destination_folder (str): The path to the destination folder where the ‘seq’ subfolder will be created, and the files will be moved. - file_name (str): The prefix used for renaming the files. Files will be renamed in the format ‘file_name_X.seq’, where ‘X’ is the extracted batch number from the original file name.
Example
If the file ‘batch_1.seq’ is found and file_name=’processed’, it will be moved and renamed to: ‘destination_folder/seq/processed_1.seq’.
Side Effects: - Creates a ‘seq’ subfolder in the destination folder if it doesn’t already exist. - Moves and renames the matched ‘.seq’ files from the current directory.
- plotResults()[source]
Plot results in a standalone window.
This method generates plots based on the output data provided. It creates a plot window, inserts each plot according to its type (image or curve), sets titles and labels, and displays the plot.
- Returns:
None
- pypulseq2mriblankseq(waveforms=None, shimming=array([0., 0., 0.]), sampling_period=0.0, hardware=True)[source]
Converts PyPulseq waveforms into a format compatible with MRI hardware.
Parameters:
- waveformsdict, optional
Dictionary containing PyPulseq waveforms. The keys represent waveform types (e.g., ‘tx0’, ‘rx0_en’, ‘grad_vx’), and values are arrays of time and amplitude pairs.
- shimmingnumpy.ndarray, optional
Array of three values representing the shimming currents to apply in the x, y, and z gradients, respectively. Defaults to [0.0, 0.0, 0.0].
- sampling_periodfloat, optional
Sampling period in seconds, used to account for delays in the CIC filter. Defaults to 0.0.
- hardware: bool, optional
Take into account gradient and ADC delay
Returns:
- bool
Returns True if the conversion is successful.
Workflow:
- Reset flo_dict:
Initializes the flo dictionary, which stores gradient, RF, and TTL signals for MRI hardware execution.
- Fill flo_dict:
Iterates through the input waveforms to populate the flo dictionary. Each key corresponds to a signal type, and the waveform data is appended.
- Fill missing keys:
Ensures that all keys in flo_dict are populated, even if no data exists for certain signals. Unfilled keys are set to default arrays with zero values.
- Apply shimming:
Adds the shimming values to the corresponding gradient channels (x, y, z).
- Set sequence end:
Ensures all signals return to zero at the end of the sequence to finalize waveform execution.
- Add hardware-specific corrections:
Applies gradient latency adjustments.
Accounts for CIC filter delays in the receive (rx) signals.
- Revalidate sequence end:
Reassesses and ensures all signal channels return to zero with a buffer period.
Notes:
This method processes and validates input waveform data to ensure compatibility with MRI hardware.
Hardware-specific parameters such as gradient delay (hw.gradDelay) and CIC filter delay (hw.cic_delay_points) are applied.
Any signal not specified in waveforms is initialized with a default value of zero.
- resetMapVals()[source]
Reset the mapVals attribute to contain only the original keys.
This method creates a new dictionary (mapVals2) that includes only the original keys specified in mapKeys and retains their corresponding values from the current mapVals. This effectively resets mapVals to its initial state defined by mapKeys, discarding any additional keys that may have been added during execution.
Example
self.resetMapVals()
Notes
Any additional keys in mapVals that are not present in mapKeys will be removed.
- rfRawPulse(tStart, rfTime, rfAmplitude, rfPhase=0, channel=0)[source]
Generate an RF pulse with a rectangular pulse shape.
- Parameters:
tStart (float) – Start time of the RF pulse.
rfTime (float) – Duration of the RF pulse.
rfAmplitude (float) – Amplitude of the RF pulse.
rfPhase (float) – Phase of the RF pulse in radians. Default is 0.
channel (int) – Channel index for the RF pulse. Default is 0.
- rfRawSincPulse(tStart, rfTime, rfAmplitude, rfPhase=0, nLobes=7, channel=0, rewrite=True)[source]
Generate an RF pulse with a sinc pulse shape. It uses a Hanning window to reduce the banding of the frequency profile.
- Parameters:
tStart (float) – Start time of the RF pulse.
rfTime (float) – Duration of the RF pulse.
rfAmplitude (float) – Amplitude of the RF pulse.
rfPhase (float) – Phase of the RF pulse in radians. Default is 0.
nLobes (int) – Number of lobes in the sinc pulse. Default is 7.
channel (int) – Channel index for the RF pulse. Default is 0.
rewrite (bool) – Whether to rewrite the existing RF pulse. Default is True.
- rfRecPulse(tStart, rfTime, rfAmplitude, rfPhase=0, channel=0)[source]
Generate an RF pulse with a rectangular pulse shape and the corresponding deblanking signal.
- Parameters:
tStart (float) – Start time of the RF pulse.
rfTime (float) – Duration of the RF pulse.
rfAmplitude (float) – Amplitude of the RF pulse.
rfPhase (float) – Phase of the RF pulse in radians. Default is 0.
channel (int) – Channel index for the RF pulse. Default is 0.
- rfSincPulse(tStart, rfTime, rfAmplitude, rfPhase=0, nLobes=7, channel=0, rewrite=True)[source]
Generate an RF pulse with a sinc pulse shape and the corresponding deblanking signal. It uses a Hanning window to reduce the banding of the frequency profile.
- Parameters:
tStart (float) – Start time of the RF pulse.
rfTime (float) – Duration of the RF pulse.
rfAmplitude (float) – Amplitude of the RF pulse.
rfPhase (float) – Phase of the RF pulse in radians. Default is 0.
nLobes (int) – Number of lobes in the sinc pulse. Default is 7.
channel (int) – Channel index for the RF pulse. Default is 0.
rewrite (bool) – Whether to rewrite the existing RF pulse. Default is True.
- runBatches(waveforms, n_readouts, n_adc, frequency=3.066, bandwidth=0.03, decimate='Normal', hardware=True, output='')[source]
Execute multiple batches of MRI waveforms, manage data acquisition, and store oversampled data.
Parameters:
- waveformsdict
Dictionary containing waveform sequences. Keys represent batch identifiers, and values are the corresponding waveform data generated with PyPulseq.
- n_readoutsdict
Dictionary specifying the number of readout points for each batch. Keys match the batch identifiers, and values indicate the number of readout points.
- n_adcint
Number of ADC windows. Each window must have the same length.
- frequencyfloat, optional
Larmor frequency in MHz for the MRI acquisition. Defaults to the system’s Larmor frequency (hw.larmorFreq).
- bandwidthfloat, optional
Bandwidth in MHz used to calculate the sampling period (sampling time = 1 / bandwidth). Defaults to 0.03 MHz.
- decimatestr, optional
Specifies the decimation method. - ‘Normal’: Decimates the acquired array without preprocessing. - ‘PETRA’: Adjusts the pre-readout points to the desired starting point.
- hardware: bool, optional
Take into account gradient and ADC delay.
- output: str, optional
String to add to the output keys saved in the mapVals parameter.
Returns:
- bool
True if all batches are executed successfully, False if an error occurs (e.g., waveform constraints exceed hardware limits).
Notes:
Initializes Red Pitaya hardware unless in demo mode.
Converts PyPulseq waveforms to Red Pitaya-compatible format.
If plotSeq is True, the sequence is plotted instead of executed.
In demo mode, simulated random data replaces hardware acquisition.
Oversampled data is stored in self.mapVals[‘data_over’].
Decimated data is stored in self.mapVals[‘data_decimated’].
Handles data loss by repeating batches until the expected points are acquired.
- static runBm4dFilter(image_data)[source]
Apply the BM4D filter to denoise the image.
This method retrieves the image data, rescales it, calculates the standard deviation for the BM4D filter, applies the BM4D filter to denoise the rescaled image, and rescales the denoised image back to its original scale.
- Parameters:
image_data (ndarray) – The input image data.
- Returns:
The denoised image.
- Return type:
ndarray
- static runCosbellFilter(sampled, data, cosbell_order)[source]
Apply the Cosbell filter operation to the k-space data along three directions.
This method applies the Cosbell filter to the k-space data along the readout (‘rd’), phase (‘ph’), and slice (‘sl’) directions. It modifies the input k-space data in-place.
- Parameters:
sampled (ndarray) – The sampled k-space coordinates in a nx3 matrix, where n is the number of points in k-space. The three columns correspond to the readout, phase, and slice directions.
data (ndarray) – The 3D matrix representing the k-space data to be filtered (sl, ph, rd).
cosbell_order (int) – The order of the Cosbell filter.
- Returns:
The filtered k-space data.
- Return type:
ndarray
- static runDFFT(image)[source]
Perform direct FFT reconstruction.
This method performs the direct Fourier transform to obtain the k-space data from an image in the spatial domain.
- Parameters:
image (ndarray) – The image in the spatial domain.
- Returns:
The k-space data.
- Return type:
ndarray
- static runIFFT(k_space)[source]
Perform inverse FFT reconstruction.
This method performs the inverse Fourier transform to reconstruct the image in the spatial domain from k-space data.
- Parameters:
k_space (ndarray) – The k-space data.
- Returns:
The reconstructed image in the spatial domain.
- Return type:
ndarray
- static runZeroPadding(k_space, zero_padding_order)[source]
Perform the zero-padding operation on k-space data.
This method applies zero-padding to the loaded k-space data to increase its size. The padding order is specified for each dimension: readout (rd), phase (ph), and slice (sl). The padded k-space data is returned as a new matrix.
- Parameters:
k_space (ndarray) – The 3D matrix k-space data to be zero-padded.
zero_padding_order (str) – The zero-padding order for each dimension represented as a string. The order should consist of three integers specifying the padding factor for the readout, phase, and slice dimensions, respectively.
- Returns:sa
ndarray: The 3D matrix containing the zero-padded k-space data.
- rxGate(tStart, gateTime, channel=0)[source]
Open the receiver gate for a specified channel.
- Parameters:
tStart (float) – Start time of the receiver gate.
gateTime (float) – Duration of the receiver gate.
channel (int) – Channel index for the receiver gate. Default is 0.
- rxGateSync(tStart, gateTime, channel=0)[source]
Open a synchronized receiver gate for a specified channel with additional points to account for the time shift and ramp of the CIC filter.
- Parameters:
tStart (float) – Start time of the receiver gate.
gateTime (float) – Duration of the receiver gate.
channel (int) – Channel index for the receiver gate. Default is 0.
Notes
This method is designed to work with the Experiment class in the controller, which inherits from Experiment in marcos_client.
- saveParams()[source]
Save the parameters in mapVals variable to a CSV file.
- This method performs the following steps:
Resets the mapVals variable by calling the resetMapVals method. Then only input parameters are accessible.
Ensures that the directory ‘experiments/parameterization’ exists, creating it if necessary.
Writes the current parameter values stored in mapVals to a CSV file named ‘<seqName>_last_parameters.csv’, where <seqName> is the value of the ‘seqName’ key in mapVals.
The CSV file is saved in the ‘experiments/parameterization’ directory, and contains the header specified by mapKeys.
- Potential exceptions:
KeyError: If ‘seqName’ is not a key in mapVals.
Example
self.saveParams()
- saveRawData()[source]
Save the rawData.
This method saves the rawData to various formats including .mat, .csv, .dcm and .h5.
The .mat file contains the rawData. The .csv file contains only the input parameters. The .dcm file is the DICOM image. The .h5 file is the ISMRMRD format.
- Returns:
None
- sequenceAtributes()[source]
Add input parameters to the sequence object.
This method iterates over the input parameters and adds them as attributes to the sequence object (self). It multiplies each parameter by its corresponding unit if units are specified (e.g. key = ‘f0’, val = 3, units = 1e-6 will create self.f0 = 3e-6.
- Returns:
None
- sequencePlot(standalone=False)[source]
Plot the TX, gradient, RX, and digital I/O sequences.
This method generates step data plots for TX channels, gradient channels, RX channels, and digital I/O channels based on the data stored in flo_dict or obtained from an experiment object. If standalone is set to True, the method will create and display the plots in a new figure window. Otherwise, it returns the plot data for further use.
- Parameters:
standalone (bool) – If True, creates and displays the plots in a new figure window. Defaults to False.
- Returns:
- A list of plot data, each element being a list containing:
xData: List of time values for the plot.
yData: List of amplitude values for the plot.
legend: List of legend labels for the plot.
title: Title of the plot.
- Return type:
list
Example
self.sequencePlot()
self.sequencePlot(standalone=True)
Notes
The method uses a nested function getStepData to generate step data for plotting.
The method handles different scenarios based on the demo attribute and data from flo_dict or an experiment object.
If demo is True, it plots the TX, gradient, and RX channels from flo_dict.
If demo is False, it plots the channels using data from an experiment object.
The method formats the time data in milliseconds (ms) for plotting.
- setGradient(t0, gAmp, gAxis, rewrite=True)[source]
Set the gradient amplitude to a given value at a specified time.
- Parameters:
t0 (float) – Time at which the gradient is set, in microseconds.
gAmp (float) – Amplitude of the gradient, in arbitrary units [-1, 1].
gAxis (int) – Axis of the gradient (0 for x, 1 for y, 2 for z).
rewrite (bool, optional) – Whether to overwrite existing values. Defaults to True.
- setGradientRamp(tStart, gradRiseTime, nStepsGradRise, g0, gf, gAxis, shimming, rewrite=True)[source]
Generate a gradient ramp from ‘g0’ to ‘gf’.
This method generates a gradient ramp from the initial amplitude ‘g0’ to the final amplitude ‘gf’ over the specified rise time.
- Parameters:
tStart (float) – Start time of the gradient ramp.
gradRiseTime (float) – Rise time of the gradient ramp in microseconds.
nStepsGradRise (int) – Number of steps in the gradient ramp.
g0 (float) – Initial gradient amplitude in T/m.
gf (float) – Final gradient amplitude in T/m.
gAxis (int) – Axis index for the gradient ramp.
shimming (list) – List of shimming values for each axis.
rewrite (bool, optional) – Whether to overwrite existing gradient data. Defaults to True.
Notes
Time inputs are in microseconds.
Amplitude inputs are in T/m.
shimming is in arbitrary units
- setParameter(key=True, string=True, val=True, unit=True)[source]
Set the value of a parameter.
- Parameters:
key (str) – The key corresponding to the parameter.
string (str) – String that will be shown in the GUI
val (Any) – The new value to be assigned to the parameter.
unit (bool) – The unit of the parameter.
- Returns:
None
seq.mse module
Created on Wen April 10 2024 @author: J.M. Algarín, MRILab, i3M, CSIC, Valencia @author: T. Guallart Naval, MRILab, i3M, CSIC, Valencia @email: tguanav@i3m.upv.es @Summary: mse sequence class (from rare sequence class)
- class MSE[source]
Bases:
MRIBLANKSEQ
- sequenceAtributes()[source]
Add input parameters to the sequence object.
This method iterates over the input parameters and adds them as attributes to the sequence object (self). It multiplies each parameter by its corresponding unit if units are specified (e.g. key = ‘f0’, val = 3, units = 1e-6 will create self.f0 = 3e-6.
- Returns:
None
seq.mse_pp module
Created on Tuesday, September 17th 2024 @author: Prof. Dr. Maxim Zaitsev, Department of Diagnostic and Interventional Radiology, University of Freiburg, Germany @author: Dr. J.M. Algarín, MRILab, i3M, CSIC, Valencia, Spain @Summary: mse sequence class coded with pypulseq compatible with MaRGE
- class MSE[source]
Bases:
MRIBLANKSEQ
- sequenceAtributes()[source]
Add input parameters to the sequence object.
This method iterates over the input parameters and adds them as attributes to the sequence object (self). It multiplies each parameter by its corresponding unit if units are specified (e.g. key = ‘f0’, val = 3, units = 1e-6 will create self.f0 = 3e-6.
- Returns:
None
- sequenceRun(plotSeq=0, demo=False, standalone=False)[source]
Runs a multi-spin echo (MSE) sequence using PyPulseq to control the pulse sequence timing and hardware settings.
This method initiates the running of an MSE sequence, handling various hardware and sequence parameters such as field of view (FOV), resolution, readout gradients, and timing. It prepares and configures the experiment for data acquisition, creates pulse sequence batches, and can either run the experiment or plot the sequence.
- Parameters:
plotSeq (int, optional) – If set to 1, the sequence will be plotted instead of executed. Defaults to 0.
demo (bool, optional) – If True, the method will simulate the sequence execution in demo mode without actual hardware. Defaults to False.
standalone (bool, optional) – If True, the method will run in standalone mode and plot the sequence. Defaults to False.
Used (Key Parameters)
-------------------
self.fov (-)
self.nPoints (-)
self.etl (-)
self.echoSpacing (-)
self.repetitionTime (-)
self.acqTime (-)
self.rfExFA (-)
self.rfReFA (-)
self.dummyPulses (-)
self.shimming (-)
Steps (Key Process)
-----------------
parameters (1. Initializes the experiment and configures the system)
times. (such as bandwidth and gradient)
readout (2. Defines the)
phase
axesOrientation. (and slice gradients according to the)
pulses. (3. Creates RF excitation and refocusing)
pulses (4. Prepares and adds sequence blocks (RF)
gradients
delays). (and)
sequence (5. Creates and processes batches of the)
sweeps. (performing slice and phase encoding)
arguments. (6. Executes the pulse sequence or plots it based on the provided)
data. (7. Handles data acquisition and decimation for oversampled)
- Returns:
True if the sequence execution or plotting was successful, False if there were errors in configuration or timing.
- Return type:
bool
- Raises:
RuntimeError – Raised if the sequence timing is incorrect or the hardware configuration is out of bounds.
Notes
The method assumes access to global hardware settings (hw) and a Experiment object (expt).
In case of sequence plotting, the plotSeq argument should be set, and the sequence will be visualized instead of executed.
seq.mse_pp_jma module
Created on Wen April 10 2024 @author: J.M. Algarín, MRILab, i3M, CSIC, Valencia @Summary: mse sequence class
- class MSE[source]
Bases:
MRIBLANKSEQ
- sequenceAtributes()[source]
Add input parameters to the sequence object.
This method iterates over the input parameters and adds them as attributes to the sequence object (self). It multiplies each parameter by its corresponding unit if units are specified (e.g. key = ‘f0’, val = 3, units = 1e-6 will create self.f0 = 3e-6.
- Returns:
None
seq.noise module
@author: J.M. Algarín, february 03th 2022 MRILAB @ I3M
seq.petra module
Created on Thu June 2 2022 @author: J.M. Algarín, MRILab, i3M, CSIC, Valencia @email: josalggui@i3m.upv.es @Summary: rare sequence class
seq.pulseq_reader module
@author: José Miguel Algarín Guisado @date: 2024 May 31 mrilab @ i3M, CSIC, Spain
- class PulseqReader[source]
Bases:
MRIBLANKSEQ
- sequenceAtributes()[source]
Add input parameters to the sequence object.
This method iterates over the input parameters and adds them as attributes to the sequence object (self). It multiplies each parameter by its corresponding unit if units are specified (e.g. key = ‘f0’, val = 3, units = 1e-6 will create self.f0 = 3e-6.
- Returns:
None
seq.rabiFlops module
@author: T. Guallart @author: J.M. Algarín
@summary: increase the pulse width and plot the peak value of the signal received @status: under development @todo:
seq.rare module
Created on Thu June 2 2022 @author: J.M. Algarín, MRILab, i3M, CSIC, Valencia @email: josalggui@i3m.upv.es @Summary: rare sequence class
- class RARE[source]
Bases:
MRIBLANKSEQ
- save_ismrmrd()[source]
Save the current instance’s data in ISMRMRD format.
This method saves the raw data, header information, and reconstructed images to an HDF5 file using the ISMRMRD (Image Storage and Reconstruction format for MR Data) format.
Steps performed: 1. Generate a timestamp-based filename and directory path for the output file. 2. Initialize the ISMRMRD dataset with the generated path. 3. Populate the header and write the XML header to the dataset. Informations can be added. 4. Reshape the raw data matrix and iterate over scans, slices, and phases to write each acquisition. WARNING : RARE sequence follows ind order to fill the k-space. 5. Set acquisition flags and properties. 6. Append the acquisition data to the dataset. 7. Reshape and save the reconstructed images. 8. Close the dataset.
Attribute: - self.data_full_mat (numpy.array): Full matrix of raw data to be reshaped and saved.
Returns: None. It creates an HDF5 file with the ISMRMRD format.
- sequenceAtributes()[source]
Add input parameters to the sequence object.
This method iterates over the input parameters and adds them as attributes to the sequence object (self). It multiplies each parameter by its corresponding unit if units are specified (e.g. key = ‘f0’, val = 3, units = 1e-6 will create self.f0 = 3e-6.
- Returns:
None
seq.rareProtocols module
Created on Thu June 2 2022 @author: J.M. Algarín, MRILab, i3M, CSIC, Valencia @email: josalggui@i3m.upv.es @Summary: rare sequence class
- class RAREProtocols[source]
Bases:
MRIBLANKSEQ
- sequenceAtributes()[source]
Add input parameters to the sequence object.
This method iterates over the input parameters and adds them as attributes to the sequence object (self). It multiplies each parameter by its corresponding unit if units are specified (e.g. key = ‘f0’, val = 3, units = 1e-6 will create self.f0 = 3e-6.
- Returns:
None
seq.rareProtocolsTest module
Created on Thu June 2 2022 @author: J.M. Algarín, MRILab, i3M, CSIC, Valencia @email: josalggui@i3m.upv.es @Summary: rare sequence class
seq.rare_pp module
Created on Thu June 2 2022 @author: J.M. Algarín, MRILab, i3M, CSIC, Valencia @email: josalggui@i3m.upv.es @Summary: rare sequence class
- class RarePyPulseq[source]
Bases:
MRIBLANKSEQ
- save_ismrmrd()[source]
Save the current instance’s data in ISMRMRD format.
This method saves the raw data, header information, and reconstructed images to an HDF5 file using the ISMRMRD (Image Storage and Reconstruction format for MR Data) format.
Steps performed: 1. Generate a timestamp-based filename and directory path for the output file. 2. Initialize the ISMRMRD dataset with the generated path. 3. Populate the header and write the XML header to the dataset. Informations can be added. 4. Reshape the raw data matrix and iterate over scans, slices, and phases to write each acquisition. WARNING : RARE sequence follows ind order to fill the k-space. 5. Set acquisition flags and properties. 6. Append the acquisition data to the dataset. 7. Reshape and save the reconstructed images. 8. Close the dataset.
Attribute: - self.data_full_mat (numpy.array): Full matrix of raw data to be reshaped and saved.
Returns: None. It creates an HDF5 file with the ISMRMRD format.
- sequenceAtributes()[source]
Add input parameters to the sequence object.
This method iterates over the input parameters and adds them as attributes to the sequence object (self). It multiplies each parameter by its corresponding unit if units are specified (e.g. key = ‘f0’, val = 3, units = 1e-6 will create self.f0 = 3e-6.
- Returns:
None
seq.rare_t2prep_pp module
Created on Thu June 2 2022 @author: J.M. Algarín, MRILab, i3M, CSIC, Valencia @email: josalggui@i3m.upv.es @Summary: rare sequence class
- class RARE_T2prep_pp[source]
Bases:
MRIBLANKSEQ
- save_ismrmrd()[source]
Save the current instance’s data in ISMRMRD format.
This method saves the raw data, header information, and reconstructed images to an HDF5 file using the ISMRMRD (Image Storage and Reconstruction format for MR Data) format.
Steps performed: 1. Generate a timestamp-based filename and directory path for the output file. 2. Initialize the ISMRMRD dataset with the generated path. 3. Populate the header and write the XML header to the dataset. Informations can be added. 4. Reshape the raw data matrix and iterate over scans, slices, and phases to write each acquisition. WARNING : RARE sequence follows ind order to fill the k-space. 5. Set acquisition flags and properties. 6. Append the acquisition data to the dataset. 7. Reshape and save the reconstructed images. 8. Close the dataset.
Attribute: - self.data_full_mat (numpy.array): Full matrix of raw data to be reshaped and saved.
Returns: None. It creates an HDF5 file with the ISMRMRD format.
- sequenceAtributes()[source]
Add input parameters to the sequence object.
This method iterates over the input parameters and adds them as attributes to the sequence object (self). It multiplies each parameter by its corresponding unit if units are specified (e.g. key = ‘f0’, val = 3, units = 1e-6 will create self.f0 = 3e-6.
- Returns:
None
seq.sequence_template module
Created on Tue October 1st, 2024 @author: [Student’s Name] @Summary: [Sequence Name] class template
- class SEQUENCE_TEMPLATE[source]
Bases:
MRIBLANKSEQ
- sequenceAtributes()[source]
Additional sequence attributes or parameters. Extend this method with specific calculations or modifications.
- sequenceRun(plotSeq=False, demo=False, standalone=False)[source]
Run the MRI sequence.
This method initializes batches and creates the full sequence by iterating through slices and phase-encoding steps.
Instructions for students: - Batches divide the sequence into smaller, hardware-manageable sections. - initializeBatch sets up new sequence batches, while createBatches iterates through slices and phase-encoding to create the full sequence.
- Parameters:
plotSeq (bool) – If True, plots the sequence.
demo (bool) – If True, runs in demo mode.
standalone (bool) – If True, runs the sequence independently.
- Returns:
Indicates success or failure of the sequence run.
- Return type:
bool
seq.sequences module
seq.shimmingSweep module
@author: J.M. Algarín, MRILab, i3M, CSIC, Valencia, Spain @date: 19 tue Apr 2022 @email: josalggui@i3m.upv.es
seq.spds module
Created on Tue October 1st, 2024 @author: [Student’s Name] @Summary: [Sequence Name] class template
- class spds[source]
Bases:
MRIBLANKSEQ
Executes the SPDS (Single Point Double Shot) sequence, designed to estimate the B₀ map by acquiring data with two distinct acquisition windows.
- sequenceAnalysis(mode=None)[source]
Analyzes the data acquired from the SPDS (Single Point Double Shot) sequence to estimate the B₀ map, generate k-space and spatial domain images, and prepare the outputs for visualization.
Parameters:
- modestr, optional
Execution mode of the analysis. If set to ‘Standalone’, the results are plotted immediately after analysis (default: None).
Outputs:
output (list): A list of dictionaries defining the data and parameters for visualization. Includes:
Spatial domain magnitude images for channels A and B.
B₀ field map.
k-space magnitude images for channels A and B.
Updates self.mapVals with intermediate results, including k-space, spatial images, and the B₀ field map.
If mode == ‘Standalone’, plots the results.
Notes:
Assumes that the k-space mask and orientation settings are correctly preconfigured.
- sequenceAtributes()[source]
Assign input parameters as attributes for the sequence.
This method is called by the GUI before invoking the sequenceRun method. It ensures that any input parameters defined using methods like self.addParameter(key=’param’, string=’Parameter’, val=1) are assigned as class attributes, allowing them to be accessed directly using self.param.
Example
- If you define an input parameter as:
self.addParameter(key=’param’, string=’Parameter’, val=1, …)
- You can access its value later in the sequence as:
self.param
- sequenceRun(plotSeq=False, demo=False, standalone=False)[source]
This method orchestrates the definition, preparation, and execution of the sequence.
Parameters:
- plotSeqbool, optional
If True, the sequence is plotted for visualization without execution (default: False).
- demobool, optional
If True, runs the sequence in demonstration mode without hardware communication (default: False).
- standalonebool, optional
If True, runs the sequence independently, without external triggering or batch processing (default: False).
Output:
Oversampled and decimated data stored in self.mapVals[‘data_over’] and self.mapVals[‘data_decimated’].
Generated sequence files for verification and debugging.
Notes:
This method is tailored for SPDS sequences, which are particularly useful for estimating B₀ inhomogeneities in low-field MRI systems under high inhomogeneities.
seq.sweepImage module
Created on Thu June 2 2022 @author: J.M. Algarín, MRILab, i3M, CSIC, Valencia @email: josalggui@i3m.upv.es @Summary: This class is able to sweep any parameter from any sequence