Skip to content

tx_device

tx_device

Implementation of transmit card.

TxCard

TxCard(path: str, max_amplitude: tuple[int, int, int, int], filter_type: tuple[int, int, int, int], sample_rate: int)

Bases: SpectrumDevice

Transmit card (arbitrary waveform generator).

Implementation of the abstract SpectrumDevice for the Spectrum Instrumentation M2p.65xx series, developed and tested with the M2p.6546-x4 (4 channels, 512 MSample on-board memory, 2 bytes/sample).

The card replays the interleaved int16 waveform of an UnrolledSequence in FIFO single mode (SPC_REP_FIFO_SINGLE). A host-side ring buffer of at most 1 GiB is streamed to the card in chunks of notify_size bytes by a background thread. Channel 0 carries the RF waveform, channels 1 to 3 carry the gradient waveforms. Bit 15 of channels 1, 2 and 3 is routed to the digital outputs X1 (ADC gate), X2 (phase reference) and X3 (RF unblanking).

The card runs on an external clock, which is provided by the receive card, and sets its own sampling rate.

Initialize the transmit card.

Parameters:

  • path (str) –

    Path of the spectrum card device, e.g. /dev/spcm0

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

    Maximum output amplitude per channel in mV.

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

    Output filter setting per channel.

  • sample_rate (int) –

    Card sampling rate in MHz.

Source code in src/console/spcm_control/tx_device.py
def __init__(
    self,
    path: str,
    max_amplitude: tuple[int, int, int, int],
    filter_type: tuple[int, int, int, int],
    sample_rate: int,
) -> None:
    """Initialize the transmit card.

    Parameters
    ----------
    path
        Path of the spectrum card device, e.g. /dev/spcm0
    max_amplitude
        Maximum output amplitude per channel in mV.
    filter_type
        Output filter setting per channel.
    sample_rate
        Card sampling rate in MHz.
    """
    self.log = logging.getLogger(self.__name__)
    super().__init__(path=path, log=self.log)
    self.max_amplitude = max_amplitude
    self.filter_type = filter_type
    self.sample_rate = sample_rate

    # Number of output channels is fixed
    self.num_ch = 4
    # Size of the current sequence
    self.data_buffer_size: int = 0

    # Define maximum ring buffer size, 512 MSamples * 2 Bytes = 1024 MB
    self.max_ring_buffer_size = ctypes.c_uint64(1024**3)

    # Threading class attributes
    self.worker: threading.Thread | None = None
    self.is_running = threading.Event()

setup_card

setup_card() -> None

Set up spectrum card in transmit (TX) mode.

The card is reset and its type is verified (M2p.65xx). The trigger is set to software, the clock to external (50 Ohm, 1.5 V threshold), and the sampling rate is set from the class attribute. All 4 channels are enabled and configured with the max. amplitude and filter values from the class attributes. The digital outputs X1, X2 and X3 are driven by bit 15 of the analog channels 1, 2 and 3. If an IO expansion module is present, the ADC gate and the unblanking signal are additionally routed to X12 and X13.

Raises:

  • Warning –

    The actual set sample rate deviates from the corresponding class attribute to be set, class attribute is overwritten.

