Skip to content

The bh_spc.spcm module

Low-level wrappers of SPCM-DLL functions and data structures.

This extension module aims to provide straightforward Python wrappers for the C functions, structs, and enums in SPCM-DLL. Currently, only the functions required to acquire data in FIFO mode are wrapped (excluding those that are specific to the DPC-230).

Error codes returned by functions are converted to exceptions (SPCMError). Functions that take output arguments are wrapped so that they provide the data as a return value. A few other small changes are made to facilitate usage from Python. In some cases enum names have been changed for readability.

A design goal of this module is to generally avoid artificially restricting user code from performing operations that the C functions allow, even if they are logically questionable or lead to unexpected return values. This is so that this module can be used to experiment with the C API and discover its behavior. A higher-level interface that guides the user toward correct usage can be built on top of this module.

As such, to fully understand the correct usage of these functions and data types, you will need to refer to the Becker & Hickl SPCM-DLL documentation.

AdjustPara

Adjustment parameters (wraps the SPC_Adjust_Para struct).

Wraps the SPCM-DLL SPC_Adjust_Para struct. Values of this type are returned by get_adjust_parameters and (as an attribute of EEPData) by get_eeprom_data.

Instances have the attributes corresponding to the C struct fields. All are read-only.

as_dict() -> dict[str, int | float] method descriptor

Return a dictionary containing the fields and values.

Returns:

Type Description
dict

Every field and its value.

items() -> Iterable[tuple[str, int | float]] method descriptor

Return an iterable yielding the fields and values in fixed order.

Returns:

Type Description
Iterable

An iterable yielding the pair (name, value) for every field.

DLLOperationMode

Bases: enum.Enum

Enum for the operation mode of SPCM-DLL.

Values of this type are returned by get_mode and are given to set_mode.

Not to be confused with ModuleType, which has similar (but slightly different) values.

Examples:

>>> for e in DLLOperationMode:
...     print(e.name, e.value)
HARDWARE 0
SIMULATE_SPC_600 600
...
SIMULATE_SPC_150NX 152
SIMULATE_SPC_150NXX 153
...

Print a table of all the enum members.

Data

The collection of values for all SPC parameters.

Wraps the SPCM-DLL SPCdata struct. Values of this type are returned by get_parameters and are passed to set_parameters.

Instances have attributes that match the ParID enum member names, but in lowercase. Attribute types match the type attribute of the corresponding ParID enum member.

An instance created by calling Data() contains zero for every parameter.

Instances can be duplicated using copy.copy() (or copy.deepcopy()), and can also be compared with == for (exact) equality (see Notes below).

Examples:

>>> for p, v in Data().items():
...     print(f"{p} = {v}")
cfd_limit_low = 0.0
cfd_limit_high = 0.0
...
mode = 0
...

Print the values of all parameters of a default instance (more interesting if you replace Data() with, say, get_parameters(0)).

See Also

ParID : Enum of SPC parameter ids.

Notes

The C struct fields base_adr, init, pci_card_no, and test_eep are hidden from this Python wrapper. These fields are either not currently meaningful or are redundant with information that can be obtained from get_module_info or get_eeprom_data. However, these fields are included in the equality comparison, so an instance created as Data() may never compare equal to an instance returned by get_parameters even if all attributes are set to be equal. Usually it is best to avoid creating an instance from scratch except in special situations such as testing. Always obtain an instance from get_parameters.

as_dict() -> dict[str, int | float] method descriptor

Return a dictionary containing the fields and values.

Returns:

Type Description
dict

Every field and its value.

diff_as_dict(other: Data) -> dict[str, int | float] method descriptor

Return a dictionary containing the fields and their values where they differ from the given other instance.

Parameters:

Name Type Description Default
other Data

The instance to compare to.

required

Returns:

Type Description
dict

Every field that differs from other and its value in this instance where the value differs from the other instance.

