pypulseq.Sequence package

Submodules

pypulseq.Sequence.block module

pypulseq.Sequence.block.get_block(self, block_index: int)types.SimpleNamespace

Returns PyPulseq block at block_index position in self.block_events.

The block is created from the sequence data with all events and shapes decompressed.

Parameters

block_index (int) – Index of PyPulseq block to be retrieved from self.block_events.

Returns

block – PyPulseq block at ‘block_index’ position in self.block_events.

Return type

SimpleNamespace

Raises

ValueError – If a trigger event of an unsupported control type is encountered. If a label object of an unknown extension ID is encountered.

pypulseq.Sequence.block.register_adc_event(self, event: pypulseq.event_lib.EventLibrary)int
Parameters

event (SimpleNamespace) – ADC event to be registered.

Returns

ID of registered ADC event.

Return type

int

pypulseq.Sequence.block.register_control_event(self, event: types.SimpleNamespace)int
Parameters

event (SimpleNamespace) – Control event to be registered.

Returns

ID of registered control event.

Return type

int

pypulseq.Sequence.block.register_grad_event(self, event: types.SimpleNamespace)Union[int, Tuple[int, List[int]]]
Parameters

event (SimpleNamespace) – Gradient event to be registered.

Returns

  • int, [int, …] – For gradient events: ID of registered gradient event, list of shape IDs

  • int – For trapezoid gradient events: ID of registered gradient event

pypulseq.Sequence.block.register_label_event(self, event: types.SimpleNamespace)int
Parameters

event (SimpleNamespace) – ID of label event to be registered.

Returns

ID of registered label event.

Return type

int

pypulseq.Sequence.block.register_rf_event(self, event: types.SimpleNamespace)Tuple[int, List[int]]
Parameters

event (SimpleNamespace) – RF event to be registered.

Returns

ID of registered RF event, list of shape IDs

Return type

int, [int, ..]

pypulseq.Sequence.block.set_block(self, block_index: int, *args: types.SimpleNamespace)None

Replace block at index with new block provided as block structure, add sequence block, or create a new block from events and store at position specified by index. The block or events are provided in uncompressed form and will be stored in the compressed, non-redundant internal libraries.

See also: - pypulseq.Sequence.sequence.Sequence.get_block() - pypulseq.Sequence.sequence.Sequence.add_block()

Parameters
  • block_index (int) – Index at which block is replaced.

  • args (SimpleNamespace) – Block or events to be replaced/added or created at block_index.

Raises
  • ValueError – If trigger event that is passed is of unsupported control event type. If delay is set for a gradient even that starts with a non-zero amplitude.

  • RuntimeError – If two consecutive gradients to not have the same amplitude at the connection point. If the first gradient in the block does not start with 0. If a gradient that doesn’t end at zero is not aligned to the block boundary.

pypulseq.Sequence.ext_test_report module

pypulseq.Sequence.ext_test_report.ext_test_report(self)str

Analyze the sequence and return a text report.

Returns

report

Return type

str

pypulseq.Sequence.parula module

pypulseq.Sequence.parula.main(N: int)matplotlib.colors.LinearSegmentedColormap

Returns a Parula colormap to be used with matplotlib’s cycler. cm_data has values copied from MATLAB for parula(64).

Parameters

N (int) – Number of RGB quantization levels.

Returns

Parula color map.

Return type

LinearSegmentedColormap

pypulseq.Sequence.read_seq module

pypulseq.Sequence.read_seq.read(self, path: str, detect_rf_use: bool = False)None

Load sequence from file - read the given filename and load sequence data into sequence object.

See also pypulseq.Sequence.write_seq.write().

Parameters
  • path (Path) – Path of sequence file to be read.

  • detect_rf_use (bool, default=False) – Boolean flag to let the function infer the currently missing flags concerning the intended use of the RF pulses (excitation, refocusing, etc). These are important for the k-space trajectory calculation.