Source code in src/console/spcm_control/tx_device.py
def setup_card(self) -> None:
    """Set up spectrum card in transmit (TX) mode.

    The card is reset and its type is verified (M2p.65xx). The trigger is set to software, the clock
    to external (50 Ohm, 1.5 V threshold), and the sampling rate is set from the class attribute.
    All 4 channels are enabled and configured with the max. amplitude and filter values from the class
    attributes. The digital outputs X1, X2 and X3 are driven by bit 15 of the analog channels 1, 2 and 3.
    If an IO expansion module is present, the ADC gate and the unblanking signal are additionally
    routed to X12 and X13.

    Raises
    ------
    Warning
        The actual set sample rate deviates from the corresponding class attribute to be set,
        class attribute is overwritten.
    """
    # Reset card
    self.handle_error(spcm.spcm_dwSetParam_i64(self.card, spcm.SPC_M2CMD, spcm.M2CMD_CARD_RESET))
    spcm.spcm_dwGetParam_i32(self.card, spcm.SPC_PCITYP, ctypes.byref(self.card_type))

    try:
        if self.name is None or "M2p.65" not in self.name:
            raise ConnectionError(f"Device with path {self.path} is of type {self.name}, no transmit card...")
    except ConnectionError as err:
        self.log.exception(err, exc_info=True)
        raise err

    # Check for presence of IO expansion cards
    card_features = spcm.int32(0)
    spcm.spcm_dwGetParam_i32(self.card, spcm.SPC_PCIFEATURES, ctypes.byref(card_features))

    # Set trigger
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_TRIG_ORMASK, spcm.SPC_TMASK_SOFTWARE)

    # Configure external clock, the clock is provided by the RX card (clock master)
    self.handle_error(spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_CLOCKMODE, spcm.SPC_CM_EXTERNAL))
    self.handle_error(spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_CLOCK50OHM, 1))
    self.handle_error(spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_CLOCK_THRESHOLD, 1500))

    # set card sampling rate in MHz
    self.handle_error(spcm.spcm_dwSetParam_i64(self.card, spcm.SPC_SAMPLERATE, spcm.MEGA(self.sample_rate)))

    # Check actual sampling rate
    sample_rate = spcm.int64(0)
    spcm.spcm_dwGetParam_i64(self.card, spcm.SPC_SAMPLERATE, ctypes.byref(sample_rate))
    self.log.info("Device sampling rate: %s MHz", sample_rate.value * 1e-6)
    if sample_rate.value != spcm.MEGA(self.sample_rate):
        self.log.warning(
            "Tx device sample rate %s MHz does not match set sample rate of %s MHz",
            sample_rate.value * 1e-6,
            self.sample_rate,
        )
        self.sample_rate = int(sample_rate.value * 1e-6)

    # Enable and setup channels
    self.handle_error(spcm.spcm_dwSetParam_i32(
        self.card,
        spcm.SPC_CHENABLE,
        spcm.CHANNEL0 | spcm.CHANNEL1 | spcm.CHANNEL2 | spcm.CHANNEL3,
    ))

    self.log.info("Setup max. output amplitude: %s.", self.max_amplitude)

    # Use loop to enable and setup active channels
    # Channel 0: RF
    self.handle_error(spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_ENABLEOUT0, 1))
    self.handle_error(spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_AMP0, self.max_amplitude[0]))
    self.handle_error(spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_FILTER0, self.filter_type[0]))

    # Channel 1: Gradient, synchronous digital output (bit 15 -> X1): ADC gate
    self.handle_error(spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_ENABLEOUT1, 1))
    self.handle_error(spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_AMP1, self.max_amplitude[1]))
    self.handle_error(spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_FILTER1, self.filter_type[1]))

    # Channel 2: Gradient, synchronous digital output (bit 15 -> X2): phase reference
    self.handle_error(spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_ENABLEOUT2, 1))
    self.handle_error(spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_AMP2, self.max_amplitude[2]))
    self.handle_error(spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_FILTER2, self.filter_type[2]))

    # Channel 3: Gradient, synchronous digital output (bit 15 -> X3): RF unblanking
    self.handle_error(spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_ENABLEOUT3, 1))
    self.handle_error(spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_AMP3, self.max_amplitude[3]))
    self.handle_error(spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_FILTER3, self.filter_type[3]))

    # Setup the card in FIFO mode
    self.handle_error(spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_CARDMODE, spcm.SPC_REP_FIFO_SINGLE))

    # >> Setup digital output channels
    # Channel X1: dig. ADC gate (15th bit from analog channel 1)
    self.handle_error(spcm.spcm_dwSetParam_i32(
        self.card,
        spcm.SPCM_X1_MODE,
        (spcm.SPCM_XMODE_DIGOUT | spcm.SPCM_XMODE_DIGOUTSRC_CH1 | spcm.SPCM_XMODE_DIGOUTSRC_BIT15),
    ))
    # Channel X2: dig. reference signal (15th bit from analog channel 2)
    self.handle_error(spcm.spcm_dwSetParam_i32(
        self.card,
        spcm.SPCM_X2_MODE,
        (spcm.SPCM_XMODE_DIGOUT | spcm.SPCM_XMODE_DIGOUTSRC_CH2 | spcm.SPCM_XMODE_DIGOUTSRC_BIT15),
    ))
    # Channel X3: dig. unblanking signal (15th bit of analog channel 3)
    self.handle_error(spcm.spcm_dwSetParam_i32(
        self.card,
        spcm.SPCM_X3_MODE,
        (spcm.SPCM_XMODE_DIGOUT | spcm.SPCM_XMODE_DIGOUTSRC_CH3 | spcm.SPCM_XMODE_DIGOUTSRC_BIT15),
    ))

    # >> Setup additional GPIO ports, if extender is available
    if card_features.value & (spcm.SPCM_FEAT_DIG16_FX2 | spcm.SPCM_FEAT_DIG16_SMB):
        self.log.info("IO expansion card with FX2 connector detected, performing additional setup...")

        # Replicate ADC gate on extension port X12
        self.handle_error(spcm.spcm_dwSetParam_i32(
            self.card,
            spcm.SPCM_X12_MODE,
            (spcm.SPCM_XMODE_DIGOUT | spcm.SPCM_XMODE_DIGOUTSRC_CH1 | spcm.SPCM_XMODE_DIGOUTSRC_BIT15),
        ))

        # Replicate unblanking signal at extension port X13
        self.handle_error(spcm.spcm_dwSetParam_i32(
            self.card,
            spcm.SPCM_X13_MODE,
            (spcm.SPCM_XMODE_DIGOUT | spcm.SPCM_XMODE_DIGOUTSRC_CH3 | spcm.SPCM_XMODE_DIGOUTSRC_BIT15),
        ))

    self.log.debug("Device setup completed")

