Skip to content

rx_device

rx_device

Implementation of receive card.

RxCard dataclass

RxCard(path: str, sample_rate: int, channel_enable: tuple[bool, ...], max_amplitude: tuple[int, ...], impedance_50_ohms: tuple[bool, ...])

Bases: SpectrumDevice

Receive card (digitizer).

Implementation of the abstract SpectrumDevice for the Spectrum Instrumentation M2p.59xx series, developed and tested with the M2p.5933-x4 (up to 8 channels).

The card is the clock master of the system: it runs on its internal PLL and exports its clock to the transmit card. Data are recorded in gated FIFO mode (SPC_REC_FIFO_GATE). The ADC gate generated by the transmit card is applied to the external trigger input. Start and end of each gate are recorded by the timestamp engine. The digital phase reference (input X2) is sampled synchronously into bit 15 of analog channel 0.

Initialize the receive card.

Parameters:

  • path (str) –

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

  • sample_rate (int) –

    Card sampling rate in MHz.

  • channel_enable (tuple[bool, ...]) –

    Enable flag per channel (8 entries); the number of enabled channels must be 1, 2, 4 or 8.

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

    Input range per channel in mV.

  • impedance_50_ohms (tuple[bool, ...]) –

    Input termination per channel, True for 50 Ohm, False for high impedance (1 MOhm).

Source code in src/console/spcm_control/rx_device.py
def __init__(
    self,
    path: str,
    sample_rate: int,
    channel_enable: tuple[bool, ...],
    max_amplitude: tuple[int, ...],
    impedance_50_ohms: tuple[bool, ...],
) -> None:
    """Initialize the receive card.

    Parameters
    ----------
    path
        Path of the spectrum card device, e.g. /dev/spcm0
    sample_rate
        Card sampling rate in MHz.
    channel_enable
        Enable flag per channel (8 entries); the number of enabled channels must be 1, 2, 4 or 8.
    max_amplitude
        Input range per channel in mV.
    impedance_50_ohms
        Input termination per channel, True for 50 Ohm, False for high impedance (1 MOhm).
    """
    self.log = logging.getLogger(self.__name__)
    super().__init__(path, log=self.log)

    self.sample_rate = sample_rate
    self.channel_enable = [int(val) for val in channel_enable]
    self.max_amplitude = max_amplitude
    self.impedance_50_ohms = [int(val) for val in impedance_50_ohms]
    self.rx_data: list[RxData | None] | None = None

    self.num_channels = c_int32(0)
    self.card_type = c_int32(0)

    self.worker: threading.Thread | None = None
    self.is_running = threading.Event()
    self.is_receiving = threading.Event()
    self._total_gates: int = 0

    # Pre trigger is set to minimum, post trigger depends on active channel count and is defined later.
    self.pre_trigger: int = 8
    self.post_trigger: int | None = None

    self.rx_scaling = [amp / (2**15) for amp in self.max_amplitude]

    self._submit_fn: Callable[[int, RxData], None] | None = None
    self._index_offset: int = 0

total_gates property

total_gates: int

Helper function to return the number of gates that have been collected by the Rx Card.

setup_card

setup_card() -> None

Set up spectrum card in receive (RX) mode.