diff_items(other: Data) -> Iterable[tuple[str, int | float]] method descriptor

Return an iterable yielding the fields and values where they differ from the given other instance, in fixed order.

The order matches with the ParID enum members.

Returns:

Type Description
Iterable

An iterable yielding the pair (name, value) for every field in this instance where the value differs from the other instance.

items() -> Iterable[tuple[str, int | float]] method descriptor

Return an iterable yielding the fields and values in fixed order.

The order matches with the ParID enum members.

Returns:

Type Description
Iterable

An iterable yielding the pair (name, value) for every field.

EEPData

Information read from an SPC modules non-volatile memory.

Wraps the SPCM-DLL SPC_EEP_Data struct. Values of this type are returned by get_eeprom_data.

Attributes:

Name Type Description
module_type str

The module type as a string, such as "SPC-180NX" (read-only).

serial_no str

The serial number (read-only).

date str

Production date, such as "2024-03-26" (read-only).

adj_para AdjustPara

Adjustment parameters (read-only).

as_dict() -> dict[str, Any] method descriptor

Return a dictionary containing the fields and values.

Returns:

Type Description
dict

Every field and its value.

items() -> Iterable[tuple[str, Any]] method descriptor

Return an iterable yielding the fields and values in fixed order.

Returns:

Type Description
Iterable

An iterable yielding the pair (name, value) for every field.

ErrorEnum

Bases: enum.Enum

Enum of SPCM-DLL error codes.

The members' values are SPCM-DLL error codes (except for UNKNOWN). An additional member, UNKNOWN, which does not appear in SPCM-DLL, is used for any unknown error code that is encountered.

Usually you will get a value of this type from the enum attribute of an SPCMError exception.

Examples:

>>> for e in ErrorEnum:
...     print(e.value, e.name, get_error_string(e))
0 NONE No error
-1 OPEN_FILE Can't open file
...
-32769 UNKNOWN Unknown SPCM error

Print a list of all enum members and the corresponding error message.

See Also

SPCMError : Exception class for SPCM-DLL errors.

FIFOInitVars

Dataclass aggregating the return values of get_fifo_init_vars.

Attributes:

Name Type Description
fifo_type FIFOType

FIFO data format.

stream_type StreamType

Stream properties.

mt_clock int

Macrotime clock units in units of 0.1 ns (or 1 fs in the case of DPC-230).

spc_header array

4-byte .spc file header. In the case of SPC-600/630 FIFO-48 format, two zero bytes should be appended to form the 6-byte file header.

FIFOType

Bases: enum.Enum

Enum of FIFO data formats.

Values of this type are returned by get_fifo_init_vars as an attribute of FIFOInitVars.

Examples:

>>> for e in FIFOType:
...     print(e.name, e.value)
SPC_600_48BIT 2
SPC_600_32BIT 3
SPC_130 4
SPC_830 5
SPC_140 6
SPC_150 7
DPC_230 8
IMAGE 9
TDC 11
TDC_ABS 12
UNKNOWN 0

Print a table of all enum members.

InUseStatus

Bases: enum.Enum

Enum representing whether an SPC module is in use.

Possible values are NOT_IN_USE (0), IN_USE_HERE (1), and IN_USE_ELSEWHERE (-1), "elsewhere" meaning by another program or process.

Values of this type are returned (as an attribute of ModInfo) by get_module_info.

InitStatus

Bases: enum.Enum

Enum for the initialization status of an SPC module.

Values of this type are returned by get_init_status and (as an attribute of ModInfo) by get_module_info.

Attributes:

Name Type Description
message str

Human-readable message string

Examples:

>>> for e in InitStatus:
...     print(e.name, e.value, e.message)
OK 0 Initialized
NOT_DONE -1 Initialization not requested
...
XILINX_ERR -100 FPGA configuration error

Print a table of all the enum members and corresponding messages.

Notes

The member XILINX_ERR is used for all possible Xilinx (FPGA configuration) errors (-100 through -199) returned by SPCM-DLL functions.