set_gradient_offsets

set_gradient_offsets(offsets: Dimensions, is_50ohms: bool = False) -> None

Set offset values of the gradient output channels.

Parameters:

  • offsets (Dimensions) –

    Offset values given by Dimensions interface with integers in mV

  • is_50ohms (bool, default: False ) –

    Boolean flag indicating if the gradient outputs are terminated into 50 ohms or into high impedance.

Returns:

  • List of integer values read from card for x, y and z offset values –
Source code in src/console/spcm_control/tx_device.py
def set_gradient_offsets(self, offsets: Dimensions, is_50ohms: bool = False) -> None:
    """Set offset values of the gradient output channels.

    Parameters
    ----------
    offsets
        Offset values given by Dimensions interface with integers in mV
    is_50ohms
        Boolean flag indicating if the gradient outputs are terminated into 50 ohms or into high impedance.

    Returns
    -------
        List of integer values read from card for x, y and z offset values
    """
    # Check card connection
    try:
        if not self.card:
            raise ConnectionError("No connection to TX card.")
    except ConnectionError as err:
        self.log.exception(err, exc_info=True)
        raise err

    # Check offset values
    if abs(offsets.x) > self.max_amplitude[1]:
        self.log.error("Gradient offset of channel x exceeds maximum amplitude.")
    if abs(offsets.y) > self.max_amplitude[2]:
        self.log.error("Gradient offset of channel y exceeds maximum amplitude.")
    if abs(offsets.z) > self.max_amplitude[3]:
        self.log.error("Gradient offset of channel z exceeds maximum amplitude.")

    # If the outputs are terminated with high impedance, only half of the offsets need to be set,
    # as the value at the card output automatically doubles.
    z_scaling = 1. if is_50ohms else 0.5

    # Set offset values, scale offset by 0.5 if channel is terminated into high impedance
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_OFFS1, int(offsets.x * z_scaling))
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_OFFS2, int(offsets.y * z_scaling))
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_OFFS3, int(offsets.z * z_scaling))

    # Write setup
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_M2CMD, spcm.M2CMD_CARD_WRITESETUP)

    # Define variables to read offset values
    offset_x = spcm.int32(0)
    offset_y = spcm.int32(0)
    offset_z = spcm.int32(0)

    # Read offset values from card
    spcm.spcm_dwGetParam_i64(self.card, spcm.SPC_OFFS1, ctypes.byref(offset_x))
    spcm.spcm_dwGetParam_i64(self.card, spcm.SPC_OFFS2, ctypes.byref(offset_y))
    spcm.spcm_dwGetParam_i64(self.card, spcm.SPC_OFFS3, ctypes.byref(offset_z))

    set_offsets = [offset_x.value, offset_y.value, offset_z.value]
    self.log.info("Set gradient values %s mV for x, y and z.", set_offsets)

    # Check values read from card and log error if they are not correct
    if not (set_offsets[0] == offsets.x and set_offsets[1] == offsets.y and set_offsets[2] == offsets.z):
        self.log.error(
            "Actual gradient offsets do not correspond to the values to be set (x=%s, y=%s, z=%s mV)",
            offsets.x, offsets.y, offsets.z
        )

