Skip to content

sequence_provider

sequence_provider

Sequence provider class.

ADCGate dataclass

ADCGate(start: int, num_samples_discard: int, num_samples_raw: int)

Define precalculated attributes of an ADC gate.

SequenceProvider

SequenceProvider(gradient_efficiency: tuple[float, float, float], gpa_gain: tuple[float, float, float], gradient_output_limits: tuple[int, int, int], gradients_50ohms: bool, rf_output_limit: int, rf_50ohms: bool, rf_to_mvolt: float, spcm_dwell_time: float, system: Opts, rf_gain_lut_path: Path | None = None)

Bases: Sequence

Sequence provider class.

Subclass of the PyPulseq Sequence, so that all PyPulseq sequence methods remain accessible. The main functionality is unroll_sequence, which translates the block-structured sequence into the interleaved int16 replay buffer of the transmit card (RF, three gradients and three digital control signals in bit 15 of the gradient channels).

Examples:

>>> seq_provider = SequenceProvider(..., system=opts)
>>> seq_provider.read("./seq_file.seq")
>>> unrolled = seq_provider.unroll_sequence(acquisition_parameter)

Initialize sequence provider class which is used to unroll a pulseq sequence.

Parameters:

  • gradient_efficiency (tuple[float, float, float]) –

    Efficiency of the gradient coils in T/m/A per physical gradient channel, e.g. [0.4e-3, 0.4e-3, 0.4e-3].

  • gpa_gain (tuple[float, float, float]) –

    Transconductance of the gradient power amplifier in A/V per physical gradient channel, e.g. [4.7, 4.7, 4.7].

  • gradient_output_limits (tuple[int, int, int]) –

    Integer output limit per gradient channel in mV, e.g. [6000, 6000, 6000].

  • gradients_50ohms (bool) –

    Boolean flag which indicates if the gradient output is terminated into 50 ohms or high impedance. If terminated into high impedance, the card output doubles, what needs to be considered when calculating the sequence.

  • rf_output_limit (int) –

    Integer output limit of the RF channel in mV.

  • rf_50ohms (bool) –

    Boolean flag which indicates if the rf output is terminated into 50 ohms (see gradients_50ohms).

  • rf_to_mvolt (float) –

    Translation of RF waveform from pulseq (Hz) to mV.

  • spcm_dwell_time (float) –

    Sampling time raster of the output waveform (depends on spectrum card).

  • system (Opts) –

    Pypulseq system limits object used for sequence construction.

  • rf_gain_lut_path (Path or None, default: None ) –

    Path to the RF power amplifier gain lookup table (.npy file), by default None. If None or the file does not exist, no LUT is applied.