Raises
  • FileNotFoundError – If no sequence file is found at path.

  • RuntimeError – If incompatible sequence files are attempted to be loaded.

  • ValueError – If unexpected sections are encountered when loading a sequence file.

pypulseq.Sequence.sequence module

class pypulseq.Sequence.sequence.Sequence(system=<pypulseq.opts.Opts object>)

Bases: object

Generate sequences and read/write sequence files. This class defines properties and methods to define a complete MR sequence including RF pulses, gradients, ADC events, etc. The class provides an implementation of the open MR sequence format defined by the Pulseq project. See http://pulseq.github.io/.

See also demo_read.py, demo_write.py.

add_block(*args: types.SimpleNamespace)None

Add a new block/multiple events to the sequence. Adds a sequence block with provided as a block structure

See also: - pypulseq.Sequence.sequence.Sequence.set_block() - pypulseq.make_adc.make_adc() - pypulseq.make_trapezoid.make_trapezoid() - pypulseq.make_sinc_pulse.make_sinc_pulse()

Parameters

args (SimpleNamespace) – Block structure or events to be added as a block to Sequence.

calculate_kspace(trajectory_delay: int = 0)Tuple[numpy.array, numpy.array, numpy.array, numpy.array, numpy.array]

Calculates the k-space trajectory of the entire pulse sequence.

Parameters

trajectory_delay (int, default=0) – Compensation factor in seconds (s) to align ADC and gradients in the reconstruction.

Returns

  • k_traj_adc (numpy.array) – K-space trajectory sampled at t_adc timepoints.

  • k_traj (numpy.array) – K-space trajectory of the entire pulse sequence.

  • t_excitation (numpy.array) – Excitation timepoints.

  • t_refocusing (numpy.array) – Refocusing timepoints.

  • t_adc (numpy.array) – Sampling timepoints.

calculate_kspacePP(trajectory_delay: Union[int, float, numpy.ndarray] = 0, gradient_offset: int = 0)Tuple[numpy.array, numpy.array, numpy.array, numpy.array, numpy.array]

Calculates the k-space trajectory of the entire pulse sequence.

Parameters

trajectory_delay (int, default=0) – Compensation factor in seconds (s) to align ADC and gradients in the reconstruction.

Returns

  • k_traj_adc (numpy.array) – K-space trajectory sampled at t_adc timepoints.

  • k_traj (numpy.array) – K-space trajectory of the entire pulse sequence.

  • t_excitation (numpy.array) – Excitation timepoints.

  • t_refocusing (numpy.array) – Refocusing timepoints.

  • t_adc (numpy.array) – Sampling timepoints.

check_timing()Tuple[bool, List[str]]

Checks timing of all blocks and objects in the sequence optionally returns the detailed error log. This function also modifies the sequence object by adding the field “TotalDuration” to sequence definitions.

Returns

  • is_ok (bool) – Boolean flag indicating timing errors.

  • error_report (str) – Error report in case of timing errors.

duration()Tuple[int, int, numpy.ndarray]

Returns the total duration of this sequence, and the total count of blocks and events.

Returns

  • duration (int) – Duration of this sequence in seconds (s).

  • num_blocks (int) – Number of blocks in this sequence.

  • event_count (np.ndarray) – Number of events in this sequence.

flip_grad_axis(axis: str)None

Invert all gradients along the corresponding axis/channel. The function acts on all gradient objects already added to the sequence object.

Parameters

axis (str) – Gradients to invert or scale. Must be one of ‘x’, ‘y’ or ‘z’.

get_block(block_index: int)types.SimpleNamespace

Return a block of the sequence specified by the index. The block is created from the sequence data with all events and shapes decompressed.

See also: - pypulseq.Sequence.sequence.Sequence.set_block(). - pypulseq.Sequence.sequence.Sequence.add_block().

Parameters

block_index (int) – Index of block to be retrieved from Sequence.

Returns

Event identified by block_index.