MeasurementState

Bases: enum.Flag

Flag enum for measurement state.

Values of this type are returned by test_state.

For the sake of readability, the enum members are named differently from SPCM-DLL. See the example below for how to view the correspondence.

Examples:

>>> for n in MeasurementState.__members__:
...     e = MeasurementState[n]
...     print(e.name, e.value)
STOPPED_ON_OVERFLOW 1
OVERFLOW 2
...

Print a table of all enum members, including aliases.

>>> for name in MeasurementState.__members__:
...     e = MeasurementState[name]
...     print(
...         f"{measurement_state_bh_name(name):16} {e.value: 6} {name}"
...     )
SPC_OVERFL            1 STOPPED_ON_OVERFLOW
SPC_OVERFLOW          2 OVERFLOW
SPC_TIME_OVER         4 STOPPED_ON_COLLECT_TIME
SPC_COLTIM_OVER       8 COLLECT_TIME_ELAPSED
SPC_CMD_STOP         16 STOPPED_ON_COMMAND
SPC_REPTIM_OVER      32 REPEAT_TIME_ELAPSED
SPC_ARMED           128 ARMED
SPC_COLTIM_2OVER    256 COLLECT_TIME_ELAPSED_2ND_TIME
SPC_REPTIM_2OVER    512 REPEAT_TIME_ELAPSED_2ND_TIME
SPC_FOVFL          1024 FIFO_OVERFLOW
SPC_FEMPTY         2048 FIFO_EMPTY
SPC_WAIT_FR        8192 WAITING_FOR_FRAME
SPC_MEASURE          64 MEASUREMENT_ACTIVE
SPC_SCRDY          1024 SCAN_READY
SPC_FBRDY          2048 SCAN_FLOWBACK_READY
SPC_WAIT_TRG       4096 WAITING_FOR_TRIGGER
SPC_HFILL_NRDY    32768 HARDWARE_FILL_NOT_READY
SPC_SEQ_STOP      16384 STOPPED_BY_SEQUENCER
SPC_SEQ_GAP150     8192 SEQUENCER_GAP_150
SPC_SEQ_GAP          64 SEQUENCER_GAP
SPC_ARMED1          128 TDC1_ARMED
SPC_CTIM_OVER1        8 TDC1_COLLECT_TIME_ELAPSED
SPC_FEMPTY1         256 TDC1_FIFO_EMPTY
SPC_FOVFL1         1024 TDC1_FIFO_OVERFLOW
SPC_ARMED2        16384 TDC2_ARMED
SPC_CTIM_OVER2       32 TDC2_COLLECT_TIME_ELAPSED
SPC_FEMPTY2         512 TDC2_FIFO_EMPTY
SPC_FOVFL2         2048 TDC2_FIFO_OVERFLOW

Print the correspondence from SPCM-DLL names to pybhspc names.

See Also

measurement_state_bh_name

ModInfo

SPC module information.

Wraps the SPCM-DLL SPCModInfo struct. Values of this type are returned by get_module_info.

Attributes:

Name Type Description
module_type ModuleType

The module type (read-only).

bus_number int

The PCI bus number (read-only).

slot_number int

The PCI slot number (read-only).

in_use InUseStatus

Whether the module is in use (read-only).

init InitStatus

Whether the module is initialized, and the reason why if not (read-only).

as_dict() -> dict[str, Any] method descriptor

Return a dictionary containing the fields and values.

Returns:

Type Description
dict

Every field and its value.

items() -> Iterable[tuple[str, Any]] method descriptor

Return an iterable yielding the fields and values in fixed order.

Returns:

Type Description
Iterable

An iterable yielding the pair (name, value) for every field.

ModuleType

Bases: enum.Enum

Enum for the module type (model number) of an SPC module.

Values of this type are returned by test_id and (as an attribute of ModInfo) by get_module_info.