Source code in src/console/pulseq_interpreter/sequence_provider.py
def __init__(
    self,
    gradient_efficiency: tuple[float, float, float],
    gpa_gain: tuple[float, float, float],
    gradient_output_limits: tuple[int, int, int],
    gradients_50ohms: bool,
    rf_output_limit: int,
    rf_50ohms: bool,
    rf_to_mvolt: float,
    spcm_dwell_time: float,
    system: Opts,
    rf_gain_lut_path: Path | None = None,
) -> None:
    """Initialize sequence provider class which is used to unroll a pulseq sequence.

    Parameters
    ----------
    gradient_efficiency
        Efficiency of the gradient coils in T/m/A per physical gradient channel, e.g. [0.4e-3, 0.4e-3, 0.4e-3].
    gpa_gain
        Transconductance of the gradient power amplifier in A/V per physical gradient channel,
        e.g. [4.7, 4.7, 4.7].
    gradient_output_limits
        Integer output limit per gradient channel in mV, e.g. [6000, 6000, 6000].
    gradients_50ohms
        Boolean flag which indicates if the gradient output is terminated into 50 ohms or high impedance.
        If terminated into high impedance, the card output doubles,
        what needs to be considered when calculating the sequence.
    rf_output_limit
        Integer output limit of the RF channel in mV.
    rf_50ohms
        Boolean flag which indicates if the rf output is terminated into 50 ohms (see gradients_50ohms).
    rf_to_mvolt
        Translation of RF waveform from pulseq (Hz) to mV.
    spcm_dwell_time
        Sampling time raster of the output waveform (depends on spectrum card).
    system : Opts
        Pypulseq system limits object used for sequence construction.
    rf_gain_lut_path : Path or None, optional
        Path to the RF power amplifier gain lookup table (.npy file), by default None.
        If None or the file does not exist, no LUT is applied.
    """
    if not isinstance(system, Opts):
        raise AttributeError("Invalid system: Pypulseq `Opts` definition required.")
    super().__init__(system=system)
    self.log = logging.getLogger("SeqProv")

    # Set class instance attributes
    self.rf_to_mvolt = rf_to_mvolt
    self.spcm_dwell_time = spcm_dwell_time
    self.spcm_freq = 1 / spcm_dwell_time
    self.gpa_gain = gpa_gain
    self.grad_eff = gradient_efficiency

    # Scale output limit dependent on high impedance flags:
    # If output is terminated into high impedance (flag is true), the channel output is doubled.
    # Otherwise, if output is terminated into 50 ohms impedance, output limit remains unchanged.
    self.rf_out_limit = rf_output_limit if rf_50ohms else int(2 * rf_output_limit)
    # Ensure tuple[int, int, int] for mypy typing
    self.gradient_out_limits = (
        gradient_output_limits[0] if gradients_50ohms else int(2 * gradient_output_limits[0]),
        gradient_output_limits[1] if gradients_50ohms else int(2 * gradient_output_limits[1]),
        gradient_output_limits[2] if gradients_50ohms else int(2 * gradient_output_limits[2]),
    )

    # Setup phase reference signal
    time = np.arange(NUM_REFERENCE_SAMPLES) * self.spcm_dwell_time
    signal = np.exp(2j * np.pi * REFERENCE_FREQUENCY * time)
    self.phase_reference = np.zeros(NUM_REFERENCE_SAMPLES, dtype=np.uint16)
    self.phase_reference[signal > 0] = np.uint16(2**15)

    # Load LUT for RF gain correction if path to LUT is provided
    self._rf_gain_lut: np.ndarray | None = None
    self._load_rfpa_lut(rf_gain_lut_path)

from_pypulseq

from_pypulseq(seq: Sequence) -> None

Read a pypulseq sequence to sequence provider.

Parameters:

  • seq (Sequence) –

    Pypulseq Sequence instance

Raises:

Source code in src/console/pulseq_interpreter/sequence_provider.py
def from_pypulseq(self, seq: Sequence) -> None:
    """Read a pypulseq sequence to sequence provider.

    Parameters
    ----------
    seq
        Pypulseq ``Sequence`` instance

    Raises
    ------
    AttributeError
        seq is not a valid pypulseq ``Sequence`` instance
    """
    if not isinstance(seq, Sequence):
        raise AttributeError("Invalid sequence.")
    # Re-initialize the parent to start from a clean pypulseq sequence
    super().__init__(system=self.system)
    for block_index, _ in seq.block_events.items():
        block = seq.get_block(block_index)
        self.add_block(block)
    # Set definitions without overwriting existing ones
    for key, value in seq.definitions.items():
        self.definitions.setdefault(key, value)

to_pypulseq

to_pypulseq() -> Sequence | None

Create a pypulseq sequence from sequence provider.

Source code in src/console/pulseq_interpreter/sequence_provider.py
def to_pypulseq(self) -> Sequence | None:
    """Create a pypulseq sequence from sequence provider."""
    seq = Sequence(system=self.system)
    for block_index, _ in self.block_events.items():
        block = self.get_block(block_index)
        seq.add_block(block)
    seq.definitions = self.definitions
    return seq

dict

dict() -> dict

Abstract method which returns variables for logging in dictionary.

Source code in src/console/pulseq_interpreter/sequence_provider.py
def dict(self) -> dict:
    """Abstract method which returns variables for logging in dictionary."""
    return {
        "rf_to_mvolt": self.rf_to_mvolt,
        "spcm_freq": self.spcm_freq,
        "spcm_dwell_time": self.spcm_dwell_time,
        "gpa_gain": self.gpa_gain,
        "gradient_efficiency": self.grad_eff,
        "output_limits": self.gradient_out_limits,
    }