Return type

SimpleNamespace

get_definition(key: str)str

Return value of the definition specified by the key. These definitions can be added manually or read from the header of a sequence file defined in the sequence header. An empty array is returned if the key is not defined.

See also pypulseq.Sequence.sequence.Sequence.set_definition().

Parameters

key (str) – Key of definition to retrieve.

Returns

Definition identified by key if found, else returns ‘’.

Return type

str

get_extension_type_ID(extension_string: str)int

Get numeric extension ID for extension_string. Will automatically create a new ID if unknown.

Parameters

extension_string (str) – Given string extension ID.

Returns

extension_id – Numeric ID for given string extension ID.

Return type

int

get_extension_type_string(extension_id: int)str

Get string extension ID for extension_id.

Parameters

extension_id (int) – Given numeric extension ID.

Returns

extension_str – String ID for the given numeric extension ID.

Return type

str

Raises

ValueError – If given numeric extension ID is unknown.

mod_grad_axis(axis: str, modifier: int)None

Invert or scale all gradients along the corresponding axis/channel. The function acts on all gradient objects already added to the sequence object.

Parameters
  • axis (str) – Gradients to invert or scale. Must be one of ‘x’, ‘y’ or ‘z’.

  • modifier (int) – Scaling value.

Raises
  • ValueError – If invalid axis is passed. Must be one of ‘x’, ‘y’,’z’.

  • RuntimeError – If same gradient event is used on multiple axes.

plot(label: str = '', show_blocks: bool = False, save: bool = False, time_range=(0, numpy.inf), time_disp: str = 's', grad_disp: str = 'kHz/m', plot_now: bool = True)None

Plot Sequence.

Parameters
  • label (str, defualt=str()) – Plot label values for ADC events: in this example for LIN and REP labels; other valid labes are accepted as a comma-separated list.

  • save (bool, default=False) – Boolean flag indicating if plots should be saved. The two figures will be saved as JPG with numerical suffixes to the filename ‘seq_plot’.

  • show_blocks (bool, default=False) – Boolean flag to indicate if grid and tick labels at the block boundaries are to be plotted.

  • time_range (iterable, default=(0, np.inf)) – Time range (x-axis limits) for plotting the sequence. Default is 0 to infinity (entire sequence).

  • time_disp (str, default='s') – Time display type, must be one of s, ms or us.

  • grad_disp (str, default='s') – Gradient display unit, must be one of kHz/m or mT/m.

  • plot_now (bool, default=True) – If true, function immediately shows the plots, blocking the rest of the code until plots are exited. If false, plots are shown when plt.show() is called. Useful if plots are to be modified.

  • plot_type (str, default='Gradient') – Gradients display type, must be one of either ‘Gradient’ or ‘Kspace’.

ppval_MATLAB(arr_MATLAB_poly: numpy.ndarray, xq: numpy.ndarray)numpy.array

Perform piece-wise polynomial evaluation on MATLAB’s polyfit objects.

ppval_numpy(arr_np_poly: numpy.ndarray, xq: numpy.ndarray)

Perform piece-wise polynomial evaluation on Numpy’s polyfit objects.

Parameters
  • arr_np_poly (Iterable[np.poly1d]) –

  • xq (np.array) –

read(file_path: str, detect_rf_use: bool = False)None

Read .seq file from file_path.

Parameters
  • detect_rf_use

  • file_path (str) – Path to .seq file to be read.

register_adc_event(event: pypulseq.event_lib.EventLibrary)int
register_grad_event(event: types.SimpleNamespace)Union[int, Tuple[int, int]]
register_label_event(event: types.SimpleNamespace)int
register_rf_event(event: types.SimpleNamespace)Tuple[int, List[int]]
rf_from_lib_data(lib_data: list, use: str = '')types.SimpleNamespace

Construct RF object from lib_data.

Parameters
  • lib_data (list) – RF envelope.

  • use (str, default=str()) – RF event use.