Not to be confused with DLLOperationMode, which has similar (but slightly different) values.

Examples:

>>> for e in ModuleType:
...     print(e.name, e.value)
SPC_600 600
SPC_630 630
...
SPC_150NX_OR_150NXX 152
...

Print a table of all the enum members.

ParID

Bases: enum.Enum

Enum of SPC parameter ids.

The members' values are the SPCM-DLL parameter ids. Members also have an attribute type which is either int or float.

Values of this type are passed to get_parameter and set_parameter. The attributes of the Data class match the lowercased version of the enum member names.

C language parameter types short, unsigned short, and unsigned long all map to Python int. C language float maps to Python float.

Attributes:

Name Type Description
type type

The parameter type: int or float.

Examples:

>>> for e in ParID:
...     print(e.value, e.name, e.type.__name__)
0 CFD_LIMIT_LOW float
1 CFD_LIMIT_HIGH float
...
27 MODE int
...

Print a list of all parameter ids, their names, and types.

See Also

Data : Aggregate object of all the parameters and their values.

RateValues

Rate counter values.

Wraps the SPCM-DLL rate_values struct. Values of this type are returned by read_rates.

Attributes:

Name Type Description
sync_rate float

The SYNC rate (counts/s, read-only).

cfd_rate float

The CFD rate (counts/s, read-only).

tac_rate float

The TAC rate (counts/s, read-only).

adc_rate float

The ADC rate (counts/s, read-only).

as_dict() -> dict[str, float] method descriptor

Return a dictionary containing the fields and values.

Returns:

Type Description
dict

Every field and its value.

items() -> Iterable[tuple[str, float]] method descriptor

Return an iterable yielding the fields and values in fixed order.

Returns:

Type Description
Iterable

An iterable yielding the pair (name, value) for every field.

SPCMError

Bases: builtins.RuntimeError

Exception raised when an SPCM function returns an error.

Attributes:

Name Type Description
enum ErrorEnum

The error enum (read-only).

code int

The raw error code, a negative value (read-only). This is usually redundant with the enum attribute but provided so that the code for an unknown (to pybhspc) error can be retrieved when enum is ErrorEnum.UNKNOWN.

See Also

ErrorEnum : Enum of SPCM-DLL error codes.

StreamType

Bases: enum.Flag

Flag enum for properties of SPCM-DLL streams.

Values of this type are returned by get_fifo_init_vars as an attribute of FIFOInitVars.

Examples:

>>> for f in StreamType:
...     print(f.name, f.value)
HAS_SPC_HEADER 1
HAS_MARKERS 512
RAW_DATA 1024
SPC_QC 2048
BUFFERED 4096
AUTOFREE_BUFFER 8192
RING_BUFFER 16384
DPC_TDC1_RAW_DATA 2
DPC_TDC2_RAW_DATA 4
DPC_TDC_TTL_RAW_DATA 8
DPC 256

Print a table of all flag members.

Notes

pybhspc does not support SPCM-DLL stream functions.

SyncState

Bases: enum.Flag

Flag enum for sync state.

Values of this type are returned by get_sync_state.

There are two flags: SYNC_OK (bit 0) and SYNC_OVERLOAD (bit 1). When the SYNC_OVERLOAD bit is set, the SYNC_OK bit is invalid.

clear_rates(mod_no: int) -> None method descriptor

Initialize and clear the rate counters and start a count cycle.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

close() -> None method descriptor

Uninitialize SPCM-DLL.

get_actual_coltime(mod_no: int) -> float method descriptor

Get the remaining time to the end of the measurement, taking dead time compensation into account.

Under some conditions (e.g., in FIFO mode with STOP_ON_TIME disabled), the return value counts up similarly to get_time_from_start.

test_state must be called periodically for this function to work correctly during measurements that exceed 80 seconds.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

Returns:

Type Description
float

Remaining or elapsed collection time, in seconds.