unroll_sequence

unroll_sequence(parameter: AcquisitionParameter) -> UnrolledSequence

Unroll the pypulseq sequence description.

Parameters:

  • parameter (AcquisitionParameter) –

    Instance of AcquisitionParameter containing all necessary parameters to calculate the sequence waveforms, i.e. larmor frequency, gradient offsets, etc.

Returns:

  • UnrolledSequence –

    Interleaved int16 replay buffer of the transmit card (channel order RF, gradient 1, 2, 3), in which bit 15 of the gradient channels carries the digital control signals, together with one RxData template per ADC event.

Raises:

  • ValueError –

    Invalid acquisition parameter, or a waveform exceeds the output limit of its channel.

  • IndexError –

    Inconsistent block timing or an RF waveform exceeding its block.

Examples:

For channels ch0, ch1, ch2, ch3, data values n = 0, 1, ..., N are ordered the following way.

>>> data = [ch0_0, ch1_0, ch2_0, ch3_0, ch0_1, ch1_1, ..., ch0_n, ..., ch3_N]

Per channel data can be extracted by the following code.

>>> rf = seq[0::4]
>>> g1 = (seq[1::4].view(np.uint16) << 1).view(np.int16)
>>> g2 = (seq[2::4].view(np.uint16) << 1).view(np.int16)
>>> g3 = (seq[3::4].view(np.uint16) << 1).view(np.int16)

Bit 15 of the gradient channels carries the digital signals: channel 1 the ADC gate, channel 2 the phase reference and channel 3 the RF unblanking signal. As bit 15 does not encode the sign, the values are viewed as uint16 before shifting.