Returns

rf – RF object constructed from lib_data.

Return type

SimpleNamespace

set_block(block_index: int, *args: types.SimpleNamespace)None

Replace block at index with new block provided as block structure, add sequence block, or create a new block from events and store at position specified by index. The block or events are provided in uncompressed form and will be stored in the compressed, non-redundant internal libraries.

See also: - pypulseq.Sequence.sequence.Sequence.get_block() - pypulseq.Sequence.sequence.Sequence.add_block()

Parameters
  • block_index (int) – Index at which block is replaced.

  • args (SimpleNamespace) – Block or events to be replaced/added or created at block_index.

set_definition(key: str, value: Union[float, int, list, numpy.ndarray, str, tuple])None

Modify a custom definition of the sequence. Set the user definition ‘key’ to value ‘value’. If the definition does not exist it will be created.

See also pypulseq.Sequence.sequence.Sequence.get_definition().

Parameters
  • key (str) – Definition key.

  • value (int, list, np.ndarray, str or tuple) – Definition value.

set_extension_string_ID(extension_str: str, extension_id: int)None

Set numeric ID for the given string extension ID.

Parameters
  • extension_str (str) – Given string extension ID.

  • extension_id (int) – Given numeric extension ID.

Raises

ValueError – If given numeric or string extension ID is not unique.

test_report()str

Analyze the sequence and return a text report.

version_major = 1
version_minor = 4
version_revision = 0
waveforms_and_times(append_RF: bool = False)Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray]

Decompress the entire gradient waveform. Returns gradient waveforms as a tuple of np.ndarray of gradient_axes (typically 3) dimensions. Each np.ndarray contains timepoints and the corresponding gradient amplitude values. Additional return values are time points of excitations, refocusings and ADC sampling points.

Parameters

append_RF (bool, default=False) – Boolean flag to indicate if RF wave shapes are to be appended after the gradients.

Returns

  • wave_data (np.ndarray)

  • tfp_excitation (np.ndarray) – Contains time moments, frequency and phase offsets of the excitation RF pulses (similar for ` tfp_refocusing`).

  • tfp_refocusing (np.ndarray)

  • t_adc (np.ndarray) – Contains times of all ADC sample points.

  • fp_adc (np.ndarray) – Contains frequency and phase offsets of each ADC object (not samples).

waveforms_export(time_range=(0, numpy.inf))dict

Plot Sequence.

Parameters

time_range (iterable, default=(0, np.inf)) – Time range (x-axis limits) for all waveforms. Default is 0 to infinity (entire sequence).

Returns

all_waveforms – Dictionary containing the following sequence waveforms and time array(s): - t_adc - ADC timing array [seconds] - t_rf - RF timing array [seconds] - t_rf_centers: rf_t_centers, - t_gx: x gradient timing array, - t_gy: y gradient timing array, - t_gz: z gradient timing array, - adc - ADC complex signal (amplitude=1, phase=adc phase) [a.u.] - rf - RF complex signal - rf_centers: RF centers array, - gx - x gradient - gy - y gradient - gz - z gradient - grad_unit: [kHz/m], - rf_unit: [Hz], - time_unit: [seconds],

Return type

dict

write(name: str, create_signature: bool = True)None

Write the sequence data to the given filename using the open file format for MR sequences.

See also pypulseq.Sequence.read_seq.read().

Parameters
  • name (str) – Filename of .seq file to be written to disk.

  • create_signature (bool, default=True) – Boolean flag to indicate if the file has to be signed.

pypulseq.Sequence.write_seq module

pypulseq.Sequence.write_seq.write(self, file_name: str, create_signature)None

Write the sequence data to the given filename using the open file format for MR sequences.

See also pypulseq.Sequence.read_seq.read().

Parameters
  • file_name (str) – File name of .seq file to be written to disk.

  • create_signature (bool) –

Raises

RuntimeError – If an unsupported definition is encountered.

Module contents