get_adjust_parameters(mod_no: int) -> AdjustPara method descriptor

Get adjustment parameters of an SPC module.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

Returns:

Type Description
AdjustPara

Adjustment parameters of the module.

get_break_time(mod_no: int) -> float method descriptor

Get the time from measurement start to stop or pause.

The return value may not be valid in FIFO mode (to be investigated).

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

Returns:

Type Description
float

Duration of measurement in seconds.

get_eeprom_data(mod_no: int) -> EEPData method descriptor

Get EEPROM data of an SPC module.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

Returns:

Type Description
EEPData

EEPROM data of the module.

get_error_string(error_id: int | ErrorEnum) -> str method descriptor

Return the error message for the given SPCM error code.

Parameters:

Name Type Description Default
error_id int or ErrorEnum

The error code

required

Returns:

Type Description
str

The error message

get_fifo_init_vars(mod_no: int) -> FIFOInitVars method descriptor

Get format information on the currently set FIFO mode.

The return value is only meaningful if the module is set to a FIFO mode.

For SPC-600/630, the number of routing bits in the SPCHeader may always be zero (in both FIFO formats).

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

Returns:

Type Description
FIFOInitVars

The FIFO format information.

get_fifo_usage(mod_no: int) -> float method descriptor

Get the used fraction of the FIFO.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

Returns:

Type Description
float

The fraction of the FIFO occupied (0.0 to 1.0).

get_init_status(mod_no: int) -> InitStatus method descriptor

Get the initialization status of the given SPC module.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

Returns:

Type Description
InitStatus

Whether the module is initialized, or the reason why if not.

get_mode() -> DLLOperationMode method descriptor

Get the operation mode of SPCM-DLL.

Returns:

Type Description
DLLOperationMode

The mode, either hardware or simulation of a module type.

Raises:

Type Description
SPCMError

If there was an error (e.g., if SPCM-DLL is not initialized).

get_module_info(mod_no: int) -> ModInfo method descriptor

Get information about an SPC module.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

Returns:

Type Description
ModInfo

Basic information about the module.

get_parameter(mod_no: int, par_id: ParID) -> float | int method descriptor

Get one parameter's value.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required
par_id ParID

The parameter to read.

required

Returns:

Type Description
float or int

The parameter value.

get_parameters(mod_no: int) -> Data method descriptor

Get all parameter values of an SPC module.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

Returns:

Type Description
Data

The parameter values.

get_sync_state(mod_no: int) -> SyncState method descriptor

Get the state of the SYNC input.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

Returns:

Type Description
SyncState

Whether the SYNC signal is triggering and whether it is overloaded.

get_time_from_start(mod_no: int) -> float method descriptor

Get the time since measurement start.

test_state must be called periodically for this function to work correctly during measurements that exceed 80 seconds.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

Returns:

Type Description
float

Elapsed time since measurement start, in seconds.

get_version(mod_no: int) -> str method descriptor

Get the FPGA version of an SPC module.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

Returns:

Type Description
str

The FPGA version (4 hex digits).

init(ini_file: bytes | str) -> None method descriptor

Initialize SPCM-DLL and one or all of the available SPC modules.

Parameters:

Name Type Description Default
ini_file bytes or str

Filename of the .ini file used to specify parameters.

required

Raises:

Type Description
SPCMError

If initialization fails or there were no available SPC modules.

measurement_state_bh_name(name: str) -> str method descriptor

Map MeasurementState enum member names to their SPCM-DLL names.

Parameters:

Name Type Description Default
name str

The pybhspc MeasurementState enum member name.

required

Returns:

Type Description
str

The corresponding SPCM-DLL constant name.

See Also

MeasurementState

read_fifo(mod_no: int, data) -> int method descriptor

Read data from a FIFO mode measurement.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required
data array_like

The destination buffer for the data read. The object must implement the buffer protocol, be typed unsigned short (uint16), be 1-dimentional, and be C-contiguous. For example, np.empty(65536, dtype=np.uint16).