>>> adc_gate = seq[1::4].view(np.uint16) >> 15
>>> reference = seq[2::4].view(np.uint16) >> 15
>>> unblanking = seq[3::4].view(np.uint16) >> 15
Source code in src/console/pulseq_interpreter/sequence_provider.py
@profile
def unroll_sequence(self, parameter: AcquisitionParameter) -> UnrolledSequence:
    """Unroll the pypulseq sequence description.

    Parameters
    ----------
    parameter
        Instance of AcquisitionParameter containing all necessary parameters to
        calculate the sequence waveforms, i.e. larmor frequency, gradient offsets, etc.

    Returns
    -------
    UnrolledSequence
        Interleaved int16 replay buffer of the transmit card (channel order RF, gradient 1, 2, 3),
        in which bit 15 of the gradient channels carries the digital control signals, together with
        one `RxData` template per ADC event.

    Raises
    ------
    ValueError
        Invalid acquisition parameter, or a waveform exceeds the output limit of its channel.
    IndexError
        Inconsistent block timing or an RF waveform exceeding its block.

    Examples
    --------
    For channels ch0, ch1, ch2, ch3, data values n = 0, 1, ..., N are ordered the following way.

    >>> data = [ch0_0, ch1_0, ch2_0, ch3_0, ch0_1, ch1_1, ..., ch0_n, ..., ch3_N]

    Per channel data can be extracted by the following code.

    >>> rf = seq[0::4]
    >>> g1 = (seq[1::4].view(np.uint16) << 1).view(np.int16)
    >>> g2 = (seq[2::4].view(np.uint16) << 1).view(np.int16)
    >>> g3 = (seq[3::4].view(np.uint16) << 1).view(np.int16)

    Bit 15 of the gradient channels carries the digital signals: channel 1 the ADC gate,
    channel 2 the phase reference and channel 3 the RF unblanking signal.
    As bit 15 does not encode the sign, the values are viewed as uint16 before shifting.

    >>> adc_gate = seq[1::4].view(np.uint16) >> 15
    >>> reference = seq[2::4].view(np.uint16) >> 15
    >>> unblanking = seq[3::4].view(np.uint16) >> 15
    """
    try:
        self._check_parameter(parameter)
        self._check_sequence()
    except Exception:
        self.log.exception("Checks not passed")
        raise

    gradient_index: Dimensions = parameter.channel_assignment

    # Get list of all events and list of unique RF and ADC events, since they are frequently reused
    events_list = self.block_events
    seq_duration, _, _ = self.duration()
    seq_samples = round(seq_duration * self.spcm_freq)

    # Calculate the start time (and sample position) and duration of each block
    block_durations = np.array(
        [self.get_block(block_idx).block_duration for block_idx in list(events_list.keys())],
    )
    block_durations = np.round(block_durations * self.spcm_freq).astype(int)
    block_pos = np.cumsum(block_durations, dtype=np.int64)
    block_pos = np.insert(block_pos, 0, 0)

    if seq_samples != block_pos[-1]:
        msg = "Number of sequence samples does not match total number of block samples"
        raise IndexError(msg)

    # Setup output arrays
    _seq = np.zeros(4 * seq_samples, dtype=np.int16)
    _rx_data = []  # list containing rx data objects for each ADC event

    # Count the total number of sample points and gate signals
    adc_count: int = 0
    labels = {}

    for event_idx, event_key in enumerate(events_list.keys()):
        block = self.get_block(event_key)
        # Calculate gradient waveform start and end positions according to block position
        waveform_start = block_pos[event_idx] * 4

        if block.gx is not None:  # Gx event
            waveform = self._calculate_gradient(
                block=block.gx,
                # FoV scaling refers to the sequence, block.gx -> x
                fov_scaling=parameter.fov_scaling.x,
                # Offset value are set independent of the sequence orientation,
                # must be considered with respect to the target output channel!
                # Offsets mapping: x -> channel 1, y -> channel 2, z -> channel 3
                offset=parameter.gradient_offset.to_list()[int(gradient_index.x-1)],
                # Gradient indexing starts at 1 (RF is channel 0)
                # -> correct indexing to match tuple index
                output_channel=int(gradient_index.x-1),
            )
            delay = block.gx.delay
            delay_samples = round(delay * self.spcm_freq)
            waveform_start_gx = waveform_start + 4 * delay_samples
            gx_slice = slice(
                waveform_start_gx + gradient_index.x,
                waveform_start_gx + 4 * np.size(waveform) + gradient_index.x,
                4,
            )
            _seq[gx_slice] = waveform

        if block.gy is not None:  # Gy event
            waveform = self._calculate_gradient(
                block=block.gy,
                # FoV scaling refers to the sequence, block.gy -> y
                fov_scaling=parameter.fov_scaling.y,
                # Offset value are set independent of the sequence orientation,
                # must be considered with respect to the target output channel!
                # Offsets mapping: x -> channel 1, y -> channel 2, z -> channel 3
                offset=parameter.gradient_offset.to_list()[int(gradient_index.y-1)],
                # Gradient indexing starts at 1 (RF is channel 0)
                # -> correct indexing to match tuple index
                output_channel=int(gradient_index.y-1),
            )
            delay = block.gy.delay
            delay_samples = round(delay * self.spcm_freq)
            waveform_start_gy = waveform_start + 4 * delay_samples
            gy_slice = slice(
                waveform_start_gy + gradient_index.y,
                waveform_start_gy + 4 * np.size(waveform) + gradient_index.y,
                4,
            )
            _seq[gy_slice] = waveform

        if block.gz is not None:  # Gz event
            waveform = self._calculate_gradient(
                block=block.gz,
                # FoV scaling refers to the sequence, block.gz -> z
                fov_scaling=parameter.fov_scaling.z,
                # Offset value are set independent of the sequence orientation,
                # must be considered with respect to the target output channel!
                # Offsets mapping: x -> channel 1, y -> channel 2, z -> channel 3
                offset=parameter.gradient_offset.to_list()[int(gradient_index.z-1)],
                # Gradient indexing starts at 1 (RF is channel 0)
                # -> correct indexing to match tuple index
                output_channel=int(gradient_index.z-1),
            )
            delay = block.gz.delay
            delay_samples = round(delay * self.spcm_freq)
            waveform_start_gz = waveform_start + 4 * delay_samples
            gz_slice = slice(
                waveform_start_gz + gradient_index.z,
                waveform_start_gz + 4 * np.size(waveform) + gradient_index.z,
                4,
            )
            _seq[gz_slice] = waveform

        if block.rf is not None:  # RF event
            # Pre-calculated RF event size can be shorter than the duration of the block since it doesn't
            # consider the post-pulse ring-down time. The RF waveform is placed at the start of the block
            # and the array is then sliced using the duration of the RF waveform to ensure a good fit
            rf_waveform, rf_unblanking = self._calculate_rf(
                block=block.rf,
                b1_scaling=parameter.b1_scaling,
                larmor_frequency=parameter.larmor_frequency,
            )

            rf_size = np.size(rf_waveform)  # Get size of the RF waveform
            if rf_size > (block_pos[event_idx + 1] - block_pos[event_idx]):
                msg = "RF waveform size exceeds block size."
                raise IndexError(msg)

            # Calculate RF waveform start and end positions according to block position
            rf_start = block_pos[event_idx] * 4
            rf_end = (block_pos[event_idx] + rf_size) * 4

            # Add RF waveform and unblanking signal to Z gradient
            _seq[rf_start:rf_end:4] = rf_waveform
            _seq[rf_start + 3:rf_end + 3:4] = _seq[rf_start + 3:rf_end + 3:4] | rf_unblanking

        if block.label is not None:
            # Update dictionary with current labels
            for label in block.label.values():
                labels[label.label] = label.value

        if block.adc is not None:  # ADC event
            # Calculate the number of samples to be discarded from the decimated signal
            num_samples_discard = floor(block.adc.dead_time / block.adc.dwell)
            # Calculate the total gate duration, given by number of samples
            # and two times the number of discarded samples for symmetric adc dead time
            # Note: The total gate duration is only increased if the dead time is a multiple of the adc dwell time.
            total_gate_duration = (block.adc.num_samples + 2 * num_samples_discard) * block.adc.dwell
            num_samples_raw = round(total_gate_duration * self.spcm_freq)

            # Remaining delay = dead_time minus pre- and post-sampling fractions
            remaining_delay = block.adc.delay - num_samples_discard * block.adc.dwell
            num_delay_samples = round(remaining_delay * self.spcm_freq)

            adc_start = (block_pos[event_idx] + num_delay_samples) * 4
            adc_end = adc_start + num_samples_raw * 4

            # Add ADC gate to 16th bit of output channel 1 (first gradient channel)
            _seq[adc_start + 1:adc_end + 1:4] |= np.uint16(2**15)

            # Add phase reference signal
            num_samples_reference = min(num_samples_raw, self.phase_reference.size)
            phase_ref_end = adc_start + num_samples_reference * 4
            _seq[adc_start + 2:phase_ref_end + 2:4] |= self.phase_reference[:num_samples_reference]

            _rx_data.append(
                RxData(
                    index=adc_count,
                    num_samples=block.adc.num_samples,
                    num_samples_raw=num_samples_raw,
                    num_samples_discard=num_samples_discard,
                    dwell_time=block.adc.dwell,
                    dwell_time_raw=self.spcm_dwell_time,
                    phase_offset=block.adc.phase_offset,
                    freq_offset=block.adc.freq_offset,
                    total_averages=parameter.num_averages,
                    ddc_method=parameter.ddc_method,
                    phase_ref_frequency=REFERENCE_FREQUENCY,
                    labels=labels,
                )
            )
            adc_count += 1
            labels = {}  # Reset labels dict

    self.log.debug(
        "Unrolled sequence; Total sample points: %s; Total block events: %s",
        seq_samples,
        len(block_durations),
    )

    return UnrolledSequence(
        seq=_seq,
        sample_count=seq_samples,
        gpa_gain=self.gpa_gain,
        gradient_efficiency=self.grad_eff,
        rf_to_mvolt=self.rf_to_mvolt,
        dwell_time=self.spcm_dwell_time,
        gradient_output_limits=self.gradient_out_limits,
        rf_output_limit=self.rf_out_limit,
        duration=self.duration()[0],
        adc_count=adc_count,
        parameter=parameter,
        rx_data=_rx_data,
    )