The card is reset and its type is verified (M2p.59xx). The clock is set to the internal PLL with clock output enabled, and the sampling rate is set from the class attribute. The enabled channels (1, 2, 4 or 8) are configured with input range and termination. X2 is configured as digital input and sampled into bit 15 of channel 0. The card is armed in gated FIFO mode on the positive edge of the external trigger (ADC gate), with timestamps recording start and end of each gate.

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/rx_device.py
def setup_card(self) -> None:
    """Set up spectrum card in receive (RX) mode.

    The card is reset and its type is verified (M2p.59xx). The clock is set to the internal PLL with
    clock output enabled, and the sampling rate is set from the class attribute.
    The enabled channels (1, 2, 4 or 8) are configured with input range and termination.
    X2 is configured as digital input and sampled into bit 15 of channel 0.
    The card is armed in gated FIFO mode on the positive edge of the external trigger (ADC gate),
    with timestamps recording start and end of each gate.

    Raises
    ------
    Warning
        The actual set sample rate deviates from the corresponding class attribute to be set,
        class attribute is overwritten.
    """
    # Get the card type and reset card
    spcm.spcm_dwGetParam_i32(self.card, spcm.SPC_PCITYP, byref(self.card_type))
    spcm.spcm_dwSetParam_i64(self.card, spcm.SPC_M2CMD, spcm.M2CMD_CARD_RESET)  # Needed?

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

    # Setup the internal clockmode, clock output enable (use RX clock output to enable anti-alias filter)
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_CLOCKMODE, spcm.SPC_CM_INTPLL)
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_CLOCKOUT, 1)

    # Use external clock: Terminate to 50 Ohms, set threshold to 1.5V, suitable for 3.3V clock
    # spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_CLOCKMODE, spcm.SPC_CM_EXTERNAL)
    # spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_CLOCK50OHM, 1)
    # spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_CLOCK_THRESHOLD, 1500)

    # Set card sampling rate in MHz and read the actual sampling rate
    spcm.spcm_dwSetParam_i64(self.card, spcm.SPC_SAMPLERATE, spcm.MEGA(self.sample_rate))
    sample_rate = spcm.int64(0)
    spcm.spcm_dwGetParam_i64(self.card, spcm.SPC_SAMPLERATE, 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(
            "Actual device sample rate %s MHz does not match set sample rate of %s MHz; Updating class attribute",
            sample_rate.value * 1e-6,
            self.sample_rate,
        )
        self.sample_rate = int(sample_rate.value * 1e-6)

    # Check channel enable, max. amplitude per channel and impedance values
    try:
        # Check that the length of the channel enable list is 8
        # this has to be true for cards with fewer channels too
        if (num_enable := len(self.channel_enable)) != 8:
            raise ValueError(f"Channel enable list is incomplete: {num_enable}/8")
        # Impedance and amplitude configuration lists must also be of length 8
        if (num_imp := len(self.impedance_50_ohms)) != 8:
            raise ValueError(f"Channel impedance list is incomplete: {num_imp}/8")
        if (num_amp := len(self.max_amplitude)) != 8:
            raise ValueError(f"channel max. amplitude list is incomplete: {num_amp}/8")
        # Number of enabled channels must be either 1, 2, 4 or 8
        if not np.log2(sum(self.channel_enable)).is_integer():
            raise ValueError("Invalid number of enabled channels, must be power of 2.")
    except ValueError as err:
        self.log.exception(err, exc_info=True)
        raise err

    # Enable receive channels, compress list of channel select registers to obtain list of channels to be enabled
    # Sum of the compressed list equals logical or operator
    # e.g. spcm.CHANNEL0 | spcm.CHANNEL1 | spcm.CHANNEL5 = sum([spcm.CHANNEL0, spcm.CHANNEL1, spcm.CHANNEL5]) = 35
    ch_select = [getattr(spcm, f"CHANNEL{k}") for k in range(8)]
    channel_selection = sum(list(compress(ch_select, map(bool, self.channel_enable))))
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_CHENABLE, channel_selection)

    # Set impedance and amplitude limits for each channel according to device configuration
    for k, enable in enumerate(map(bool, self.channel_enable)):
        if enable:
            self.log.info(
                "Channel %s enabled; 50 ohms impedance: %s; Max. amplitude: %s mV",
                k,
                self.impedance_50_ohms[k],
                self.max_amplitude[k],
            )
            spcm.spcm_dwSetParam_i32(self.card, getattr(spcm, f"SPC_50OHM{k}"), self.impedance_50_ohms[k])
            spcm.spcm_dwSetParam_i32(self.card, getattr(spcm, f"SPC_AMP{k}"), self.max_amplitude[k])

    # Get the number of actual active channels and compare against provided channel enable list
    spcm.spcm_dwGetParam_i32(self.card, spcm.SPC_CHCOUNT, byref(self.num_channels))
    try:
        self.log.info(
            "Number of enabled receive channels (read from card): %s",
            self.num_channels.value,
        )
        if not self.num_channels.value == sum(self.channel_enable):
            raise ValueError("Actual number of enabled channels does not match the provided channel enable list")
    except ValueError as err:
        self.log.exception(err, exc_info=True)
        raise err

    # Digital filter setting for receiver, 0 = disable digital bandwidth filter
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_DIGITALBWFILTER, 0)

    # Configure X2 as digital input for phase reference signal and sample it in sync with analog channel 0
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPCM_X2_MODE, spcm.SPCM_XMODE_DIGIN)
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_DIGMODE0, (spcm.DIGMODEMASK_BIT15 & spcm.SPCM_DIGMODE_X2))

    # Calculate trigger size depending on the number of active channels
    # Since data can only be gathered in notify size chunks, post_trigger // channel_count should be at least one
    # notify size to ensure that we can always access the full gate data.
    self.post_trigger = 4096 // self.num_channels.value

    # Set the memory size, pre and post trigger and loop parameters, SPC_LOOPS = 0 => runs infinitely long
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_POSTTRIGGER, self.post_trigger)
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_PRETRIGGER, self.pre_trigger)
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_LOOPS, 0)

    # Setup timestamp mode to read number of samples per gate if available
    spcm.spcm_dwSetParam_i32(
        self.card,
        spcm.SPC_TIMESTAMP_CMD,
        spcm.SPC_TSMODE_STARTRESET | spcm.SPC_TSCNT_INTERNAL,
    )
    # Configure trigger on EXT1 channel; and trigger on positive edge
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_TRIG_EXT1_MODE, spcm.SPC_TM_POS)
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_TRIG_ORMASK, spcm.SPC_TMASK_EXT1)

    # Setup gated FIFO mode
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_CARDMODE, spcm.SPC_REC_FIFO_GATE)

    # Get gate length alignment, number of samples must be integer multiple of this
    gate_alignment = spcm.int64(0)
    spcm.spcm_dwGetParam_i64(self.card, spcm.SPC_GATE_LEN_ALIGNMENT, byref(gate_alignment))
    self.gate_alignment = gate_alignment.value
    self.log.debug("Alignment samples: %d samples", self.gate_alignment)

    # Set timeout used for DMA wait to 10 ms
    spcm.spcm_dwSetParam_i32(self.card, spcm.SPC_TIMEOUT, 10)

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