start_operation

start_operation(data: UnrolledSequence | None = None) -> None

Start transmit (TX) card operation.

Steps: (1) Setup the transmit card (2) Clear emergency stop flag, reset to False (3) Start worker thread (card streaming mode), with provided replay data

Parameters:

  • data (UnrolledSequence | None, default: None ) –

    Sequence replay data as int16 numpy array in correct order. Checkout prepare_sequence function for reference of correct replay data format. This value is None per default

Raises:

  • ValueError –

    Raised if replay data is not provided as numpy int16 values

Source code in src/console/spcm_control/tx_device.py
def start_operation(self, data: UnrolledSequence | None = None) -> None:
    """Start transmit (TX) card operation.

    Steps:
    (1) Setup the transmit card
    (2) Clear emergency stop flag, reset to False
    (3) Start worker thread (card streaming mode), with provided replay data

    Parameters
    ----------
    data
        Sequence replay data as int16 numpy array in correct order.
        Checkout `prepare_sequence` function for reference of correct replay data format.
        This value is None per default

    Raises
    ------
    ValueError
        Raised if replay data is not provided as numpy int16 values
    """
    try:
        # Data must have a default value as start_operation is an abstract method and data is optional
        if not data:
            raise ValueError("No unrolled sequence data provided.")
        sqnc = data.seq

        # Check if sequence datatype is valid
        if sqnc.dtype != np.int16:
            raise ValueError("Sequence replay data is not int16, please unroll sequence to int16.")

        # Check if card connection is established
        if not self.card:
            raise ConnectionError("No connection to card established...")

    except Exception as exc:
        self.log.exception(exc, exc_info=True)
        raise exc

    # Check if sequence dwell time is valid
    if sqnc_sample_rate := 1 / (data.dwell_time * 1e6) != self.sample_rate:
        self.log.warning(
            "Sequence sample rate (%s MHz) differs from device sample rate (%s MHz).",
            sqnc_sample_rate,
            self.sample_rate,
        )

    # Setup card, clear emergency stop thread event and start thread
    self.is_running.clear()
    self.worker = threading.Thread(target=self._fifo_stream_worker, args=(sqnc,))
    self.worker.start()

stop_operation

stop_operation() -> None

Stop card operation by thread event and stop card.

Source code in src/console/spcm_control/tx_device.py
def stop_operation(self) -> None:
    """Stop card operation by thread event and stop card."""
    if self.worker is not None:
        self.is_running.set()
        self.worker.join()

        self.handle_error(spcm.spcm_dwSetParam_i32(
            self.card,
            spcm.SPC_M2CMD,
            spcm.M2CMD_CARD_STOP | spcm.M2CMD_DATA_STOPDMA,
        ))
        self.worker = None
    else:
        print("No active replay thread found...")