required

Returns:

Type Description
int

The number of 16-bit words read. Thus, if the return value is r, data[:r] contains valid data.

read_fifo_to_array(mod_no: int, max_words: int) -> array.array method descriptor

Convenience wrapper around read_fifo that allocates an array for the output.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required
max_words int

Maximum number of 16-bit words to read.

required

Returns:

Type Description
array.array of unsigned short

The FIFO data read. The length of the array is between 0 and max_words.

read_parameters_from_inifile(inifile: bytes | str) -> Data method descriptor

Read an .ini file in the spcm.ini format.

The .ini file must contain a first-line comment starting with (whitespace followed by) SPCM, an [spc_base] section, and an [spc_module] section. The sections may be empty but the section headers need to be terminated with a newline.

Parameters:

Name Type Description Default
inifile bytes or str

Filename of the .ini file.

required

Returns:

Type Description
Data

The parameters read from the .ini file.

read_rates(mod_no: int) -> RateValues | None method descriptor

Read the rate counters and start a new count cycle.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

Returns:

Type Description
RateValues or None

The rate counts, or None if a count cycle has not yet completed.

save_parameters_to_inifile(data: Data, dest_inifile: bytes | str, *, source_inifile: bytes | str | None = None, with_comments: bool = False) -> None method descriptor

Save parameters to an .ini file in the spcm.ini format.

A source .ini file is required for this function to work, optionally given by source_inifile. If not given, the filename previously passed to init is used. Either way, this file must exist and must contain a first-line comment starting with (whitespace followed by) SPCM, an [spc_base] section, and an [spc_module] section. The sections may be empty but the section headers need to be terminated with a newline.

When with_comments is True, it appears that there need to be at least 2 fields set in the [spc_module] section of the source_inifile. The precise requirements have not been determined.

Parameters:

Name Type Description Default
data Data

The parameters to save.

required
dest_inifile bytes or str

Filename of the .ini file to write.

required
source_inifile bytes or str or None

Filename of an .ini file from which to copy initial comment lines and the [spc_base] section. If None, the .ini file passed to init() is used.

None
with_comments bool

If True, also copy parameter comments from source_inifile.

False

set_mode(mode: DLLOperationMode, force_use: bool, use: Sequence[bool]) -> None method descriptor

Set the operation mode of SPCM-DLL and activate or deactivate each of the SPC modules.

Parameters:

Name Type Description Default
mode DLLOperationMode

The operation mode specifying hardware or simulation module type.

required
force_use bool

If true, try to obtain control of the requested modules even if they are in use by another process.

required
use sequence of bool

Which SPC modules to activate. Currently up to 8 are supported. If fewer are given, the remaining modules will be deactivated.

required

Raises:

Type Description
SPCMError

If there was an error or if no modules were activated.

set_parameter(mod_no: int, par_id: ParID, value: float | int) -> None method descriptor

Set one parameter's value.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required
par_id ParID

The parameter to write.

required
value float or int

The parameter value.

required

set_parameters(mod_no: int, data: Data) -> None method descriptor

Set all parameter values of an SPC module.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required
data Data

The parameter values.

required

start_measurement(mod_no: int) -> None method descriptor

Start a measurement.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

stop_measurement(mod_no: int) -> None method descriptor

Stop any ongoing measurement.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

test_id(mod_no: int) -> ModuleType method descriptor

Return the module type (model number) of the given SPC module.

The return value is not accurate if called before init.

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

Returns:

Type Description
ModuleType

The module type enum.

test_state(mod_no: int) -> MeasurementState method descriptor

Get various status flags for the last-started measurement.

This function should be called periodically during a measurement in order to detect when the measurement is stopped (among other things).

Parameters:

Name Type Description Default
mod_no int

The SPC module index.

required

Returns:

Type Description
MeasurementState

Flags indicating timer and FIFO states, reason for measurement stop, etc.