start_operation

start_operation(submit_fn: Callable[[int, RxData], None] | None = None, index_offset: int = 0) -> None

Start card operation.

Parameters:

  • submit_fn (Callable[[int, RxData], None] | None, default: None ) –

    Optional callback invoked as submit_fn(global_index, rx_data) for each completed gate. When provided the gate's slot in rx_data is set to None immediately after the call so the caller owns the object. When None the populated items remain in rx_data for the caller to collect after stop_operation().

  • index_offset (int, default: 0 ) –

    Added to the per-gate index before calling submit_fn, allowing the caller to assign globally unique indices across multiple averages.

Source code in src/console/spcm_control/rx_device.py
def start_operation(
    self,
    submit_fn: Callable[[int, RxData], None] | None = None,
    index_offset: int = 0,
) -> None:
    """Start card operation.

    Parameters
    ----------
    submit_fn
        Optional callback invoked as ``submit_fn(global_index, rx_data)``
        for each completed gate.  When provided the gate's slot in
        ``rx_data`` is set to ``None`` immediately after the call so the
        caller owns the object.  When ``None`` the populated items remain
        in ``rx_data`` for the caller to collect after ``stop_operation()``.
    index_offset
        Added to the per-gate index before calling *submit_fn*, allowing
        the caller to assign globally unique indices across multiple averages.
    """
    self._submit_fn = submit_fn
    self._index_offset = index_offset
    self.is_running.clear()
    self.is_receiving.clear()
    self.worker = threading.Thread(target=self._gated_timestamps_stream)
    self.worker.start()

stop_operation

stop_operation() -> None

Stop card thread.

Source code in src/console/spcm_control/rx_device.py
def stop_operation(self) -> None:
    """Stop card thread."""
    if self.worker is not None:
        self.is_running.set()
        self.worker.join()
        self._submit_fn = None
        self._index_offset = 0

        # Stop card operation with the following steps:
        # 1. Stop card acquisition
        # 2. Stop data DMA transfer
        # 3. Stop timestamp DMA transfer
        self.handle_error(
            spcm.spcm_dwSetParam_i32(
                self.card,
                spcm.SPC_M2CMD,
                spcm.M2CMD_CARD_STOP | spcm.M2CMD_DATA_STOPDMA | spcm.M2CMD_EXTRA_STOPDMA,
            )
        )
    else:
        # No thread is running
        self.log.error("No active process found")