spcm
A high-level, general purpose, object-oriented Python package to control Spectrum Instrumentation GmbH devices.
spcm
can connect to digitizers, AWGs, StarHubs and Netboxes. The package contains classes for controlling specific
cards and synchronization devices (StarHub) as well as for specific functionality, such as DDS and TimeStamps.
Classes
Hardware classes
Hardware classes are the interfaces to the actual devices. These hardware classes support context management, hence the opening of specific devices is handled as a file open, using the Python with-statement.
Name | Parent | Description |
---|---|---|
Device |
(none) | general base class for connecting to Spectrum Instrumentation GmbH devices and an interface for other classes. |
Card |
Device |
a class to control the low-level API interface of Spectrum Instrumentation cards. |
Sync |
Device |
a class for controling StarHub devices. |
CardStack |
ExitStack |
a class that handles the opening and closing of a combination of different cards either with or without a StarHub that synchronizes the cards. |
Netbox |
CardStack |
a class that handles the opening and closing of a group of cards combined in a Netbox. |
Diagram
classDiagram class Device class Card class Sync class `contextlib.ExitStack` class CardStack class Netbox Device <|-- Card Device <|-- Sync `contextlib.ExitStack` <|-- CardStack CardStack <|-- Netbox
Functionality classes
Functionality classes handle specific functionality that is available to the card, as well as specific add-on options. A functionality class is provided with a hardware class object to handle functionality on that card. Some classes, in addition, also support groups of cards and can be provided with objects of type CardStack
.
Name | Parent | Description |
---|---|---|
CardFunctionality |
(none) | interface class for additional card functionality |
Channels |
(none) | class for controlling the channels of a card or a stack of cards |
Channel |
(none) | class for controlling a single channel |
Clock |
CardFunctionality |
class for setting up the clock engine of the card |
Trigger |
CardFunctionality |
class for setting up the trigger engine of the card |
MultiPurposeIOs |
CardFunctionality |
class for setting up the multi purpose i/o's of the card |
MultiPurposeIO |
(none) | class for handling a single multi purpose i/o line a list of these objects resides inside MultiPurposeIOs |
DataTransfer |
CardFunctionality |
special class for handling data transfer functionality |
Multi |
DataTransfer |
special class for handling multiple recording and replay mode functionality |
Sequence |
DataTransfer |
special class for handling sequence mode functionality |
TimeStamp |
DataTransfer |
special class for handling time stamped data |
SCAPPTransfer |
DataTransfer |
special class for handling direct card to GPU class using the SCAPP option |
Boxcar |
Multi |
special class for handling boxcar averaging |
BlockAverage |
Multi |
special class for handling block averaging functionality |
PulseGenerators |
CardFunctionality |
class for handling the pulse generator functionality |
PulseGenerator |
(none) | class for handling a single pulse generator a list of these objects resides inside PulseGenerators |
DDS |
CardFunctionality |
class for handling DDS functionality |
DDSCore |
(none) | class for handling a DDS core, a list of these objects resides inside a DDS object |
DDSCommandList |
DDS |
class for handling streaming DDS commands in blocks |
DDSCommandQueue |
DDS |
class for handling streaming DDS commands in queues, where commands are added to the queue and automatically written to the card |
Diagram
classDiagram class CardFunctionality <<interface>> CardFunctionality class Channels class Clock class Trigger class MultiPurposeIOs class DataTransfer class DDS class DDSCore class DDSCommandList class DDSCommandQueue class PulseGenerators class Multi class TimeStamp class Sequence class SCAPPTransfer class Boxcar class BlockAverage CardFunctionality <|-- Clock CardFunctionality <|-- Trigger CardFunctionality <|-- MultiPurposeIOs CardFunctionality <|-- DataTransfer CardFunctionality <|-- DDS CardFunctionality <|-- PulseGenerators DataTransfer <|-- Multi DataTransfer <|-- TimeStamp DataTransfer <|-- Sequence DataTransfer <|-- SCAPPTransfer Multi <|-- Boxcar Multi <|-- BlockAverage Channels *-- Channel MultiPurposeIOs *-- MultiPurposeIO PulseGenerators *-- PulseGenerator DDS *-- DDSCore DDS <|-- DDSCommandList DDSCommandList <|-- DDSCommandQueue
Exception classes
When an error in the driver occures, the user is notified with an exception that contains an error object. Timeouts are also handled through exceptions and have their own class.
Name | Parent | Description |
---|---|---|
SpcmException |
(none) | the main class to control exceptions that are raised due to errors that are raised by the low-level driver. |
SpcmTimeout |
SpcmException |
when an timeout of the device occurs a special exception is raised of type SpcmTimeout |
Diagram
classDiagram class SpcmTimeout class SpcmException SpcmException <|-- SpcmTimeout
Error classes
Errors coming from the driver API, are stored in an error object and then raised as an exception. The error object contains all the information coming from the driver.
Name | Parent | Description |
---|---|---|
SpcmError |
(none) | all the errors that are raised by the low-level driver are packed into objects of this class and handled through exceptions |
Diagram
classDiagram class SpcmError
Notes
- See the files
regs.py
andspcerr.py
for an extensive list of all the register names and errors that are handled by the driver. - For more information, please have a look at our hardware specific user manuals.
See also
Supported devices
The following product series are supported:
- Digitizers
- M2p
- M4i / M4x
- M5i
- digitizerNetbox
- Arbitrary Waveform Generators (AWGs) and DDS Generators
- M2p
- M4i / M4x
- M5i
- generatorNetbox
- Digital Waveform Acquisition/Pattern Generation
- M2p
- M4i / M4x
- Hybrid
1""" 2.. include:: ./README.md 3 4.. include:: ./SUPPORTED_DEVICES.md 5""" 6 7__docformat__ = "numpy" 8import numpy as np 9 10# Units available 11from pint import UnitRegistry 12try: 13 import matplotlib.pyplot as plt 14 mpl = True 15except ImportError: 16 mpl = False 17units = UnitRegistry(autoconvert_offset_to_baseunit=True) 18units.define("sample = 1 = Sa = Sample = Samples = S") 19units.define("promille = 0.001 = ‰ = permille = perthousand = perthousands = ppt") 20units.define("fraction = 1 = frac = Frac = Fracs = Fraction = Fractions = Frac = Fracs") 21units.highZ = np.inf * units.ohm 22units.formatter.default_format = "~P" # see https://pint.readthedocs.io/en/stable/user/formatting.html 23if mpl: 24 units.setup_matplotlib(mpl) 25 units.mpl_formatter = "{:~P}" # see https://pint.readthedocs.io/en/stable/user/plotting.html 26__all__ = ["units"] 27 28# Import all registery entries and spectrum card errors into the module's name space 29from spcm_core import * 30 31# Import all the public classes into the module's namespace 32from .classes_device import Device 33from .classes_card import Card 34from .classes_error_exception import SpcmError, SpcmException, SpcmTimeout, SpcmDeviceNotFound 35from .classes_sync import Sync 36from .classes_card_stack import CardStack 37from .classes_netbox import Netbox 38# Functionality 39from .classes_functionality import CardFunctionality 40from .classes_channels import Channels, Channel 41from .classes_clock import Clock 42from .classes_trigger import Trigger 43from .classes_multi_purpose_ios import MultiPurposeIO, MultiPurposeIOs 44from .classes_data_transfer import DataTransfer 45from .classes_multi import Multi 46from .classes_time_stamp import TimeStamp 47from .classes_sequence import Sequence 48from .classes_dds import DDS, DDSCore 49from .classes_dds_command_list import DDSCommandList 50from .classes_dds_command_queue import DDSCommandQueue 51from .classes_pulse_generators import PulseGenerator, PulseGenerators 52from .classes_block_average import BlockAverage 53from .classes_boxcar import Boxcar 54from .classes_scapp import SCAPPTransfer 55 56__all__ = [*__all__, 57 "Device", "Card", "Sync", "CardStack", "Netbox", "CardFunctionality", "Channels", "Channel", "Clock", "Trigger", "MultiPurposeIOs", "MultiPurposeIO", 58 "DataTransfer", "DDS", "DDSCore", "DDSCommandList", "DDSCommandQueue", "PulseGenerator", "PulseGenerators", "Multi", "TimeStamp", "Sequence", 59 "BlockAverage", "Boxcar", "SpcmException", "SpcmTimeout", "SpcmDeviceNotFound", "SpcmError", "SCAPPTransfer" 60] 61 62# Versioning support using versioneer 63from . import _version 64__version__ = _version.get_versions()['version'] 65 66# Writing spcm package version to log file 67try: 68 driver_version = int64(0) 69 spcm_dwGetParam_i64(None, SPC_GETDRVVERSION, byref(driver_version)) 70 version_hex = driver_version.value 71 major = (version_hex & 0xFF000000) >> 24 72 minor = (version_hex & 0x00FF0000) >> 16 73 build = version_hex & 0x0000FFFF 74 # Available starting from build 21797 75 if build < 21797: 76 version_str = "v{}.{}.{}".format(major, minor, build) 77 raise OSError(f"Driver version build {version_str} does not support writing spcm version to log") 78 from importlib.metadata import version 79 version_tag = version('spcm') 80 version_str = bytes("Python package spcm v{}".format(version_tag), "utf-8") 81 version_ptr = create_string_buffer(version_str) 82 dwErr = spcm_dwSetParam_ptr(None, SPC_WRITE_TO_LOG, version_ptr, len(version_str)) 83except OSError as e: 84 print(e)
21class Device(): 22 """ 23 a class to control the low-level API interface of Spectrum Instrumentation devices 24 25 For more information about what setups are available, please have a look at the user manual 26 for your specific device. 27 28 Parameters 29 ---------- 30 device_identifier 31 the identifying string that defines the used device 32 33 Raises 34 ---------- 35 SpcmException 36 SpcmTimeout 37 """ 38 39 # public 40 device_identifier : str = "" 41 42 # private 43 _kwargs : Dict[str, Union[int, float, str]] = {} 44 _last_error = None 45 _handle = None 46 """the handle object used for the card connection""" 47 48 _str_len = 256 49 _reraise : bool = False 50 _throw_error : bool = True 51 _verbose : bool = False 52 _closed : bool = True 53 """the indicator that indicated whether a connection is opened or closed is set to open (False)""" 54 55 56 def __init__(self, device_identifier : str = "", handle = False, **kwargs) -> None: 57 """Puts the device_identifier in the class parameter self.device_parameter 58 59 Parameters 60 ---------- 61 device_identifier : str = "" 62 an identifier string to connect to a specific device, for example: 63 64 * Local PCIe device '/dev/spcm0' 65 * Remote 'TCPIP::192.168.1.10::inst0::INSTR' 66 handle = False 67 directly supply the object with an existing handle 68 """ 69 self.device_identifier = device_identifier 70 self._handle = handle 71 self._kwargs = kwargs 72 self._throw_error = kwargs.get("throw_error", True) 73 self._verbose = kwargs.get("verbose", False) 74 75 def __del__(self) -> None: 76 """Destructor that closes the connection associated with the handle""" 77 if not self._closed and self._handle: 78 self.stop() 79 self.close(self._handle) 80 self._closed = True 81 82 def __enter__(self) -> object: 83 """ 84 Constructs a handle using the parameter `device_identifier`, when using the with statement 85 86 Returns 87 ------- 88 object 89 The active card handle 90 91 Raises 92 ------ 93 SpcmException 94 """ 95 return self.open() 96 97 def open(self, device_identifier : str = None) -> object: 98 """ 99 Opens a connection to the card and creates a handle, when no with statement is used 100 101 Parameters 102 ---------- 103 device_identifier : str 104 The card identifier string (e.g. '/dev/spcm0' for a local device 105 NOTE: this is to keep the API consistent with a previous version. The original open() 106 method is now in _open() 107 108 Returns 109 ------- 110 object 111 This Card object 112 """ 113 114 if device_identifier: # this is to keep the API consistent 115 return self._open(device_identifier) 116 # This used to be in enter. It is now split up to allow for the open method 117 # to be used when no with statement is used 118 if self.device_identifier and not self._handle: 119 self._open(self.device_identifier) 120 if not self._handle and self._throw_error: 121 error = SpcmError(text="{} not found...".format(self.device_identifier)) 122 raise SpcmDeviceNotFound(error) 123 if self._handle: 124 self._closed = False 125 return self 126 127 def __exit__(self, exception : SpcmException = None, error_value : str = None, trace : types.TracebackType = None) -> None: 128 """ 129 Handles the exiting of the with statement, when either no code is left or an exception is thrown before 130 131 Parameters 132 ---------- 133 exception : SpcmException 134 Only this parameter is used and printed 135 error_value : str 136 trace : types.TracebackType 137 138 Raises 139 ------ 140 SpcmException 141 """ 142 if self._verbose and exception: 143 self._print("Error type: {}".format(exception)) 144 self._print("Error value: {}".format(error_value)) 145 self._print("Traceback:") 146 traceback.print_tb(trace) 147 elif exception: 148 self._print("Error: {}".format(error_value)) 149 self.stop(M2CMD_DATA_STOPDMA) # stop the card and the DMA transfer 150 self._closed = True 151 self.close(self._handle) 152 self._handle = None 153 if exception and self._reraise: 154 raise exception 155 156 def handle(self) -> object: 157 """ 158 Returns the handle used by the object to connect to the active card 159 160 Class Parameters 161 ---------- 162 self._handle 163 164 Returns 165 ------- 166 drv_handle 167 The active card handle 168 """ 169 170 return self._handle 171 172 # Check if a card was found 173 def __bool__(self) -> bool: 174 """ 175 Check for a connection to the active card 176 177 Class Parameters 178 ---------- 179 self._handle 180 181 Returns 182 ------- 183 bool 184 True for an active connection and false otherwise 185 186 Examples 187 ----------- 188 >>> card = spcm.Card('/dev/spcm0') 189 >>> print(bool(card)) 190 <<< True # if a card was found at '/dev/spcm0' 191 """ 192 193 return bool(self._handle) 194 195 # High-level parameter functions, that use the low-level get and set function 196 def drv_type(self) -> int: 197 """ 198 Get the driver type of the currently used driver (see register `SPC_GETDRVTYPE` in the manual) 199 200 Returns 201 ------- 202 int 203 The driver type of the currently used driver 204 """ 205 206 return self.get_i(SPC_GETDRVTYPE) 207 208 def drv_version(self) -> dict: 209 """ 210 Get the version of the currently used driver. (see register `SPC_GETDRVVERSION` in the manual) 211 212 Returns 213 ------- 214 dict 215 version of the currently used driver 216 * "major" - the major version number, 217 * "minor" - the minor version number, 218 * "build" - the actual build 219 """ 220 version_hex = self.get_i(SPC_GETDRVVERSION) 221 major = (version_hex & 0xFF000000) >> 24 222 minor = (version_hex & 0x00FF0000) >> 16 223 build = version_hex & 0x0000FFFF 224 version_dict = {"major": major, "minor": minor, "build": build} 225 return version_dict 226 227 def kernel_version(self) -> dict: 228 """ 229 Get the version of the currently used kernel. (see register `SPC_GETKERNELVERSION` in the manual) 230 231 Returns 232 ------- 233 dict 234 version of the currently used driver 235 * "major" - the major version number, 236 * "minor" - the minor version number, 237 * "build" - the actual build 238 """ 239 version_hex = self.get_i(SPC_GETKERNELVERSION) 240 major = (version_hex & 0xFF000000) >> 24 241 minor = (version_hex & 0x00FF0000) >> 16 242 build = version_hex & 0x0000FFFF 243 version_dict = {"major": major, "minor": minor, "build": build} 244 return version_dict 245 246 def custom_modifications(self) -> dict: 247 """ 248 Get the custom modifications of the currently used device. (see register `SPCM_CUSTOMMOD` in the manual) 249 250 Returns 251 ------- 252 dict 253 The custom modifications of the currently used device 254 * "starhub" - custom modifications to the starhub, 255 * "module" - custom modification of the front-end module(s) 256 * "base" - custom modification of the base card 257 """ 258 259 custom_mode = self.get_i(SPCM_CUSTOMMOD) 260 starhub = (custom_mode & SPCM_CUSTOMMOD_STARHUB_MASK) >> 16 261 module = (custom_mode & SPCM_CUSTOMMOD_MODULE_MASK) >> 8 262 base = custom_mode & SPCM_CUSTOMMOD_BASE_MASK 263 custom_dict = {"starhub": starhub, "module": module, "base": base} 264 return custom_dict 265 266 def log_level(self, log_level : int = None) -> int: 267 """ 268 Set the logging level of the driver 269 270 Parameters 271 ---------- 272 log_level : int 273 The logging level that is set for the driver 274 275 Returns 276 ------- 277 int 278 The logging level of the driver 279 """ 280 281 if log_level is not None: 282 self.set_i(SPC_LOGDLLCALLS, log_level) 283 return self.get_i(SPC_LOGDLLCALLS) 284 285 def cmd(self, *args) -> None: 286 """ 287 Execute spcm commands (see register `SPC_M2CMD` in the manual) 288 289 Parameters 290 ---------- 291 *args : int 292 The different command flags to be executed. 293 """ 294 295 cmd = 0 296 for arg in args: 297 cmd |= arg 298 self.set_i(SPC_M2CMD, cmd) 299 300 #@Decorators.unitize(units.ms, "timeout", int) 301 def timeout(self, timeout : int = None, return_unit = None) -> int: 302 """ 303 Sets the timeout in ms (see register `SPC_TIMEOUT` in the manual) 304 305 Parameters 306 ---------- 307 timeout : int 308 The timeout in ms 309 310 Returns 311 ------- 312 int 313 returns the current timeout in ms 314 """ 315 316 if timeout is not None: 317 timeout = UnitConversion.convert(timeout, units.ms, int) 318 self.set_i(SPC_TIMEOUT, timeout) 319 return_value = self.get_i(SPC_TIMEOUT) 320 if return_unit is not None: return_value = UnitConversion.to_unit(return_value, return_unit) 321 return return_value 322 323 def start(self, *args) -> None: 324 """ 325 Starts the connected card and enables triggering on the card (see command `M2CMD_CARD_START` in the manual) 326 327 Parameters 328 ---------- 329 *args : int 330 flags that are send together with the start command 331 """ 332 333 self.cmd(M2CMD_CARD_START, *args) 334 335 def stop(self, *args : int) -> None: 336 """ 337 Stops the connected card (see command `M2CMD_CARD_STOP` in the manual) 338 339 Parameters 340 ---------- 341 *args : int 342 flags that are send together with the stop command (e.g. M2CMD_DATA_STOPDMA) 343 """ 344 345 self.cmd(M2CMD_CARD_STOP, *args) 346 347 def reset(self) -> None: 348 """ 349 Resets the connected device (see command `M2CMD_CARD_RESET` in the manual) 350 """ 351 352 self.cmd(M2CMD_CARD_RESET) 353 354 def write_setup(self, *args) -> None: 355 """ 356 Writes of the configuration registers previously changed to the device (see command `M2CMD_CARD_WRITESETUP` in the manual) 357 358 Parameters 359 ---------- 360 *args : int 361 flags that are set with the write command 362 """ 363 364 self.cmd(M2CMD_CARD_WRITESETUP, *args) 365 366 def register_list(self, register_list : List[dict[str, Union[int, float]]]) -> None: 367 """ 368 Writes a list with dictionaries, where each dictionary corresponds to a command (see the user manual of your device for all the available registers) 369 370 Parameters 371 ---------- 372 register_list : List[dict[str, Union[int, float]]] 373 The list of commands that needs to written to the specific registers of the card. 374 """ 375 376 c_astParams = (ST_LIST_PARAM * 1024)() 377 astParams = ctypes.cast(c_astParams, ctypes.POINTER(ST_LIST_PARAM)) 378 for i, register in enumerate(register_list): 379 astParams[i].lReg = register["lReg"] 380 astParams[i].lType = register["lType"] 381 if register["lType"] == TYPE_INT64: 382 astParams[i].Value.llValue = register["llValue"] 383 elif register["lType"] == TYPE_DOUBLE: 384 astParams[i].Value.dValue = register["dValue"] 385 self.set_ptr(SPC_REGISTER_LIST, astParams, len(register_list) * ctypes.sizeof(ST_LIST_PARAM)) 386 387 # Low-level get and set functions 388 def get_i(self, register : int) -> int: 389 """ 390 Get the integer value of a specific register of the card (see the user manual of your device for all the available registers) 391 392 Parameters 393 ---------- 394 register : int 395 The specific register that will be read from. 396 397 Returns 398 ------- 399 int 400 The value as stored in the specific register 401 """ 402 403 self._check_closed() 404 return_value = int64(0) 405 dwErr = spcm_dwGetParam_i64(self._handle, register, byref(return_value)) 406 self._check_error(dwErr) 407 return return_value.value 408 get = get_i 409 """Alias of get_i""" 410 411 def get_d(self, register : int) -> float: 412 """ 413 Get the float value of a specific register of the card (see the user manual of your device for all the available registers) 414 415 Parameters 416 ---------- 417 register : int 418 The specific register that will be read from. 419 420 Returns 421 ------- 422 float 423 The value as stored in the specific register 424 """ 425 426 self._check_closed() 427 return_value = c_double(0) 428 self._check_error(spcm_dwGetParam_d64(self._handle, register, byref(return_value))) 429 return return_value.value 430 431 def get_str(self, register : int) -> str: 432 """ 433 Get the string value of a specific register of the card (see the user manual of your device for all the available registers) 434 435 Parameters 436 ---------- 437 register : int 438 The specific register that will be read from. 439 440 Returns 441 ------- 442 str 443 The value as stored in the specific register 444 """ 445 446 self._check_closed() 447 return_value = create_string_buffer(self._str_len) 448 self._check_error(spcm_dwGetParam_ptr(self._handle, register, byref(return_value), self._str_len)) 449 return return_value.value.decode('utf-8') 450 451 def set_i(self, register : int, value : int) -> None: 452 """ 453 Write the value of a specific register to the card (see the user manual of your device for all the available registers) 454 455 Parameters 456 ---------- 457 register : int 458 The specific register that will be written. 459 value : int 460 The value that is written to the card. 461 """ 462 463 self._check_closed() 464 self._check_error(spcm_dwSetParam_i64(self._handle, register, value)) 465 466 def set_d(self, register : int, value : float) -> None: 467 """ 468 Write the value of a specific register to the card (see the user manual of your device for all the available registers) 469 470 Parameters 471 ---------- 472 register : int 473 The specific register that will be written. 474 value : float 475 The value that is written to the card. 476 """ 477 478 self._check_closed() 479 self._check_error(spcm_dwSetParam_d64(self._handle, register, value)) 480 481 def set_ptr(self, register : int, reference : c_void_p, size : int) -> None: 482 """ 483 Use a memory segment to write to a specific register of the card (see the user manual of your device for all the available registers) 484 485 Parameters 486 ---------- 487 register : int 488 The specific register that will be read from. 489 reference : c_void_p 490 pointer to the memory segment 491 size : int 492 size of the memory segment 493 494 Returns 495 ------- 496 int 497 The value as stored in the specific register 498 """ 499 500 self._check_closed() 501 self._check_error(spcm_dwSetParam_ptr(self._handle, register, reference, size)) 502 503 # Error handling and exception raising 504 def _check_error(self, dwErr : int): 505 """ 506 Create an SpcmError object and check for the last error (see the appendix in the user manual of your device for all the possible error codes) 507 508 Parameters 509 ---------- 510 dwErr : int 511 The error value as returned from a direct driver call 512 513 Raises 514 ------ 515 SpcmException 516 SpcmTimeout 517 """ 518 519 # pass 520 if dwErr not in [ERR_OK, ERR_TIMEOUT] and self._throw_error: 521 self.get_error_info() 522 raise SpcmException(self._last_error) 523 elif dwErr == ERR_TIMEOUT: 524 raise SpcmTimeout("A card timeout occured") 525 526 def get_error_info(self) -> SpcmError: 527 """ 528 Create an SpcmError object and store it in an object parameter 529 530 Returns 531 ---------- 532 SpcmError 533 the Error object containing the last error 534 """ 535 536 self._last_error = SpcmError(self._handle) 537 return self._last_error 538 539 def _check_closed(self) -> None: 540 """ 541 Check if a connection to the card exists and if not throw an error 542 543 Raises 544 ------ 545 SpcmException 546 """ 547 if self._closed: 548 error_text = "The connection to the card has been closed. Please reopen the connection before sending commands." 549 if self._throw_error: 550 raise SpcmException(text=error_text) 551 else: 552 self._print(error_text) 553 554 def _print(self, text : str, verbose : bool = False, **kwargs) -> None: 555 """ 556 Print information 557 558 Parameters 559 ---------- 560 text : str 561 The text that is printed 562 verbose : bool 563 A boolean that indicates if the text should forced to be printed 564 **kwargs 565 Additional parameters that are passed to the print function 566 567 """ 568 569 if self._verbose or verbose: 570 print(text, **kwargs) 571 572 def _open(self, device_identifier : str) -> None: 573 """ 574 Open a connection to the card and create a handle (see the user manual of your specific device on how to find out the device_identifier string) 575 576 Parameters 577 ---------- 578 device_identifier : str 579 The card identifier string (e.g. '/dev/spcm0' for a local device or 'TCPIP::192.168.1.10::inst0::INSTR' for a remote device) 580 """ 581 582 self._handle = spcm_hOpen(create_string_buffer(bytes(device_identifier, 'utf-8'))) 583 self._closed = False 584 585 @staticmethod 586 def close(handle) -> None: 587 """ 588 Close a connection to the card using a handle 589 590 Parameters 591 ---------- 592 handle 593 the handle object used for the card connection that is closed 594 """ 595 596 spcm_vClose(handle)
a class to control the low-level API interface of Spectrum Instrumentation devices
For more information about what setups are available, please have a look at the user manual for your specific device.
Parameters
- device_identifier: the identifying string that defines the used device
Raises
- SpcmException
- SpcmTimeout
56 def __init__(self, device_identifier : str = "", handle = False, **kwargs) -> None: 57 """Puts the device_identifier in the class parameter self.device_parameter 58 59 Parameters 60 ---------- 61 device_identifier : str = "" 62 an identifier string to connect to a specific device, for example: 63 64 * Local PCIe device '/dev/spcm0' 65 * Remote 'TCPIP::192.168.1.10::inst0::INSTR' 66 handle = False 67 directly supply the object with an existing handle 68 """ 69 self.device_identifier = device_identifier 70 self._handle = handle 71 self._kwargs = kwargs 72 self._throw_error = kwargs.get("throw_error", True) 73 self._verbose = kwargs.get("verbose", False)
Puts the device_identifier in the class parameter self.device_parameter
Parameters
device_identifier (str = ""): an identifier string to connect to a specific device, for example:
- Local PCIe device '/dev/spcm0'
- Remote 'TCPIP::192.168.1.10::inst0::INSTR'
- handle = False: directly supply the object with an existing handle
97 def open(self, device_identifier : str = None) -> object: 98 """ 99 Opens a connection to the card and creates a handle, when no with statement is used 100 101 Parameters 102 ---------- 103 device_identifier : str 104 The card identifier string (e.g. '/dev/spcm0' for a local device 105 NOTE: this is to keep the API consistent with a previous version. The original open() 106 method is now in _open() 107 108 Returns 109 ------- 110 object 111 This Card object 112 """ 113 114 if device_identifier: # this is to keep the API consistent 115 return self._open(device_identifier) 116 # This used to be in enter. It is now split up to allow for the open method 117 # to be used when no with statement is used 118 if self.device_identifier and not self._handle: 119 self._open(self.device_identifier) 120 if not self._handle and self._throw_error: 121 error = SpcmError(text="{} not found...".format(self.device_identifier)) 122 raise SpcmDeviceNotFound(error) 123 if self._handle: 124 self._closed = False 125 return self
Opens a connection to the card and creates a handle, when no with statement is used
Parameters
- device_identifier (str): The card identifier string (e.g. '/dev/spcm0' for a local device NOTE: this is to keep the API consistent with a previous version. The original open() method is now in _open()
Returns
- object: This Card object
156 def handle(self) -> object: 157 """ 158 Returns the handle used by the object to connect to the active card 159 160 Class Parameters 161 ---------- 162 self._handle 163 164 Returns 165 ------- 166 drv_handle 167 The active card handle 168 """ 169 170 return self._handle
Returns the handle used by the object to connect to the active card
Class Parameters
self._handle
Returns
- drv_handle: The active card handle
196 def drv_type(self) -> int: 197 """ 198 Get the driver type of the currently used driver (see register `SPC_GETDRVTYPE` in the manual) 199 200 Returns 201 ------- 202 int 203 The driver type of the currently used driver 204 """ 205 206 return self.get_i(SPC_GETDRVTYPE)
Get the driver type of the currently used driver (see register SPC_GETDRVTYPE
in the manual)
Returns
- int: The driver type of the currently used driver
208 def drv_version(self) -> dict: 209 """ 210 Get the version of the currently used driver. (see register `SPC_GETDRVVERSION` in the manual) 211 212 Returns 213 ------- 214 dict 215 version of the currently used driver 216 * "major" - the major version number, 217 * "minor" - the minor version number, 218 * "build" - the actual build 219 """ 220 version_hex = self.get_i(SPC_GETDRVVERSION) 221 major = (version_hex & 0xFF000000) >> 24 222 minor = (version_hex & 0x00FF0000) >> 16 223 build = version_hex & 0x0000FFFF 224 version_dict = {"major": major, "minor": minor, "build": build} 225 return version_dict
Get the version of the currently used driver. (see register SPC_GETDRVVERSION
in the manual)
Returns
- dict: version of the currently used driver
- "major" - the major version number,
- "minor" - the minor version number,
- "build" - the actual build
227 def kernel_version(self) -> dict: 228 """ 229 Get the version of the currently used kernel. (see register `SPC_GETKERNELVERSION` in the manual) 230 231 Returns 232 ------- 233 dict 234 version of the currently used driver 235 * "major" - the major version number, 236 * "minor" - the minor version number, 237 * "build" - the actual build 238 """ 239 version_hex = self.get_i(SPC_GETKERNELVERSION) 240 major = (version_hex & 0xFF000000) >> 24 241 minor = (version_hex & 0x00FF0000) >> 16 242 build = version_hex & 0x0000FFFF 243 version_dict = {"major": major, "minor": minor, "build": build} 244 return version_dict
Get the version of the currently used kernel. (see register SPC_GETKERNELVERSION
in the manual)
Returns
- dict: version of the currently used driver
- "major" - the major version number,
- "minor" - the minor version number,
- "build" - the actual build
246 def custom_modifications(self) -> dict: 247 """ 248 Get the custom modifications of the currently used device. (see register `SPCM_CUSTOMMOD` in the manual) 249 250 Returns 251 ------- 252 dict 253 The custom modifications of the currently used device 254 * "starhub" - custom modifications to the starhub, 255 * "module" - custom modification of the front-end module(s) 256 * "base" - custom modification of the base card 257 """ 258 259 custom_mode = self.get_i(SPCM_CUSTOMMOD) 260 starhub = (custom_mode & SPCM_CUSTOMMOD_STARHUB_MASK) >> 16 261 module = (custom_mode & SPCM_CUSTOMMOD_MODULE_MASK) >> 8 262 base = custom_mode & SPCM_CUSTOMMOD_BASE_MASK 263 custom_dict = {"starhub": starhub, "module": module, "base": base} 264 return custom_dict
Get the custom modifications of the currently used device. (see register SPCM_CUSTOMMOD
in the manual)
Returns
- dict: The custom modifications of the currently used device
- "starhub" - custom modifications to the starhub,
- "module" - custom modification of the front-end module(s)
- "base" - custom modification of the base card
266 def log_level(self, log_level : int = None) -> int: 267 """ 268 Set the logging level of the driver 269 270 Parameters 271 ---------- 272 log_level : int 273 The logging level that is set for the driver 274 275 Returns 276 ------- 277 int 278 The logging level of the driver 279 """ 280 281 if log_level is not None: 282 self.set_i(SPC_LOGDLLCALLS, log_level) 283 return self.get_i(SPC_LOGDLLCALLS)
Set the logging level of the driver
Parameters
- log_level (int): The logging level that is set for the driver
Returns
- int: The logging level of the driver
285 def cmd(self, *args) -> None: 286 """ 287 Execute spcm commands (see register `SPC_M2CMD` in the manual) 288 289 Parameters 290 ---------- 291 *args : int 292 The different command flags to be executed. 293 """ 294 295 cmd = 0 296 for arg in args: 297 cmd |= arg 298 self.set_i(SPC_M2CMD, cmd)
Execute spcm commands (see register SPC_M2CMD
in the manual)
Parameters
- *args (int): The different command flags to be executed.
301 def timeout(self, timeout : int = None, return_unit = None) -> int: 302 """ 303 Sets the timeout in ms (see register `SPC_TIMEOUT` in the manual) 304 305 Parameters 306 ---------- 307 timeout : int 308 The timeout in ms 309 310 Returns 311 ------- 312 int 313 returns the current timeout in ms 314 """ 315 316 if timeout is not None: 317 timeout = UnitConversion.convert(timeout, units.ms, int) 318 self.set_i(SPC_TIMEOUT, timeout) 319 return_value = self.get_i(SPC_TIMEOUT) 320 if return_unit is not None: return_value = UnitConversion.to_unit(return_value, return_unit) 321 return return_value
Sets the timeout in ms (see register SPC_TIMEOUT
in the manual)
Parameters
- timeout (int): The timeout in ms
Returns
- int: returns the current timeout in ms
323 def start(self, *args) -> None: 324 """ 325 Starts the connected card and enables triggering on the card (see command `M2CMD_CARD_START` in the manual) 326 327 Parameters 328 ---------- 329 *args : int 330 flags that are send together with the start command 331 """ 332 333 self.cmd(M2CMD_CARD_START, *args)
Starts the connected card and enables triggering on the card (see command M2CMD_CARD_START
in the manual)
Parameters
- *args (int): flags that are send together with the start command
335 def stop(self, *args : int) -> None: 336 """ 337 Stops the connected card (see command `M2CMD_CARD_STOP` in the manual) 338 339 Parameters 340 ---------- 341 *args : int 342 flags that are send together with the stop command (e.g. M2CMD_DATA_STOPDMA) 343 """ 344 345 self.cmd(M2CMD_CARD_STOP, *args)
Stops the connected card (see command M2CMD_CARD_STOP
in the manual)
Parameters
- *args (int): flags that are send together with the stop command (e.g. M2CMD_DATA_STOPDMA)
347 def reset(self) -> None: 348 """ 349 Resets the connected device (see command `M2CMD_CARD_RESET` in the manual) 350 """ 351 352 self.cmd(M2CMD_CARD_RESET)
Resets the connected device (see command M2CMD_CARD_RESET
in the manual)
354 def write_setup(self, *args) -> None: 355 """ 356 Writes of the configuration registers previously changed to the device (see command `M2CMD_CARD_WRITESETUP` in the manual) 357 358 Parameters 359 ---------- 360 *args : int 361 flags that are set with the write command 362 """ 363 364 self.cmd(M2CMD_CARD_WRITESETUP, *args)
Writes of the configuration registers previously changed to the device (see command M2CMD_CARD_WRITESETUP
in the manual)
Parameters
- *args (int): flags that are set with the write command
366 def register_list(self, register_list : List[dict[str, Union[int, float]]]) -> None: 367 """ 368 Writes a list with dictionaries, where each dictionary corresponds to a command (see the user manual of your device for all the available registers) 369 370 Parameters 371 ---------- 372 register_list : List[dict[str, Union[int, float]]] 373 The list of commands that needs to written to the specific registers of the card. 374 """ 375 376 c_astParams = (ST_LIST_PARAM * 1024)() 377 astParams = ctypes.cast(c_astParams, ctypes.POINTER(ST_LIST_PARAM)) 378 for i, register in enumerate(register_list): 379 astParams[i].lReg = register["lReg"] 380 astParams[i].lType = register["lType"] 381 if register["lType"] == TYPE_INT64: 382 astParams[i].Value.llValue = register["llValue"] 383 elif register["lType"] == TYPE_DOUBLE: 384 astParams[i].Value.dValue = register["dValue"] 385 self.set_ptr(SPC_REGISTER_LIST, astParams, len(register_list) * ctypes.sizeof(ST_LIST_PARAM))
Writes a list with dictionaries, where each dictionary corresponds to a command (see the user manual of your device for all the available registers)
Parameters
- register_list (List[dict[str, Union[int, float]]]): The list of commands that needs to written to the specific registers of the card.
388 def get_i(self, register : int) -> int: 389 """ 390 Get the integer value of a specific register of the card (see the user manual of your device for all the available registers) 391 392 Parameters 393 ---------- 394 register : int 395 The specific register that will be read from. 396 397 Returns 398 ------- 399 int 400 The value as stored in the specific register 401 """ 402 403 self._check_closed() 404 return_value = int64(0) 405 dwErr = spcm_dwGetParam_i64(self._handle, register, byref(return_value)) 406 self._check_error(dwErr) 407 return return_value.value
Get the integer value of a specific register of the card (see the user manual of your device for all the available registers)
Parameters
- register (int): The specific register that will be read from.
Returns
- int: The value as stored in the specific register
388 def get_i(self, register : int) -> int: 389 """ 390 Get the integer value of a specific register of the card (see the user manual of your device for all the available registers) 391 392 Parameters 393 ---------- 394 register : int 395 The specific register that will be read from. 396 397 Returns 398 ------- 399 int 400 The value as stored in the specific register 401 """ 402 403 self._check_closed() 404 return_value = int64(0) 405 dwErr = spcm_dwGetParam_i64(self._handle, register, byref(return_value)) 406 self._check_error(dwErr) 407 return return_value.value
Alias of get_i
411 def get_d(self, register : int) -> float: 412 """ 413 Get the float value of a specific register of the card (see the user manual of your device for all the available registers) 414 415 Parameters 416 ---------- 417 register : int 418 The specific register that will be read from. 419 420 Returns 421 ------- 422 float 423 The value as stored in the specific register 424 """ 425 426 self._check_closed() 427 return_value = c_double(0) 428 self._check_error(spcm_dwGetParam_d64(self._handle, register, byref(return_value))) 429 return return_value.value
Get the float value of a specific register of the card (see the user manual of your device for all the available registers)
Parameters
- register (int): The specific register that will be read from.
Returns
- float: The value as stored in the specific register
431 def get_str(self, register : int) -> str: 432 """ 433 Get the string value of a specific register of the card (see the user manual of your device for all the available registers) 434 435 Parameters 436 ---------- 437 register : int 438 The specific register that will be read from. 439 440 Returns 441 ------- 442 str 443 The value as stored in the specific register 444 """ 445 446 self._check_closed() 447 return_value = create_string_buffer(self._str_len) 448 self._check_error(spcm_dwGetParam_ptr(self._handle, register, byref(return_value), self._str_len)) 449 return return_value.value.decode('utf-8')
Get the string value of a specific register of the card (see the user manual of your device for all the available registers)
Parameters
- register (int): The specific register that will be read from.
Returns
- str: The value as stored in the specific register
451 def set_i(self, register : int, value : int) -> None: 452 """ 453 Write the value of a specific register to the card (see the user manual of your device for all the available registers) 454 455 Parameters 456 ---------- 457 register : int 458 The specific register that will be written. 459 value : int 460 The value that is written to the card. 461 """ 462 463 self._check_closed() 464 self._check_error(spcm_dwSetParam_i64(self._handle, register, value))
Write the value of a specific register to the card (see the user manual of your device for all the available registers)
Parameters
- register (int): The specific register that will be written.
- value (int): The value that is written to the card.
466 def set_d(self, register : int, value : float) -> None: 467 """ 468 Write the value of a specific register to the card (see the user manual of your device for all the available registers) 469 470 Parameters 471 ---------- 472 register : int 473 The specific register that will be written. 474 value : float 475 The value that is written to the card. 476 """ 477 478 self._check_closed() 479 self._check_error(spcm_dwSetParam_d64(self._handle, register, value))
Write the value of a specific register to the card (see the user manual of your device for all the available registers)
Parameters
- register (int): The specific register that will be written.
- value (float): The value that is written to the card.
481 def set_ptr(self, register : int, reference : c_void_p, size : int) -> None: 482 """ 483 Use a memory segment to write to a specific register of the card (see the user manual of your device for all the available registers) 484 485 Parameters 486 ---------- 487 register : int 488 The specific register that will be read from. 489 reference : c_void_p 490 pointer to the memory segment 491 size : int 492 size of the memory segment 493 494 Returns 495 ------- 496 int 497 The value as stored in the specific register 498 """ 499 500 self._check_closed() 501 self._check_error(spcm_dwSetParam_ptr(self._handle, register, reference, size))
Use a memory segment to write to a specific register of the card (see the user manual of your device for all the available registers)
Parameters
- register (int): The specific register that will be read from.
- reference (c_void_p): pointer to the memory segment
- size (int): size of the memory segment
Returns
- int: The value as stored in the specific register
526 def get_error_info(self) -> SpcmError: 527 """ 528 Create an SpcmError object and store it in an object parameter 529 530 Returns 531 ---------- 532 SpcmError 533 the Error object containing the last error 534 """ 535 536 self._last_error = SpcmError(self._handle) 537 return self._last_error
Create an SpcmError object and store it in an object parameter
Returns
- SpcmError: the Error object containing the last error
585 @staticmethod 586 def close(handle) -> None: 587 """ 588 Close a connection to the card using a handle 589 590 Parameters 591 ---------- 592 handle 593 the handle object used for the card connection that is closed 594 """ 595 596 spcm_vClose(handle)
Close a connection to the card using a handle
Parameters
- handle: the handle object used for the card connection that is closed
15class Card(Device): 16 """ 17 a high-level class to control Spectrum Instrumentation cards 18 19 For more information about what setups are available, please have a look at the user manual 20 for your specific card. 21 22 """ 23 24 _std_device_identifier : str = "/dev/spcm{}" 25 _max_cards : int = 64 26 27 _function_type : int = 0 28 _card_type : int = 0 29 _max_sample_value : int = 0 30 31 def __enter__(self) -> 'Card': 32 """ 33 Context manager entry function 34 35 Returns 36 ------- 37 Card 38 The card object 39 40 Raises 41 ------ 42 SpcmException 43 """ 44 return super().__enter__() 45 46 def open(self, device_identifier : str = None) -> 'Card': 47 """ 48 Open a connection to the card 49 50 Parameters 51 ---------- 52 device_identifier : str = "" 53 The device identifier of the card that needs to be opened 54 55 Returns 56 ------- 57 Card 58 The card object 59 60 Raises 61 ------ 62 SpcmException 63 """ 64 65 if device_identifier is not None: 66 return super().open(device_identifier=device_identifier) 67 68 super().open() 69 70 # keyword arguments 71 card_type = self._kwargs.get("card_type", 0) 72 serial_number = self._kwargs.get("serial_number", 0) 73 74 if self.device_identifier == "": 75 # No device identifier was given, so we need to find the first card 76 self._handle = self.find(card_type=card_type, serial_number=serial_number) 77 if not self._handle: 78 if card_type: 79 raise SpcmException(text="No card found of right type") 80 elif serial_number: 81 raise SpcmException(text="No card found with serial number: {}".format(serial_number)) 82 else: 83 self._closed = False 84 elif self._handle: 85 if card_type != 0 and self.function_type() != card_type: 86 raise SpcmException(text="The card with the given device identifier is not the correct type") 87 elif serial_number != 0 and self.sn() != serial_number: 88 raise SpcmException(text="The card with the given device identifier does not have the correct serial number") 89 90 # Check python, driver and kernel version 91 if self._verbose: 92 print("Python version: {} on {}".format (platform.python_version(), platform.system())) 93 print("Driver version: {major}.{minor}.{build}".format(**self.drv_version())) 94 print("Kernel version: {major}.{minor}.{build}".format(**self.kernel_version())) 95 if self._handle: 96 print("Found '{}': {} sn {:05d}".format(self.device_identifier, self.product_name(), self.sn())) 97 98 # Get the function type of the card 99 self._function_type = self.get_i(SPC_FNCTYPE) 100 self._card_type = self.get_i(SPC_PCITYP) 101 self._features = self.get_i(SPC_PCIFEATURES) 102 self._ext_features = self.get_i(SPC_PCIEXTFEATURES) 103 self._max_sample_value = self.get_i(SPC_MIINST_MAXADCVALUE) 104 105 return self 106 107 def __str__(self) -> str: 108 """ 109 String representation of the card 110 111 Returns 112 ------- 113 str 114 String representation of the card 115 """ 116 return "Card: {} sn {:05d}".format(self.product_name(), self.sn()) 117 __repr__ = __str__ 118 119 def find(self, card_type : int = 0, serial_number : int = 0) -> Union[bool, int]: 120 """ 121 Find first card that is connected to the computer, with either the given card type or serial number 122 123 Parameters 124 ---------- 125 card_type : int = 0 126 The function type of the card that needs to be found 127 serial_number : int = 0 128 The serial number of the card that needs to be found 129 130 """ 131 for nr in range(self._max_cards): 132 device_identifier = self._std_device_identifier.format(nr) 133 handle = spcm_hOpen(ctypes.create_string_buffer(bytes(device_identifier, 'utf-8'))) 134 if handle: 135 self.device_identifier = device_identifier 136 return_value = ctypes.c_int64() 137 spcm_dwGetParam_i64(handle, SPC_FNCTYPE, ctypes.byref(return_value)) 138 function_type = return_value.value 139 spcm_dwGetParam_i64(handle, SPC_PCISERIALNO, ctypes.byref(return_value)) 140 sn = return_value.value 141 if card_type != 0 and (card_type & function_type) == function_type: 142 return handle 143 elif sn != 0 and sn == serial_number: 144 return handle 145 elif serial_number == 0 and card_type == 0: 146 return handle 147 spcm_vClose(handle) 148 return False 149 150 151 # High-level parameter functions, that use the low-level get and set function 152 def status(self) -> int: 153 """ 154 Get the status of the card (see register `SPC_M2STATUS` in the manual) 155 156 Returns 157 ------- 158 int 159 The status of the card 160 """ 161 162 return self.get_i(SPC_M2STATUS) 163 164 def card_type(self) -> int: 165 """ 166 Get the card type of the card (see register `SPC_PCITYP` in the manual) 167 168 Returns 169 ------- 170 int 171 The card type of the card 172 """ 173 174 return self._card_type 175 176 def series(self) -> int: 177 """ 178 Get the series of the card (see register `SPC_PCITYP` and `TYP_SERIESMASK` in the manual) 179 180 Returns 181 ------- 182 int 183 The series of the card 184 """ 185 186 return self.card_type() & TYP_SERIESMASK 187 188 def function_type(self) -> int: 189 """ 190 Gives information about what type of card it is. (see register `SPC_FNCTYPE` in the manual) 191 192 Returns 193 ------- 194 int 195 The function type of the card 196 197 * SPCM_TYPE_AI = 1h - Analog input card (analog acquisition; the M2i.4028 and M2i.4038 also return this value) 198 * SPCM_TYPE_AO = 2h - Analog output card (arbitrary waveform generators) 199 * SPCM_TYPE_DI = 4h - Digital input card (logic analyzer card) 200 * SPCM_TYPE_DO = 8h - Digital output card (pattern generators) 201 * SPCM_TYPE_DIO = 10h - Digital I/O (input/output) card, where the direction is software selectable. 202 """ 203 204 return self._function_type 205 206 def features(self) -> int: 207 """ 208 Get the features of the card (see register `SPC_PCIFEATURES` in the manual) 209 210 Returns 211 ------- 212 int 213 The features of the card 214 """ 215 216 return self._features 217 218 def ext_features(self) -> int: 219 """ 220 Get the extended features of the card (see register `SPC_PCIEXTFEATURES` in the manual) 221 222 Returns 223 ------- 224 int 225 The extended features of the card 226 """ 227 228 return self._ext_features 229 230 def starhub_card(self) -> bool: 231 """ 232 Check if the card is a starhub card (see register `SPC_PCIFEATURES` in the manual) 233 234 Returns 235 ------- 236 bool 237 True if the card is the card that carriers a starhub, False otherwise 238 """ 239 240 return bool(self._features & SPCM_FEAT_STARHUBXX_MASK) 241 242 def num_modules(self) -> int: 243 """ 244 Get the number of modules of the card (see register `SPC_MIINST_MODULES` in the manual) 245 246 Returns 247 ------- 248 int 249 The number of modules of the card 250 """ 251 252 return self.get_i(SPC_MIINST_MODULES) 253 254 def channels_per_module(self) -> int: 255 """ 256 Get the number of channels per module of the card (see register `SPC_MIINST_CHPERMODULE` in the manual) 257 258 Returns 259 ------- 260 int 261 The number of channels per module of the card 262 """ 263 264 return self.get_i(SPC_MIINST_CHPERMODULE) 265 266 def num_channels(self) -> int: 267 """ 268 Get the number of channels of the card (= SPC_MIINST_MODULES * SPC_MIINST_CHPERMODULE) 269 270 Returns 271 ------- 272 int 273 The number of channels of the card 274 """ 275 276 return self.num_modules() * self.channels_per_module() 277 278 def card_mode(self, card_mode : int = None) -> int: 279 """ 280 Set the card mode of the connected card (see register `SPC_CARDMODE` in the manual) 281 282 Parameters 283 ---------- 284 card_mode : int 285 the mode that the card needs to operate in 286 287 Returns 288 ------- 289 int 290 the mode that the card operates in 291 """ 292 293 if card_mode is not None: 294 self.set_i(SPC_CARDMODE, card_mode) 295 return self.get_i(SPC_CARDMODE) 296 297 def product_name(self) -> str: 298 """ 299 Get the product name of the card (see register `SPC_PCITYP` in the manual) 300 301 Returns 302 ------- 303 str 304 The product name of the connected card (e.g. M4i.6631-x8) 305 """ 306 307 return self.get_str(SPC_PCITYP) 308 309 def sn(self) -> int: 310 """ 311 Get the serial number of a product (see register `SPC_PCISERIALNO` in the manual) 312 313 Returns 314 ------- 315 int 316 The serial number of the connected card (e.g. 12345) 317 """ 318 319 return self.get_i(SPC_PCISERIALNO) 320 321 def active_channels(self) -> int: 322 """ 323 Get the number of channels of the card (see register `SPC_CHCOUNT` in the manual) 324 325 Returns 326 ------- 327 int 328 The number of channels of the card 329 """ 330 331 return self.get_i(SPC_CHCOUNT) 332 333 def bits_per_sample(self) -> int: 334 """ 335 Get the number of bits per sample of the card (see register `SPC_MIINST_BITSPERSAMPLE` in the manual) 336 337 Returns 338 ------- 339 int 340 The number of bits per sample of the card 341 """ 342 343 return self.get_i(SPC_MIINST_BITSPERSAMPLE) 344 345 def bytes_per_sample(self) -> int: 346 """ 347 Get the number of bytes per sample 348 349 Returns 350 ------- 351 int 352 number of bytes per sample 353 """ 354 return self.get_i(SPC_MIINST_BYTESPERSAMPLE) 355 356 def max_sample_value(self) -> int: 357 """ 358 Get the maximum ADC value of the card (see register `SPC_MIINST_MAXADCVALUE` in the manual) 359 360 Returns 361 ------- 362 int 363 The maximum ADC value of the card 364 """ 365 366 return self._max_sample_value 367 368 def loops(self, loops : int = None) -> int: 369 """ 370 Set the number of times the memory is replayed. If set to zero the generation will run continuously until it is 371 stopped by the user. (see register `SPC_LOOPS` in the manual) 372 373 Parameters 374 ---------- 375 loops : int 376 the number of loops that the card should perform 377 """ 378 379 if loops is not None: 380 self.set_i(SPC_LOOPS, loops) 381 return self.get_i(SPC_LOOPS)
a high-level class to control Spectrum Instrumentation cards
For more information about what setups are available, please have a look at the user manual for your specific card.
46 def open(self, device_identifier : str = None) -> 'Card': 47 """ 48 Open a connection to the card 49 50 Parameters 51 ---------- 52 device_identifier : str = "" 53 The device identifier of the card that needs to be opened 54 55 Returns 56 ------- 57 Card 58 The card object 59 60 Raises 61 ------ 62 SpcmException 63 """ 64 65 if device_identifier is not None: 66 return super().open(device_identifier=device_identifier) 67 68 super().open() 69 70 # keyword arguments 71 card_type = self._kwargs.get("card_type", 0) 72 serial_number = self._kwargs.get("serial_number", 0) 73 74 if self.device_identifier == "": 75 # No device identifier was given, so we need to find the first card 76 self._handle = self.find(card_type=card_type, serial_number=serial_number) 77 if not self._handle: 78 if card_type: 79 raise SpcmException(text="No card found of right type") 80 elif serial_number: 81 raise SpcmException(text="No card found with serial number: {}".format(serial_number)) 82 else: 83 self._closed = False 84 elif self._handle: 85 if card_type != 0 and self.function_type() != card_type: 86 raise SpcmException(text="The card with the given device identifier is not the correct type") 87 elif serial_number != 0 and self.sn() != serial_number: 88 raise SpcmException(text="The card with the given device identifier does not have the correct serial number") 89 90 # Check python, driver and kernel version 91 if self._verbose: 92 print("Python version: {} on {}".format (platform.python_version(), platform.system())) 93 print("Driver version: {major}.{minor}.{build}".format(**self.drv_version())) 94 print("Kernel version: {major}.{minor}.{build}".format(**self.kernel_version())) 95 if self._handle: 96 print("Found '{}': {} sn {:05d}".format(self.device_identifier, self.product_name(), self.sn())) 97 98 # Get the function type of the card 99 self._function_type = self.get_i(SPC_FNCTYPE) 100 self._card_type = self.get_i(SPC_PCITYP) 101 self._features = self.get_i(SPC_PCIFEATURES) 102 self._ext_features = self.get_i(SPC_PCIEXTFEATURES) 103 self._max_sample_value = self.get_i(SPC_MIINST_MAXADCVALUE) 104 105 return self
Open a connection to the card
Parameters
- device_identifier (str = ""): The device identifier of the card that needs to be opened
Returns
- Card: The card object
Raises
- SpcmException
119 def find(self, card_type : int = 0, serial_number : int = 0) -> Union[bool, int]: 120 """ 121 Find first card that is connected to the computer, with either the given card type or serial number 122 123 Parameters 124 ---------- 125 card_type : int = 0 126 The function type of the card that needs to be found 127 serial_number : int = 0 128 The serial number of the card that needs to be found 129 130 """ 131 for nr in range(self._max_cards): 132 device_identifier = self._std_device_identifier.format(nr) 133 handle = spcm_hOpen(ctypes.create_string_buffer(bytes(device_identifier, 'utf-8'))) 134 if handle: 135 self.device_identifier = device_identifier 136 return_value = ctypes.c_int64() 137 spcm_dwGetParam_i64(handle, SPC_FNCTYPE, ctypes.byref(return_value)) 138 function_type = return_value.value 139 spcm_dwGetParam_i64(handle, SPC_PCISERIALNO, ctypes.byref(return_value)) 140 sn = return_value.value 141 if card_type != 0 and (card_type & function_type) == function_type: 142 return handle 143 elif sn != 0 and sn == serial_number: 144 return handle 145 elif serial_number == 0 and card_type == 0: 146 return handle 147 spcm_vClose(handle) 148 return False
Find first card that is connected to the computer, with either the given card type or serial number
Parameters
- card_type (int = 0): The function type of the card that needs to be found
- serial_number (int = 0): The serial number of the card that needs to be found
152 def status(self) -> int: 153 """ 154 Get the status of the card (see register `SPC_M2STATUS` in the manual) 155 156 Returns 157 ------- 158 int 159 The status of the card 160 """ 161 162 return self.get_i(SPC_M2STATUS)
Get the status of the card (see register SPC_M2STATUS
in the manual)
Returns
- int: The status of the card
164 def card_type(self) -> int: 165 """ 166 Get the card type of the card (see register `SPC_PCITYP` in the manual) 167 168 Returns 169 ------- 170 int 171 The card type of the card 172 """ 173 174 return self._card_type
Get the card type of the card (see register SPC_PCITYP
in the manual)
Returns
- int: The card type of the card
176 def series(self) -> int: 177 """ 178 Get the series of the card (see register `SPC_PCITYP` and `TYP_SERIESMASK` in the manual) 179 180 Returns 181 ------- 182 int 183 The series of the card 184 """ 185 186 return self.card_type() & TYP_SERIESMASK
Get the series of the card (see register SPC_PCITYP
and TYP_SERIESMASK
in the manual)
Returns
- int: The series of the card
188 def function_type(self) -> int: 189 """ 190 Gives information about what type of card it is. (see register `SPC_FNCTYPE` in the manual) 191 192 Returns 193 ------- 194 int 195 The function type of the card 196 197 * SPCM_TYPE_AI = 1h - Analog input card (analog acquisition; the M2i.4028 and M2i.4038 also return this value) 198 * SPCM_TYPE_AO = 2h - Analog output card (arbitrary waveform generators) 199 * SPCM_TYPE_DI = 4h - Digital input card (logic analyzer card) 200 * SPCM_TYPE_DO = 8h - Digital output card (pattern generators) 201 * SPCM_TYPE_DIO = 10h - Digital I/O (input/output) card, where the direction is software selectable. 202 """ 203 204 return self._function_type
Gives information about what type of card it is. (see register SPC_FNCTYPE
in the manual)
Returns
int: The function type of the card
- SPCM_TYPE_AI = 1h - Analog input card (analog acquisition; the M2i.4028 and M2i.4038 also return this value)
- SPCM_TYPE_AO = 2h - Analog output card (arbitrary waveform generators)
- SPCM_TYPE_DI = 4h - Digital input card (logic analyzer card)
- SPCM_TYPE_DO = 8h - Digital output card (pattern generators)
- SPCM_TYPE_DIO = 10h - Digital I/O (input/output) card, where the direction is software selectable.
206 def features(self) -> int: 207 """ 208 Get the features of the card (see register `SPC_PCIFEATURES` in the manual) 209 210 Returns 211 ------- 212 int 213 The features of the card 214 """ 215 216 return self._features
Get the features of the card (see register SPC_PCIFEATURES
in the manual)
Returns
- int: The features of the card
218 def ext_features(self) -> int: 219 """ 220 Get the extended features of the card (see register `SPC_PCIEXTFEATURES` in the manual) 221 222 Returns 223 ------- 224 int 225 The extended features of the card 226 """ 227 228 return self._ext_features
Get the extended features of the card (see register SPC_PCIEXTFEATURES
in the manual)
Returns
- int: The extended features of the card
230 def starhub_card(self) -> bool: 231 """ 232 Check if the card is a starhub card (see register `SPC_PCIFEATURES` in the manual) 233 234 Returns 235 ------- 236 bool 237 True if the card is the card that carriers a starhub, False otherwise 238 """ 239 240 return bool(self._features & SPCM_FEAT_STARHUBXX_MASK)
Check if the card is a starhub card (see register SPC_PCIFEATURES
in the manual)
Returns
- bool: True if the card is the card that carriers a starhub, False otherwise
242 def num_modules(self) -> int: 243 """ 244 Get the number of modules of the card (see register `SPC_MIINST_MODULES` in the manual) 245 246 Returns 247 ------- 248 int 249 The number of modules of the card 250 """ 251 252 return self.get_i(SPC_MIINST_MODULES)
Get the number of modules of the card (see register SPC_MIINST_MODULES
in the manual)
Returns
- int: The number of modules of the card
254 def channels_per_module(self) -> int: 255 """ 256 Get the number of channels per module of the card (see register `SPC_MIINST_CHPERMODULE` in the manual) 257 258 Returns 259 ------- 260 int 261 The number of channels per module of the card 262 """ 263 264 return self.get_i(SPC_MIINST_CHPERMODULE)
Get the number of channels per module of the card (see register SPC_MIINST_CHPERMODULE
in the manual)
Returns
- int: The number of channels per module of the card
266 def num_channels(self) -> int: 267 """ 268 Get the number of channels of the card (= SPC_MIINST_MODULES * SPC_MIINST_CHPERMODULE) 269 270 Returns 271 ------- 272 int 273 The number of channels of the card 274 """ 275 276 return self.num_modules() * self.channels_per_module()
Get the number of channels of the card (= SPC_MIINST_MODULES * SPC_MIINST_CHPERMODULE)
Returns
- int: The number of channels of the card
278 def card_mode(self, card_mode : int = None) -> int: 279 """ 280 Set the card mode of the connected card (see register `SPC_CARDMODE` in the manual) 281 282 Parameters 283 ---------- 284 card_mode : int 285 the mode that the card needs to operate in 286 287 Returns 288 ------- 289 int 290 the mode that the card operates in 291 """ 292 293 if card_mode is not None: 294 self.set_i(SPC_CARDMODE, card_mode) 295 return self.get_i(SPC_CARDMODE)
Set the card mode of the connected card (see register SPC_CARDMODE
in the manual)
Parameters
- card_mode (int): the mode that the card needs to operate in
Returns
- int: the mode that the card operates in
297 def product_name(self) -> str: 298 """ 299 Get the product name of the card (see register `SPC_PCITYP` in the manual) 300 301 Returns 302 ------- 303 str 304 The product name of the connected card (e.g. M4i.6631-x8) 305 """ 306 307 return self.get_str(SPC_PCITYP)
Get the product name of the card (see register SPC_PCITYP
in the manual)
Returns
- str: The product name of the connected card (e.g. M4i.6631-x8)
309 def sn(self) -> int: 310 """ 311 Get the serial number of a product (see register `SPC_PCISERIALNO` in the manual) 312 313 Returns 314 ------- 315 int 316 The serial number of the connected card (e.g. 12345) 317 """ 318 319 return self.get_i(SPC_PCISERIALNO)
Get the serial number of a product (see register SPC_PCISERIALNO
in the manual)
Returns
- int: The serial number of the connected card (e.g. 12345)
321 def active_channels(self) -> int: 322 """ 323 Get the number of channels of the card (see register `SPC_CHCOUNT` in the manual) 324 325 Returns 326 ------- 327 int 328 The number of channels of the card 329 """ 330 331 return self.get_i(SPC_CHCOUNT)
Get the number of channels of the card (see register SPC_CHCOUNT
in the manual)
Returns
- int: The number of channels of the card
333 def bits_per_sample(self) -> int: 334 """ 335 Get the number of bits per sample of the card (see register `SPC_MIINST_BITSPERSAMPLE` in the manual) 336 337 Returns 338 ------- 339 int 340 The number of bits per sample of the card 341 """ 342 343 return self.get_i(SPC_MIINST_BITSPERSAMPLE)
Get the number of bits per sample of the card (see register SPC_MIINST_BITSPERSAMPLE
in the manual)
Returns
- int: The number of bits per sample of the card
345 def bytes_per_sample(self) -> int: 346 """ 347 Get the number of bytes per sample 348 349 Returns 350 ------- 351 int 352 number of bytes per sample 353 """ 354 return self.get_i(SPC_MIINST_BYTESPERSAMPLE)
Get the number of bytes per sample
Returns
- int: number of bytes per sample
356 def max_sample_value(self) -> int: 357 """ 358 Get the maximum ADC value of the card (see register `SPC_MIINST_MAXADCVALUE` in the manual) 359 360 Returns 361 ------- 362 int 363 The maximum ADC value of the card 364 """ 365 366 return self._max_sample_value
Get the maximum ADC value of the card (see register SPC_MIINST_MAXADCVALUE
in the manual)
Returns
- int: The maximum ADC value of the card
368 def loops(self, loops : int = None) -> int: 369 """ 370 Set the number of times the memory is replayed. If set to zero the generation will run continuously until it is 371 stopped by the user. (see register `SPC_LOOPS` in the manual) 372 373 Parameters 374 ---------- 375 loops : int 376 the number of loops that the card should perform 377 """ 378 379 if loops is not None: 380 self.set_i(SPC_LOOPS, loops) 381 return self.get_i(SPC_LOOPS)
Set the number of times the memory is replayed. If set to zero the generation will run continuously until it is
stopped by the user. (see register SPC_LOOPS
in the manual)
Parameters
- loops (int): the number of loops that the card should perform
8class Sync(Device): 9 """a class to control Spectrum Instrumentation Starhub synchronization devices 10 11 For more information about what setups are available, please have a look at the user manual 12 for your specific Starhub. 13 14 Exceptions 15 ---------- 16 SpcmException 17 SpcmTimeout 18 """ 19 20 def enable(self, enable : int = None) -> int: 21 """ 22 Enable or disable the Starthub (see register 'SPC_SYNC_ENABLEMASK' in chapter `Star-Hub` in the manual) 23 24 Parameters 25 ---------- 26 enable : int or bool 27 enable or disable the Starthub 28 """ 29 30 if enable is not None: 31 enable_mask = 0 32 if isinstance(enable, bool): 33 num_cards = self.sync_count() 34 enable_mask = ((1 << num_cards) - 1) if enable else 0 35 elif isinstance(enable, int): 36 enable_mask = enable 37 else: 38 raise ValueError("The enable parameter must be a boolean or an integer") 39 self.set_i(SPC_SYNC_ENABLEMASK, enable_mask) 40 return self.get_i(SPC_SYNC_ENABLEMASK) 41 42 def num_connectors(self) -> int: 43 """ 44 Number of connectors that the Star-Hub offers at max. (see register 'SPC_SYNC_READ_NUMCONNECTORS' in chapter `Star-Hub` in the manual) 45 46 Returns 47 ------- 48 int 49 number of connectors on the StarHub 50 """ 51 52 return self.get_i(SPC_SYNC_READ_NUMCONNECTORS) 53 54 def sync_count(self) -> int: 55 """ 56 Number of cards that are connected to this Star-Hub (see register 'SPC_SYNC_READ_SYNCCOUNT' in chapter `Star-Hub` in the manual) 57 58 Returns 59 ------- 60 int 61 number of synchronized cards 62 """ 63 64 return self.get_i(SPC_SYNC_READ_SYNCCOUNT) 65 66 def card_index(self, index) -> int: 67 """ 68 Index of the card that is connected to the Star-Hub at the given local index (see register 'SPC_SYNC_READ_CARDIDX0' in chapter `Star-Hub` in the manual) 69 70 Parameters 71 ---------- 72 index : int 73 connector index 74 75 Returns 76 ------- 77 int 78 card index 79 """ 80 81 return self.get_i(SPC_SYNC_READ_CARDIDX0 + index) 82 83 def cable_connection(self, index) -> int: 84 """ 85 Returns the index of the cable connection that is used for the logical connection `index`. (see register 'SPC_SYNC_READ_CABLECON0' in chapter `Star-Hub` in the manual) 86 The cable connections can be seen printed on the PCB of the star-hub. Use these cable connection information in case 87 that there are hardware failures with the star-hub cabeling. 88 89 Parameters 90 ---------- 91 index : int 92 connector index 93 94 Returns 95 ------- 96 int 97 cable index 98 """ 99 100 return self.get_i(SPC_SYNC_READ_CABLECON0 + index)
a class to control Spectrum Instrumentation Starhub synchronization devices
For more information about what setups are available, please have a look at the user manual for your specific Starhub.
Exceptions
SpcmException SpcmTimeout
20 def enable(self, enable : int = None) -> int: 21 """ 22 Enable or disable the Starthub (see register 'SPC_SYNC_ENABLEMASK' in chapter `Star-Hub` in the manual) 23 24 Parameters 25 ---------- 26 enable : int or bool 27 enable or disable the Starthub 28 """ 29 30 if enable is not None: 31 enable_mask = 0 32 if isinstance(enable, bool): 33 num_cards = self.sync_count() 34 enable_mask = ((1 << num_cards) - 1) if enable else 0 35 elif isinstance(enable, int): 36 enable_mask = enable 37 else: 38 raise ValueError("The enable parameter must be a boolean or an integer") 39 self.set_i(SPC_SYNC_ENABLEMASK, enable_mask) 40 return self.get_i(SPC_SYNC_ENABLEMASK)
Enable or disable the Starthub (see register 'SPC_SYNC_ENABLEMASK' in chapter Star-Hub
in the manual)
Parameters
- enable (int or bool): enable or disable the Starthub
42 def num_connectors(self) -> int: 43 """ 44 Number of connectors that the Star-Hub offers at max. (see register 'SPC_SYNC_READ_NUMCONNECTORS' in chapter `Star-Hub` in the manual) 45 46 Returns 47 ------- 48 int 49 number of connectors on the StarHub 50 """ 51 52 return self.get_i(SPC_SYNC_READ_NUMCONNECTORS)
Number of connectors that the Star-Hub offers at max. (see register 'SPC_SYNC_READ_NUMCONNECTORS' in chapter Star-Hub
in the manual)
Returns
- int: number of connectors on the StarHub
54 def sync_count(self) -> int: 55 """ 56 Number of cards that are connected to this Star-Hub (see register 'SPC_SYNC_READ_SYNCCOUNT' in chapter `Star-Hub` in the manual) 57 58 Returns 59 ------- 60 int 61 number of synchronized cards 62 """ 63 64 return self.get_i(SPC_SYNC_READ_SYNCCOUNT)
Number of cards that are connected to this Star-Hub (see register 'SPC_SYNC_READ_SYNCCOUNT' in chapter Star-Hub
in the manual)
Returns
- int: number of synchronized cards
66 def card_index(self, index) -> int: 67 """ 68 Index of the card that is connected to the Star-Hub at the given local index (see register 'SPC_SYNC_READ_CARDIDX0' in chapter `Star-Hub` in the manual) 69 70 Parameters 71 ---------- 72 index : int 73 connector index 74 75 Returns 76 ------- 77 int 78 card index 79 """ 80 81 return self.get_i(SPC_SYNC_READ_CARDIDX0 + index)
Index of the card that is connected to the Star-Hub at the given local index (see register 'SPC_SYNC_READ_CARDIDX0' in chapter Star-Hub
in the manual)
Parameters
- index (int): connector index
Returns
- int: card index
83 def cable_connection(self, index) -> int: 84 """ 85 Returns the index of the cable connection that is used for the logical connection `index`. (see register 'SPC_SYNC_READ_CABLECON0' in chapter `Star-Hub` in the manual) 86 The cable connections can be seen printed on the PCB of the star-hub. Use these cable connection information in case 87 that there are hardware failures with the star-hub cabeling. 88 89 Parameters 90 ---------- 91 index : int 92 connector index 93 94 Returns 95 ------- 96 int 97 cable index 98 """ 99 100 return self.get_i(SPC_SYNC_READ_CABLECON0 + index)
Returns the index of the cable connection that is used for the logical connection index
. (see register 'SPC_SYNC_READ_CABLECON0' in chapter Star-Hub
in the manual)
The cable connections can be seen printed on the PCB of the star-hub. Use these cable connection information in case
that there are hardware failures with the star-hub cabeling.
Parameters
- index (int): connector index
Returns
- int: cable index
13class CardStack(ExitStack): 14 """ 15 A context manager object for handling multiple Card objects with or without a Sync object 16 17 Parameters 18 ---------- 19 cards : list[Card] 20 a list of card objects that is managed by the context manager 21 sync : Sync 22 an object for handling the synchronization of cards 23 sync_card : Card 24 a card object that is used for synchronization 25 sync_id : int 26 the index of the sync card in the list of cards 27 is_synced : bool 28 a boolean that indicates if the cards are synchronized 29 """ 30 31 cards : list[Card] = [] 32 sync : Sync = None 33 sync_card : Card = None 34 sync_id : int = -1 35 is_synced : bool = False 36 37 def __init__(self, card_identifiers : list[str] = [], sync_identifier : str = "", find_sync_card : bool = False) -> None: 38 """ 39 Initialize the CardStack object with a list of card identifiers and a sync identifier 40 41 Parameters 42 ---------- 43 card_identifiers : list[str] = [] 44 a list of strings that represent the VISA strings of the cards 45 sync_identifier : str = "" 46 a string that represents the VISA string of the sync card 47 find_sync : bool = False 48 a boolean that indicates if the sync card should be found automatically 49 """ 50 51 super().__init__() 52 # Handle card objects 53 self.cards = [self.enter_context(Card(identifier)) for identifier in card_identifiers] 54 if find_sync_card: 55 for id, card in enumerate(self.cards): 56 if card.starhub_card(): 57 self.sync_card = card 58 self.sync_id = id 59 self.is_synced = True 60 break 61 if sync_identifier and (not find_sync_card or self.is_synced): 62 self.sync = self.enter_context(Sync(sync_identifier)) 63 self.is_synced = bool(self.sync) 64 65 def __bool__(self) -> bool: 66 """Checks if all defined cards are connected""" 67 connected = True 68 for card in self.cards: 69 connected &= bool(card) 70 return connected 71 72 def synched(self): 73 """Checks if the sync card is connected 74 """ 75 return bool(self.is_synched) 76 77 def start(self, *args) -> None: 78 """ 79 Start all cards 80 81 Parameters 82 ---------- 83 args : list 84 a list of arguments that will be passed to the start method of the cards 85 """ 86 87 if self.sync: 88 self.sync.start(*args) 89 else: 90 for card in self.cards: 91 card.start(*args) 92 93 def stop(self, *args) -> None: 94 """ 95 Stop all cards 96 97 Parameters 98 ---------- 99 args : list 100 a list of arguments that will be passed to the stop method of the cards 101 """ 102 103 if self.sync: 104 self.sync.stop(*args) 105 else: 106 for card in self.cards: 107 card.stop(*args) 108 109 def reset(self, *args) -> None: 110 """ 111 Reset all cards 112 113 Parameters 114 ---------- 115 args : list 116 a list of arguments that will be passed to the reset method of the cards 117 """ 118 119 if self.sync: 120 self.sync.reset(*args) 121 else: 122 for card in self.cards: 123 card.reset(*args) 124 125 def force_trigger(self, *args) -> None: 126 """ 127 Force trigger on all cards 128 129 Parameters 130 ---------- 131 args : list 132 a list of arguments that will be passed with the force trigger command for the cards 133 """ 134 135 # TODO: the force trigger needs to be correctly implemented in the driver 136 if self.sync_card: 137 self.sync_card.cmd(M2CMD_CARD_FORCETRIGGER, *args) 138 elif self.sync: 139 # self.sync.cmd(M2CMD_CARD_FORCETRIGGER, *args) 140 self.cards[0].cmd(M2CMD_CARD_FORCETRIGGER, *args) 141 else: 142 for card in self.cards: 143 card.cmd(M2CMD_CARD_FORCETRIGGER, *args) 144 145 def sync_enable(self, enable : int = True) -> int: 146 """ 147 Enable synchronization on all cards 148 149 Parameters 150 ---------- 151 enable : int or bool 152 a boolean or integer mask to enable or disable the synchronization of different channels 153 154 Returns 155 ------- 156 int 157 the mask of the enabled channels 158 159 Raises 160 ------ 161 ValueError 162 The enable parameter must be a boolean or an integer 163 SpcmException 164 No sync card avaliable to enable synchronization on the cards 165 """ 166 167 if self.sync: 168 return self.sync.enable(enable) 169 else: 170 raise SpcmException("No sync card avaliable to enable synchronization on the cards") 171 172 173 @staticmethod 174 def id_to_ip(device_identifier : str) -> str: 175 """ 176 Returns the IP address of the Netbox using the device identifier 177 178 Parameters 179 ---------- 180 device_identifier : str 181 The device identifier of the Netbox 182 183 Returns 184 ------- 185 str 186 The IP address of the Netbox 187 """ 188 ip = device_identifier 189 ip = ip[ip.find('::') + 2:] 190 ip = ip[:ip.find ('::')] 191 return ip 192 193 @staticmethod 194 def discover(max_num_remote_cards : int = 50, max_visa_string_len : int = 256, max_idn_string_len : int = 256, timeout_ms : int = 5000) -> dict[list[str]]: 195 """ 196 Do a discovery of the cards connected through a network 197 198 Parameters 199 ---------- 200 max_num_remote_cards : int = 50 201 the maximum number of remote cards that can be discovered 202 max_visa_string_len : int = 256 203 the maximum length of the VISA string 204 max_idn_string_len : int = 256 205 the maximum length of the IDN string 206 timeout_ms : int = 5000 207 the timeout in milliseconds for the discovery process 208 209 Returns 210 ------- 211 CardStack 212 a stack object with all the discovered cards 213 214 Raises 215 ------ 216 SpcmException 217 No Spectrum devices found 218 """ 219 220 visa = (spcm_core.c_char_p * max_num_remote_cards)() 221 for i in range(max_num_remote_cards): 222 visa[i] = spcm_core.cast(spcm_core.create_string_buffer(max_visa_string_len), spcm_core.c_char_p) 223 spcm_core.spcm_dwDiscovery (visa, spcm_core.uint32(max_num_remote_cards), spcm_core.uint32(max_visa_string_len), spcm_core.uint32(timeout_ms)) 224 225 # ----- check from which manufacturer the devices are ----- 226 idn = (spcm_core.c_char_p * max_num_remote_cards)() 227 for i in range(max_num_remote_cards): 228 idn[i] = spcm_core.cast(spcm_core.create_string_buffer(max_idn_string_len), spcm_core.c_char_p) 229 spcm_core.spcm_dwSendIDNRequest (idn, spcm_core.uint32(max_num_remote_cards), spcm_core.uint32(max_idn_string_len)) 230 231 # ----- store VISA strings for all discovered cards and open them afterwards ----- 232 list_spectrum_devices = {} 233 for (id, visa) in zip(idn, visa): 234 if not id: 235 break 236 237 if id.decode('utf-8').startswith("Spectrum GmbH,"): 238 ip = __class__.id_to_ip(visa.decode("utf-8")) 239 if ip in list_spectrum_devices: 240 list_spectrum_devices[ip].append(visa.decode("utf-8")) 241 else: 242 list_spectrum_devices[ip] = [visa.decode("utf-8")] 243 244 if not list_spectrum_devices: 245 raise SpcmException("No Spectrum devices found") 246 247 return list_spectrum_devices
A context manager object for handling multiple Card objects with or without a Sync object
Parameters
- cards (list[Card]): a list of card objects that is managed by the context manager
- sync (Sync): an object for handling the synchronization of cards
- sync_card (Card): a card object that is used for synchronization
- sync_id (int): the index of the sync card in the list of cards
- is_synced (bool): a boolean that indicates if the cards are synchronized
37 def __init__(self, card_identifiers : list[str] = [], sync_identifier : str = "", find_sync_card : bool = False) -> None: 38 """ 39 Initialize the CardStack object with a list of card identifiers and a sync identifier 40 41 Parameters 42 ---------- 43 card_identifiers : list[str] = [] 44 a list of strings that represent the VISA strings of the cards 45 sync_identifier : str = "" 46 a string that represents the VISA string of the sync card 47 find_sync : bool = False 48 a boolean that indicates if the sync card should be found automatically 49 """ 50 51 super().__init__() 52 # Handle card objects 53 self.cards = [self.enter_context(Card(identifier)) for identifier in card_identifiers] 54 if find_sync_card: 55 for id, card in enumerate(self.cards): 56 if card.starhub_card(): 57 self.sync_card = card 58 self.sync_id = id 59 self.is_synced = True 60 break 61 if sync_identifier and (not find_sync_card or self.is_synced): 62 self.sync = self.enter_context(Sync(sync_identifier)) 63 self.is_synced = bool(self.sync)
Initialize the CardStack object with a list of card identifiers and a sync identifier
Parameters
- card_identifiers (list[str] = []): a list of strings that represent the VISA strings of the cards
- sync_identifier (str = ""): a string that represents the VISA string of the sync card
- find_sync (bool = False): a boolean that indicates if the sync card should be found automatically
72 def synched(self): 73 """Checks if the sync card is connected 74 """ 75 return bool(self.is_synched)
Checks if the sync card is connected
77 def start(self, *args) -> None: 78 """ 79 Start all cards 80 81 Parameters 82 ---------- 83 args : list 84 a list of arguments that will be passed to the start method of the cards 85 """ 86 87 if self.sync: 88 self.sync.start(*args) 89 else: 90 for card in self.cards: 91 card.start(*args)
Start all cards
Parameters
- args (list): a list of arguments that will be passed to the start method of the cards
93 def stop(self, *args) -> None: 94 """ 95 Stop all cards 96 97 Parameters 98 ---------- 99 args : list 100 a list of arguments that will be passed to the stop method of the cards 101 """ 102 103 if self.sync: 104 self.sync.stop(*args) 105 else: 106 for card in self.cards: 107 card.stop(*args)
Stop all cards
Parameters
- args (list): a list of arguments that will be passed to the stop method of the cards
109 def reset(self, *args) -> None: 110 """ 111 Reset all cards 112 113 Parameters 114 ---------- 115 args : list 116 a list of arguments that will be passed to the reset method of the cards 117 """ 118 119 if self.sync: 120 self.sync.reset(*args) 121 else: 122 for card in self.cards: 123 card.reset(*args)
Reset all cards
Parameters
- args (list): a list of arguments that will be passed to the reset method of the cards
125 def force_trigger(self, *args) -> None: 126 """ 127 Force trigger on all cards 128 129 Parameters 130 ---------- 131 args : list 132 a list of arguments that will be passed with the force trigger command for the cards 133 """ 134 135 # TODO: the force trigger needs to be correctly implemented in the driver 136 if self.sync_card: 137 self.sync_card.cmd(M2CMD_CARD_FORCETRIGGER, *args) 138 elif self.sync: 139 # self.sync.cmd(M2CMD_CARD_FORCETRIGGER, *args) 140 self.cards[0].cmd(M2CMD_CARD_FORCETRIGGER, *args) 141 else: 142 for card in self.cards: 143 card.cmd(M2CMD_CARD_FORCETRIGGER, *args)
Force trigger on all cards
Parameters
- args (list): a list of arguments that will be passed with the force trigger command for the cards
145 def sync_enable(self, enable : int = True) -> int: 146 """ 147 Enable synchronization on all cards 148 149 Parameters 150 ---------- 151 enable : int or bool 152 a boolean or integer mask to enable or disable the synchronization of different channels 153 154 Returns 155 ------- 156 int 157 the mask of the enabled channels 158 159 Raises 160 ------ 161 ValueError 162 The enable parameter must be a boolean or an integer 163 SpcmException 164 No sync card avaliable to enable synchronization on the cards 165 """ 166 167 if self.sync: 168 return self.sync.enable(enable) 169 else: 170 raise SpcmException("No sync card avaliable to enable synchronization on the cards")
Enable synchronization on all cards
Parameters
- enable (int or bool): a boolean or integer mask to enable or disable the synchronization of different channels
Returns
- int: the mask of the enabled channels
Raises
- ValueError: The enable parameter must be a boolean or an integer
- SpcmException: No sync card avaliable to enable synchronization on the cards
173 @staticmethod 174 def id_to_ip(device_identifier : str) -> str: 175 """ 176 Returns the IP address of the Netbox using the device identifier 177 178 Parameters 179 ---------- 180 device_identifier : str 181 The device identifier of the Netbox 182 183 Returns 184 ------- 185 str 186 The IP address of the Netbox 187 """ 188 ip = device_identifier 189 ip = ip[ip.find('::') + 2:] 190 ip = ip[:ip.find ('::')] 191 return ip
Returns the IP address of the Netbox using the device identifier
Parameters
- device_identifier (str): The device identifier of the Netbox
Returns
- str: The IP address of the Netbox
193 @staticmethod 194 def discover(max_num_remote_cards : int = 50, max_visa_string_len : int = 256, max_idn_string_len : int = 256, timeout_ms : int = 5000) -> dict[list[str]]: 195 """ 196 Do a discovery of the cards connected through a network 197 198 Parameters 199 ---------- 200 max_num_remote_cards : int = 50 201 the maximum number of remote cards that can be discovered 202 max_visa_string_len : int = 256 203 the maximum length of the VISA string 204 max_idn_string_len : int = 256 205 the maximum length of the IDN string 206 timeout_ms : int = 5000 207 the timeout in milliseconds for the discovery process 208 209 Returns 210 ------- 211 CardStack 212 a stack object with all the discovered cards 213 214 Raises 215 ------ 216 SpcmException 217 No Spectrum devices found 218 """ 219 220 visa = (spcm_core.c_char_p * max_num_remote_cards)() 221 for i in range(max_num_remote_cards): 222 visa[i] = spcm_core.cast(spcm_core.create_string_buffer(max_visa_string_len), spcm_core.c_char_p) 223 spcm_core.spcm_dwDiscovery (visa, spcm_core.uint32(max_num_remote_cards), spcm_core.uint32(max_visa_string_len), spcm_core.uint32(timeout_ms)) 224 225 # ----- check from which manufacturer the devices are ----- 226 idn = (spcm_core.c_char_p * max_num_remote_cards)() 227 for i in range(max_num_remote_cards): 228 idn[i] = spcm_core.cast(spcm_core.create_string_buffer(max_idn_string_len), spcm_core.c_char_p) 229 spcm_core.spcm_dwSendIDNRequest (idn, spcm_core.uint32(max_num_remote_cards), spcm_core.uint32(max_idn_string_len)) 230 231 # ----- store VISA strings for all discovered cards and open them afterwards ----- 232 list_spectrum_devices = {} 233 for (id, visa) in zip(idn, visa): 234 if not id: 235 break 236 237 if id.decode('utf-8').startswith("Spectrum GmbH,"): 238 ip = __class__.id_to_ip(visa.decode("utf-8")) 239 if ip in list_spectrum_devices: 240 list_spectrum_devices[ip].append(visa.decode("utf-8")) 241 else: 242 list_spectrum_devices[ip] = [visa.decode("utf-8")] 243 244 if not list_spectrum_devices: 245 raise SpcmException("No Spectrum devices found") 246 247 return list_spectrum_devices
Do a discovery of the cards connected through a network
Parameters
- max_num_remote_cards (int = 50): the maximum number of remote cards that can be discovered
- max_visa_string_len (int = 256): the maximum length of the VISA string
- max_idn_string_len (int = 256): the maximum length of the IDN string
- timeout_ms (int = 5000): the timeout in milliseconds for the discovery process
Returns
- CardStack: a stack object with all the discovered cards
Raises
- SpcmException: No Spectrum devices found
9class Netbox(CardStack): 10 """ 11 A hardware class that controls a Netbox device 12 13 Parameters 14 ---------- 15 netbox_card : Card 16 a card object that is the main card in the Netbox 17 netbox_number : int 18 the index of the netbox card in the list of cards 19 is_netbox : bool 20 a boolean that indicates if the card is a Netbox 21 22 """ 23 netbox_card : Card = None 24 netbox_number : int = -1 25 is_netbox : bool = False 26 27 def __init__(self, card_identifiers : list[str] = [], sync_identifier : str = "", find_sync : bool = False, **kwargs) -> None: 28 """ 29 Initialize the Netbox object with a list of card identifiers and a sync identifier 30 31 Parameters 32 ---------- 33 card_identifiers : list[str] = [] 34 a list of strings that represent the VISA strings of the cards 35 sync_identifier : str = "" 36 a string that represents the VISA string of the sync card 37 find_sync : bool = False 38 a boolean that indicates if the sync card should be found automatically 39 """ 40 41 super().__init__(card_identifiers, sync_identifier, find_sync, **kwargs) 42 43 for id, card in enumerate(self.cards): 44 netbox_type = card.get_i(SPC_NETBOX_TYPE) 45 if netbox_type != 0: 46 self.netbox_card = card 47 self.netbox_number = id 48 self.is_netbox = True 49 break 50 51 def __bool__(self) -> bool: 52 """ 53 Checks if the Netbox is connected and returns true if the connection is alive 54 55 Returns 56 ------- 57 bool 58 True if the Netbox is connected 59 """ 60 61 return self.is_netbox 62 63 def __str__(self) -> str: 64 """ 65 Returns the string representation of the Netbox 66 67 Returns 68 ------- 69 str 70 The string representation of the Netbox 71 """ 72 73 netbox_type = self.type() 74 netbox_str = "DN{series:x}.{family:x}{speed:x}-{channel:d}".format(**netbox_type) 75 return f"Netbox: {netbox_str} at {self.ip()} sn {self.sn():05d}" 76 77 def type(self) -> dict[int, int, int, int]: 78 """ 79 Returns the type of the Netbox (see register 'SPC_NETBOX_TYPE' in chapter `Netbox` in the manual) 80 81 Returns 82 ------- 83 dict[int, int, int, int] 84 A dictionary with the series, family, speed and number of channels of the Netbox 85 """ 86 87 netbox_type = self.netbox_card.get_i(SPC_NETBOX_TYPE) 88 netbox_series = (netbox_type & NETBOX_SERIES_MASK) >> 24 89 netbox_family = (netbox_type & NETBOX_FAMILY_MASK) >> 16 90 netbox_speed = (netbox_type & NETBOX_SPEED_MASK) >> 8 91 netbox_channel = (netbox_type & NETBOX_CHANNEL_MASK) 92 return {"series" : netbox_series, "family" : netbox_family, "speed" : netbox_speed, "channel" : netbox_channel} 93 94 def ip(self) -> str: 95 """ 96 Returns the IP address of the Netbox using the device identifier of the netbox_card 97 98 Returns 99 ------- 100 str 101 The IP address of the Netbox 102 """ 103 104 return self.id_to_ip(self.netbox_card.device_identifier) 105 106 def sn(self) -> int: 107 """ 108 Returns the serial number of the Netbox (see register 'SPC_NETBOX_SERIALNO' in chapter `Netbox` in the manual) 109 110 Returns 111 ------- 112 int 113 The serial number of the Netbox 114 """ 115 116 return self.netbox_card.get_i(SPC_NETBOX_SERIALNO) 117 118 def production_date(self) -> int: 119 """ 120 Returns the production date of the Netbox (see register 'SPC_NETBOX_PRODUCTIONDATE' in chapter `Netbox` in the manual) 121 122 Returns 123 ------- 124 int 125 The production date of the Netbox 126 """ 127 128 return self.netbox_card.get_i(SPC_NETBOX_PRODUCTIONDATE) 129 130 def hw_version(self) -> int: 131 """ 132 Returns the hardware version of the Netbox (see register 'SPC_NETBOX_HWVERSION' in chapter `Netbox` in the manual) 133 134 Returns 135 ------- 136 int 137 The hardware version of the Netbox 138 """ 139 140 return self.netbox_card.get_i(SPC_NETBOX_HWVERSION) 141 142 def sw_version(self) -> int: 143 """ 144 Returns the software version of the Netbox (see register 'SPC_NETBOX_SWVERSION' in chapter `Netbox` in the manual) 145 146 Returns 147 ------- 148 int 149 The software version of the Netbox 150 """ 151 152 return self.netbox_card.get_i(SPC_NETBOX_SWVERSION) 153 154 def features(self) -> int: 155 """ 156 Returns the features of the Netbox (see register 'SPC_NETBOX_FEATURES' in chapter `Netbox` in the manual) 157 158 Returns 159 ------- 160 int 161 The features of the Netbox 162 """ 163 164 return self.netbox_card.get_i(SPC_NETBOX_FEATURES) 165 166 def custom(self) -> int: 167 """ 168 Returns the custom code of the Netbox (see register 'SPC_NETBOX_CUSTOM' in chapter `Netbox` in the manual) 169 170 Returns 171 ------- 172 int 173 The custom of the Netbox 174 """ 175 return self.netbox_card.get_i(SPC_NETBOX_CUSTOM) 176 177 def wake_on_lan(self, mac : int): 178 """ 179 Set the wake on lan for the Netbox (see register 'SPC_NETBOX_WAKEONLAN' in chapter `Netbox` in the manual) 180 181 Parameters 182 ---------- 183 mac : int 184 The mac addresse of the Netbox to wake on lan 185 """ 186 self.netbox_card.set_i(SPC_NETBOX_WAKEONLAN, mac) 187 188 def mac_address(self) -> int: 189 """ 190 Returns the mac address of the Netbox (see register 'SPC_NETBOX_MACADDRESS' in chapter `Netbox` in the manual) 191 192 Returns 193 ------- 194 int 195 The mac address of the Netbox 196 """ 197 return self.netbox_card.get_i(SPC_NETBOX_MACADDRESS) 198 199 def temperature(self) -> int: 200 """ 201 Returns the temperature of the Netbox (see register 'SPC_NETBOX_TEMPERATURE' in chapter `Netbox` in the manual) 202 203 Returns 204 ------- 205 int 206 The temperature of the Netbox 207 """ 208 return self.netbox_card.get_i(SPC_NETBOX_TEMPERATURE) 209 210 def shutdown(self): 211 """ 212 Shutdown the Netbox (see register 'SPC_NETBOX_SHUTDOWN' in chapter `Netbox` in the manual) 213 """ 214 self.netbox_card.set_i(SPC_NETBOX_SHUTDOWN, 0) 215 216 def restart(self): 217 """ 218 Restart the Netbox (see register 'SPC_NETBOX_RESTART' in chapter `Netbox` in the manual) 219 """ 220 self.netbox_card.set_i(SPC_NETBOX_RESTART, 0) 221 222 def fan_speed(self, id : int) -> int: 223 """ 224 Returns the fan speed of the Netbox (see register 'SPC_NETBOX_FANSPEED' in chapter `Netbox` in the manual) 225 226 Returns 227 ------- 228 int 229 The fan speed of the Netbox 230 """ 231 return self.netbox_card.get_i(SPC_NETBOX_FANSPEED0 + id)
A hardware class that controls a Netbox device
Parameters
- netbox_card (Card): a card object that is the main card in the Netbox
- netbox_number (int): the index of the netbox card in the list of cards
- is_netbox (bool): a boolean that indicates if the card is a Netbox
27 def __init__(self, card_identifiers : list[str] = [], sync_identifier : str = "", find_sync : bool = False, **kwargs) -> None: 28 """ 29 Initialize the Netbox object with a list of card identifiers and a sync identifier 30 31 Parameters 32 ---------- 33 card_identifiers : list[str] = [] 34 a list of strings that represent the VISA strings of the cards 35 sync_identifier : str = "" 36 a string that represents the VISA string of the sync card 37 find_sync : bool = False 38 a boolean that indicates if the sync card should be found automatically 39 """ 40 41 super().__init__(card_identifiers, sync_identifier, find_sync, **kwargs) 42 43 for id, card in enumerate(self.cards): 44 netbox_type = card.get_i(SPC_NETBOX_TYPE) 45 if netbox_type != 0: 46 self.netbox_card = card 47 self.netbox_number = id 48 self.is_netbox = True 49 break
Initialize the Netbox object with a list of card identifiers and a sync identifier
Parameters
- card_identifiers (list[str] = []): a list of strings that represent the VISA strings of the cards
- sync_identifier (str = ""): a string that represents the VISA string of the sync card
- find_sync (bool = False): a boolean that indicates if the sync card should be found automatically
77 def type(self) -> dict[int, int, int, int]: 78 """ 79 Returns the type of the Netbox (see register 'SPC_NETBOX_TYPE' in chapter `Netbox` in the manual) 80 81 Returns 82 ------- 83 dict[int, int, int, int] 84 A dictionary with the series, family, speed and number of channels of the Netbox 85 """ 86 87 netbox_type = self.netbox_card.get_i(SPC_NETBOX_TYPE) 88 netbox_series = (netbox_type & NETBOX_SERIES_MASK) >> 24 89 netbox_family = (netbox_type & NETBOX_FAMILY_MASK) >> 16 90 netbox_speed = (netbox_type & NETBOX_SPEED_MASK) >> 8 91 netbox_channel = (netbox_type & NETBOX_CHANNEL_MASK) 92 return {"series" : netbox_series, "family" : netbox_family, "speed" : netbox_speed, "channel" : netbox_channel}
Returns the type of the Netbox (see register 'SPC_NETBOX_TYPE' in chapter Netbox
in the manual)
Returns
- dict[int, int, int, int]: A dictionary with the series, family, speed and number of channels of the Netbox
94 def ip(self) -> str: 95 """ 96 Returns the IP address of the Netbox using the device identifier of the netbox_card 97 98 Returns 99 ------- 100 str 101 The IP address of the Netbox 102 """ 103 104 return self.id_to_ip(self.netbox_card.device_identifier)
Returns the IP address of the Netbox using the device identifier of the netbox_card
Returns
- str: The IP address of the Netbox
106 def sn(self) -> int: 107 """ 108 Returns the serial number of the Netbox (see register 'SPC_NETBOX_SERIALNO' in chapter `Netbox` in the manual) 109 110 Returns 111 ------- 112 int 113 The serial number of the Netbox 114 """ 115 116 return self.netbox_card.get_i(SPC_NETBOX_SERIALNO)
Returns the serial number of the Netbox (see register 'SPC_NETBOX_SERIALNO' in chapter Netbox
in the manual)
Returns
- int: The serial number of the Netbox
118 def production_date(self) -> int: 119 """ 120 Returns the production date of the Netbox (see register 'SPC_NETBOX_PRODUCTIONDATE' in chapter `Netbox` in the manual) 121 122 Returns 123 ------- 124 int 125 The production date of the Netbox 126 """ 127 128 return self.netbox_card.get_i(SPC_NETBOX_PRODUCTIONDATE)
Returns the production date of the Netbox (see register 'SPC_NETBOX_PRODUCTIONDATE' in chapter Netbox
in the manual)
Returns
- int: The production date of the Netbox
130 def hw_version(self) -> int: 131 """ 132 Returns the hardware version of the Netbox (see register 'SPC_NETBOX_HWVERSION' in chapter `Netbox` in the manual) 133 134 Returns 135 ------- 136 int 137 The hardware version of the Netbox 138 """ 139 140 return self.netbox_card.get_i(SPC_NETBOX_HWVERSION)
Returns the hardware version of the Netbox (see register 'SPC_NETBOX_HWVERSION' in chapter Netbox
in the manual)
Returns
- int: The hardware version of the Netbox
142 def sw_version(self) -> int: 143 """ 144 Returns the software version of the Netbox (see register 'SPC_NETBOX_SWVERSION' in chapter `Netbox` in the manual) 145 146 Returns 147 ------- 148 int 149 The software version of the Netbox 150 """ 151 152 return self.netbox_card.get_i(SPC_NETBOX_SWVERSION)
Returns the software version of the Netbox (see register 'SPC_NETBOX_SWVERSION' in chapter Netbox
in the manual)
Returns
- int: The software version of the Netbox
154 def features(self) -> int: 155 """ 156 Returns the features of the Netbox (see register 'SPC_NETBOX_FEATURES' in chapter `Netbox` in the manual) 157 158 Returns 159 ------- 160 int 161 The features of the Netbox 162 """ 163 164 return self.netbox_card.get_i(SPC_NETBOX_FEATURES)
Returns the features of the Netbox (see register 'SPC_NETBOX_FEATURES' in chapter Netbox
in the manual)
Returns
- int: The features of the Netbox
166 def custom(self) -> int: 167 """ 168 Returns the custom code of the Netbox (see register 'SPC_NETBOX_CUSTOM' in chapter `Netbox` in the manual) 169 170 Returns 171 ------- 172 int 173 The custom of the Netbox 174 """ 175 return self.netbox_card.get_i(SPC_NETBOX_CUSTOM)
Returns the custom code of the Netbox (see register 'SPC_NETBOX_CUSTOM' in chapter Netbox
in the manual)
Returns
- int: The custom of the Netbox
177 def wake_on_lan(self, mac : int): 178 """ 179 Set the wake on lan for the Netbox (see register 'SPC_NETBOX_WAKEONLAN' in chapter `Netbox` in the manual) 180 181 Parameters 182 ---------- 183 mac : int 184 The mac addresse of the Netbox to wake on lan 185 """ 186 self.netbox_card.set_i(SPC_NETBOX_WAKEONLAN, mac)
Set the wake on lan for the Netbox (see register 'SPC_NETBOX_WAKEONLAN' in chapter Netbox
in the manual)
Parameters
- mac (int): The mac addresse of the Netbox to wake on lan
188 def mac_address(self) -> int: 189 """ 190 Returns the mac address of the Netbox (see register 'SPC_NETBOX_MACADDRESS' in chapter `Netbox` in the manual) 191 192 Returns 193 ------- 194 int 195 The mac address of the Netbox 196 """ 197 return self.netbox_card.get_i(SPC_NETBOX_MACADDRESS)
Returns the mac address of the Netbox (see register 'SPC_NETBOX_MACADDRESS' in chapter Netbox
in the manual)
Returns
- int: The mac address of the Netbox
199 def temperature(self) -> int: 200 """ 201 Returns the temperature of the Netbox (see register 'SPC_NETBOX_TEMPERATURE' in chapter `Netbox` in the manual) 202 203 Returns 204 ------- 205 int 206 The temperature of the Netbox 207 """ 208 return self.netbox_card.get_i(SPC_NETBOX_TEMPERATURE)
Returns the temperature of the Netbox (see register 'SPC_NETBOX_TEMPERATURE' in chapter Netbox
in the manual)
Returns
- int: The temperature of the Netbox
210 def shutdown(self): 211 """ 212 Shutdown the Netbox (see register 'SPC_NETBOX_SHUTDOWN' in chapter `Netbox` in the manual) 213 """ 214 self.netbox_card.set_i(SPC_NETBOX_SHUTDOWN, 0)
Shutdown the Netbox (see register 'SPC_NETBOX_SHUTDOWN' in chapter Netbox
in the manual)
216 def restart(self): 217 """ 218 Restart the Netbox (see register 'SPC_NETBOX_RESTART' in chapter `Netbox` in the manual) 219 """ 220 self.netbox_card.set_i(SPC_NETBOX_RESTART, 0)
Restart the Netbox (see register 'SPC_NETBOX_RESTART' in chapter Netbox
in the manual)
222 def fan_speed(self, id : int) -> int: 223 """ 224 Returns the fan speed of the Netbox (see register 'SPC_NETBOX_FANSPEED' in chapter `Netbox` in the manual) 225 226 Returns 227 ------- 228 int 229 The fan speed of the Netbox 230 """ 231 return self.netbox_card.get_i(SPC_NETBOX_FANSPEED0 + id)
Returns the fan speed of the Netbox (see register 'SPC_NETBOX_FANSPEED' in chapter Netbox
in the manual)
Returns
- int: The fan speed of the Netbox
6class CardFunctionality: 7 """ 8 A prototype class for card specific functionality that needs it's own namespace 9 """ 10 card : Card 11 function_type = 0 12 13 def __init__(self, card : Card, *args, **kwargs) -> None: 14 """ 15 Takes a Card object that is used by the functionality 16 17 Parameters 18 ---------- 19 card : Card 20 a Card object on which the functionality works 21 """ 22 self.card = card 23 self.function_type = self.card.function_type() 24 25 26 # Check if a card was found 27 def __bool__(self) -> bool: 28 """ 29 Check for a connection to the active card 30 31 Returns 32 ------- 33 bool 34 True for an active connection and false otherwise 35 36 """ 37 38 return bool(self.card)
A prototype class for card specific functionality that needs it's own namespace
13 def __init__(self, card : Card, *args, **kwargs) -> None: 14 """ 15 Takes a Card object that is used by the functionality 16 17 Parameters 18 ---------- 19 card : Card 20 a Card object on which the functionality works 21 """ 22 self.card = card 23 self.function_type = self.card.function_type()
Takes a Card object that is used by the functionality
Parameters
- card (Card): a Card object on which the functionality works
494class Channels: 495 """ 496 a higher-level abstraction of the CardFunctionality class to implement the Card's channel settings 497 """ 498 499 cards : list[Card] = [] 500 channels : list[Channel] = [] 501 num_channels : list[int] = [] 502 503 def __init__(self, card : Card = None, card_enable : int = None, stack : CardStack = None, stack_enable : list[int] = None) -> None: 504 """ 505 Constructor of the Channels class 506 507 Parameters 508 ---------- 509 card : Card = None 510 The card to be used 511 card_enable : int = None 512 The bitmask to enable specific channels 513 stack : CardStack = None 514 The card stack to be used 515 stack_enable : list[int] = None 516 The list of bitmasks to enable specific channels 517 518 Raises 519 ------ 520 SpcmException 521 No card or card stack provided 522 """ 523 524 self.cards = [] 525 self.channels = [] 526 self.num_channels = [] 527 if card is not None: 528 self.cards.append(card) 529 if card_enable is not None: 530 self.channels_enable(enable_list=[card_enable]) 531 else: 532 self.channels_enable(enable_all=True) 533 elif stack is not None: 534 self.cards = stack.cards 535 if stack_enable is not None: 536 self.channels_enable(enable_list=stack_enable) 537 else: 538 self.channels_enable(enable_all=True) 539 else: 540 raise SpcmException(text="No card or card stack provided") 541 542 def __str__(self) -> str: 543 """ 544 String representation of the Channels class 545 546 Returns 547 ------- 548 str 549 String representation of the Channels class 550 """ 551 552 return f"Channels()" 553 554 __repr__ = __str__ 555 556 def __iter__(self) -> "Channels": 557 """Define this class as an iterator""" 558 return self 559 560 def __getitem__(self, index : int) -> Channel: 561 """ 562 This method is called to access the channel by index 563 564 Parameters 565 ---------- 566 index : int 567 The index of the channel 568 569 Returns 570 ------- 571 Channel 572 the channel at the specific index 573 """ 574 575 576 return self.channels[index] 577 578 _channel_iterator_index = -1 579 def __next__(self) -> Channel: 580 """ 581 This method is called when the next element is requested from the iterator 582 583 Returns 584 ------- 585 Channel 586 the next available channel 587 588 Raises 589 ------ 590 StopIteration 591 """ 592 self._channel_iterator_index += 1 593 if self._channel_iterator_index >= len(self.channels): 594 self._channel_iterator_index = -1 595 raise StopIteration 596 return self.channels[self._channel_iterator_index] 597 598 def __len__(self) -> int: 599 """Returns the number of channels""" 600 return len(self.channels) 601 602 def write_setup(self) -> None: 603 """Write the setup to the card""" 604 self.card.write_setup() 605 606 def channels_enable(self, enable_list : list[int] = None, enable_all : bool = False) -> int: 607 """ 608 Enables or disables the channels of all the available cards (see register `SPC_CHENABLE` in the manual) 609 610 Parameters 611 ---------- 612 enable_list : list[int] = None 613 A list of channels bitmasks to be enable or disable specific channels 614 enable_all : bool = False 615 Enable all the channels 616 617 Returns 618 ------- 619 int 620 A list with items that indicate for each card the number of channels that are enabled, or True to enable all channels. 621 """ 622 623 self.channels = [] 624 self.num_channels = [] 625 num_channels = 0 626 627 if enable_all: 628 for card in self.cards: 629 num_channels = card.num_channels() 630 card.set_i(SPC_CHENABLE, (1 << num_channels) - 1) 631 num_channels = card.get_i(SPC_CHCOUNT) 632 self.num_channels.append(num_channels) 633 for i in range(num_channels): 634 self.channels.append(Channel(i, i, card)) 635 elif enable_list is not None: 636 for enable, card in zip(enable_list, self.cards): 637 card.set_i(SPC_CHENABLE, enable) 638 num_channels = card.get_i(SPC_CHCOUNT) 639 self.num_channels.append(num_channels) 640 counter = 0 641 for i in range(len(bin(enable))): 642 if (enable >> i) & 1: 643 self.channels.append(Channel(i, counter, card)) 644 counter += 1 645 return sum(self.num_channels) 646 647 # def __getattribute__(self, name): 648 # # print("Calling __getattr__: {}".format(name)) 649 # if hasattr(Channel, name): 650 # def wrapper(*args, **kw): 651 # for channel in self.channels: 652 # getattr(channel, name)(*args, **kw) 653 # return wrapper 654 # else: 655 # return object.__getattribute__(self, name) 656 657 def enable(self, enable : bool) -> None: 658 """ 659 Enables or disables the analog front-end of all channels of the card (see register `SPC_ENABLEOUT` in the manual) 660 661 Parameters 662 ---------- 663 enable : bool 664 Turn-on (True) or off (False) the spezific channel 665 """ 666 667 for channel in self.channels: 668 channel.enable(enable) 669 enable_out = enable 670 671 def path(self, value : int) -> None: 672 """ 673 Sets the input path of the analog front-end of all channels of the card (see register `SPC_PATH` in the manual) 674 675 Parameters 676 ---------- 677 value : int 678 The input path of the specific channel 679 """ 680 681 for channel in self.channels: 682 channel.path(value) 683 684 def amp(self, value : int) -> None: 685 """ 686 Sets the output/input range (amplitude) of the analog front-end of all channels of the card in mV (see register `SPC_AMP` in the manual) 687 688 Parameters 689 ---------- 690 value : int 691 The output range (amplitude) of all channels in millivolts 692 """ 693 694 for channel in self.channels: 695 channel.amp(value) 696 697 def offset(self, value : int) -> None: 698 """ 699 Sets the offset of the analog front-end of all channels of the card in mV (see register `SPC_OFFSET` in the manual) 700 701 Parameters 702 ---------- 703 value : int 704 The offset of all channels in millivolts 705 """ 706 707 for channel in self.channels: 708 channel.offset(value) 709 710 def termination(self, value : int) -> None: 711 """ 712 Sets the termination of the analog front-end of all channels of the card (see register `SPC_50OHM` in the manual) 713 714 Parameters 715 ---------- 716 value : int 717 The termination of all channels 718 """ 719 720 for channel in self.channels: 721 channel.termination(value) 722 723 def coupling(self, value : int) -> None: 724 """ 725 Sets the coupling of the analog front-end of all channels of the card (see register `SPC_ACDC` in the manual) 726 727 Parameters 728 ---------- 729 value : int 730 The coupling of all channels 731 """ 732 733 for channel in self.channels: 734 channel.coupling(value) 735 736 def coupling_offset_compensation(self, value : int) -> None: 737 """ 738 Sets the coupling offset compensation of the analog front-end of all channels of the card (see register `SPC_ACDC_OFFS_COMPENSATION` in the manual) 739 740 Parameters 741 ---------- 742 value : int 743 The coupling offset compensation of all channels 744 """ 745 746 for channel in self.channels: 747 channel.coupling_offset_compensation(value) 748 749 def filter(self, value : int) -> None: 750 """ 751 Sets the filter of the analog front-end of all channels of the card (see register `SPC_FILTER` in the manual) 752 753 Parameters 754 ---------- 755 value : int 756 The filter of all channels 757 """ 758 759 for channel in self.channels: 760 channel.filter(value) 761 762 def stop_level(self, value : int) -> None: 763 """ 764 Usually the used outputs of the analog generation boards are set to zero level after replay. 765 This is in most cases adequate. In some cases it can be necessary to hold the last sample, 766 to output the maximum positive level or maximum negative level after replay. The stoplevel will 767 stay on the defined level until the next output has been made. With this function 768 you can define the behavior after replay (see register `SPC_CH0_STOPLEVEL` in the manual) 769 770 Parameters 771 ---------- 772 value : int 773 The wanted stop behaviour: 774 """ 775 776 for channel in self.channels: 777 channel.stop_level(value) 778 779 def custom_stop(self, value : int) -> None: 780 """ 781 Allows to define a 16bit wide custom level per channel for the analog output to enter in pauses. The sample format is 782 exactly the same as during replay, as described in the „sample format“ section. 783 When synchronous digital bits are replayed along, the custom level must include these as well and therefore allows to 784 set a custom level for each multi-purpose line separately. (see register `SPC_CH0_CUSTOM_STOP` in the manual) 785 786 Parameters 787 ---------- 788 value : int 789 The custom stop value 790 """ 791 792 for channel in self.channels: 793 channel.custom_stop(value) 794 795 def output_load(self, value : pint.Quantity) -> None: 796 """ 797 Sets the electrical load of the user system connect the channel of the card. This is important for the correct 798 calculation of the output power. Typically, the load would be 50 Ohms, but it can be different. 799 800 Parameters 801 ---------- 802 value : pint.Quantity 803 The electrical load connected by the user to the specific channel 804 """ 805 for channel in self.channels: 806 channel.output_load(value) 807 808 def ch_mask(self) -> int: 809 """ 810 Gets mask for the "or"- or "and"-mask 811 812 Returns 813 ------- 814 int 815 The mask for the "or"- or "and"-mask 816 """ 817 818 return sum([channel.ch_mask() for channel in self.channels])
a higher-level abstraction of the CardFunctionality class to implement the Card's channel settings
503 def __init__(self, card : Card = None, card_enable : int = None, stack : CardStack = None, stack_enable : list[int] = None) -> None: 504 """ 505 Constructor of the Channels class 506 507 Parameters 508 ---------- 509 card : Card = None 510 The card to be used 511 card_enable : int = None 512 The bitmask to enable specific channels 513 stack : CardStack = None 514 The card stack to be used 515 stack_enable : list[int] = None 516 The list of bitmasks to enable specific channels 517 518 Raises 519 ------ 520 SpcmException 521 No card or card stack provided 522 """ 523 524 self.cards = [] 525 self.channels = [] 526 self.num_channels = [] 527 if card is not None: 528 self.cards.append(card) 529 if card_enable is not None: 530 self.channels_enable(enable_list=[card_enable]) 531 else: 532 self.channels_enable(enable_all=True) 533 elif stack is not None: 534 self.cards = stack.cards 535 if stack_enable is not None: 536 self.channels_enable(enable_list=stack_enable) 537 else: 538 self.channels_enable(enable_all=True) 539 else: 540 raise SpcmException(text="No card or card stack provided")
Constructor of the Channels class
Parameters
- card (Card = None): The card to be used
- card_enable (int = None): The bitmask to enable specific channels
- stack (CardStack = None): The card stack to be used
- stack_enable (list[int] = None): The list of bitmasks to enable specific channels
Raises
- SpcmException: No card or card stack provided
602 def write_setup(self) -> None: 603 """Write the setup to the card""" 604 self.card.write_setup()
Write the setup to the card
606 def channels_enable(self, enable_list : list[int] = None, enable_all : bool = False) -> int: 607 """ 608 Enables or disables the channels of all the available cards (see register `SPC_CHENABLE` in the manual) 609 610 Parameters 611 ---------- 612 enable_list : list[int] = None 613 A list of channels bitmasks to be enable or disable specific channels 614 enable_all : bool = False 615 Enable all the channels 616 617 Returns 618 ------- 619 int 620 A list with items that indicate for each card the number of channels that are enabled, or True to enable all channels. 621 """ 622 623 self.channels = [] 624 self.num_channels = [] 625 num_channels = 0 626 627 if enable_all: 628 for card in self.cards: 629 num_channels = card.num_channels() 630 card.set_i(SPC_CHENABLE, (1 << num_channels) - 1) 631 num_channels = card.get_i(SPC_CHCOUNT) 632 self.num_channels.append(num_channels) 633 for i in range(num_channels): 634 self.channels.append(Channel(i, i, card)) 635 elif enable_list is not None: 636 for enable, card in zip(enable_list, self.cards): 637 card.set_i(SPC_CHENABLE, enable) 638 num_channels = card.get_i(SPC_CHCOUNT) 639 self.num_channels.append(num_channels) 640 counter = 0 641 for i in range(len(bin(enable))): 642 if (enable >> i) & 1: 643 self.channels.append(Channel(i, counter, card)) 644 counter += 1 645 return sum(self.num_channels)
Enables or disables the channels of all the available cards (see register SPC_CHENABLE
in the manual)
Parameters
- enable_list (list[int] = None): A list of channels bitmasks to be enable or disable specific channels
- enable_all (bool = False): Enable all the channels
Returns
- int: A list with items that indicate for each card the number of channels that are enabled, or True to enable all channels.
657 def enable(self, enable : bool) -> None: 658 """ 659 Enables or disables the analog front-end of all channels of the card (see register `SPC_ENABLEOUT` in the manual) 660 661 Parameters 662 ---------- 663 enable : bool 664 Turn-on (True) or off (False) the spezific channel 665 """ 666 667 for channel in self.channels: 668 channel.enable(enable)
Enables or disables the analog front-end of all channels of the card (see register SPC_ENABLEOUT
in the manual)
Parameters
- enable (bool): Turn-on (True) or off (False) the spezific channel
657 def enable(self, enable : bool) -> None: 658 """ 659 Enables or disables the analog front-end of all channels of the card (see register `SPC_ENABLEOUT` in the manual) 660 661 Parameters 662 ---------- 663 enable : bool 664 Turn-on (True) or off (False) the spezific channel 665 """ 666 667 for channel in self.channels: 668 channel.enable(enable)
Enables or disables the analog front-end of all channels of the card (see register SPC_ENABLEOUT
in the manual)
Parameters
- enable (bool): Turn-on (True) or off (False) the spezific channel
671 def path(self, value : int) -> None: 672 """ 673 Sets the input path of the analog front-end of all channels of the card (see register `SPC_PATH` in the manual) 674 675 Parameters 676 ---------- 677 value : int 678 The input path of the specific channel 679 """ 680 681 for channel in self.channels: 682 channel.path(value)
Sets the input path of the analog front-end of all channels of the card (see register SPC_PATH
in the manual)
Parameters
- value (int): The input path of the specific channel
684 def amp(self, value : int) -> None: 685 """ 686 Sets the output/input range (amplitude) of the analog front-end of all channels of the card in mV (see register `SPC_AMP` in the manual) 687 688 Parameters 689 ---------- 690 value : int 691 The output range (amplitude) of all channels in millivolts 692 """ 693 694 for channel in self.channels: 695 channel.amp(value)
Sets the output/input range (amplitude) of the analog front-end of all channels of the card in mV (see register SPC_AMP
in the manual)
Parameters
- value (int): The output range (amplitude) of all channels in millivolts
697 def offset(self, value : int) -> None: 698 """ 699 Sets the offset of the analog front-end of all channels of the card in mV (see register `SPC_OFFSET` in the manual) 700 701 Parameters 702 ---------- 703 value : int 704 The offset of all channels in millivolts 705 """ 706 707 for channel in self.channels: 708 channel.offset(value)
Sets the offset of the analog front-end of all channels of the card in mV (see register SPC_OFFSET
in the manual)
Parameters
- value (int): The offset of all channels in millivolts
710 def termination(self, value : int) -> None: 711 """ 712 Sets the termination of the analog front-end of all channels of the card (see register `SPC_50OHM` in the manual) 713 714 Parameters 715 ---------- 716 value : int 717 The termination of all channels 718 """ 719 720 for channel in self.channels: 721 channel.termination(value)
Sets the termination of the analog front-end of all channels of the card (see register SPC_50OHM
in the manual)
Parameters
- value (int): The termination of all channels
723 def coupling(self, value : int) -> None: 724 """ 725 Sets the coupling of the analog front-end of all channels of the card (see register `SPC_ACDC` in the manual) 726 727 Parameters 728 ---------- 729 value : int 730 The coupling of all channels 731 """ 732 733 for channel in self.channels: 734 channel.coupling(value)
Sets the coupling of the analog front-end of all channels of the card (see register SPC_ACDC
in the manual)
Parameters
- value (int): The coupling of all channels
736 def coupling_offset_compensation(self, value : int) -> None: 737 """ 738 Sets the coupling offset compensation of the analog front-end of all channels of the card (see register `SPC_ACDC_OFFS_COMPENSATION` in the manual) 739 740 Parameters 741 ---------- 742 value : int 743 The coupling offset compensation of all channels 744 """ 745 746 for channel in self.channels: 747 channel.coupling_offset_compensation(value)
Sets the coupling offset compensation of the analog front-end of all channels of the card (see register SPC_ACDC_OFFS_COMPENSATION
in the manual)
Parameters
- value (int): The coupling offset compensation of all channels
749 def filter(self, value : int) -> None: 750 """ 751 Sets the filter of the analog front-end of all channels of the card (see register `SPC_FILTER` in the manual) 752 753 Parameters 754 ---------- 755 value : int 756 The filter of all channels 757 """ 758 759 for channel in self.channels: 760 channel.filter(value)
Sets the filter of the analog front-end of all channels of the card (see register SPC_FILTER
in the manual)
Parameters
- value (int): The filter of all channels
762 def stop_level(self, value : int) -> None: 763 """ 764 Usually the used outputs of the analog generation boards are set to zero level after replay. 765 This is in most cases adequate. In some cases it can be necessary to hold the last sample, 766 to output the maximum positive level or maximum negative level after replay. The stoplevel will 767 stay on the defined level until the next output has been made. With this function 768 you can define the behavior after replay (see register `SPC_CH0_STOPLEVEL` in the manual) 769 770 Parameters 771 ---------- 772 value : int 773 The wanted stop behaviour: 774 """ 775 776 for channel in self.channels: 777 channel.stop_level(value)
Usually the used outputs of the analog generation boards are set to zero level after replay.
This is in most cases adequate. In some cases it can be necessary to hold the last sample,
to output the maximum positive level or maximum negative level after replay. The stoplevel will
stay on the defined level until the next output has been made. With this function
you can define the behavior after replay (see register SPC_CH0_STOPLEVEL
in the manual)
Parameters
- value (int): The wanted stop behaviour:
779 def custom_stop(self, value : int) -> None: 780 """ 781 Allows to define a 16bit wide custom level per channel for the analog output to enter in pauses. The sample format is 782 exactly the same as during replay, as described in the „sample format“ section. 783 When synchronous digital bits are replayed along, the custom level must include these as well and therefore allows to 784 set a custom level for each multi-purpose line separately. (see register `SPC_CH0_CUSTOM_STOP` in the manual) 785 786 Parameters 787 ---------- 788 value : int 789 The custom stop value 790 """ 791 792 for channel in self.channels: 793 channel.custom_stop(value)
Allows to define a 16bit wide custom level per channel for the analog output to enter in pauses. The sample format is
exactly the same as during replay, as described in the „sample format“ section.
When synchronous digital bits are replayed along, the custom level must include these as well and therefore allows to
set a custom level for each multi-purpose line separately. (see register SPC_CH0_CUSTOM_STOP
in the manual)
Parameters
- value (int): The custom stop value
795 def output_load(self, value : pint.Quantity) -> None: 796 """ 797 Sets the electrical load of the user system connect the channel of the card. This is important for the correct 798 calculation of the output power. Typically, the load would be 50 Ohms, but it can be different. 799 800 Parameters 801 ---------- 802 value : pint.Quantity 803 The electrical load connected by the user to the specific channel 804 """ 805 for channel in self.channels: 806 channel.output_load(value)
Sets the electrical load of the user system connect the channel of the card. This is important for the correct calculation of the output power. Typically, the load would be 50 Ohms, but it can be different.
Parameters
- value (pint.Quantity): The electrical load connected by the user to the specific channel
808 def ch_mask(self) -> int: 809 """ 810 Gets mask for the "or"- or "and"-mask 811 812 Returns 813 ------- 814 int 815 The mask for the "or"- or "and"-mask 816 """ 817 818 return sum([channel.ch_mask() for channel in self.channels])
Gets mask for the "or"- or "and"-mask
Returns
- int: The mask for the "or"- or "and"-mask
18class Channel: 19 """A class to represent a channel of a card only used inside the Channels class in the list of channels""" 20 21 card : Card = None 22 index : int = 0 23 data_index : int = 0 24 25 _conversion_amp : pint.Quantity = None 26 _conversion_offset : pint.Quantity = None 27 _output_load : pint.Quantity = None 28 _series_impedance : pint.Quantity = None 29 30 def __init__(self, index : int, data_index : int, card : Card) -> None: 31 """ 32 Constructor of the Channel class 33 34 Parameters 35 ---------- 36 index : int 37 The index of the channel 38 card : Card 39 The card of the channel 40 """ 41 42 self.card = card 43 self.index = index 44 self.data_index = data_index 45 self._conversion_amp = None 46 self._conversion_offset = 0 * units.percent 47 self._output_load = 50 * units.ohm 48 self._series_impedance = 50 * units.ohm 49 50 def __str__(self) -> str: 51 """ 52 String representation of the Channel class 53 54 Returns 55 ------- 56 str 57 String representation of the Channel class 58 """ 59 60 return f"Channel {self.index}" 61 62 __repr__ = __str__ 63 64 def __int__(self) -> int: 65 """ 66 The Channel object acts like an int and returns the index of the channel and can also be used as the index in an array 67 68 Returns 69 ------- 70 int 71 The index of the channel 72 """ 73 return self.data_index 74 __index__ = __int__ 75 76 def __add__(self, other): 77 """ 78 The Channel object again acts like an int and returns the index of the channel plus the other value 79 80 Parameters 81 ---------- 82 other : int or float 83 The value to be added to the index of the channel 84 85 Returns 86 ------- 87 int or float 88 The index of the channel plus the other value 89 """ 90 return self.index + other 91 92 def enable(self, enable : bool = None) -> bool: 93 """ 94 Enables the analog front-end of the channel of the card (see register `SPC_ENABLEOUT` in the manual) 95 96 Parameters 97 ---------- 98 enable : bool 99 Turn-on (True) or off (False) the spezific channel 100 101 Returns 102 ------- 103 bool 104 The enable state of the specific channel 105 """ 106 107 if enable is not None: 108 self.card.set_i(SPC_ENABLEOUT0 + (SPC_ENABLEOUT1 - SPC_ENABLEOUT0) * self.index, int(enable)) 109 return bool(self.card.get_i(SPC_ENABLEOUT0 + (SPC_ENABLEOUT1 - SPC_ENABLEOUT0) * self.index)) 110 enable_out = enable 111 112 def path(self, value : int = None) -> int: 113 """ 114 Sets the input path of the channel of the card (see register `SPC_PATH0` in the manual) 115 116 Parameters 117 ---------- 118 value : int 119 The input path of the specific channel 120 121 Returns 122 ------- 123 int 124 The input path of the specific channel 125 """ 126 127 if value is not None: 128 self.card.set_i(SPC_PATH0 + (SPC_PATH1 - SPC_PATH0) * self.index, value) 129 return self.card.get_i(SPC_PATH0 + (SPC_PATH1 - SPC_PATH0) * self.index) 130 131 def amp(self, value : int = None, return_unit = None) -> int: 132 """ 133 Sets the output/input range (amplitude) of the analog front-end of the channel of the card in mV (see register `SPC_AMP` in the manual) 134 135 Parameters 136 ---------- 137 value : int 138 The output range (amplitude) of the specific channel in millivolts 139 unit : pint.Unit = None 140 The unit of the return value 141 142 Returns 143 ------- 144 int | pint.Quantity 145 The output range (amplitude) of the specific channel in millivolts or the unit specified 146 """ 147 148 if value is not None: 149 if isinstance(value, pint.Quantity): 150 value = self.voltage_conversion(value) 151 self._conversion_amp = UnitConversion.force_unit(value, units.mV) 152 value = UnitConversion.convert(value, units.mV, int) 153 self.card.set_i(SPC_AMP0 + (SPC_AMP1 - SPC_AMP0) * self.index, value) 154 value = self.card.get_i(SPC_AMP0 + (SPC_AMP1 - SPC_AMP0) * self.index) 155 value = UnitConversion.to_unit(value * units.mV, return_unit) 156 return value 157 158 def offset(self, value : int = None, return_unit = None) -> int: 159 """ 160 Sets the offset of the analog front-end of the channel of the card in % of the full range o rmV (see register `SPC_OFFS0` in the manual) 161 If the value is given and has a unit, then this unit is converted to the unit of the card (mV or %) 162 163 Parameters 164 ---------- 165 value : int | pint.Quantity = None 166 The offset of the specific channel as integer in % or as a Quantity in % or mV 167 unit : pint.Unit = None 168 The unit of the return value 169 170 Returns 171 ------- 172 int | pint.Quantity 173 The offset of the specific channel in % or the unit specified by return_unit 174 """ 175 176 # Analog in cards are programmed in percent of the full range and analog output cards in mV (in the M2p, M4i/x and M5i families) 177 card_unit = 1 178 fnc_type = self.card.function_type() 179 if fnc_type == SPCM_TYPE_AI: 180 card_unit = units.percent 181 elif fnc_type == SPCM_TYPE_AO: 182 card_unit = units.mV 183 184 if value is not None: 185 # The user gives a value as a Quantity 186 if isinstance(value, pint.Quantity): 187 if fnc_type == SPCM_TYPE_AO: 188 # The card expects a value in mV 189 if value.check('[]'): 190 # Convert from percent to mV 191 value = (value * self._conversion_amp).to(card_unit) 192 else: 193 value = value.to(card_unit) 194 elif fnc_type == SPCM_TYPE_AI: 195 # The card expects a value in percent 196 if value.check('[electric_potential]'): 197 # Convert from mV to percent 198 value = (value / self._conversion_amp).to(card_unit) 199 else: 200 value = value.to(card_unit) 201 else: 202 # Value is given as a number 203 pass 204 205 value = UnitConversion.convert(value, card_unit, int) 206 self.card.set_i(SPC_OFFS0 + (SPC_OFFS1 - SPC_OFFS0) * self.index, value) 207 208 return_value = self.card.get_i(SPC_OFFS0 + (SPC_OFFS1 - SPC_OFFS0) * self.index) 209 # Turn the return value into a quantity 210 return_quantity = UnitConversion.to_unit(return_value, return_unit) 211 # Save the conversion offset to be able to convert the data to a quantity with the correct unit 212 self._conversion_offset = UnitConversion.force_unit(return_value, card_unit) 213 return return_quantity 214 215 def convert_data(self, data : npt.NDArray, return_unit : pint.Unit = units.mV) -> npt.NDArray: 216 """ 217 Converts the data to the correct unit in units of electrical potential 218 219 Parameters 220 ---------- 221 data : numpy.ndarray 222 The data to be converted 223 return_unit : pint.Unit = None 224 The unit of the return value 225 226 Returns 227 ------- 228 numpy.ndarray 229 The converted data in units of electrical potential 230 """ 231 232 max_value = self.card.max_sample_value() 233 if self._conversion_offset.check('[]'): 234 return_data = (data / max_value - self._conversion_offset) * self._conversion_amp 235 else: 236 return_data = (data / max_value) * self._conversion_amp - self._conversion_offset 237 return_data = UnitConversion.to_unit(return_data, return_unit) 238 return return_data 239 240 def reconvert_data(self, data : npt.NDArray) -> npt.NDArray: 241 """ 242 Convert data with units back to integer values in units of electrical potential 243 244 Parameters 245 ---------- 246 data : numpy.ndarray 247 The data to be reconverted 248 249 Returns 250 ------- 251 numpy.ndarray 252 The reconverted data as integer in mV 253 """ 254 255 if self._conversion_offset.check('[]'): 256 return_data = int((data / self._conversion_amp + self._conversion_offset) * self.card.max_sample_value()) 257 else: 258 return_data = int(((data + self._conversion_offset) / self._conversion_amp) * self.card.max_sample_value()) 259 return return_data 260 261 def termination(self, value : int) -> None: 262 """ 263 Sets the termination of the analog front-end of the channel of the card (see register `SPC_50OHM0` in the manual) 264 265 Parameters 266 ---------- 267 value : int | bool 268 The termination of the specific channel 269 """ 270 271 self.card.set_i(SPC_50OHM0 + (SPC_50OHM1 - SPC_50OHM0) * self.index, int(value)) 272 273 def get_termination(self) -> int: 274 """ 275 Gets the termination of the analog front-end of the channel of the card (see register `SPC_50OHM0` in the manual) 276 277 Returns 278 ------- 279 int 280 The termination of the specific channel 281 """ 282 283 return self.card.get_i(SPC_50OHM0 + (SPC_50OHM1 - SPC_50OHM0) * self.index) 284 285 def coupling(self, value : int = None) -> int: 286 """ 287 Sets the coupling of the analog front-end of the channel of the card (see register `SPC_ACDC0` in the manual) 288 289 Parameters 290 ---------- 291 value : int 292 The coupling of the specific channel 293 294 Returns 295 ------- 296 int 297 The coupling of the specific channel 298 """ 299 300 if value is not None: 301 self.card.set_i(SPC_ACDC0 + (SPC_ACDC1 - SPC_ACDC0) * self.index, value) 302 return self.card.get_i(SPC_ACDC0 + (SPC_ACDC1 - SPC_ACDC0) * self.index) 303 304 def coupling_offset_compensation(self, value : int = None) -> int: 305 """ 306 Enables or disables the coupling offset compensation of the analog front-end of the channel of the card (see register `SPC_ACDC_OFFS_COMPENSATION0` in the manual) 307 308 Parameters 309 ---------- 310 value : int 311 Enables the coupling offset compensation of the specific channel 312 313 Returns 314 ------- 315 int 316 return if the coupling offset compensation of the specific channel is enabled ("1") or disabled ("0") 317 """ 318 319 if value is not None: 320 self.card.set_i(SPC_ACDC_OFFS_COMPENSATION0 + (SPC_ACDC_OFFS_COMPENSATION1 - SPC_ACDC_OFFS_COMPENSATION0) * self.index, value) 321 return self.card.get_i(SPC_ACDC_OFFS_COMPENSATION0 + (SPC_ACDC_OFFS_COMPENSATION1 - SPC_ACDC_OFFS_COMPENSATION0) * self.index) 322 323 def filter(self, value : int = None) -> int: 324 """ 325 Sets the filter of the analog front-end of the channel of the card (see register `SPC_FILTER0` in the manual) 326 327 Parameters 328 ---------- 329 value : int 330 The filter of the specific channel 331 332 Returns 333 ------- 334 int 335 The filter of the specific channel 336 """ 337 338 if value is not None: 339 self.card.set_i(SPC_FILTER0 + (SPC_FILTER1 - SPC_FILTER0) * self.index, value) 340 return self.card.get_i(SPC_FILTER0 + (SPC_FILTER1 - SPC_FILTER0) * self.index) 341 342 def stop_level(self, value : int = None) -> int: 343 """ 344 Usually the used outputs of the analog generation boards are set to zero level after replay. 345 This is in most cases adequate. In some cases it can be necessary to hold the last sample, 346 to output the maximum positive level or maximum negative level after replay. The stoplevel will 347 stay on the defined level until the next output has been made. With this function 348 you can define the behavior after replay (see register `SPC_CH0_STOPLEVEL` in the manual) 349 350 Parameters 351 ---------- 352 value : int 353 The wanted stop behaviour 354 355 Returns 356 ------- 357 int 358 The stop behaviour of the specific channel 359 """ 360 361 if value is not None: 362 self.card.set_i(SPC_CH0_STOPLEVEL + self.index * (SPC_CH1_STOPLEVEL - SPC_CH0_STOPLEVEL), value) 363 return self.card.get_i(SPC_CH0_STOPLEVEL + self.index * (SPC_CH1_STOPLEVEL - SPC_CH0_STOPLEVEL)) 364 365 def custom_stop(self, value : int = None) -> int: 366 """ 367 Allows to define a 16bit wide custom level per channel for the analog output to enter in pauses. The sample format is 368 exactly the same as during replay, as described in the „sample format“ section. 369 When synchronous digital bits are replayed along, the custom level must include these as well and therefore allows to 370 set a custom level for each multi-purpose line separately. (see register `SPC_CH0_CUSTOM_STOP` in the manual) 371 372 Parameters 373 ---------- 374 value : int 375 The custom stop value 376 377 Returns 378 ------- 379 int 380 The custom stop value of the specific channel 381 382 TODO: change this to a specific unit? 383 """ 384 385 if value is not None: 386 self.card.set_i(SPC_CH0_CUSTOM_STOP + self.index * (SPC_CH1_CUSTOM_STOP - SPC_CH0_CUSTOM_STOP), value) 387 return self.card.get_i(SPC_CH0_CUSTOM_STOP + self.index * (SPC_CH1_CUSTOM_STOP - SPC_CH0_CUSTOM_STOP)) 388 389 def ch_mask(self) -> int: 390 """ 391 Gets mask for the "or"- or "and"-mask 392 393 Returns 394 ------- 395 int 396 The mask for the "or"- or "and"-mask 397 """ 398 399 return 1 << self.index 400 401 def output_load(self, value : pint.Quantity = None) -> pint.Quantity: 402 """ 403 Sets the electrical load of the user system connect the channel of the card. This is important for the correct 404 calculation of the output power. Typically, the load would be 50 Ohms, but it can be different. 405 406 Parameters 407 ---------- 408 value : pint.Quantity 409 The electrical load connected by the user to the specific channel 410 411 Returns 412 ------- 413 pint.Quantity 414 The electrical load connected by the user to the specific channel 415 """ 416 if value is not None: 417 self._output_load = value 418 return self._output_load 419 420 def voltage_conversion(self, value : pint.Quantity) -> pint.Quantity: 421 """ 422 Convert the voltage that is needed at a certain output load to the voltage setting of the card if the load would be 50 Ohm 423 424 Parameters 425 ---------- 426 value : pint.Quantity 427 The voltage that is needed at a certain output load 428 429 Returns 430 ------- 431 pint.Quantity 432 The corresponding voltage at an output load of 50 Ohm 433 """ 434 435 # The two at the end is because the value expected by the card is defined for a 50 Ohm load 436 if self._output_load == np.inf * units.ohm: 437 return value / 2 438 return value / (self._output_load / (self._output_load + self._series_impedance)) / 2 439 440 def to_amplitude_fraction(self, value) -> float: 441 """ 442 Convert the voltage, percentage or power to percentage of the full range of the card 443 444 Parameters 445 ---------- 446 value : pint.Quantity | float 447 The voltage that should be outputted at a certain output load 448 449 Returns 450 ------- 451 float 452 The corresponding fraction of the full range of the card 453 """ 454 455 if isinstance(value, units.Quantity) and value.check("[power]"): 456 # U_pk = U_rms * sqrt(2) 457 value = np.sqrt(2 * value.to('mW') * self._output_load) / self._conversion_amp * 100 * units.percent 458 elif isinstance(value, units.Quantity) and value.check("[electric_potential]"): 459 # value in U_pk 460 value = self.voltage_conversion(value) / self._conversion_amp * 100 * units.percent 461 value = UnitConversion.convert(value, units.fraction, float, rounding=None) 462 return value 463 464 def from_amplitude_fraction(self, fraction, return_unit : pint.Quantity = None) -> pint.Quantity: 465 """ 466 Convert the percentage of the full range to voltage, percentage or power 467 468 Parameters 469 ---------- 470 fraction : float 471 The percentage of the full range of the card 472 return_unit : pint.Quantity 473 The unit of the return value 474 475 Returns 476 ------- 477 pint.Quantity 478 The corresponding voltage, percentage or power 479 """ 480 481 return_value = fraction 482 if isinstance(return_unit, units.Unit) and (1*return_unit).check("[power]"): 483 return_value = (np.power(self._conversion_amp * fraction, 2) / self._output_load / 2).to(return_unit) 484 # U_pk = U_rms * sqrt(2) 485 elif isinstance(return_unit, units.Unit) and (1*return_unit).check("[electric_potential]"): 486 return_value = (self._conversion_amp * fraction / 100).to(return_unit) 487 # value in U_pk 488 # value = self.voltage_conversion(value) / self._conversion_amp * 100 * units.percent 489 elif isinstance(return_unit, units.Unit) and (1*return_unit).check("[]"): 490 return_value = UnitConversion.force_unit(fraction, return_unit) 491 return return_value
A class to represent a channel of a card only used inside the Channels class in the list of channels
30 def __init__(self, index : int, data_index : int, card : Card) -> None: 31 """ 32 Constructor of the Channel class 33 34 Parameters 35 ---------- 36 index : int 37 The index of the channel 38 card : Card 39 The card of the channel 40 """ 41 42 self.card = card 43 self.index = index 44 self.data_index = data_index 45 self._conversion_amp = None 46 self._conversion_offset = 0 * units.percent 47 self._output_load = 50 * units.ohm 48 self._series_impedance = 50 * units.ohm
Constructor of the Channel class
Parameters
- index (int): The index of the channel
- card (Card): The card of the channel
92 def enable(self, enable : bool = None) -> bool: 93 """ 94 Enables the analog front-end of the channel of the card (see register `SPC_ENABLEOUT` in the manual) 95 96 Parameters 97 ---------- 98 enable : bool 99 Turn-on (True) or off (False) the spezific channel 100 101 Returns 102 ------- 103 bool 104 The enable state of the specific channel 105 """ 106 107 if enable is not None: 108 self.card.set_i(SPC_ENABLEOUT0 + (SPC_ENABLEOUT1 - SPC_ENABLEOUT0) * self.index, int(enable)) 109 return bool(self.card.get_i(SPC_ENABLEOUT0 + (SPC_ENABLEOUT1 - SPC_ENABLEOUT0) * self.index))
Enables the analog front-end of the channel of the card (see register SPC_ENABLEOUT
in the manual)
Parameters
- enable (bool): Turn-on (True) or off (False) the spezific channel
Returns
- bool: The enable state of the specific channel
92 def enable(self, enable : bool = None) -> bool: 93 """ 94 Enables the analog front-end of the channel of the card (see register `SPC_ENABLEOUT` in the manual) 95 96 Parameters 97 ---------- 98 enable : bool 99 Turn-on (True) or off (False) the spezific channel 100 101 Returns 102 ------- 103 bool 104 The enable state of the specific channel 105 """ 106 107 if enable is not None: 108 self.card.set_i(SPC_ENABLEOUT0 + (SPC_ENABLEOUT1 - SPC_ENABLEOUT0) * self.index, int(enable)) 109 return bool(self.card.get_i(SPC_ENABLEOUT0 + (SPC_ENABLEOUT1 - SPC_ENABLEOUT0) * self.index))
Enables the analog front-end of the channel of the card (see register SPC_ENABLEOUT
in the manual)
Parameters
- enable (bool): Turn-on (True) or off (False) the spezific channel
Returns
- bool: The enable state of the specific channel
112 def path(self, value : int = None) -> int: 113 """ 114 Sets the input path of the channel of the card (see register `SPC_PATH0` in the manual) 115 116 Parameters 117 ---------- 118 value : int 119 The input path of the specific channel 120 121 Returns 122 ------- 123 int 124 The input path of the specific channel 125 """ 126 127 if value is not None: 128 self.card.set_i(SPC_PATH0 + (SPC_PATH1 - SPC_PATH0) * self.index, value) 129 return self.card.get_i(SPC_PATH0 + (SPC_PATH1 - SPC_PATH0) * self.index)
Sets the input path of the channel of the card (see register SPC_PATH0
in the manual)
Parameters
- value (int): The input path of the specific channel
Returns
- int: The input path of the specific channel
131 def amp(self, value : int = None, return_unit = None) -> int: 132 """ 133 Sets the output/input range (amplitude) of the analog front-end of the channel of the card in mV (see register `SPC_AMP` in the manual) 134 135 Parameters 136 ---------- 137 value : int 138 The output range (amplitude) of the specific channel in millivolts 139 unit : pint.Unit = None 140 The unit of the return value 141 142 Returns 143 ------- 144 int | pint.Quantity 145 The output range (amplitude) of the specific channel in millivolts or the unit specified 146 """ 147 148 if value is not None: 149 if isinstance(value, pint.Quantity): 150 value = self.voltage_conversion(value) 151 self._conversion_amp = UnitConversion.force_unit(value, units.mV) 152 value = UnitConversion.convert(value, units.mV, int) 153 self.card.set_i(SPC_AMP0 + (SPC_AMP1 - SPC_AMP0) * self.index, value) 154 value = self.card.get_i(SPC_AMP0 + (SPC_AMP1 - SPC_AMP0) * self.index) 155 value = UnitConversion.to_unit(value * units.mV, return_unit) 156 return value
Sets the output/input range (amplitude) of the analog front-end of the channel of the card in mV (see register SPC_AMP
in the manual)
Parameters
- value (int): The output range (amplitude) of the specific channel in millivolts
- unit (pint.Unit = None): The unit of the return value
Returns
- int | pint.Quantity: The output range (amplitude) of the specific channel in millivolts or the unit specified
158 def offset(self, value : int = None, return_unit = None) -> int: 159 """ 160 Sets the offset of the analog front-end of the channel of the card in % of the full range o rmV (see register `SPC_OFFS0` in the manual) 161 If the value is given and has a unit, then this unit is converted to the unit of the card (mV or %) 162 163 Parameters 164 ---------- 165 value : int | pint.Quantity = None 166 The offset of the specific channel as integer in % or as a Quantity in % or mV 167 unit : pint.Unit = None 168 The unit of the return value 169 170 Returns 171 ------- 172 int | pint.Quantity 173 The offset of the specific channel in % or the unit specified by return_unit 174 """ 175 176 # Analog in cards are programmed in percent of the full range and analog output cards in mV (in the M2p, M4i/x and M5i families) 177 card_unit = 1 178 fnc_type = self.card.function_type() 179 if fnc_type == SPCM_TYPE_AI: 180 card_unit = units.percent 181 elif fnc_type == SPCM_TYPE_AO: 182 card_unit = units.mV 183 184 if value is not None: 185 # The user gives a value as a Quantity 186 if isinstance(value, pint.Quantity): 187 if fnc_type == SPCM_TYPE_AO: 188 # The card expects a value in mV 189 if value.check('[]'): 190 # Convert from percent to mV 191 value = (value * self._conversion_amp).to(card_unit) 192 else: 193 value = value.to(card_unit) 194 elif fnc_type == SPCM_TYPE_AI: 195 # The card expects a value in percent 196 if value.check('[electric_potential]'): 197 # Convert from mV to percent 198 value = (value / self._conversion_amp).to(card_unit) 199 else: 200 value = value.to(card_unit) 201 else: 202 # Value is given as a number 203 pass 204 205 value = UnitConversion.convert(value, card_unit, int) 206 self.card.set_i(SPC_OFFS0 + (SPC_OFFS1 - SPC_OFFS0) * self.index, value) 207 208 return_value = self.card.get_i(SPC_OFFS0 + (SPC_OFFS1 - SPC_OFFS0) * self.index) 209 # Turn the return value into a quantity 210 return_quantity = UnitConversion.to_unit(return_value, return_unit) 211 # Save the conversion offset to be able to convert the data to a quantity with the correct unit 212 self._conversion_offset = UnitConversion.force_unit(return_value, card_unit) 213 return return_quantity
Sets the offset of the analog front-end of the channel of the card in % of the full range o rmV (see register SPC_OFFS0
in the manual)
If the value is given and has a unit, then this unit is converted to the unit of the card (mV or %)
Parameters
- value (int | pint.Quantity = None): The offset of the specific channel as integer in % or as a Quantity in % or mV
- unit (pint.Unit = None): The unit of the return value
Returns
- int | pint.Quantity: The offset of the specific channel in % or the unit specified by return_unit
215 def convert_data(self, data : npt.NDArray, return_unit : pint.Unit = units.mV) -> npt.NDArray: 216 """ 217 Converts the data to the correct unit in units of electrical potential 218 219 Parameters 220 ---------- 221 data : numpy.ndarray 222 The data to be converted 223 return_unit : pint.Unit = None 224 The unit of the return value 225 226 Returns 227 ------- 228 numpy.ndarray 229 The converted data in units of electrical potential 230 """ 231 232 max_value = self.card.max_sample_value() 233 if self._conversion_offset.check('[]'): 234 return_data = (data / max_value - self._conversion_offset) * self._conversion_amp 235 else: 236 return_data = (data / max_value) * self._conversion_amp - self._conversion_offset 237 return_data = UnitConversion.to_unit(return_data, return_unit) 238 return return_data
Converts the data to the correct unit in units of electrical potential
Parameters
- data (numpy.ndarray): The data to be converted
- return_unit (pint.Unit = None): The unit of the return value
Returns
- numpy.ndarray: The converted data in units of electrical potential
240 def reconvert_data(self, data : npt.NDArray) -> npt.NDArray: 241 """ 242 Convert data with units back to integer values in units of electrical potential 243 244 Parameters 245 ---------- 246 data : numpy.ndarray 247 The data to be reconverted 248 249 Returns 250 ------- 251 numpy.ndarray 252 The reconverted data as integer in mV 253 """ 254 255 if self._conversion_offset.check('[]'): 256 return_data = int((data / self._conversion_amp + self._conversion_offset) * self.card.max_sample_value()) 257 else: 258 return_data = int(((data + self._conversion_offset) / self._conversion_amp) * self.card.max_sample_value()) 259 return return_data
Convert data with units back to integer values in units of electrical potential
Parameters
- data (numpy.ndarray): The data to be reconverted
Returns
- numpy.ndarray: The reconverted data as integer in mV
261 def termination(self, value : int) -> None: 262 """ 263 Sets the termination of the analog front-end of the channel of the card (see register `SPC_50OHM0` in the manual) 264 265 Parameters 266 ---------- 267 value : int | bool 268 The termination of the specific channel 269 """ 270 271 self.card.set_i(SPC_50OHM0 + (SPC_50OHM1 - SPC_50OHM0) * self.index, int(value))
Sets the termination of the analog front-end of the channel of the card (see register SPC_50OHM0
in the manual)
Parameters
- value (int | bool): The termination of the specific channel
273 def get_termination(self) -> int: 274 """ 275 Gets the termination of the analog front-end of the channel of the card (see register `SPC_50OHM0` in the manual) 276 277 Returns 278 ------- 279 int 280 The termination of the specific channel 281 """ 282 283 return self.card.get_i(SPC_50OHM0 + (SPC_50OHM1 - SPC_50OHM0) * self.index)
Gets the termination of the analog front-end of the channel of the card (see register SPC_50OHM0
in the manual)
Returns
- int: The termination of the specific channel
285 def coupling(self, value : int = None) -> int: 286 """ 287 Sets the coupling of the analog front-end of the channel of the card (see register `SPC_ACDC0` in the manual) 288 289 Parameters 290 ---------- 291 value : int 292 The coupling of the specific channel 293 294 Returns 295 ------- 296 int 297 The coupling of the specific channel 298 """ 299 300 if value is not None: 301 self.card.set_i(SPC_ACDC0 + (SPC_ACDC1 - SPC_ACDC0) * self.index, value) 302 return self.card.get_i(SPC_ACDC0 + (SPC_ACDC1 - SPC_ACDC0) * self.index)
Sets the coupling of the analog front-end of the channel of the card (see register SPC_ACDC0
in the manual)
Parameters
- value (int): The coupling of the specific channel
Returns
- int: The coupling of the specific channel
304 def coupling_offset_compensation(self, value : int = None) -> int: 305 """ 306 Enables or disables the coupling offset compensation of the analog front-end of the channel of the card (see register `SPC_ACDC_OFFS_COMPENSATION0` in the manual) 307 308 Parameters 309 ---------- 310 value : int 311 Enables the coupling offset compensation of the specific channel 312 313 Returns 314 ------- 315 int 316 return if the coupling offset compensation of the specific channel is enabled ("1") or disabled ("0") 317 """ 318 319 if value is not None: 320 self.card.set_i(SPC_ACDC_OFFS_COMPENSATION0 + (SPC_ACDC_OFFS_COMPENSATION1 - SPC_ACDC_OFFS_COMPENSATION0) * self.index, value) 321 return self.card.get_i(SPC_ACDC_OFFS_COMPENSATION0 + (SPC_ACDC_OFFS_COMPENSATION1 - SPC_ACDC_OFFS_COMPENSATION0) * self.index)
Enables or disables the coupling offset compensation of the analog front-end of the channel of the card (see register SPC_ACDC_OFFS_COMPENSATION0
in the manual)
Parameters
- value (int): Enables the coupling offset compensation of the specific channel
Returns
- int: return if the coupling offset compensation of the specific channel is enabled ("1") or disabled ("0")
323 def filter(self, value : int = None) -> int: 324 """ 325 Sets the filter of the analog front-end of the channel of the card (see register `SPC_FILTER0` in the manual) 326 327 Parameters 328 ---------- 329 value : int 330 The filter of the specific channel 331 332 Returns 333 ------- 334 int 335 The filter of the specific channel 336 """ 337 338 if value is not None: 339 self.card.set_i(SPC_FILTER0 + (SPC_FILTER1 - SPC_FILTER0) * self.index, value) 340 return self.card.get_i(SPC_FILTER0 + (SPC_FILTER1 - SPC_FILTER0) * self.index)
Sets the filter of the analog front-end of the channel of the card (see register SPC_FILTER0
in the manual)
Parameters
- value (int): The filter of the specific channel
Returns
- int: The filter of the specific channel
342 def stop_level(self, value : int = None) -> int: 343 """ 344 Usually the used outputs of the analog generation boards are set to zero level after replay. 345 This is in most cases adequate. In some cases it can be necessary to hold the last sample, 346 to output the maximum positive level or maximum negative level after replay. The stoplevel will 347 stay on the defined level until the next output has been made. With this function 348 you can define the behavior after replay (see register `SPC_CH0_STOPLEVEL` in the manual) 349 350 Parameters 351 ---------- 352 value : int 353 The wanted stop behaviour 354 355 Returns 356 ------- 357 int 358 The stop behaviour of the specific channel 359 """ 360 361 if value is not None: 362 self.card.set_i(SPC_CH0_STOPLEVEL + self.index * (SPC_CH1_STOPLEVEL - SPC_CH0_STOPLEVEL), value) 363 return self.card.get_i(SPC_CH0_STOPLEVEL + self.index * (SPC_CH1_STOPLEVEL - SPC_CH0_STOPLEVEL))
Usually the used outputs of the analog generation boards are set to zero level after replay.
This is in most cases adequate. In some cases it can be necessary to hold the last sample,
to output the maximum positive level or maximum negative level after replay. The stoplevel will
stay on the defined level until the next output has been made. With this function
you can define the behavior after replay (see register SPC_CH0_STOPLEVEL
in the manual)
Parameters
- value (int): The wanted stop behaviour
Returns
- int: The stop behaviour of the specific channel
365 def custom_stop(self, value : int = None) -> int: 366 """ 367 Allows to define a 16bit wide custom level per channel for the analog output to enter in pauses. The sample format is 368 exactly the same as during replay, as described in the „sample format“ section. 369 When synchronous digital bits are replayed along, the custom level must include these as well and therefore allows to 370 set a custom level for each multi-purpose line separately. (see register `SPC_CH0_CUSTOM_STOP` in the manual) 371 372 Parameters 373 ---------- 374 value : int 375 The custom stop value 376 377 Returns 378 ------- 379 int 380 The custom stop value of the specific channel 381 382 TODO: change this to a specific unit? 383 """ 384 385 if value is not None: 386 self.card.set_i(SPC_CH0_CUSTOM_STOP + self.index * (SPC_CH1_CUSTOM_STOP - SPC_CH0_CUSTOM_STOP), value) 387 return self.card.get_i(SPC_CH0_CUSTOM_STOP + self.index * (SPC_CH1_CUSTOM_STOP - SPC_CH0_CUSTOM_STOP))
Allows to define a 16bit wide custom level per channel for the analog output to enter in pauses. The sample format is
exactly the same as during replay, as described in the „sample format“ section.
When synchronous digital bits are replayed along, the custom level must include these as well and therefore allows to
set a custom level for each multi-purpose line separately. (see register SPC_CH0_CUSTOM_STOP
in the manual)
Parameters
- value (int): The custom stop value
Returns
- int: The custom stop value of the specific channel
- TODO (change this to a specific unit?):
389 def ch_mask(self) -> int: 390 """ 391 Gets mask for the "or"- or "and"-mask 392 393 Returns 394 ------- 395 int 396 The mask for the "or"- or "and"-mask 397 """ 398 399 return 1 << self.index
Gets mask for the "or"- or "and"-mask
Returns
- int: The mask for the "or"- or "and"-mask
401 def output_load(self, value : pint.Quantity = None) -> pint.Quantity: 402 """ 403 Sets the electrical load of the user system connect the channel of the card. This is important for the correct 404 calculation of the output power. Typically, the load would be 50 Ohms, but it can be different. 405 406 Parameters 407 ---------- 408 value : pint.Quantity 409 The electrical load connected by the user to the specific channel 410 411 Returns 412 ------- 413 pint.Quantity 414 The electrical load connected by the user to the specific channel 415 """ 416 if value is not None: 417 self._output_load = value 418 return self._output_load
Sets the electrical load of the user system connect the channel of the card. This is important for the correct calculation of the output power. Typically, the load would be 50 Ohms, but it can be different.
Parameters
- value (pint.Quantity): The electrical load connected by the user to the specific channel
Returns
- pint.Quantity: The electrical load connected by the user to the specific channel
420 def voltage_conversion(self, value : pint.Quantity) -> pint.Quantity: 421 """ 422 Convert the voltage that is needed at a certain output load to the voltage setting of the card if the load would be 50 Ohm 423 424 Parameters 425 ---------- 426 value : pint.Quantity 427 The voltage that is needed at a certain output load 428 429 Returns 430 ------- 431 pint.Quantity 432 The corresponding voltage at an output load of 50 Ohm 433 """ 434 435 # The two at the end is because the value expected by the card is defined for a 50 Ohm load 436 if self._output_load == np.inf * units.ohm: 437 return value / 2 438 return value / (self._output_load / (self._output_load + self._series_impedance)) / 2
Convert the voltage that is needed at a certain output load to the voltage setting of the card if the load would be 50 Ohm
Parameters
- value (pint.Quantity): The voltage that is needed at a certain output load
Returns
- pint.Quantity: The corresponding voltage at an output load of 50 Ohm
440 def to_amplitude_fraction(self, value) -> float: 441 """ 442 Convert the voltage, percentage or power to percentage of the full range of the card 443 444 Parameters 445 ---------- 446 value : pint.Quantity | float 447 The voltage that should be outputted at a certain output load 448 449 Returns 450 ------- 451 float 452 The corresponding fraction of the full range of the card 453 """ 454 455 if isinstance(value, units.Quantity) and value.check("[power]"): 456 # U_pk = U_rms * sqrt(2) 457 value = np.sqrt(2 * value.to('mW') * self._output_load) / self._conversion_amp * 100 * units.percent 458 elif isinstance(value, units.Quantity) and value.check("[electric_potential]"): 459 # value in U_pk 460 value = self.voltage_conversion(value) / self._conversion_amp * 100 * units.percent 461 value = UnitConversion.convert(value, units.fraction, float, rounding=None) 462 return value
Convert the voltage, percentage or power to percentage of the full range of the card
Parameters
- value (pint.Quantity | float): The voltage that should be outputted at a certain output load
Returns
- float: The corresponding fraction of the full range of the card
464 def from_amplitude_fraction(self, fraction, return_unit : pint.Quantity = None) -> pint.Quantity: 465 """ 466 Convert the percentage of the full range to voltage, percentage or power 467 468 Parameters 469 ---------- 470 fraction : float 471 The percentage of the full range of the card 472 return_unit : pint.Quantity 473 The unit of the return value 474 475 Returns 476 ------- 477 pint.Quantity 478 The corresponding voltage, percentage or power 479 """ 480 481 return_value = fraction 482 if isinstance(return_unit, units.Unit) and (1*return_unit).check("[power]"): 483 return_value = (np.power(self._conversion_amp * fraction, 2) / self._output_load / 2).to(return_unit) 484 # U_pk = U_rms * sqrt(2) 485 elif isinstance(return_unit, units.Unit) and (1*return_unit).check("[electric_potential]"): 486 return_value = (self._conversion_amp * fraction / 100).to(return_unit) 487 # value in U_pk 488 # value = self.voltage_conversion(value) / self._conversion_amp * 100 * units.percent 489 elif isinstance(return_unit, units.Unit) and (1*return_unit).check("[]"): 490 return_value = UnitConversion.force_unit(fraction, return_unit) 491 return return_value
Convert the percentage of the full range to voltage, percentage or power
Parameters
- fraction (float): The percentage of the full range of the card
- return_unit (pint.Quantity): The unit of the return value
Returns
- pint.Quantity: The corresponding voltage, percentage or power
12class Clock(CardFunctionality): 13 """a higher-level abstraction of the CardFunctionality class to implement the Card's clock engine""" 14 15 def __str__(self) -> str: 16 """ 17 String representation of the Clock class 18 19 Returns 20 ------- 21 str 22 String representation of the Clock class 23 """ 24 25 return f"Clock(card={self.card})" 26 27 __repr__ = __str__ 28 29 def write_setup(self) -> None: 30 """Write the setup to the card""" 31 self.card.write_setup() 32 33 34 def mode(self, mode : int = None) -> int: 35 """ 36 Set the clock mode of the card (see register `SPC_CLOCKMODE` in the manual) 37 38 Parameters 39 ---------- 40 mode : int 41 The clock mode of the card 42 43 Returns 44 ------- 45 int 46 The clock mode of the card 47 """ 48 49 if mode is not None: 50 self.card.set_i(SPC_CLOCKMODE, mode) 51 return self.card.get_i(SPC_CLOCKMODE) 52 53 def max_sample_rate(self, return_unit = None) -> int: 54 """ 55 Returns the maximum sample rate of the active card (see register `SPC_MIINST_MAXADCLOCK` in the manual) 56 57 Returns 58 ------- 59 int 60 """ 61 62 max_sr = self.card.get_i(SPC_MIINST_MAXADCLOCK) 63 if return_unit is not None: max_sr = UnitConversion.to_unit(max_sr * units.Hz, return_unit) 64 return max_sr 65 66 def sample_rate(self, sample_rate = 0, max : bool = False, return_unit = None) -> int: 67 """ 68 Sets or gets the current sample rate of the handled card (see register `SPC_SAMPLERATE` in the manual) 69 70 Parameters 71 ---------- 72 sample_rate : int | pint.Quantity = 0 73 if the parameter sample_rate is given with the function call, then the card's sample rate is set to that value 74 max : bool = False 75 if max is True, the method sets the maximum sample rate of the card 76 unit : pint.Unit = None 77 the unit of the sample rate, by default None 78 79 Returns 80 ------- 81 int 82 the current sample rate in Samples/s 83 """ 84 85 if max: sample_rate = self.max_sample_rate() 86 if sample_rate: 87 if isinstance(sample_rate, units.Quantity) and sample_rate.check("[]"): 88 max_sr = self.max_sample_rate() 89 sample_rate = sample_rate.to_base_units().magnitude * max_sr 90 sample_rate = UnitConversion.convert(sample_rate, units.Hz, int) 91 self.card.set_i(SPC_SAMPLERATE, int(sample_rate)) 92 return_value = self.card.get_i(SPC_SAMPLERATE) 93 if return_unit is not None: return_value = UnitConversion.to_unit(return_value * units.Hz, return_unit) 94 return return_value 95 96 def clock_output(self, clock_output : int = None) -> int: 97 """ 98 Set the clock output of the card (see register `SPC_CLOCKOUT` in the manual) 99 100 Parameters 101 ---------- 102 clock_output : int 103 the clock output of the card 104 105 Returns 106 ------- 107 int 108 the clock output of the card 109 """ 110 111 if clock_output is not None: 112 self.card.set_i(SPC_CLOCKOUT, int(clock_output)) 113 return self.card.get_i(SPC_CLOCKOUT) 114 output = clock_output 115 116 def reference_clock(self, reference_clock : int = None) -> int: 117 """ 118 Set the reference clock of the card (see register `SPC_REFERENCECLOCK` in the manual) 119 120 Parameters 121 ---------- 122 reference_clock : int | pint.Quantity 123 the reference clock of the card in Hz 124 125 Returns 126 ------- 127 int 128 the reference clock of the card in Hz 129 """ 130 131 if reference_clock is not None: 132 reference_clock = UnitConversion.convert(reference_clock, units.Hz, int) 133 self.card.set_i(SPC_REFERENCECLOCK, reference_clock) 134 return self.card.get_i(SPC_REFERENCECLOCK) 135 136 def termination(self, termination : int = None) -> int: 137 """ 138 Set the termination for the clock input of the card (see register `SPC_CLOCK50OHM` in the manual) 139 140 Parameters 141 ---------- 142 termination : int | bool 143 the termination of the card 144 145 Returns 146 ------- 147 int 148 the termination of the card 149 """ 150 151 if termination is not None: 152 self.card.set_i(SPC_CLOCK50OHM, int(termination)) 153 return self.card.get_i(SPC_CLOCK50OHM) 154 155 def threshold(self, value : int = None, return_unit = None) -> int: 156 """ 157 Set the clock threshold of the card (see register `SPC_CLOCKTHRESHOLD` in the manual) 158 159 Parameters 160 ---------- 161 value : int 162 the clock threshold of the card 163 return_unit : pint.Unit = None 164 the unit of the clock threshold 165 166 Returns 167 ------- 168 int | pint.Quantity 169 the clock threshold of the card 170 """ 171 172 if value is not None: 173 value = UnitConversion.convert(value, units.mV, int) 174 self.card.set_i(SPC_CLOCK_THRESHOLD, int(value)) 175 value = self.card.get_i(SPC_CLOCK_THRESHOLD) 176 value = UnitConversion.to_unit(value * units.mV, return_unit) 177 return value 178 179 def threshold_min(self, return_unit = None) -> int: 180 """ 181 Returns the minimum clock threshold of the card (see register `SPC_CLOCK_AVAILTHRESHOLD_MIN` in the manual) 182 183 Parameters 184 ---------- 185 return_unit : pint.Unit = None 186 the unit of the return clock threshold 187 188 Returns 189 ------- 190 int 191 the minimum clock threshold of the card 192 """ 193 194 value = self.card.get_i(SPC_CLOCK_AVAILTHRESHOLD_MIN) 195 value = UnitConversion.to_unit(value * units.mV, return_unit) 196 return value 197 198 def threshold_max(self, return_unit = None) -> int: 199 """ 200 Returns the maximum clock threshold of the card (see register `SPC_CLOCK_AVAILTHRESHOLD_MAX` in the manual) 201 202 Parameters 203 ---------- 204 return_unit : pint.Unit = None 205 the unit of the return clock threshold 206 207 Returns 208 ------- 209 int 210 the maximum clock threshold of the card 211 """ 212 213 value = self.card.get_i(SPC_CLOCK_AVAILTHRESHOLD_MAX) 214 value = UnitConversion.to_unit(value * units.mV, return_unit) 215 return value 216 217 def threshold_step(self, return_unit = None) -> int: 218 """ 219 Returns the step of the clock threshold of the card (see register `SPC_CLOCK_AVAILTHRESHOLD_STEP` in the manual) 220 221 Parameters 222 ---------- 223 return_unit : pint.Unit = None 224 the unit of the return clock threshold 225 226 Returns 227 ------- 228 int 229 the step of the clock threshold of the card 230 """ 231 232 value = self.card.get_i(SPC_CLOCK_AVAILTHRESHOLD_STEP) 233 value = UnitConversion.to_unit(value * units.mV, return_unit) 234 return value
a higher-level abstraction of the CardFunctionality class to implement the Card's clock engine
34 def mode(self, mode : int = None) -> int: 35 """ 36 Set the clock mode of the card (see register `SPC_CLOCKMODE` in the manual) 37 38 Parameters 39 ---------- 40 mode : int 41 The clock mode of the card 42 43 Returns 44 ------- 45 int 46 The clock mode of the card 47 """ 48 49 if mode is not None: 50 self.card.set_i(SPC_CLOCKMODE, mode) 51 return self.card.get_i(SPC_CLOCKMODE)
Set the clock mode of the card (see register SPC_CLOCKMODE
in the manual)
Parameters
- mode (int): The clock mode of the card
Returns
- int: The clock mode of the card
53 def max_sample_rate(self, return_unit = None) -> int: 54 """ 55 Returns the maximum sample rate of the active card (see register `SPC_MIINST_MAXADCLOCK` in the manual) 56 57 Returns 58 ------- 59 int 60 """ 61 62 max_sr = self.card.get_i(SPC_MIINST_MAXADCLOCK) 63 if return_unit is not None: max_sr = UnitConversion.to_unit(max_sr * units.Hz, return_unit) 64 return max_sr
Returns the maximum sample rate of the active card (see register SPC_MIINST_MAXADCLOCK
in the manual)
Returns
- int
66 def sample_rate(self, sample_rate = 0, max : bool = False, return_unit = None) -> int: 67 """ 68 Sets or gets the current sample rate of the handled card (see register `SPC_SAMPLERATE` in the manual) 69 70 Parameters 71 ---------- 72 sample_rate : int | pint.Quantity = 0 73 if the parameter sample_rate is given with the function call, then the card's sample rate is set to that value 74 max : bool = False 75 if max is True, the method sets the maximum sample rate of the card 76 unit : pint.Unit = None 77 the unit of the sample rate, by default None 78 79 Returns 80 ------- 81 int 82 the current sample rate in Samples/s 83 """ 84 85 if max: sample_rate = self.max_sample_rate() 86 if sample_rate: 87 if isinstance(sample_rate, units.Quantity) and sample_rate.check("[]"): 88 max_sr = self.max_sample_rate() 89 sample_rate = sample_rate.to_base_units().magnitude * max_sr 90 sample_rate = UnitConversion.convert(sample_rate, units.Hz, int) 91 self.card.set_i(SPC_SAMPLERATE, int(sample_rate)) 92 return_value = self.card.get_i(SPC_SAMPLERATE) 93 if return_unit is not None: return_value = UnitConversion.to_unit(return_value * units.Hz, return_unit) 94 return return_value
Sets or gets the current sample rate of the handled card (see register SPC_SAMPLERATE
in the manual)
Parameters
- sample_rate (int | pint.Quantity = 0): if the parameter sample_rate is given with the function call, then the card's sample rate is set to that value
- max (bool = False): if max is True, the method sets the maximum sample rate of the card
- unit (pint.Unit = None): the unit of the sample rate, by default None
Returns
- int: the current sample rate in Samples/s
96 def clock_output(self, clock_output : int = None) -> int: 97 """ 98 Set the clock output of the card (see register `SPC_CLOCKOUT` in the manual) 99 100 Parameters 101 ---------- 102 clock_output : int 103 the clock output of the card 104 105 Returns 106 ------- 107 int 108 the clock output of the card 109 """ 110 111 if clock_output is not None: 112 self.card.set_i(SPC_CLOCKOUT, int(clock_output)) 113 return self.card.get_i(SPC_CLOCKOUT)
Set the clock output of the card (see register SPC_CLOCKOUT
in the manual)
Parameters
- clock_output (int): the clock output of the card
Returns
- int: the clock output of the card
96 def clock_output(self, clock_output : int = None) -> int: 97 """ 98 Set the clock output of the card (see register `SPC_CLOCKOUT` in the manual) 99 100 Parameters 101 ---------- 102 clock_output : int 103 the clock output of the card 104 105 Returns 106 ------- 107 int 108 the clock output of the card 109 """ 110 111 if clock_output is not None: 112 self.card.set_i(SPC_CLOCKOUT, int(clock_output)) 113 return self.card.get_i(SPC_CLOCKOUT)
Set the clock output of the card (see register SPC_CLOCKOUT
in the manual)
Parameters
- clock_output (int): the clock output of the card
Returns
- int: the clock output of the card
116 def reference_clock(self, reference_clock : int = None) -> int: 117 """ 118 Set the reference clock of the card (see register `SPC_REFERENCECLOCK` in the manual) 119 120 Parameters 121 ---------- 122 reference_clock : int | pint.Quantity 123 the reference clock of the card in Hz 124 125 Returns 126 ------- 127 int 128 the reference clock of the card in Hz 129 """ 130 131 if reference_clock is not None: 132 reference_clock = UnitConversion.convert(reference_clock, units.Hz, int) 133 self.card.set_i(SPC_REFERENCECLOCK, reference_clock) 134 return self.card.get_i(SPC_REFERENCECLOCK)
Set the reference clock of the card (see register SPC_REFERENCECLOCK
in the manual)
Parameters
- reference_clock (int | pint.Quantity): the reference clock of the card in Hz
Returns
- int: the reference clock of the card in Hz
136 def termination(self, termination : int = None) -> int: 137 """ 138 Set the termination for the clock input of the card (see register `SPC_CLOCK50OHM` in the manual) 139 140 Parameters 141 ---------- 142 termination : int | bool 143 the termination of the card 144 145 Returns 146 ------- 147 int 148 the termination of the card 149 """ 150 151 if termination is not None: 152 self.card.set_i(SPC_CLOCK50OHM, int(termination)) 153 return self.card.get_i(SPC_CLOCK50OHM)
Set the termination for the clock input of the card (see register SPC_CLOCK50OHM
in the manual)
Parameters
- termination (int | bool): the termination of the card
Returns
- int: the termination of the card
155 def threshold(self, value : int = None, return_unit = None) -> int: 156 """ 157 Set the clock threshold of the card (see register `SPC_CLOCKTHRESHOLD` in the manual) 158 159 Parameters 160 ---------- 161 value : int 162 the clock threshold of the card 163 return_unit : pint.Unit = None 164 the unit of the clock threshold 165 166 Returns 167 ------- 168 int | pint.Quantity 169 the clock threshold of the card 170 """ 171 172 if value is not None: 173 value = UnitConversion.convert(value, units.mV, int) 174 self.card.set_i(SPC_CLOCK_THRESHOLD, int(value)) 175 value = self.card.get_i(SPC_CLOCK_THRESHOLD) 176 value = UnitConversion.to_unit(value * units.mV, return_unit) 177 return value
Set the clock threshold of the card (see register SPC_CLOCKTHRESHOLD
in the manual)
Parameters
- value (int): the clock threshold of the card
- return_unit (pint.Unit = None): the unit of the clock threshold
Returns
- int | pint.Quantity: the clock threshold of the card
179 def threshold_min(self, return_unit = None) -> int: 180 """ 181 Returns the minimum clock threshold of the card (see register `SPC_CLOCK_AVAILTHRESHOLD_MIN` in the manual) 182 183 Parameters 184 ---------- 185 return_unit : pint.Unit = None 186 the unit of the return clock threshold 187 188 Returns 189 ------- 190 int 191 the minimum clock threshold of the card 192 """ 193 194 value = self.card.get_i(SPC_CLOCK_AVAILTHRESHOLD_MIN) 195 value = UnitConversion.to_unit(value * units.mV, return_unit) 196 return value
Returns the minimum clock threshold of the card (see register SPC_CLOCK_AVAILTHRESHOLD_MIN
in the manual)
Parameters
- return_unit (pint.Unit = None): the unit of the return clock threshold
Returns
- int: the minimum clock threshold of the card
198 def threshold_max(self, return_unit = None) -> int: 199 """ 200 Returns the maximum clock threshold of the card (see register `SPC_CLOCK_AVAILTHRESHOLD_MAX` in the manual) 201 202 Parameters 203 ---------- 204 return_unit : pint.Unit = None 205 the unit of the return clock threshold 206 207 Returns 208 ------- 209 int 210 the maximum clock threshold of the card 211 """ 212 213 value = self.card.get_i(SPC_CLOCK_AVAILTHRESHOLD_MAX) 214 value = UnitConversion.to_unit(value * units.mV, return_unit) 215 return value
Returns the maximum clock threshold of the card (see register SPC_CLOCK_AVAILTHRESHOLD_MAX
in the manual)
Parameters
- return_unit (pint.Unit = None): the unit of the return clock threshold
Returns
- int: the maximum clock threshold of the card
217 def threshold_step(self, return_unit = None) -> int: 218 """ 219 Returns the step of the clock threshold of the card (see register `SPC_CLOCK_AVAILTHRESHOLD_STEP` in the manual) 220 221 Parameters 222 ---------- 223 return_unit : pint.Unit = None 224 the unit of the return clock threshold 225 226 Returns 227 ------- 228 int 229 the step of the clock threshold of the card 230 """ 231 232 value = self.card.get_i(SPC_CLOCK_AVAILTHRESHOLD_STEP) 233 value = UnitConversion.to_unit(value * units.mV, return_unit) 234 return value
Returns the step of the clock threshold of the card (see register SPC_CLOCK_AVAILTHRESHOLD_STEP
in the manual)
Parameters
- return_unit (pint.Unit = None): the unit of the return clock threshold
Returns
- int: the step of the clock threshold of the card
16class Trigger(CardFunctionality): 17 """a higher-level abstraction of the CardFunctionality class to implement the Card's Trigger engine""" 18 19 channels : Channels = None 20 21 def __init__(self, card : 'Card', **kwargs) -> None: 22 """ 23 Constructor of the Trigger class 24 25 Parameters 26 ---------- 27 card : Card 28 The card to use for the Trigger class 29 """ 30 31 super().__init__(card) 32 self.channels = kwargs.get('channels', None) 33 34 def __str__(self) -> str: 35 """ 36 String representation of the Trigger class 37 38 Returns 39 ------- 40 str 41 String representation of the Trigger class 42 """ 43 44 return f"Trigger(card={self.card})" 45 46 __repr__ = __str__ 47 48 def enable(self) -> None: 49 """Enables the trigger engine (see command 'M2CMD_CARD_ENABLETRIGGER' in chapter `Trigger` in the manual)""" 50 self.card.cmd(M2CMD_CARD_ENABLETRIGGER) 51 52 def disable(self) -> None: 53 """Disables the trigger engine (see command 'M2CMD_CARD_DISABLETRIGGER' in chapter `Trigger` in the manual)""" 54 self.card.cmd(M2CMD_CARD_DISABLETRIGGER) 55 56 def force(self) -> None: 57 """Forces a trigger event if the hardware is still waiting for a trigger event. (see command 'M2CMD_CARD_FORCETRIGGER' in chapter `Trigger` in the manual)""" 58 self.card.cmd(M2CMD_CARD_FORCETRIGGER) 59 60 def write_setup(self) -> None: 61 """Write the trigger setup to the card""" 62 self.card.write_setup() 63 64 # OR Mask 65 def or_mask(self, mask : int = None) -> int: 66 """ 67 Set the OR mask for the trigger input lines (see register 'SPC_TRIG_ORMASK' in chapter `Trigger` in the manual) 68 69 Parameters 70 ---------- 71 mask : int 72 The OR mask for the trigger input lines 73 74 Returns 75 ------- 76 int 77 The OR mask for the trigger input lines 78 """ 79 80 if mask is not None: 81 self.card.set_i(SPC_TRIG_ORMASK, mask) 82 return self.card.get_i(SPC_TRIG_ORMASK) 83 84 # AND Mask 85 def and_mask(self, mask : int = None) -> int: 86 """ 87 Set the AND mask for the trigger input lines (see register 'SPC_TRIG_ANDMASK' in chapter `Trigger` in the manual) 88 89 Parameters 90 ---------- 91 mask : int 92 The AND mask for the trigger input lines 93 94 Returns 95 ------- 96 int 97 The AND mask for the trigger input lines 98 """ 99 100 if mask is not None: 101 self.card.set_i(SPC_TRIG_ANDMASK, mask) 102 return self.card.get_i(SPC_TRIG_ANDMASK) 103 104 # Channel triggering 105 def ch_mode(self, channel, mode : int = None) -> int: 106 """ 107 Set the mode for the trigger input lines (see register 'SPC_TRIG_CH0_MODE' in chapter `Trigger` in the manual) 108 109 Parameters 110 ---------- 111 channel : int | Channel 112 The channel to set the mode for 113 mode : int 114 The mode for the trigger input lines 115 116 Returns 117 ------- 118 int 119 The mode for the trigger input lines 120 121 """ 122 123 channel_index = int(channel) 124 if mode is not None: 125 self.card.set_i(SPC_TRIG_CH0_MODE + channel_index, mode) 126 return self.card.get_i(SPC_TRIG_CH0_MODE + channel_index) 127 128 def ch_level(self, channel : int, level_num : int, level_value = None, return_unit : pint.Unit = None) -> int: 129 """ 130 Set the level for the trigger input lines (see register 'SPC_TRIG_CH0_LEVEL0' in chapter `Trigger` in the manual) 131 132 Parameters 133 ---------- 134 channel : int | Channel 135 The channel to set the level for 136 level_num : int 137 The level 0 or level 1 138 level_value : int | pint.Quantity | None 139 The level for the trigger input lines 140 141 Returns 142 ------- 143 int 144 The level for the trigger input lines 145 """ 146 147 channel_index = int(channel) 148 # if a level value is given in the form of a quantity, convert it to the card's unit as a integer value 149 if isinstance(level_value, units.Quantity): 150 if isinstance(channel, Channel): 151 level_value = channel.reconvert_data(level_value) 152 elif self.channels and isinstance(self.channels[channel_index], Channel): 153 level_value = self.channels[channel_index].reconvert_data(level_value) 154 else: 155 raise ValueError("No channel information available to convert the trigger level value. Please provide a channel object or set the channel information in the Trigger object.") 156 157 if isinstance(level_value, int): 158 self.card.set_i(SPC_TRIG_CH0_LEVEL0 + channel_index + 100 * level_num, level_value) 159 160 return_value = self.card.get_i(SPC_TRIG_CH0_LEVEL0 + channel_index + 100 * level_num) 161 # if a return unit is given, convert the value to the given unit if a channel object is available 162 if isinstance(return_unit, pint.Unit): 163 if isinstance(channel, Channel): 164 return_value = channel.convert_data(return_value, return_unit=return_unit) 165 elif self.channels and isinstance(self.channels[channel_index], Channel): 166 return_value = self.channels[channel_index].convert_data(return_value, return_unit=return_unit) 167 else: 168 raise ValueError("No channel information available to convert the returning trigger level value. Please provide a channel object or set the channel information in the Trigger object.") 169 170 return return_value 171 172 def ch_level0(self, channel : int, level_value = None, return_unit : pint.Unit = None) -> int: 173 """ 174 Set the level 0 for the trigger input lines (see register 'SPC_TRIG_CH0_LEVEL0' in chapter `Trigger` in the manual) 175 176 Parameters 177 ---------- 178 channel : int | Channel 179 The channel to set the level for 180 level_value : int | pint.Quantity | None 181 The level for the trigger input lines 182 183 Returns 184 ------- 185 int 186 The level for the trigger input lines 187 """ 188 189 return self.ch_level(channel, 0, level_value, return_unit) 190 191 def ch_level1(self, channel : int, level_value = None, return_unit : pint.Unit = None) -> int: 192 """ 193 Set the level 1 for the trigger input lines (see register 'SPC_TRIG_CH0_LEVEL1' in chapter `Trigger` in the manual) 194 195 Parameters 196 ---------- 197 channel : int | Channel 198 The channel to set the level for 199 level_value : int | pint.Quantity | None 200 The level for the trigger input lines 201 202 Returns 203 ------- 204 int 205 The level for the trigger input lines 206 """ 207 208 return self.ch_level(channel, 1, level_value, return_unit) 209 210 # Channel OR Mask0 211 def ch_or_mask0(self, mask : int = None) -> int: 212 """ 213 Set the channel OR mask0 for the trigger input lines (see register 'SPC_TRIG_CH_ORMASK0' in chapter `Trigger` in the manual) 214 215 Parameters 216 ---------- 217 mask : int 218 The OR mask for the trigger input lines 219 220 Returns 221 ------- 222 int 223 The OR mask for the trigger input lines 224 """ 225 226 if mask is not None: 227 self.card.set_i(SPC_TRIG_CH_ORMASK0, mask) 228 return self.card.get_i(SPC_TRIG_CH_ORMASK0) 229 230 # Channel AND Mask0 231 def ch_and_mask0(self, mask : int = None) -> int: 232 """ 233 Set the AND mask0 for the trigger input lines (see register 'SPC_TRIG_CH_ANDMASK0' in chapter `Trigger` in the manual) 234 235 Parameters 236 ---------- 237 mask : int 238 The AND mask0 for the trigger input lines 239 240 Returns 241 ------- 242 int 243 The AND mask0 for the trigger input lines 244 """ 245 246 if mask is not None: 247 self.card.set_i(SPC_TRIG_CH_ANDMASK0, mask) 248 return self.card.get_i(SPC_TRIG_CH_ANDMASK0) 249 250 # Delay 251 def delay(self, delay : int = None, return_unit : pint.Unit = None) -> int: 252 """ 253 Set the delay for the trigger input lines in number of sample clocks (see register 'SPC_TRIG_DELAY' in chapter `Trigger` in the manual) 254 255 Parameters 256 ---------- 257 delay : int | pint.Quantity 258 The delay for the trigger input lines 259 return_unit : pint.Unit 260 The unit to return the value in 261 262 Returns 263 ------- 264 int | pint.Quantity 265 The delay for the trigger input lines 266 267 NOTE 268 ---- 269 different cards have different step sizes for the delay. 270 If a delay with unit is given, this function takes the value, 271 calculates the integer value and rounds to the nearest allowed delay value 272 """ 273 274 sr = self.card.get_i(SPC_SAMPLERATE) * units.Hz 275 if delay is not None: 276 if isinstance(delay, units.Quantity): 277 delay_step = self.card.get_i(SPC_TRIG_AVAILDELAY_STEP) 278 delay = np.rint(int(delay * sr) / delay_step).astype(np.int64) * delay_step 279 self.card.set_i(SPC_TRIG_DELAY, delay) 280 return_value = self.card.get_i(SPC_TRIG_DELAY) 281 if return_unit is not None: 282 return_value = UnitConversion.to_unit(return_value / sr, return_unit) 283 return return_value 284 285 def trigger_counter(self) -> int: 286 """ 287 Get the number of trigger events since acquisition start (see register 'SPC_TRIGGERCOUNTER' in chapter `Trigger` in the manual) 288 289 Returns 290 ------- 291 int 292 The trigger counter 293 """ 294 295 return self.card.get_i(SPC_TRIGGERCOUNTER) 296 297 # Main external window trigger (ext0/Trg0) 298 def ext0_mode(self, mode : int = None) -> int: 299 """ 300 Set the mode for the main external window trigger (ext0/Trg0) (see register 'SPC_TRIG_EXT0_MODE' in chapter `Trigger` in the manual) 301 302 Parameters 303 ---------- 304 mode : int 305 The mode for the main external window trigger (ext0/Trg0) 306 307 Returns 308 ------- 309 int 310 The mode for the main external window trigger (ext0/Trg0) 311 """ 312 313 if mode is not None: 314 self.card.set_i(SPC_TRIG_EXT0_MODE, mode) 315 return self.card.get_i(SPC_TRIG_EXT0_MODE) 316 317 # Trigger termination 318 def termination(self, termination : int = None) -> int: 319 """ 320 Set the trigger termination (see register 'SPC_TRIG_TERM' in chapter `Trigger` in the manual) 321 322 Parameters 323 ---------- 324 termination : int 325 The trigger termination: a „1“ sets the 50 Ohm termination for external trigger signals. A „0“ sets the high impedance termination 326 327 Returns 328 ------- 329 int 330 The trigger termination: a „1“ sets the 50 Ohm termination for external trigger signals. A „0“ sets the high impedance termination 331 """ 332 333 if termination is not None: 334 self.card.set_i(SPC_TRIG_TERM, termination) 335 return self.card.get_i(SPC_TRIG_TERM) 336 337 # Trigger input coupling 338 def ext0_coupling(self, coupling : int = None) -> int: 339 """ 340 Set the trigger input coupling (see hardware manual register name 'SPC_TRIG_EXT0_ACDC') 341 342 Parameters 343 ---------- 344 coupling : int 345 The trigger input coupling: COUPLING_DC enables DC coupling, COUPLING_AC enables AC coupling for the external trigger 346 input (AC coupling is the default). 347 348 Returns 349 ------- 350 int 351 The trigger input coupling: COUPLING_DC enables DC coupling, COUPLING_AC enables AC coupling for the external trigger 352 input (AC coupling is the default). 353 """ 354 355 if coupling is not None: 356 self.card.set_i(SPC_TRIG_EXT0_ACDC, coupling) 357 return self.card.get_i(SPC_TRIG_EXT0_ACDC) 358 359 # ext1 trigger mode 360 def ext1_mode(self, mode : int = None) -> int: 361 """ 362 Set the mode for the ext1 trigger (see register 'SPC_TRIG_EXT1_MODE' in chapter `Trigger` in the manual) 363 364 Parameters 365 ---------- 366 mode : int 367 The mode for the ext1 trigger 368 369 Returns 370 ------- 371 int 372 The mode for the ext1 trigger 373 """ 374 375 if mode is not None: 376 self.card.set_i(SPC_TRIG_EXT1_MODE, mode) 377 return self.card.get_i(SPC_TRIG_EXT1_MODE) 378 379 # Trigger level 380 def ext0_level0(self, level = None, return_unit = None) -> int: 381 """ 382 Set the trigger level 0 for the ext0 trigger (see register 'SPC_TRIG_EXT0_LEVEL0' in chapter `Trigger` in the manual) 383 384 Parameters 385 ---------- 386 level : int 387 The trigger level 0 for the ext0 trigger in mV 388 return_unit : pint.Unit 389 The unit to return the value in 390 391 Returns 392 ------- 393 int | pint.Quantity 394 The trigger level 0 for the ext0 trigger in mV or in the specified unit 395 """ 396 397 if level is not None: 398 level = UnitConversion.convert(level, units.mV, int) 399 self.card.set_i(SPC_TRIG_EXT0_LEVEL0, level) 400 return_value = self.card.get_i(SPC_TRIG_EXT0_LEVEL0) 401 if return_unit is not None: return UnitConversion.to_unit(return_value * units.mV, return_unit) 402 return return_value 403 404 def ext0_level1(self, level = None, return_unit = None) -> int: 405 """ 406 Set the trigger level 1 for the ext0 trigger (see register 'SPC_TRIG_EXT0_LEVEL1' in chapter `Trigger` in the manual) 407 408 Parameters 409 ---------- 410 level : int 411 The trigger level for the ext0 trigger in mV 412 return_unit : pint.Unit 413 The unit to return the value in 414 415 Returns 416 ------- 417 int | pint.Quantity 418 The trigger level for the ext0 trigger in mV or in the specified unit 419 """ 420 421 if level is not None: 422 level = UnitConversion.convert(level, units.mV, int) 423 self.card.set_i(SPC_TRIG_EXT0_LEVEL1, level) 424 return_value = self.card.get_i(SPC_TRIG_EXT0_LEVEL1) 425 if return_unit is not None: return UnitConversion.to_unit(return_value * units.mV, return_unit) 426 return return_value 427 428 def ext1_level0(self, level = None, return_unit = None) -> int: 429 """ 430 Set the trigger level 0 for the ext1 trigger (see register 'SPC_TRIG_EXT1_LEVEL0' in chapter `Trigger` in the manual) 431 432 Parameters 433 ---------- 434 level : int 435 The trigger level 0 for the ext1 trigger in mV 436 return_unit : pint.Unit 437 The unit to return the value in 438 439 Returns 440 ------- 441 int | pint.Quantity 442 The trigger level 0 for the ext1 trigger in mV or in the specified unit 443 """ 444 445 if level is not None: 446 level = UnitConversion.convert(level, units.mV, int) 447 self.card.set_i(SPC_TRIG_EXT1_LEVEL0, level) 448 return_value = self.card.get_i(SPC_TRIG_EXT1_LEVEL0) 449 if return_unit is not None: return UnitConversion.to_unit(return_value * units.mV, return_unit) 450 return return_value
a higher-level abstraction of the CardFunctionality class to implement the Card's Trigger engine
21 def __init__(self, card : 'Card', **kwargs) -> None: 22 """ 23 Constructor of the Trigger class 24 25 Parameters 26 ---------- 27 card : Card 28 The card to use for the Trigger class 29 """ 30 31 super().__init__(card) 32 self.channels = kwargs.get('channels', None)
Constructor of the Trigger class
Parameters
- card (Card): The card to use for the Trigger class
48 def enable(self) -> None: 49 """Enables the trigger engine (see command 'M2CMD_CARD_ENABLETRIGGER' in chapter `Trigger` in the manual)""" 50 self.card.cmd(M2CMD_CARD_ENABLETRIGGER)
Enables the trigger engine (see command 'M2CMD_CARD_ENABLETRIGGER' in chapter Trigger
in the manual)
52 def disable(self) -> None: 53 """Disables the trigger engine (see command 'M2CMD_CARD_DISABLETRIGGER' in chapter `Trigger` in the manual)""" 54 self.card.cmd(M2CMD_CARD_DISABLETRIGGER)
Disables the trigger engine (see command 'M2CMD_CARD_DISABLETRIGGER' in chapter Trigger
in the manual)
56 def force(self) -> None: 57 """Forces a trigger event if the hardware is still waiting for a trigger event. (see command 'M2CMD_CARD_FORCETRIGGER' in chapter `Trigger` in the manual)""" 58 self.card.cmd(M2CMD_CARD_FORCETRIGGER)
Forces a trigger event if the hardware is still waiting for a trigger event. (see command 'M2CMD_CARD_FORCETRIGGER' in chapter Trigger
in the manual)
60 def write_setup(self) -> None: 61 """Write the trigger setup to the card""" 62 self.card.write_setup()
Write the trigger setup to the card
65 def or_mask(self, mask : int = None) -> int: 66 """ 67 Set the OR mask for the trigger input lines (see register 'SPC_TRIG_ORMASK' in chapter `Trigger` in the manual) 68 69 Parameters 70 ---------- 71 mask : int 72 The OR mask for the trigger input lines 73 74 Returns 75 ------- 76 int 77 The OR mask for the trigger input lines 78 """ 79 80 if mask is not None: 81 self.card.set_i(SPC_TRIG_ORMASK, mask) 82 return self.card.get_i(SPC_TRIG_ORMASK)
Set the OR mask for the trigger input lines (see register 'SPC_TRIG_ORMASK' in chapter Trigger
in the manual)
Parameters
- mask (int): The OR mask for the trigger input lines
Returns
- int: The OR mask for the trigger input lines
85 def and_mask(self, mask : int = None) -> int: 86 """ 87 Set the AND mask for the trigger input lines (see register 'SPC_TRIG_ANDMASK' in chapter `Trigger` in the manual) 88 89 Parameters 90 ---------- 91 mask : int 92 The AND mask for the trigger input lines 93 94 Returns 95 ------- 96 int 97 The AND mask for the trigger input lines 98 """ 99 100 if mask is not None: 101 self.card.set_i(SPC_TRIG_ANDMASK, mask) 102 return self.card.get_i(SPC_TRIG_ANDMASK)
Set the AND mask for the trigger input lines (see register 'SPC_TRIG_ANDMASK' in chapter Trigger
in the manual)
Parameters
- mask (int): The AND mask for the trigger input lines
Returns
- int: The AND mask for the trigger input lines
105 def ch_mode(self, channel, mode : int = None) -> int: 106 """ 107 Set the mode for the trigger input lines (see register 'SPC_TRIG_CH0_MODE' in chapter `Trigger` in the manual) 108 109 Parameters 110 ---------- 111 channel : int | Channel 112 The channel to set the mode for 113 mode : int 114 The mode for the trigger input lines 115 116 Returns 117 ------- 118 int 119 The mode for the trigger input lines 120 121 """ 122 123 channel_index = int(channel) 124 if mode is not None: 125 self.card.set_i(SPC_TRIG_CH0_MODE + channel_index, mode) 126 return self.card.get_i(SPC_TRIG_CH0_MODE + channel_index)
Set the mode for the trigger input lines (see register 'SPC_TRIG_CH0_MODE' in chapter Trigger
in the manual)
Parameters
- channel (int | Channel): The channel to set the mode for
- mode (int): The mode for the trigger input lines
Returns
- int: The mode for the trigger input lines
128 def ch_level(self, channel : int, level_num : int, level_value = None, return_unit : pint.Unit = None) -> int: 129 """ 130 Set the level for the trigger input lines (see register 'SPC_TRIG_CH0_LEVEL0' in chapter `Trigger` in the manual) 131 132 Parameters 133 ---------- 134 channel : int | Channel 135 The channel to set the level for 136 level_num : int 137 The level 0 or level 1 138 level_value : int | pint.Quantity | None 139 The level for the trigger input lines 140 141 Returns 142 ------- 143 int 144 The level for the trigger input lines 145 """ 146 147 channel_index = int(channel) 148 # if a level value is given in the form of a quantity, convert it to the card's unit as a integer value 149 if isinstance(level_value, units.Quantity): 150 if isinstance(channel, Channel): 151 level_value = channel.reconvert_data(level_value) 152 elif self.channels and isinstance(self.channels[channel_index], Channel): 153 level_value = self.channels[channel_index].reconvert_data(level_value) 154 else: 155 raise ValueError("No channel information available to convert the trigger level value. Please provide a channel object or set the channel information in the Trigger object.") 156 157 if isinstance(level_value, int): 158 self.card.set_i(SPC_TRIG_CH0_LEVEL0 + channel_index + 100 * level_num, level_value) 159 160 return_value = self.card.get_i(SPC_TRIG_CH0_LEVEL0 + channel_index + 100 * level_num) 161 # if a return unit is given, convert the value to the given unit if a channel object is available 162 if isinstance(return_unit, pint.Unit): 163 if isinstance(channel, Channel): 164 return_value = channel.convert_data(return_value, return_unit=return_unit) 165 elif self.channels and isinstance(self.channels[channel_index], Channel): 166 return_value = self.channels[channel_index].convert_data(return_value, return_unit=return_unit) 167 else: 168 raise ValueError("No channel information available to convert the returning trigger level value. Please provide a channel object or set the channel information in the Trigger object.") 169 170 return return_value
Set the level for the trigger input lines (see register 'SPC_TRIG_CH0_LEVEL0' in chapter Trigger
in the manual)
Parameters
- channel (int | Channel): The channel to set the level for
- level_num (int): The level 0 or level 1
- level_value (int | pint.Quantity | None): The level for the trigger input lines
Returns
- int: The level for the trigger input lines
172 def ch_level0(self, channel : int, level_value = None, return_unit : pint.Unit = None) -> int: 173 """ 174 Set the level 0 for the trigger input lines (see register 'SPC_TRIG_CH0_LEVEL0' in chapter `Trigger` in the manual) 175 176 Parameters 177 ---------- 178 channel : int | Channel 179 The channel to set the level for 180 level_value : int | pint.Quantity | None 181 The level for the trigger input lines 182 183 Returns 184 ------- 185 int 186 The level for the trigger input lines 187 """ 188 189 return self.ch_level(channel, 0, level_value, return_unit)
Set the level 0 for the trigger input lines (see register 'SPC_TRIG_CH0_LEVEL0' in chapter Trigger
in the manual)
Parameters
- channel (int | Channel): The channel to set the level for
- level_value (int | pint.Quantity | None): The level for the trigger input lines
Returns
- int: The level for the trigger input lines
191 def ch_level1(self, channel : int, level_value = None, return_unit : pint.Unit = None) -> int: 192 """ 193 Set the level 1 for the trigger input lines (see register 'SPC_TRIG_CH0_LEVEL1' in chapter `Trigger` in the manual) 194 195 Parameters 196 ---------- 197 channel : int | Channel 198 The channel to set the level for 199 level_value : int | pint.Quantity | None 200 The level for the trigger input lines 201 202 Returns 203 ------- 204 int 205 The level for the trigger input lines 206 """ 207 208 return self.ch_level(channel, 1, level_value, return_unit)
Set the level 1 for the trigger input lines (see register 'SPC_TRIG_CH0_LEVEL1' in chapter Trigger
in the manual)
Parameters
- channel (int | Channel): The channel to set the level for
- level_value (int | pint.Quantity | None): The level for the trigger input lines
Returns
- int: The level for the trigger input lines
211 def ch_or_mask0(self, mask : int = None) -> int: 212 """ 213 Set the channel OR mask0 for the trigger input lines (see register 'SPC_TRIG_CH_ORMASK0' in chapter `Trigger` in the manual) 214 215 Parameters 216 ---------- 217 mask : int 218 The OR mask for the trigger input lines 219 220 Returns 221 ------- 222 int 223 The OR mask for the trigger input lines 224 """ 225 226 if mask is not None: 227 self.card.set_i(SPC_TRIG_CH_ORMASK0, mask) 228 return self.card.get_i(SPC_TRIG_CH_ORMASK0)
Set the channel OR mask0 for the trigger input lines (see register 'SPC_TRIG_CH_ORMASK0' in chapter Trigger
in the manual)
Parameters
- mask (int): The OR mask for the trigger input lines
Returns
- int: The OR mask for the trigger input lines
231 def ch_and_mask0(self, mask : int = None) -> int: 232 """ 233 Set the AND mask0 for the trigger input lines (see register 'SPC_TRIG_CH_ANDMASK0' in chapter `Trigger` in the manual) 234 235 Parameters 236 ---------- 237 mask : int 238 The AND mask0 for the trigger input lines 239 240 Returns 241 ------- 242 int 243 The AND mask0 for the trigger input lines 244 """ 245 246 if mask is not None: 247 self.card.set_i(SPC_TRIG_CH_ANDMASK0, mask) 248 return self.card.get_i(SPC_TRIG_CH_ANDMASK0)
Set the AND mask0 for the trigger input lines (see register 'SPC_TRIG_CH_ANDMASK0' in chapter Trigger
in the manual)
Parameters
- mask (int): The AND mask0 for the trigger input lines
Returns
- int: The AND mask0 for the trigger input lines
251 def delay(self, delay : int = None, return_unit : pint.Unit = None) -> int: 252 """ 253 Set the delay for the trigger input lines in number of sample clocks (see register 'SPC_TRIG_DELAY' in chapter `Trigger` in the manual) 254 255 Parameters 256 ---------- 257 delay : int | pint.Quantity 258 The delay for the trigger input lines 259 return_unit : pint.Unit 260 The unit to return the value in 261 262 Returns 263 ------- 264 int | pint.Quantity 265 The delay for the trigger input lines 266 267 NOTE 268 ---- 269 different cards have different step sizes for the delay. 270 If a delay with unit is given, this function takes the value, 271 calculates the integer value and rounds to the nearest allowed delay value 272 """ 273 274 sr = self.card.get_i(SPC_SAMPLERATE) * units.Hz 275 if delay is not None: 276 if isinstance(delay, units.Quantity): 277 delay_step = self.card.get_i(SPC_TRIG_AVAILDELAY_STEP) 278 delay = np.rint(int(delay * sr) / delay_step).astype(np.int64) * delay_step 279 self.card.set_i(SPC_TRIG_DELAY, delay) 280 return_value = self.card.get_i(SPC_TRIG_DELAY) 281 if return_unit is not None: 282 return_value = UnitConversion.to_unit(return_value / sr, return_unit) 283 return return_value
Set the delay for the trigger input lines in number of sample clocks (see register 'SPC_TRIG_DELAY' in chapter Trigger
in the manual)
Parameters
- delay (int | pint.Quantity): The delay for the trigger input lines
- return_unit (pint.Unit): The unit to return the value in
Returns
- int | pint.Quantity: The delay for the trigger input lines
NOTE
different cards have different step sizes for the delay. If a delay with unit is given, this function takes the value, calculates the integer value and rounds to the nearest allowed delay value
285 def trigger_counter(self) -> int: 286 """ 287 Get the number of trigger events since acquisition start (see register 'SPC_TRIGGERCOUNTER' in chapter `Trigger` in the manual) 288 289 Returns 290 ------- 291 int 292 The trigger counter 293 """ 294 295 return self.card.get_i(SPC_TRIGGERCOUNTER)
Get the number of trigger events since acquisition start (see register 'SPC_TRIGGERCOUNTER' in chapter Trigger
in the manual)
Returns
- int: The trigger counter
298 def ext0_mode(self, mode : int = None) -> int: 299 """ 300 Set the mode for the main external window trigger (ext0/Trg0) (see register 'SPC_TRIG_EXT0_MODE' in chapter `Trigger` in the manual) 301 302 Parameters 303 ---------- 304 mode : int 305 The mode for the main external window trigger (ext0/Trg0) 306 307 Returns 308 ------- 309 int 310 The mode for the main external window trigger (ext0/Trg0) 311 """ 312 313 if mode is not None: 314 self.card.set_i(SPC_TRIG_EXT0_MODE, mode) 315 return self.card.get_i(SPC_TRIG_EXT0_MODE)
Set the mode for the main external window trigger (ext0/Trg0) (see register 'SPC_TRIG_EXT0_MODE' in chapter Trigger
in the manual)
Parameters
- mode (int): The mode for the main external window trigger (ext0/Trg0)
Returns
- int: The mode for the main external window trigger (ext0/Trg0)
318 def termination(self, termination : int = None) -> int: 319 """ 320 Set the trigger termination (see register 'SPC_TRIG_TERM' in chapter `Trigger` in the manual) 321 322 Parameters 323 ---------- 324 termination : int 325 The trigger termination: a „1“ sets the 50 Ohm termination for external trigger signals. A „0“ sets the high impedance termination 326 327 Returns 328 ------- 329 int 330 The trigger termination: a „1“ sets the 50 Ohm termination for external trigger signals. A „0“ sets the high impedance termination 331 """ 332 333 if termination is not None: 334 self.card.set_i(SPC_TRIG_TERM, termination) 335 return self.card.get_i(SPC_TRIG_TERM)
Set the trigger termination (see register 'SPC_TRIG_TERM' in chapter Trigger
in the manual)
Parameters
- termination (int): The trigger termination: a „1“ sets the 50 Ohm termination for external trigger signals. A „0“ sets the high impedance termination
Returns
- int: The trigger termination: a „1“ sets the 50 Ohm termination for external trigger signals. A „0“ sets the high impedance termination
338 def ext0_coupling(self, coupling : int = None) -> int: 339 """ 340 Set the trigger input coupling (see hardware manual register name 'SPC_TRIG_EXT0_ACDC') 341 342 Parameters 343 ---------- 344 coupling : int 345 The trigger input coupling: COUPLING_DC enables DC coupling, COUPLING_AC enables AC coupling for the external trigger 346 input (AC coupling is the default). 347 348 Returns 349 ------- 350 int 351 The trigger input coupling: COUPLING_DC enables DC coupling, COUPLING_AC enables AC coupling for the external trigger 352 input (AC coupling is the default). 353 """ 354 355 if coupling is not None: 356 self.card.set_i(SPC_TRIG_EXT0_ACDC, coupling) 357 return self.card.get_i(SPC_TRIG_EXT0_ACDC)
Set the trigger input coupling (see hardware manual register name 'SPC_TRIG_EXT0_ACDC')
Parameters
- coupling (int): The trigger input coupling: COUPLING_DC enables DC coupling, COUPLING_AC enables AC coupling for the external trigger input (AC coupling is the default).
Returns
- int: The trigger input coupling: COUPLING_DC enables DC coupling, COUPLING_AC enables AC coupling for the external trigger input (AC coupling is the default).
360 def ext1_mode(self, mode : int = None) -> int: 361 """ 362 Set the mode for the ext1 trigger (see register 'SPC_TRIG_EXT1_MODE' in chapter `Trigger` in the manual) 363 364 Parameters 365 ---------- 366 mode : int 367 The mode for the ext1 trigger 368 369 Returns 370 ------- 371 int 372 The mode for the ext1 trigger 373 """ 374 375 if mode is not None: 376 self.card.set_i(SPC_TRIG_EXT1_MODE, mode) 377 return self.card.get_i(SPC_TRIG_EXT1_MODE)
Set the mode for the ext1 trigger (see register 'SPC_TRIG_EXT1_MODE' in chapter Trigger
in the manual)
Parameters
- mode (int): The mode for the ext1 trigger
Returns
- int: The mode for the ext1 trigger
380 def ext0_level0(self, level = None, return_unit = None) -> int: 381 """ 382 Set the trigger level 0 for the ext0 trigger (see register 'SPC_TRIG_EXT0_LEVEL0' in chapter `Trigger` in the manual) 383 384 Parameters 385 ---------- 386 level : int 387 The trigger level 0 for the ext0 trigger in mV 388 return_unit : pint.Unit 389 The unit to return the value in 390 391 Returns 392 ------- 393 int | pint.Quantity 394 The trigger level 0 for the ext0 trigger in mV or in the specified unit 395 """ 396 397 if level is not None: 398 level = UnitConversion.convert(level, units.mV, int) 399 self.card.set_i(SPC_TRIG_EXT0_LEVEL0, level) 400 return_value = self.card.get_i(SPC_TRIG_EXT0_LEVEL0) 401 if return_unit is not None: return UnitConversion.to_unit(return_value * units.mV, return_unit) 402 return return_value
Set the trigger level 0 for the ext0 trigger (see register 'SPC_TRIG_EXT0_LEVEL0' in chapter Trigger
in the manual)
Parameters
- level (int): The trigger level 0 for the ext0 trigger in mV
- return_unit (pint.Unit): The unit to return the value in
Returns
- int | pint.Quantity: The trigger level 0 for the ext0 trigger in mV or in the specified unit
404 def ext0_level1(self, level = None, return_unit = None) -> int: 405 """ 406 Set the trigger level 1 for the ext0 trigger (see register 'SPC_TRIG_EXT0_LEVEL1' in chapter `Trigger` in the manual) 407 408 Parameters 409 ---------- 410 level : int 411 The trigger level for the ext0 trigger in mV 412 return_unit : pint.Unit 413 The unit to return the value in 414 415 Returns 416 ------- 417 int | pint.Quantity 418 The trigger level for the ext0 trigger in mV or in the specified unit 419 """ 420 421 if level is not None: 422 level = UnitConversion.convert(level, units.mV, int) 423 self.card.set_i(SPC_TRIG_EXT0_LEVEL1, level) 424 return_value = self.card.get_i(SPC_TRIG_EXT0_LEVEL1) 425 if return_unit is not None: return UnitConversion.to_unit(return_value * units.mV, return_unit) 426 return return_value
Set the trigger level 1 for the ext0 trigger (see register 'SPC_TRIG_EXT0_LEVEL1' in chapter Trigger
in the manual)
Parameters
- level (int): The trigger level for the ext0 trigger in mV
- return_unit (pint.Unit): The unit to return the value in
Returns
- int | pint.Quantity: The trigger level for the ext0 trigger in mV or in the specified unit
428 def ext1_level0(self, level = None, return_unit = None) -> int: 429 """ 430 Set the trigger level 0 for the ext1 trigger (see register 'SPC_TRIG_EXT1_LEVEL0' in chapter `Trigger` in the manual) 431 432 Parameters 433 ---------- 434 level : int 435 The trigger level 0 for the ext1 trigger in mV 436 return_unit : pint.Unit 437 The unit to return the value in 438 439 Returns 440 ------- 441 int | pint.Quantity 442 The trigger level 0 for the ext1 trigger in mV or in the specified unit 443 """ 444 445 if level is not None: 446 level = UnitConversion.convert(level, units.mV, int) 447 self.card.set_i(SPC_TRIG_EXT1_LEVEL0, level) 448 return_value = self.card.get_i(SPC_TRIG_EXT1_LEVEL0) 449 if return_unit is not None: return UnitConversion.to_unit(return_value * units.mV, return_unit) 450 return return_value
Set the trigger level 0 for the ext1 trigger (see register 'SPC_TRIG_EXT1_LEVEL0' in chapter Trigger
in the manual)
Parameters
- level (int): The trigger level 0 for the ext1 trigger in mV
- return_unit (pint.Unit): The unit to return the value in
Returns
- int | pint.Quantity: The trigger level 0 for the ext1 trigger in mV or in the specified unit
89class MultiPurposeIOs(CardFunctionality): 90 """a higher-level abstraction of the CardFunctionality class to implement the Card's Multi purpose I/O functionality""" 91 92 xio_lines : list[MultiPurposeIO] = [] 93 num_xio_lines : int = None 94 95 def __init__(self, card : Card, *args, **kwargs) -> None: 96 """ 97 Constructor for the MultiPurposeIO class 98 99 Parameters 100 ---------- 101 card : Card 102 The card object to communicate with the card 103 """ 104 105 super().__init__(card, *args, **kwargs) 106 107 self.xio_lines = [] 108 self.num_xio_lines = self.get_num_xio_lines() 109 self.load() 110 111 def __str__(self) -> str: 112 """ 113 String representation of the MultiPurposeIO class 114 115 Returns 116 ------- 117 str 118 String representation of the MultiPurposeIO class 119 """ 120 121 return f"MultiPurposeIOs(card={self.card})" 122 123 __repr__ = __str__ 124 def __iter__(self) -> "MultiPurposeIOs": 125 """Define this class as an iterator""" 126 return self 127 128 def __getitem__(self, index : int) -> MultiPurposeIO: 129 """ 130 Get the xio line at the given index 131 132 Parameters 133 ---------- 134 index : int 135 The index of the xio line to be returned 136 137 Returns 138 ------- 139 MultiPurposeIO 140 The xio line at the given index 141 """ 142 143 return self.xio_lines[index] 144 145 _xio_iterator_index = -1 146 def __next__(self) -> MultiPurposeIO: 147 """ 148 This method is called when the next element is requested from the iterator 149 150 Returns 151 ------- 152 MultiPurposeIO 153 The next xio line in the iterator 154 155 Raises 156 ------ 157 StopIteration 158 """ 159 self._xio_iterator_index += 1 160 if self._xio_iterator_index >= len(self.xio_lines): 161 self._xio_iterator_index = -1 162 raise StopIteration 163 return self.xio_lines[self._xio_iterator_index] 164 165 def __len__(self) -> int: 166 """Returns the number of available xio lines of the card""" 167 return len(self.xio_lines) 168 169 170 def get_num_xio_lines(self) -> int: 171 """ 172 Returns the number of digital input/output lines of the card (see register 'SPCM_NUM_XIO_LINES' in chapter `Multi Purpose I/O Lines` in the manual) 173 174 Returns 175 ------- 176 int 177 The number of digital input/output lines of the card 178 179 """ 180 181 return self.card.get_i(SPC_NUM_XIO_LINES) 182 183 def load(self) -> None: 184 """ 185 Loads the digital input/output lines of the card 186 """ 187 188 self.xio_lines = [MultiPurposeIO(self.card, x_index) for x_index in range(self.num_xio_lines)] 189 190 def asyncio(self, output : int = None) -> int: 191 """ 192 Sets the async input/output of the card (see register 'SPCM_XX_ASYNCIO' in chapter `Multi Purpose I/O Lines` in the manual) 193 194 Parameters 195 ---------- 196 output : int 197 The async input/output of the card 198 199 Returns 200 ------- 201 int 202 The async input/output of the card 203 """ 204 205 if output is not None: 206 self.card.set_i(SPCM_XX_ASYNCIO, output) 207 return self.card.get_i(SPCM_XX_ASYNCIO)
a higher-level abstraction of the CardFunctionality class to implement the Card's Multi purpose I/O functionality
95 def __init__(self, card : Card, *args, **kwargs) -> None: 96 """ 97 Constructor for the MultiPurposeIO class 98 99 Parameters 100 ---------- 101 card : Card 102 The card object to communicate with the card 103 """ 104 105 super().__init__(card, *args, **kwargs) 106 107 self.xio_lines = [] 108 self.num_xio_lines = self.get_num_xio_lines() 109 self.load()
Constructor for the MultiPurposeIO class
Parameters
- card (Card): The card object to communicate with the card
170 def get_num_xio_lines(self) -> int: 171 """ 172 Returns the number of digital input/output lines of the card (see register 'SPCM_NUM_XIO_LINES' in chapter `Multi Purpose I/O Lines` in the manual) 173 174 Returns 175 ------- 176 int 177 The number of digital input/output lines of the card 178 179 """ 180 181 return self.card.get_i(SPC_NUM_XIO_LINES)
Returns the number of digital input/output lines of the card (see register 'SPCM_NUM_XIO_LINES' in chapter Multi Purpose I/O Lines
in the manual)
Returns
- int: The number of digital input/output lines of the card
183 def load(self) -> None: 184 """ 185 Loads the digital input/output lines of the card 186 """ 187 188 self.xio_lines = [MultiPurposeIO(self.card, x_index) for x_index in range(self.num_xio_lines)]
Loads the digital input/output lines of the card
190 def asyncio(self, output : int = None) -> int: 191 """ 192 Sets the async input/output of the card (see register 'SPCM_XX_ASYNCIO' in chapter `Multi Purpose I/O Lines` in the manual) 193 194 Parameters 195 ---------- 196 output : int 197 The async input/output of the card 198 199 Returns 200 ------- 201 int 202 The async input/output of the card 203 """ 204 205 if output is not None: 206 self.card.set_i(SPCM_XX_ASYNCIO, output) 207 return self.card.get_i(SPCM_XX_ASYNCIO)
Sets the async input/output of the card (see register 'SPCM_XX_ASYNCIO' in chapter Multi Purpose I/O Lines
in the manual)
Parameters
- output (int): The async input/output of the card
Returns
- int: The async input/output of the card
9class MultiPurposeIO: 10 """a higher-level abstraction of the CardFunctionality class to implement the Card's Multi purpose I/O functionality""" 11 12 card : Card = None 13 x_index : int = None 14 15 def __init__(self, card : Card, x_index : int = None) -> None: 16 """ 17 Constructor for the MultiPurposeIO class 18 19 Parameters 20 ---------- 21 card : Card 22 The card object to communicate with the card 23 x_index : int 24 The index of the digital input/output to be enabled. 25 """ 26 27 self.card = card 28 self.x_index = x_index 29 30 def __str__(self) -> str: 31 """ 32 String representation of the MultiPurposeIO class 33 34 Returns 35 ------- 36 str 37 String representation of the MultiPurposeIO class 38 """ 39 40 return f"MultiPurposeIO(card={self.card}, x_index={self.x_index})" 41 42 __repr__ = __str__ 43 44 def avail_modes(self) -> int: 45 """ 46 Returns the available modes of the digital input/output of the card (see register 'SPCM_X0_AVAILMODES' in chapter `Multi Purpose I/O Lines` in the manual) 47 48 Returns 49 ------- 50 int 51 The available modes of the digital input/output 52 """ 53 54 return self.get_i(SPCM_X0_AVAILMODES + self.x_index) 55 56 def x_mode(self, mode : int = None) -> int: 57 """ 58 Sets the mode of the digital input/output of the card (see register 'SPCM_X0_MODE' in chapter `Multi Purpose I/O Lines` in the manual) 59 60 Parameters 61 ---------- 62 mode : int 63 The mode of the digital input/output 64 """ 65 66 if mode is not None: 67 self.card.set_i(SPCM_X0_MODE + self.x_index, mode) 68 return self.card.get_i(SPCM_X0_MODE + self.x_index) 69 70 def dig_mode(self, mode : int = None) -> int: 71 """ 72 Sets the digital input/output mode of the xio line (see register 'SPCM_DIGMODE0' in chapter `Multi Purpose I/O Lines` in the manual) 73 74 Parameters 75 ---------- 76 mode : int 77 The digital input/output mode of the xio line 78 79 Returns 80 ------- 81 int 82 The digital input/output mode of the xio line 83 """ 84 85 if mode is not None: 86 self.card.set_i(SPC_DIGMODE0 + self.x_index, mode) 87 return self.card.get_i(SPC_DIGMODE0 + self.x_index)
a higher-level abstraction of the CardFunctionality class to implement the Card's Multi purpose I/O functionality
15 def __init__(self, card : Card, x_index : int = None) -> None: 16 """ 17 Constructor for the MultiPurposeIO class 18 19 Parameters 20 ---------- 21 card : Card 22 The card object to communicate with the card 23 x_index : int 24 The index of the digital input/output to be enabled. 25 """ 26 27 self.card = card 28 self.x_index = x_index
Constructor for the MultiPurposeIO class
Parameters
- card (Card): The card object to communicate with the card
- x_index (int): The index of the digital input/output to be enabled.
44 def avail_modes(self) -> int: 45 """ 46 Returns the available modes of the digital input/output of the card (see register 'SPCM_X0_AVAILMODES' in chapter `Multi Purpose I/O Lines` in the manual) 47 48 Returns 49 ------- 50 int 51 The available modes of the digital input/output 52 """ 53 54 return self.get_i(SPCM_X0_AVAILMODES + self.x_index)
Returns the available modes of the digital input/output of the card (see register 'SPCM_X0_AVAILMODES' in chapter Multi Purpose I/O Lines
in the manual)
Returns
- int: The available modes of the digital input/output
56 def x_mode(self, mode : int = None) -> int: 57 """ 58 Sets the mode of the digital input/output of the card (see register 'SPCM_X0_MODE' in chapter `Multi Purpose I/O Lines` in the manual) 59 60 Parameters 61 ---------- 62 mode : int 63 The mode of the digital input/output 64 """ 65 66 if mode is not None: 67 self.card.set_i(SPCM_X0_MODE + self.x_index, mode) 68 return self.card.get_i(SPCM_X0_MODE + self.x_index)
Sets the mode of the digital input/output of the card (see register 'SPCM_X0_MODE' in chapter Multi Purpose I/O Lines
in the manual)
Parameters
- mode (int): The mode of the digital input/output
70 def dig_mode(self, mode : int = None) -> int: 71 """ 72 Sets the digital input/output mode of the xio line (see register 'SPCM_DIGMODE0' in chapter `Multi Purpose I/O Lines` in the manual) 73 74 Parameters 75 ---------- 76 mode : int 77 The digital input/output mode of the xio line 78 79 Returns 80 ------- 81 int 82 The digital input/output mode of the xio line 83 """ 84 85 if mode is not None: 86 self.card.set_i(SPC_DIGMODE0 + self.x_index, mode) 87 return self.card.get_i(SPC_DIGMODE0 + self.x_index)
Sets the digital input/output mode of the xio line (see register 'SPCM_DIGMODE0' in chapter Multi Purpose I/O Lines
in the manual)
Parameters
- mode (int): The digital input/output mode of the xio line
Returns
- int: The digital input/output mode of the xio line
21class DataTransfer(CardFunctionality): 22 """ 23 A high-level class to control Data Transfer to and from Spectrum Instrumentation cards. 24 25 This class is an iterator class that implements the functions `__iter__` and `__next__`. 26 This allows the user to supply the class to a for loop and iterate over the data that 27 is transferred from or to the card. Each iteration will return a numpy array with a data 28 block of size `notify_samples`. In case of a digitizer you can read the data from that 29 block and process it. In case of a generator you can write data to the block and it's 30 then transferred. 31 32 For more information about what setups are available, please have a look at the user manual 33 for your specific card. 34 35 Parameters 36 ---------- 37 `buffer` : NDArray[np.int_] 38 numpy object that can be used to write data into the spcm buffer 39 `buffer_size`: int 40 defines the size of the current buffer shared between the PC and the card 41 `buffer_type`: int 42 defines the type of data in the buffer that is used for the transfer 43 `num_channels`: int 44 defines the number of channels that are used for the transfer 45 `bytes_per_sample`: int 46 defines the number of bytes per sample 47 `bits_per_sample`: int 48 defines the number of bits per sample 49 50 """ 51 # public 52 buffer_size : int = 0 53 notify_size : int = 0 54 55 direction : Direction = Direction.Acquisition 56 57 buffer_type : int 58 num_channels : int = 0 59 bytes_per_sample : int = 0 60 bits_per_sample : int = 0 61 62 current_user_pos : int = 0 63 64 _polling = False 65 _pollng_timer = 0 66 67 # private 68 _buffer_samples : int = 0 69 _notify_samples : int = 0 70 71 @property 72 def buffer(self) -> npt.NDArray[np.int_]: 73 """ 74 The numpy buffer object that interfaces the Card and can be written and read from 75 76 Returns 77 ------- 78 numpy array 79 the numpy buffer object with the following array index definition: 80 `[channel, sample]` 81 or in case of multiple recording / replay: 82 `[segment, sample, channel]` 83 """ 84 return self._np_buffer 85 86 @buffer.setter 87 def buffer(self, value) -> None: 88 self._np_buffer = value 89 90 @buffer.deleter 91 def buffer(self) -> None: 92 del self._np_buffer 93 94 @property 95 def buffer_samples(self) -> int: 96 """ 97 The number of samples in the buffer 98 99 Returns 100 ------- 101 int 102 the number of samples in the buffer 103 """ 104 return self._buffer_samples 105 106 @buffer_samples.setter 107 def buffer_samples(self, value) -> None: 108 if value is not None: 109 self._buffer_samples = value 110 111 self.buffer_size = self.samples_to_bytes(self._buffer_samples) 112 113 # if self.bits_per_sample > 1: 114 # self.buffer_size = int(self._buffer_samples * self.bytes_per_sample * self.num_channels) 115 # else: 116 # self.buffer_size = int(self._buffer_samples * self.num_channels // 8) 117 118 @buffer_samples.deleter 119 def buffer_samples(self) -> None: 120 del self._buffer_samples 121 122 def bytes_to_samples(self, num_bytes : int) -> int: 123 """ 124 Convert bytes to samples 125 126 Parameters 127 ---------- 128 bytes : int 129 the number of bytes 130 131 Returns 132 ------- 133 int 134 the number of samples 135 """ 136 137 if self.bits_per_sample > 1: 138 num_samples = num_bytes // self.bytes_per_sample // self.num_channels 139 else: 140 num_samples = num_bytes // self.num_channels * 8 141 return num_samples 142 143 def samples_to_bytes(self, num_samples : int) -> int: 144 """ 145 Convert samples to bytes 146 147 Parameters 148 ---------- 149 num_samples : int 150 the number of samples 151 152 Returns 153 ------- 154 int 155 the number of bytes 156 """ 157 158 if self.bits_per_sample > 1: 159 num_bytes = num_samples * self.bytes_per_sample * self.num_channels 160 else: 161 num_bytes = num_samples * self.num_channels // 8 162 return num_bytes 163 164 # @property 165 # def notify_samples(self) -> int: 166 # """ 167 # The number of samples to notify the user about 168 169 # Returns 170 # ------- 171 # int 172 # the number of samples to notify the user about 173 # """ 174 # return self._notify_samples 175 176 # @notify_samples.setter 177 def notify_samples(self, notify_samples : int = None) -> int: 178 """ 179 Set the number of samples to notify the user about 180 181 Parameters 182 ---------- 183 notify_samples : int | pint.Quantity 184 the number of samples to notify the user about 185 """ 186 187 if notify_samples is not None: 188 notify_samples = UnitConversion.convert(notify_samples, units.Sa, int) 189 self._notify_samples = notify_samples 190 self.notify_size = self.samples_to_bytes(self._notify_samples) 191 # self.notify_size = int(self._notify_samples * self.bytes_per_sample * self.num_channels) 192 return self._notify_samples 193 194 # @notify_samples.deleter 195 # def notify_samples(self) -> None: 196 # del self._notify_samples 197 198 # private 199 _memory_size : int = 0 200 _c_buffer = None # Internal numpy ctypes buffer object 201 _buffer_alignment : int = 4096 202 _np_buffer : npt.NDArray[np.int_] # Internal object on which the getter setter logic is working 203 _8bit_mode : bool = False 204 _12bit_mode : bool = False 205 _pre_trigger : int = 0 206 207 def __init__(self, card, *args, **kwargs) -> None: 208 """ 209 Initialize the DataTransfer object with a card object and additional arguments 210 211 Parameters 212 ---------- 213 card : Card 214 the card object that is used for the data transfer 215 *args : list 216 list of additional arguments 217 **kwargs : dict 218 dictionary of additional keyword arguments 219 """ 220 221 self.buffer_size = 0 222 self.notify_size = 0 223 self.num_channels = 0 224 self.bytes_per_sample = 0 225 self.bits_per_sample = 0 226 227 self.current_user_pos = 0 228 229 self._buffer_samples = 0 230 self._notify_samples = 0 231 self._memory_size = 0 232 self._c_buffer = None 233 self._buffer_alignment = 4096 234 self._np_buffer = None 235 self._8bit_mode = False 236 self._12bit_mode = False 237 self._pre_trigger = 0 238 239 super().__init__(card, *args, **kwargs) 240 self.buffer_type = SPCM_BUF_DATA 241 self._bytes_per_sample() 242 self._bits_per_sample() 243 self.num_channels = self.card.active_channels() 244 245 # Find out the direction of transfer 246 if self.function_type == SPCM_TYPE_AI or self.function_type == SPCM_TYPE_DI: 247 self.direction = Direction.Acquisition 248 elif self.function_type == SPCM_TYPE_AO or self.function_type == SPCM_TYPE_DO: 249 self.direction = Direction.Generation 250 else: 251 self.direction = Direction.Undefined 252 253 def _sample_rate(self) -> pint.Quantity: 254 """ 255 Get the sample rate of the card 256 257 Returns 258 ------- 259 pint.Quantity 260 the sample rate of the card in Hz as a pint quantity 261 """ 262 return self.card.get_i(SPC_SAMPLERATE) * units.Hz 263 264 def memory_size(self, memory_size : int = None) -> int: 265 """ 266 Sets the memory size in samples per channel. The memory size setting must be set before transferring 267 data to the card. (see register `SPC_MEMSIZE` in the manual) 268 269 Parameters 270 ---------- 271 memory_size : int | pint.Quantity 272 the size of the memory in Bytes 273 """ 274 275 if memory_size is not None: 276 memory_size = UnitConversion.convert(memory_size, units.Sa, int) 277 self.card.set_i(SPC_MEMSIZE, memory_size) 278 self._memory_size = self.card.get_i(SPC_MEMSIZE) 279 return self._memory_size 280 281 def output_buffer_size(self, buffer_samples : int = None) -> int: 282 """ 283 Set the size of the output buffer (see register `SPC_DATA_OUTBUFSIZE` in the manual) 284 285 Parameters 286 ---------- 287 buffer_samples : int | pint.Quantity 288 the size of the output buffer in Bytes 289 """ 290 291 if buffer_samples is not None: 292 buffer_samples = UnitConversion.convert(buffer_samples, units.B, int) 293 buffer_size = self.samples_to_bytes(buffer_size) 294 self.card.set_i(SPC_DATA_OUTBUFSIZE, buffer_size) 295 return self.card.get_i(SPC_DATA_OUTBUFSIZE) 296 297 def loops(self, loops : int = None) -> int: 298 return self.card.loops(loops) 299 300 def _bits_per_sample(self) -> int: 301 """ 302 Get the number of bits per sample 303 304 Returns 305 ------- 306 int 307 number of bits per sample 308 """ 309 if self._8bit_mode: 310 self.bits_per_sample = 8 311 elif self._12bit_mode: 312 self.bits_per_sample = 12 313 else: 314 self.bits_per_sample = self.card.bits_per_sample() 315 316 def _bytes_per_sample(self) -> int: 317 """ 318 Get the number of bytes per sample 319 320 Returns 321 ------- 322 int 323 number of bytes per sample 324 """ 325 if self._8bit_mode: 326 self.bytes_per_sample = 1 327 elif self._12bit_mode: 328 self.bytes_per_sample = 1.5 329 else: 330 self.bytes_per_sample = self.card.bytes_per_sample() 331 332 def pre_trigger(self, num_samples : int = None) -> int: 333 """ 334 Set the number of pre trigger samples (see register `SPC_PRETRIGGER` in the manual) 335 336 Parameters 337 ---------- 338 num_samples : int | pint.Quantity 339 the number of pre trigger samples 340 341 Returns 342 ------- 343 int 344 the number of pre trigger samples 345 """ 346 347 if num_samples is not None: 348 num_samples = UnitConversion.convert(num_samples, units.Sa, int) 349 self.card.set_i(SPC_PRETRIGGER, num_samples) 350 self._pre_trigger = self.card.get_i(SPC_PRETRIGGER) 351 return self._pre_trigger 352 353 def post_trigger(self, num_samples : int = None) -> int: 354 """ 355 Set the number of post trigger samples (see register `SPC_POSTTRIGGER` in the manual) 356 357 Parameters 358 ---------- 359 num_samples : int | pint.Quantity 360 the number of post trigger samples 361 362 Returns 363 ------- 364 int 365 the number of post trigger samples 366 """ 367 368 if self._memory_size < num_samples: 369 raise ValueError("The number of post trigger samples needs to be smaller than the total number of samples") 370 if num_samples is not None: 371 num_samples = UnitConversion.convert(num_samples, units.Sa, int) 372 self.card.set_i(SPC_POSTTRIGGER, num_samples) 373 post_trigger = self.card.get_i(SPC_POSTTRIGGER) 374 self._pre_trigger = self._memory_size - post_trigger 375 return post_trigger 376 377 def allocate_buffer(self, num_samples : int, no_reshape = False) -> None: 378 """ 379 Memory allocation for the buffer that is used for communicating with the card 380 381 Parameters 382 ---------- 383 num_samples : int | pint.Quantity = None 384 use the number of samples an get the number of active channels and bytes per samples directly from the card 385 """ 386 387 self.buffer_samples = UnitConversion.convert(num_samples, units.Sa, int) 388 389 sample_type = self.numpy_type() 390 391 dwMask = self._buffer_alignment - 1 392 393 item_size = sample_type(0).itemsize 394 # allocate a buffer (numpy array) for DMA transfer: a little bigger one to have room for address alignment 395 databuffer_unaligned = np.empty(((self._buffer_alignment + self.buffer_size) // item_size, ), dtype = sample_type) # byte count to sample (// = integer division) 396 # two numpy-arrays may share the same memory: skip the begin up to the alignment boundary (ArrayVariable[SKIP_VALUE:]) 397 # Address of data-memory from numpy-array: ArrayVariable.__array_interface__['data'][0] 398 start_pos_samples = ((self._buffer_alignment - (databuffer_unaligned.__array_interface__['data'][0] & dwMask)) // item_size) 399 self.buffer = databuffer_unaligned[start_pos_samples:start_pos_samples + (self.buffer_size // item_size)] # byte address to sample size 400 if self.bits_per_sample > 1 and not self._12bit_mode and not no_reshape: 401 self.buffer = self.buffer.reshape((self.num_channels, self.buffer_samples), order='F') # index definition: [channel, sample] ! 402 403 def start_buffer_transfer(self, *args, buffer_type=SPCM_BUF_DATA, direction=None, notify_samples=None, transfer_offset=None, transfer_length=None, exception_num_samples=False) -> None: 404 """ 405 Start the transfer of the data to or from the card (see the API function `spcm_dwDefTransfer_i64` in the manual) 406 407 Parameters 408 ---------- 409 *args : list 410 list of additonal arguments that are added as flags to the start dma command 411 buffer_type : int 412 the type of buffer that is used for the transfer 413 direction : int 414 the direction of the transfer 415 notify_samples : int 416 the number of samples to notify the user about 417 transfer_offset : int 418 the offset of the transfer 419 transfer_length : int 420 the length of the transfer 421 exception_num_samples : bool 422 if True, an exception is raised if the number of samples is not a multiple of the notify samples. The automatic buffer handling only works with the number of samples being a multiple of the notify samples. 423 424 Raises 425 ------ 426 SpcmException 427 """ 428 429 self.notify_samples(UnitConversion.convert(notify_samples, units.Sa, int)) 430 transfer_offset = UnitConversion.convert(transfer_offset, units.Sa, int) 431 transfer_length = UnitConversion.convert(transfer_length, units.Sa, int) 432 433 if self.buffer is None: 434 raise SpcmException(text="No buffer defined for transfer") 435 if buffer_type: 436 self.buffer_type = buffer_type 437 if direction is None: 438 if self.direction == Direction.Acquisition: 439 direction = SPCM_DIR_CARDTOPC 440 elif self.direction == Direction.Generation: 441 direction = SPCM_DIR_PCTOCARD 442 else: 443 raise SpcmException(text="Please define a direction for transfer (SPCM_DIR_CARDTOPC or SPCM_DIR_PCTOCARD)") 444 445 if self._notify_samples != 0 and np.remainder(self.buffer_samples, self._notify_samples) and exception_num_samples: 446 raise SpcmException("The number of samples needs to be a multiple of the notify samples.") 447 448 if transfer_offset: 449 transfer_offset_bytes = self.samples_to_bytes(transfer_offset) 450 # transfer_offset_bytes = transfer_offset * self.bytes_per_sample * self.num_channels 451 else: 452 transfer_offset_bytes = 0 453 454 self.buffer_samples = transfer_length 455 456 # we define the buffer for transfer and start the DMA transfer 457 self.card._print("Starting the DMA transfer and waiting until data is in board memory") 458 self._c_buffer = self.buffer.ctypes.data_as(c_void_p) 459 self.card._check_error(spcm_dwDefTransfer_i64(self.card._handle, self.buffer_type, direction, self.notify_size, self._c_buffer, transfer_offset_bytes, self.buffer_size)) 460 461 # Execute additional commands if available 462 cmd = 0 463 for arg in args: 464 cmd |= arg 465 self.card.cmd(cmd) 466 self.card._print("... data transfer started") 467 468 def duration(self, duration : pint.Quantity, pre_trigger_duration : pint.Quantity = None, post_trigger_duration : pint.Quantity = None) -> None: 469 """ 470 Set the duration of the data transfer 471 472 Parameters 473 ---------- 474 duration : pint.Quantity 475 the duration of the data transfer 476 pre_trigger_duration : pint.Quantity = None 477 the duration before the trigger event 478 post_trigger_duration : pint.Quantity = None 479 the duration after the trigger event 480 481 Returns 482 ------- 483 pint.Quantity 484 the duration of the data transfer 485 """ 486 487 if pre_trigger_duration is None and post_trigger_duration is None: 488 raise ValueError("Please define either pre_trigger_duration or post_trigger_duration") 489 490 memsize_min = self.card.get_i(SPC_AVAILMEMSIZE_MIN) 491 memsize_max = self.card.get_i(SPC_AVAILMEMSIZE_MAX) 492 memsize_stp = self.card.get_i(SPC_AVAILMEMSIZE_STEP) 493 num_samples = (duration * self._sample_rate()).to_base_units().magnitude 494 num_samples = np.ceil(num_samples / memsize_stp) * memsize_stp 495 num_samples = np.clip(num_samples, memsize_min, memsize_max) 496 num_samples = int(num_samples) 497 self.memory_size(num_samples) 498 self.allocate_buffer(num_samples) 499 if pre_trigger_duration is not None: 500 pre_min = self.card.get_i(SPC_AVAILPRETRIGGER_MIN) 501 pre_max = self.card.get_i(SPC_AVAILPRETRIGGER_MAX) 502 pre_stp = self.card.get_i(SPC_AVAILPRETRIGGER_STEP) 503 pre_samples = (pre_trigger_duration * self._sample_rate()).to_base_units().magnitude 504 pre_samples = np.ceil(pre_samples / pre_stp) * pre_stp 505 pre_samples = np.clip(pre_samples, pre_min, pre_max) 506 pre_samples = int(post_samples) 507 self.post_trigger(post_samples) 508 if post_trigger_duration is not None: 509 post_min = self.card.get_i(SPC_AVAILPOSTTRIGGER_MIN) 510 post_max = self.card.get_i(SPC_AVAILPOSTTRIGGER_MAX) 511 post_stp = self.card.get_i(SPC_AVAILPOSTTRIGGER_STEP) 512 post_samples = (post_trigger_duration * self._sample_rate()).to_base_units().magnitude 513 post_samples = np.ceil(post_samples / post_stp) * post_stp 514 post_samples = np.clip(post_samples, post_min, post_max) 515 post_samples = int(post_samples) 516 self.post_trigger(post_samples) 517 return num_samples, post_samples 518 519 def time_data(self, total_num_samples : int = None) -> npt.NDArray: 520 """ 521 Get the time array for the data buffer 522 523 Parameters 524 ---------- 525 total_num_samples : int | pint.Quantity 526 the total number of samples 527 528 Returns 529 ------- 530 numpy array 531 the time array 532 """ 533 534 sample_rate = self._sample_rate() 535 if total_num_samples is None: 536 total_num_samples = self._buffer_samples 537 total_num_samples = UnitConversion.convert(total_num_samples, units.Sa, int) 538 pre_trigger = UnitConversion.convert(self._pre_trigger, units.Sa, int) 539 return ((np.arange(total_num_samples) - pre_trigger) / sample_rate).to_base_units() 540 541 def unpack_12bit_buffer(self, data : npt.NDArray[np.int_] = None) -> npt.NDArray[np.int_]: 542 """ 543 Unpack the 12bit buffer to a 16bit buffer 544 545 Returns 546 ------- 547 numpy array 548 the unpacked 16bit buffer 549 """ 550 551 if not self._12bit_mode: 552 raise SpcmException("The card is not in 12bit packed mode") 553 554 if data is None: 555 data = self.buffer 556 557 fst_int8, mid_int8, lst_int8 = np.reshape(data, (data.shape[0] // 3, 3)).astype(np.int16).T 558 nibble_h = (mid_int8 >> 0) & 0x0F 559 nibble_m = (fst_int8 >> 4) & 0x0F 560 nibble_l = (fst_int8 >> 0) & 0x0F 561 fst_int12 = ((nibble_h << 12) >> 4) | (nibble_m << 4) | (nibble_l << 0) 562 nibble_h = (lst_int8 >> 4) & 0x0F 563 nibble_m = (lst_int8 >> 0) & 0x0F 564 nibble_l = (mid_int8 >> 4) & 0x0F 565 snd_int12 = ((nibble_h << 12) >> 4) | (nibble_m << 4) | (nibble_l << 0) 566 data_int12 = np.concatenate((fst_int12[:, None], snd_int12[:, None]), axis=1).reshape((-1,)) 567 data_int12 = data_int12.reshape((self.num_channels, self._buffer_samples), order='F') 568 return data_int12 569 570 def unpackbits(self): 571 """ 572 Unpack the buffer to bits 573 574 Returns 575 ------- 576 numpy array 577 the unpacked buffer 578 """ 579 data = self.buffer 580 dshape = list(data.shape) 581 return_data = data.reshape([-1, 1]) 582 num_bits = return_data.dtype.itemsize * 8 583 mask = 2**np.arange(num_bits, dtype=return_data.dtype).reshape([1, num_bits]) 584 return (return_data & mask).astype(bool).astype(int).reshape(dshape + [num_bits]) 585 586 def tofile(self, filename : str, **kwargs) -> None: 587 """ 588 Export the buffer to a file. The file format is determined by the file extension 589 Supported file formats are: 590 * .bin: raw binary file 591 * .csv: comma-separated values file 592 * .npy: numpy binary file 593 * .npz: compressed numpy binary file 594 * .txt: whitespace-delimited text file 595 * .h5: hdf5 file format 596 597 Parameters 598 ---------- 599 filename : str 600 the name of the file that the buffer should be exported to 601 602 Raises 603 ------ 604 ImportError 605 if the file format is not supported 606 """ 607 608 file_path = Path(filename) 609 if file_path.suffix == '.bin': 610 dtype = kwargs.get('dtype', self.numpy_type()) 611 self.buffer.tofile(file_path, dtype=dtype) 612 elif file_path.suffix == '.csv': 613 delimiter = kwargs.get('delimiter', ',') 614 np.savetxt(file_path, self.buffer, delimiter=delimiter) 615 elif file_path.suffix == '.npy': 616 np.save(file_path, self.buffer) 617 elif file_path.suffix == '.npz': 618 np.savez_compressed(file_path, self.buffer) 619 elif file_path.suffix == '.txt': 620 np.savetxt(file_path, self.buffer, fmt='%d') 621 elif file_path.suffix == '.h5' or file_path.suffix == '.hdf5': 622 import h5py 623 with h5py.File(file_path, 'w') as f: 624 f.create_dataset('data', data=self.buffer) 625 else: 626 raise ImportError("File format not supported") 627 628 def fromfile(self, filename : str, **kwargs) -> None: 629 """ 630 Import the buffer from a file. The file format is determined by the file extension 631 Supported file formats are: 632 * .bin: raw binary file 633 * .csv: comma-separated values file 634 * .npy: numpy binary file 635 * .npz: compressed numpy binary file 636 * .txt: whitespace-delimited text file 637 * .h5: hdf5 file format 638 639 Parameters 640 ---------- 641 filename : str 642 the name of the file that the buffer should be imported from 643 644 Raises 645 ------ 646 ImportError 647 if the file format is not supported 648 """ 649 650 file_path = Path(filename) 651 if file_path.suffix == '.bin': 652 dtype = kwargs.get('dtype', self.numpy_type()) 653 shape = kwargs.get('shape', (self.num_channels, self.buffer_size // self.num_channels)) 654 buffer = np.fromfile(file_path, dtype=dtype) 655 self.buffer[:] = buffer.reshape(shape, order='C') 656 elif file_path.suffix == '.csv': 657 delimiter = kwargs.get('delimiter', ',') 658 self.buffer[:] = np.loadtxt(file_path, delimiter=delimiter) 659 elif file_path.suffix == '.npy': 660 self.buffer[:] = np.load(file_path) 661 elif file_path.suffix == '.npz': 662 data = np.load(file_path) 663 self.buffer[:] = data['arr_0'] 664 elif file_path.suffix == '.txt': 665 self.buffer[:] = np.loadtxt(file_path) 666 elif file_path.suffix == '.h5' or file_path.suffix == '.hdf5': 667 import h5py 668 with h5py.File(file_path, 'r') as f: 669 self.buffer[:] = f['data'][()] 670 else: 671 raise ImportError("File format not supported") 672 673 def avail_card_len(self, available_samples : int = 0) -> None: 674 """ 675 Set the amount of data that has been read out of the data buffer (see register `SPC_DATA_AVAIL_CARD_LEN` in the manual) 676 677 Parameters 678 ---------- 679 available_samples : int | pint.Quantity 680 the amount of data that is available for reading 681 """ 682 683 available_samples = UnitConversion.convert(available_samples, units.Sa, int) 684 # print(available_samples, self.bytes_per_sample, self.num_channels) 685 available_bytes = self.samples_to_bytes(available_samples) 686 self.card.set_i(SPC_DATA_AVAIL_CARD_LEN, available_bytes) 687 688 def avail_user_pos(self, in_bytes : bool = False) -> int: 689 """ 690 Get the current position of the pointer in the data buffer (see register `SPC_DATA_AVAIL_USER_POS` in the manual) 691 692 Parameters 693 ---------- 694 in_bytes : bool 695 if True, the position is returned in bytes 696 697 Returns 698 ------- 699 int 700 pointer position 701 """ 702 703 self.current_user_pos = self.card.get_i(SPC_DATA_AVAIL_USER_POS) 704 if not in_bytes: 705 self.current_user_pos = self.bytes_to_samples(self.current_user_pos) 706 return self.current_user_pos 707 708 def avail_user_len(self, in_bytes : bool = False) -> int: 709 """ 710 Get the current length of the data in the data buffer (see register `SPC_DATA_AVAIL_USER_LEN` in the manual) 711 712 Parameters 713 ---------- 714 in_bytes : bool 715 if True, the length is returned in bytes 716 717 Returns 718 ------- 719 int 720 data length available 721 """ 722 723 user_len = self.card.get_i(SPC_DATA_AVAIL_USER_LEN) 724 if not in_bytes: 725 user_len = self.bytes_to_samples(user_len) 726 return user_len 727 728 def fill_size_promille(self, return_unit = None) -> int: 729 """ 730 Get the fill size of the data buffer (see register `SPC_FILLSIZEPROMILLE` in the manual) 731 732 Returns 733 ------- 734 int 735 fill size 736 """ 737 738 return_value = self.card.get_i(SPC_FILLSIZEPROMILLE) 739 if return_unit is not None: return_value = UnitConversion.to_unit(return_value * units.promille, return_unit) 740 return return_value 741 742 def wait_dma(self) -> None: 743 """ 744 Wait for the DMA transfer to finish (see register `M2CMD_DATA_WAITDMA` in the manual) 745 """ 746 747 self.card.cmd(M2CMD_DATA_WAITDMA) 748 wait = wait_dma 749 750 def numpy_type(self) -> npt.NDArray[np.int_]: 751 """ 752 Get the type of numpy data from number of bytes 753 754 Returns 755 ------- 756 numpy data type 757 the type of data that is used by the card 758 """ 759 760 if self._8bit_mode: 761 return np.uint8 762 if self._12bit_mode: 763 return np.int8 764 if self.bits_per_sample == 1: 765 if self.num_channels <= 8: 766 return np.uint8 767 elif self.num_channels <= 16: 768 return np.uint16 769 elif self.num_channels <= 32: 770 return np.uint32 771 return np.uint64 772 if self.bits_per_sample <= 8: 773 return np.int8 774 elif self.bits_per_sample <= 16: 775 return np.int16 776 elif self.bits_per_sample <= 32: 777 return np.int32 778 return np.int64 779 780 # Data conversion mode 781 def data_conversion(self, mode : int = None) -> int: 782 """ 783 Set the data conversion mode (see register `SPC_DATACONVERSION` in the manual) 784 785 Parameters 786 ---------- 787 mode : int 788 the data conversion mode 789 """ 790 791 if mode is not None: 792 self.card.set_i(SPC_DATACONVERSION, mode) 793 mode = self.card.get_i(SPC_DATACONVERSION) 794 self._8bit_mode = (mode == SPCM_DC_12BIT_TO_8BIT or mode == SPCM_DC_14BIT_TO_8BIT or mode == SPCM_DC_16BIT_TO_8BIT) 795 self._12bit_mode = (mode == SPCM_DC_12BIT_TO_12BITPACKED) 796 self._bits_per_sample() 797 self._bytes_per_sample() 798 return mode 799 800 def avail_data_conversion(self) -> int: 801 """ 802 Get the available data conversion modes (see register `SPC_AVAILDATACONVERSION` in the manual) 803 804 Returns 805 ------- 806 int 807 the available data conversion modes 808 """ 809 return self.card.get_i(SPC_AVAILDATACONVERSION) 810 811 # Iterator methods 812 813 iterator_index = 0 814 _max_timeout = 64 815 816 _to_transfer_samples = 0 817 _current_samples = 0 818 819 _verbose = False 820 821 def verbose(self, verbose : bool = None) -> bool: 822 """ 823 Set or get the verbose mode for the data transfer 824 825 Parameters 826 ---------- 827 verbose : bool = None 828 the verbose mode 829 """ 830 831 if verbose is not None: 832 self._verbose = verbose 833 return self._verbose 834 835 def to_transfer_samples(self, samples) -> None: 836 """ 837 This method sets the number of samples to transfer 838 839 Parameters 840 ---------- 841 samples : int | pint.Quantity 842 the number of samples to transfer 843 """ 844 845 samples = UnitConversion.convert(samples, units.Sa, int) 846 self._to_transfer_samples = samples 847 848 def __iter__(self): 849 """ 850 This method is called when the iterator is initialized 851 852 Returns 853 ------- 854 DataIterator 855 the iterator itself 856 """ 857 858 self.iterator_index = 0 859 return self 860 861 def polling(self, polling : bool = True, timer : float = 0.01) -> None: 862 """ 863 Set the polling mode for the data transfer otherwise wait_dma() is used 864 865 Parameters 866 ---------- 867 polling : bool 868 True to enable polling, False to disable polling 869 timer : float | pint.Quantity 870 the polling timer in seconds 871 """ 872 873 self._polling = polling 874 self._pollng_timer = UnitConversion.convert(timer, units.s, float) 875 876 def __next__(self) -> npt.ArrayLike: 877 """ 878 This method is called when the next element is requested from the iterator 879 880 Returns 881 ------- 882 npt.ArrayLike 883 the next data block 884 885 Raises 886 ------ 887 StopIteration 888 """ 889 timeout_counter = 0 890 891 if self.iterator_index != 0: 892 self.avail_card_len(self._notify_samples) 893 894 while True: 895 try: 896 # print(self.card.status()) 897 if not self._polling: 898 self.wait_dma() 899 else: 900 user_len = self.avail_user_len() 901 if user_len >= self._notify_samples: 902 break 903 time.sleep(0.01) 904 except SpcmTimeout: 905 self.card._print("... Timeout ({})".format(timeout_counter), end='\r') 906 timeout_counter += 1 907 if timeout_counter > self._max_timeout: 908 raise StopIteration 909 else: 910 if not self._polling: 911 break 912 913 self.iterator_index += 1 914 915 fill_size = self.fill_size_promille() 916 917 self._current_samples += self._notify_samples 918 if self._to_transfer_samples != 0 and self._to_transfer_samples < self._current_samples: 919 raise StopIteration 920 921 user_pos = self.avail_user_pos() 922 923 # self.card._print("Fill size: {}% Pos:{:08x} Len:{:08x} Total:{:.2f} MiS / {:.2f} MiS".format(fill_size/10, user_pos, user_len, self._current_samples / MEBI(1), self._to_transfer_samples / MEBI(1)), end='\r', verbose=self._verbose) 924 self.card._print("Fill size: {}% Pos:{:08x} Total:{:.2f} MiS / {:.2f} MiS".format(fill_size/10, user_pos, self._current_samples / MEBI(1), self._to_transfer_samples / MEBI(1)), end='\r', verbose=self._verbose) 925 926 # self.avail_card_len(self._notify_samples) # TODO this probably always a problem! Because the data is not read out yets 927 928 return self.buffer[:, user_pos:user_pos+self._notify_samples]
A high-level class to control Data Transfer to and from Spectrum Instrumentation cards.
This class is an iterator class that implements the functions __iter__
and __next__
.
This allows the user to supply the class to a for loop and iterate over the data that
is transferred from or to the card. Each iteration will return a numpy array with a data
block of size notify_samples
. In case of a digitizer you can read the data from that
block and process it. In case of a generator you can write data to the block and it's
then transferred.
For more information about what setups are available, please have a look at the user manual for your specific card.
Parameters
buffer
(NDArray[np.int_]): numpy object that can be used to write data into the spcm bufferbuffer_size
(int): defines the size of the current buffer shared between the PC and the cardbuffer_type
(int): defines the type of data in the buffer that is used for the transfernum_channels
(int): defines the number of channels that are used for the transferbytes_per_sample
(int): defines the number of bytes per samplebits_per_sample
(int): defines the number of bits per sample
207 def __init__(self, card, *args, **kwargs) -> None: 208 """ 209 Initialize the DataTransfer object with a card object and additional arguments 210 211 Parameters 212 ---------- 213 card : Card 214 the card object that is used for the data transfer 215 *args : list 216 list of additional arguments 217 **kwargs : dict 218 dictionary of additional keyword arguments 219 """ 220 221 self.buffer_size = 0 222 self.notify_size = 0 223 self.num_channels = 0 224 self.bytes_per_sample = 0 225 self.bits_per_sample = 0 226 227 self.current_user_pos = 0 228 229 self._buffer_samples = 0 230 self._notify_samples = 0 231 self._memory_size = 0 232 self._c_buffer = None 233 self._buffer_alignment = 4096 234 self._np_buffer = None 235 self._8bit_mode = False 236 self._12bit_mode = False 237 self._pre_trigger = 0 238 239 super().__init__(card, *args, **kwargs) 240 self.buffer_type = SPCM_BUF_DATA 241 self._bytes_per_sample() 242 self._bits_per_sample() 243 self.num_channels = self.card.active_channels() 244 245 # Find out the direction of transfer 246 if self.function_type == SPCM_TYPE_AI or self.function_type == SPCM_TYPE_DI: 247 self.direction = Direction.Acquisition 248 elif self.function_type == SPCM_TYPE_AO or self.function_type == SPCM_TYPE_DO: 249 self.direction = Direction.Generation 250 else: 251 self.direction = Direction.Undefined
Initialize the DataTransfer object with a card object and additional arguments
Parameters
- card (Card): the card object that is used for the data transfer
- *args (list): list of additional arguments
- **kwargs (dict): dictionary of additional keyword arguments
71 @property 72 def buffer(self) -> npt.NDArray[np.int_]: 73 """ 74 The numpy buffer object that interfaces the Card and can be written and read from 75 76 Returns 77 ------- 78 numpy array 79 the numpy buffer object with the following array index definition: 80 `[channel, sample]` 81 or in case of multiple recording / replay: 82 `[segment, sample, channel]` 83 """ 84 return self._np_buffer
The numpy buffer object that interfaces the Card and can be written and read from
Returns
- numpy array: the numpy buffer object with the following array index definition:
[channel, sample]
or in case of multiple recording / replay:[segment, sample, channel]
94 @property 95 def buffer_samples(self) -> int: 96 """ 97 The number of samples in the buffer 98 99 Returns 100 ------- 101 int 102 the number of samples in the buffer 103 """ 104 return self._buffer_samples
The number of samples in the buffer
Returns
- int: the number of samples in the buffer
122 def bytes_to_samples(self, num_bytes : int) -> int: 123 """ 124 Convert bytes to samples 125 126 Parameters 127 ---------- 128 bytes : int 129 the number of bytes 130 131 Returns 132 ------- 133 int 134 the number of samples 135 """ 136 137 if self.bits_per_sample > 1: 138 num_samples = num_bytes // self.bytes_per_sample // self.num_channels 139 else: 140 num_samples = num_bytes // self.num_channels * 8 141 return num_samples
Convert bytes to samples
Parameters
- bytes (int): the number of bytes
Returns
- int: the number of samples
143 def samples_to_bytes(self, num_samples : int) -> int: 144 """ 145 Convert samples to bytes 146 147 Parameters 148 ---------- 149 num_samples : int 150 the number of samples 151 152 Returns 153 ------- 154 int 155 the number of bytes 156 """ 157 158 if self.bits_per_sample > 1: 159 num_bytes = num_samples * self.bytes_per_sample * self.num_channels 160 else: 161 num_bytes = num_samples * self.num_channels // 8 162 return num_bytes
Convert samples to bytes
Parameters
- num_samples (int): the number of samples
Returns
- int: the number of bytes
177 def notify_samples(self, notify_samples : int = None) -> int: 178 """ 179 Set the number of samples to notify the user about 180 181 Parameters 182 ---------- 183 notify_samples : int | pint.Quantity 184 the number of samples to notify the user about 185 """ 186 187 if notify_samples is not None: 188 notify_samples = UnitConversion.convert(notify_samples, units.Sa, int) 189 self._notify_samples = notify_samples 190 self.notify_size = self.samples_to_bytes(self._notify_samples) 191 # self.notify_size = int(self._notify_samples * self.bytes_per_sample * self.num_channels) 192 return self._notify_samples
Set the number of samples to notify the user about
Parameters
- notify_samples (int | pint.Quantity): the number of samples to notify the user about
264 def memory_size(self, memory_size : int = None) -> int: 265 """ 266 Sets the memory size in samples per channel. The memory size setting must be set before transferring 267 data to the card. (see register `SPC_MEMSIZE` in the manual) 268 269 Parameters 270 ---------- 271 memory_size : int | pint.Quantity 272 the size of the memory in Bytes 273 """ 274 275 if memory_size is not None: 276 memory_size = UnitConversion.convert(memory_size, units.Sa, int) 277 self.card.set_i(SPC_MEMSIZE, memory_size) 278 self._memory_size = self.card.get_i(SPC_MEMSIZE) 279 return self._memory_size
Sets the memory size in samples per channel. The memory size setting must be set before transferring
data to the card. (see register SPC_MEMSIZE
in the manual)
Parameters
- memory_size (int | pint.Quantity): the size of the memory in Bytes
281 def output_buffer_size(self, buffer_samples : int = None) -> int: 282 """ 283 Set the size of the output buffer (see register `SPC_DATA_OUTBUFSIZE` in the manual) 284 285 Parameters 286 ---------- 287 buffer_samples : int | pint.Quantity 288 the size of the output buffer in Bytes 289 """ 290 291 if buffer_samples is not None: 292 buffer_samples = UnitConversion.convert(buffer_samples, units.B, int) 293 buffer_size = self.samples_to_bytes(buffer_size) 294 self.card.set_i(SPC_DATA_OUTBUFSIZE, buffer_size) 295 return self.card.get_i(SPC_DATA_OUTBUFSIZE)
Set the size of the output buffer (see register SPC_DATA_OUTBUFSIZE
in the manual)
Parameters
- buffer_samples (int | pint.Quantity): the size of the output buffer in Bytes
332 def pre_trigger(self, num_samples : int = None) -> int: 333 """ 334 Set the number of pre trigger samples (see register `SPC_PRETRIGGER` in the manual) 335 336 Parameters 337 ---------- 338 num_samples : int | pint.Quantity 339 the number of pre trigger samples 340 341 Returns 342 ------- 343 int 344 the number of pre trigger samples 345 """ 346 347 if num_samples is not None: 348 num_samples = UnitConversion.convert(num_samples, units.Sa, int) 349 self.card.set_i(SPC_PRETRIGGER, num_samples) 350 self._pre_trigger = self.card.get_i(SPC_PRETRIGGER) 351 return self._pre_trigger
Set the number of pre trigger samples (see register SPC_PRETRIGGER
in the manual)
Parameters
- num_samples (int | pint.Quantity): the number of pre trigger samples
Returns
- int: the number of pre trigger samples
353 def post_trigger(self, num_samples : int = None) -> int: 354 """ 355 Set the number of post trigger samples (see register `SPC_POSTTRIGGER` in the manual) 356 357 Parameters 358 ---------- 359 num_samples : int | pint.Quantity 360 the number of post trigger samples 361 362 Returns 363 ------- 364 int 365 the number of post trigger samples 366 """ 367 368 if self._memory_size < num_samples: 369 raise ValueError("The number of post trigger samples needs to be smaller than the total number of samples") 370 if num_samples is not None: 371 num_samples = UnitConversion.convert(num_samples, units.Sa, int) 372 self.card.set_i(SPC_POSTTRIGGER, num_samples) 373 post_trigger = self.card.get_i(SPC_POSTTRIGGER) 374 self._pre_trigger = self._memory_size - post_trigger 375 return post_trigger
Set the number of post trigger samples (see register SPC_POSTTRIGGER
in the manual)
Parameters
- num_samples (int | pint.Quantity): the number of post trigger samples
Returns
- int: the number of post trigger samples
377 def allocate_buffer(self, num_samples : int, no_reshape = False) -> None: 378 """ 379 Memory allocation for the buffer that is used for communicating with the card 380 381 Parameters 382 ---------- 383 num_samples : int | pint.Quantity = None 384 use the number of samples an get the number of active channels and bytes per samples directly from the card 385 """ 386 387 self.buffer_samples = UnitConversion.convert(num_samples, units.Sa, int) 388 389 sample_type = self.numpy_type() 390 391 dwMask = self._buffer_alignment - 1 392 393 item_size = sample_type(0).itemsize 394 # allocate a buffer (numpy array) for DMA transfer: a little bigger one to have room for address alignment 395 databuffer_unaligned = np.empty(((self._buffer_alignment + self.buffer_size) // item_size, ), dtype = sample_type) # byte count to sample (// = integer division) 396 # two numpy-arrays may share the same memory: skip the begin up to the alignment boundary (ArrayVariable[SKIP_VALUE:]) 397 # Address of data-memory from numpy-array: ArrayVariable.__array_interface__['data'][0] 398 start_pos_samples = ((self._buffer_alignment - (databuffer_unaligned.__array_interface__['data'][0] & dwMask)) // item_size) 399 self.buffer = databuffer_unaligned[start_pos_samples:start_pos_samples + (self.buffer_size // item_size)] # byte address to sample size 400 if self.bits_per_sample > 1 and not self._12bit_mode and not no_reshape: 401 self.buffer = self.buffer.reshape((self.num_channels, self.buffer_samples), order='F') # index definition: [channel, sample] !
Memory allocation for the buffer that is used for communicating with the card
Parameters
- num_samples (int | pint.Quantity = None): use the number of samples an get the number of active channels and bytes per samples directly from the card
403 def start_buffer_transfer(self, *args, buffer_type=SPCM_BUF_DATA, direction=None, notify_samples=None, transfer_offset=None, transfer_length=None, exception_num_samples=False) -> None: 404 """ 405 Start the transfer of the data to or from the card (see the API function `spcm_dwDefTransfer_i64` in the manual) 406 407 Parameters 408 ---------- 409 *args : list 410 list of additonal arguments that are added as flags to the start dma command 411 buffer_type : int 412 the type of buffer that is used for the transfer 413 direction : int 414 the direction of the transfer 415 notify_samples : int 416 the number of samples to notify the user about 417 transfer_offset : int 418 the offset of the transfer 419 transfer_length : int 420 the length of the transfer 421 exception_num_samples : bool 422 if True, an exception is raised if the number of samples is not a multiple of the notify samples. The automatic buffer handling only works with the number of samples being a multiple of the notify samples. 423 424 Raises 425 ------ 426 SpcmException 427 """ 428 429 self.notify_samples(UnitConversion.convert(notify_samples, units.Sa, int)) 430 transfer_offset = UnitConversion.convert(transfer_offset, units.Sa, int) 431 transfer_length = UnitConversion.convert(transfer_length, units.Sa, int) 432 433 if self.buffer is None: 434 raise SpcmException(text="No buffer defined for transfer") 435 if buffer_type: 436 self.buffer_type = buffer_type 437 if direction is None: 438 if self.direction == Direction.Acquisition: 439 direction = SPCM_DIR_CARDTOPC 440 elif self.direction == Direction.Generation: 441 direction = SPCM_DIR_PCTOCARD 442 else: 443 raise SpcmException(text="Please define a direction for transfer (SPCM_DIR_CARDTOPC or SPCM_DIR_PCTOCARD)") 444 445 if self._notify_samples != 0 and np.remainder(self.buffer_samples, self._notify_samples) and exception_num_samples: 446 raise SpcmException("The number of samples needs to be a multiple of the notify samples.") 447 448 if transfer_offset: 449 transfer_offset_bytes = self.samples_to_bytes(transfer_offset) 450 # transfer_offset_bytes = transfer_offset * self.bytes_per_sample * self.num_channels 451 else: 452 transfer_offset_bytes = 0 453 454 self.buffer_samples = transfer_length 455 456 # we define the buffer for transfer and start the DMA transfer 457 self.card._print("Starting the DMA transfer and waiting until data is in board memory") 458 self._c_buffer = self.buffer.ctypes.data_as(c_void_p) 459 self.card._check_error(spcm_dwDefTransfer_i64(self.card._handle, self.buffer_type, direction, self.notify_size, self._c_buffer, transfer_offset_bytes, self.buffer_size)) 460 461 # Execute additional commands if available 462 cmd = 0 463 for arg in args: 464 cmd |= arg 465 self.card.cmd(cmd) 466 self.card._print("... data transfer started")
Start the transfer of the data to or from the card (see the API function spcm_dwDefTransfer_i64
in the manual)
Parameters
- *args (list): list of additonal arguments that are added as flags to the start dma command
- buffer_type (int): the type of buffer that is used for the transfer
- direction (int): the direction of the transfer
- notify_samples (int): the number of samples to notify the user about
- transfer_offset (int): the offset of the transfer
- transfer_length (int): the length of the transfer
- exception_num_samples (bool): if True, an exception is raised if the number of samples is not a multiple of the notify samples. The automatic buffer handling only works with the number of samples being a multiple of the notify samples.
Raises
- SpcmException
468 def duration(self, duration : pint.Quantity, pre_trigger_duration : pint.Quantity = None, post_trigger_duration : pint.Quantity = None) -> None: 469 """ 470 Set the duration of the data transfer 471 472 Parameters 473 ---------- 474 duration : pint.Quantity 475 the duration of the data transfer 476 pre_trigger_duration : pint.Quantity = None 477 the duration before the trigger event 478 post_trigger_duration : pint.Quantity = None 479 the duration after the trigger event 480 481 Returns 482 ------- 483 pint.Quantity 484 the duration of the data transfer 485 """ 486 487 if pre_trigger_duration is None and post_trigger_duration is None: 488 raise ValueError("Please define either pre_trigger_duration or post_trigger_duration") 489 490 memsize_min = self.card.get_i(SPC_AVAILMEMSIZE_MIN) 491 memsize_max = self.card.get_i(SPC_AVAILMEMSIZE_MAX) 492 memsize_stp = self.card.get_i(SPC_AVAILMEMSIZE_STEP) 493 num_samples = (duration * self._sample_rate()).to_base_units().magnitude 494 num_samples = np.ceil(num_samples / memsize_stp) * memsize_stp 495 num_samples = np.clip(num_samples, memsize_min, memsize_max) 496 num_samples = int(num_samples) 497 self.memory_size(num_samples) 498 self.allocate_buffer(num_samples) 499 if pre_trigger_duration is not None: 500 pre_min = self.card.get_i(SPC_AVAILPRETRIGGER_MIN) 501 pre_max = self.card.get_i(SPC_AVAILPRETRIGGER_MAX) 502 pre_stp = self.card.get_i(SPC_AVAILPRETRIGGER_STEP) 503 pre_samples = (pre_trigger_duration * self._sample_rate()).to_base_units().magnitude 504 pre_samples = np.ceil(pre_samples / pre_stp) * pre_stp 505 pre_samples = np.clip(pre_samples, pre_min, pre_max) 506 pre_samples = int(post_samples) 507 self.post_trigger(post_samples) 508 if post_trigger_duration is not None: 509 post_min = self.card.get_i(SPC_AVAILPOSTTRIGGER_MIN) 510 post_max = self.card.get_i(SPC_AVAILPOSTTRIGGER_MAX) 511 post_stp = self.card.get_i(SPC_AVAILPOSTTRIGGER_STEP) 512 post_samples = (post_trigger_duration * self._sample_rate()).to_base_units().magnitude 513 post_samples = np.ceil(post_samples / post_stp) * post_stp 514 post_samples = np.clip(post_samples, post_min, post_max) 515 post_samples = int(post_samples) 516 self.post_trigger(post_samples) 517 return num_samples, post_samples
Set the duration of the data transfer
Parameters
- duration (pint.Quantity): the duration of the data transfer
- pre_trigger_duration (pint.Quantity = None): the duration before the trigger event
- post_trigger_duration (pint.Quantity = None): the duration after the trigger event
Returns
- pint.Quantity: the duration of the data transfer
519 def time_data(self, total_num_samples : int = None) -> npt.NDArray: 520 """ 521 Get the time array for the data buffer 522 523 Parameters 524 ---------- 525 total_num_samples : int | pint.Quantity 526 the total number of samples 527 528 Returns 529 ------- 530 numpy array 531 the time array 532 """ 533 534 sample_rate = self._sample_rate() 535 if total_num_samples is None: 536 total_num_samples = self._buffer_samples 537 total_num_samples = UnitConversion.convert(total_num_samples, units.Sa, int) 538 pre_trigger = UnitConversion.convert(self._pre_trigger, units.Sa, int) 539 return ((np.arange(total_num_samples) - pre_trigger) / sample_rate).to_base_units()
Get the time array for the data buffer
Parameters
- total_num_samples (int | pint.Quantity): the total number of samples
Returns
- numpy array: the time array
541 def unpack_12bit_buffer(self, data : npt.NDArray[np.int_] = None) -> npt.NDArray[np.int_]: 542 """ 543 Unpack the 12bit buffer to a 16bit buffer 544 545 Returns 546 ------- 547 numpy array 548 the unpacked 16bit buffer 549 """ 550 551 if not self._12bit_mode: 552 raise SpcmException("The card is not in 12bit packed mode") 553 554 if data is None: 555 data = self.buffer 556 557 fst_int8, mid_int8, lst_int8 = np.reshape(data, (data.shape[0] // 3, 3)).astype(np.int16).T 558 nibble_h = (mid_int8 >> 0) & 0x0F 559 nibble_m = (fst_int8 >> 4) & 0x0F 560 nibble_l = (fst_int8 >> 0) & 0x0F 561 fst_int12 = ((nibble_h << 12) >> 4) | (nibble_m << 4) | (nibble_l << 0) 562 nibble_h = (lst_int8 >> 4) & 0x0F 563 nibble_m = (lst_int8 >> 0) & 0x0F 564 nibble_l = (mid_int8 >> 4) & 0x0F 565 snd_int12 = ((nibble_h << 12) >> 4) | (nibble_m << 4) | (nibble_l << 0) 566 data_int12 = np.concatenate((fst_int12[:, None], snd_int12[:, None]), axis=1).reshape((-1,)) 567 data_int12 = data_int12.reshape((self.num_channels, self._buffer_samples), order='F') 568 return data_int12
Unpack the 12bit buffer to a 16bit buffer
Returns
- numpy array: the unpacked 16bit buffer
570 def unpackbits(self): 571 """ 572 Unpack the buffer to bits 573 574 Returns 575 ------- 576 numpy array 577 the unpacked buffer 578 """ 579 data = self.buffer 580 dshape = list(data.shape) 581 return_data = data.reshape([-1, 1]) 582 num_bits = return_data.dtype.itemsize * 8 583 mask = 2**np.arange(num_bits, dtype=return_data.dtype).reshape([1, num_bits]) 584 return (return_data & mask).astype(bool).astype(int).reshape(dshape + [num_bits])
Unpack the buffer to bits
Returns
- numpy array: the unpacked buffer
586 def tofile(self, filename : str, **kwargs) -> None: 587 """ 588 Export the buffer to a file. The file format is determined by the file extension 589 Supported file formats are: 590 * .bin: raw binary file 591 * .csv: comma-separated values file 592 * .npy: numpy binary file 593 * .npz: compressed numpy binary file 594 * .txt: whitespace-delimited text file 595 * .h5: hdf5 file format 596 597 Parameters 598 ---------- 599 filename : str 600 the name of the file that the buffer should be exported to 601 602 Raises 603 ------ 604 ImportError 605 if the file format is not supported 606 """ 607 608 file_path = Path(filename) 609 if file_path.suffix == '.bin': 610 dtype = kwargs.get('dtype', self.numpy_type()) 611 self.buffer.tofile(file_path, dtype=dtype) 612 elif file_path.suffix == '.csv': 613 delimiter = kwargs.get('delimiter', ',') 614 np.savetxt(file_path, self.buffer, delimiter=delimiter) 615 elif file_path.suffix == '.npy': 616 np.save(file_path, self.buffer) 617 elif file_path.suffix == '.npz': 618 np.savez_compressed(file_path, self.buffer) 619 elif file_path.suffix == '.txt': 620 np.savetxt(file_path, self.buffer, fmt='%d') 621 elif file_path.suffix == '.h5' or file_path.suffix == '.hdf5': 622 import h5py 623 with h5py.File(file_path, 'w') as f: 624 f.create_dataset('data', data=self.buffer) 625 else: 626 raise ImportError("File format not supported")
Export the buffer to a file. The file format is determined by the file extension Supported file formats are:
- .bin: raw binary file
- .csv: comma-separated values file
- .npy: numpy binary file
- .npz: compressed numpy binary file
- .txt: whitespace-delimited text file
- .h5: hdf5 file format
Parameters
- filename (str): the name of the file that the buffer should be exported to
Raises
- ImportError: if the file format is not supported
628 def fromfile(self, filename : str, **kwargs) -> None: 629 """ 630 Import the buffer from a file. The file format is determined by the file extension 631 Supported file formats are: 632 * .bin: raw binary file 633 * .csv: comma-separated values file 634 * .npy: numpy binary file 635 * .npz: compressed numpy binary file 636 * .txt: whitespace-delimited text file 637 * .h5: hdf5 file format 638 639 Parameters 640 ---------- 641 filename : str 642 the name of the file that the buffer should be imported from 643 644 Raises 645 ------ 646 ImportError 647 if the file format is not supported 648 """ 649 650 file_path = Path(filename) 651 if file_path.suffix == '.bin': 652 dtype = kwargs.get('dtype', self.numpy_type()) 653 shape = kwargs.get('shape', (self.num_channels, self.buffer_size // self.num_channels)) 654 buffer = np.fromfile(file_path, dtype=dtype) 655 self.buffer[:] = buffer.reshape(shape, order='C') 656 elif file_path.suffix == '.csv': 657 delimiter = kwargs.get('delimiter', ',') 658 self.buffer[:] = np.loadtxt(file_path, delimiter=delimiter) 659 elif file_path.suffix == '.npy': 660 self.buffer[:] = np.load(file_path) 661 elif file_path.suffix == '.npz': 662 data = np.load(file_path) 663 self.buffer[:] = data['arr_0'] 664 elif file_path.suffix == '.txt': 665 self.buffer[:] = np.loadtxt(file_path) 666 elif file_path.suffix == '.h5' or file_path.suffix == '.hdf5': 667 import h5py 668 with h5py.File(file_path, 'r') as f: 669 self.buffer[:] = f['data'][()] 670 else: 671 raise ImportError("File format not supported")
Import the buffer from a file. The file format is determined by the file extension Supported file formats are:
- .bin: raw binary file
- .csv: comma-separated values file
- .npy: numpy binary file
- .npz: compressed numpy binary file
- .txt: whitespace-delimited text file
- .h5: hdf5 file format
Parameters
- filename (str): the name of the file that the buffer should be imported from
Raises
- ImportError: if the file format is not supported
673 def avail_card_len(self, available_samples : int = 0) -> None: 674 """ 675 Set the amount of data that has been read out of the data buffer (see register `SPC_DATA_AVAIL_CARD_LEN` in the manual) 676 677 Parameters 678 ---------- 679 available_samples : int | pint.Quantity 680 the amount of data that is available for reading 681 """ 682 683 available_samples = UnitConversion.convert(available_samples, units.Sa, int) 684 # print(available_samples, self.bytes_per_sample, self.num_channels) 685 available_bytes = self.samples_to_bytes(available_samples) 686 self.card.set_i(SPC_DATA_AVAIL_CARD_LEN, available_bytes)
Set the amount of data that has been read out of the data buffer (see register SPC_DATA_AVAIL_CARD_LEN
in the manual)
Parameters
- available_samples (int | pint.Quantity): the amount of data that is available for reading
688 def avail_user_pos(self, in_bytes : bool = False) -> int: 689 """ 690 Get the current position of the pointer in the data buffer (see register `SPC_DATA_AVAIL_USER_POS` in the manual) 691 692 Parameters 693 ---------- 694 in_bytes : bool 695 if True, the position is returned in bytes 696 697 Returns 698 ------- 699 int 700 pointer position 701 """ 702 703 self.current_user_pos = self.card.get_i(SPC_DATA_AVAIL_USER_POS) 704 if not in_bytes: 705 self.current_user_pos = self.bytes_to_samples(self.current_user_pos) 706 return self.current_user_pos
Get the current position of the pointer in the data buffer (see register SPC_DATA_AVAIL_USER_POS
in the manual)
Parameters
- in_bytes (bool): if True, the position is returned in bytes
Returns
- int: pointer position
708 def avail_user_len(self, in_bytes : bool = False) -> int: 709 """ 710 Get the current length of the data in the data buffer (see register `SPC_DATA_AVAIL_USER_LEN` in the manual) 711 712 Parameters 713 ---------- 714 in_bytes : bool 715 if True, the length is returned in bytes 716 717 Returns 718 ------- 719 int 720 data length available 721 """ 722 723 user_len = self.card.get_i(SPC_DATA_AVAIL_USER_LEN) 724 if not in_bytes: 725 user_len = self.bytes_to_samples(user_len) 726 return user_len
Get the current length of the data in the data buffer (see register SPC_DATA_AVAIL_USER_LEN
in the manual)
Parameters
- in_bytes (bool): if True, the length is returned in bytes
Returns
- int: data length available
728 def fill_size_promille(self, return_unit = None) -> int: 729 """ 730 Get the fill size of the data buffer (see register `SPC_FILLSIZEPROMILLE` in the manual) 731 732 Returns 733 ------- 734 int 735 fill size 736 """ 737 738 return_value = self.card.get_i(SPC_FILLSIZEPROMILLE) 739 if return_unit is not None: return_value = UnitConversion.to_unit(return_value * units.promille, return_unit) 740 return return_value
Get the fill size of the data buffer (see register SPC_FILLSIZEPROMILLE
in the manual)
Returns
- int: fill size
742 def wait_dma(self) -> None: 743 """ 744 Wait for the DMA transfer to finish (see register `M2CMD_DATA_WAITDMA` in the manual) 745 """ 746 747 self.card.cmd(M2CMD_DATA_WAITDMA)
Wait for the DMA transfer to finish (see register M2CMD_DATA_WAITDMA
in the manual)
742 def wait_dma(self) -> None: 743 """ 744 Wait for the DMA transfer to finish (see register `M2CMD_DATA_WAITDMA` in the manual) 745 """ 746 747 self.card.cmd(M2CMD_DATA_WAITDMA)
Wait for the DMA transfer to finish (see register M2CMD_DATA_WAITDMA
in the manual)
750 def numpy_type(self) -> npt.NDArray[np.int_]: 751 """ 752 Get the type of numpy data from number of bytes 753 754 Returns 755 ------- 756 numpy data type 757 the type of data that is used by the card 758 """ 759 760 if self._8bit_mode: 761 return np.uint8 762 if self._12bit_mode: 763 return np.int8 764 if self.bits_per_sample == 1: 765 if self.num_channels <= 8: 766 return np.uint8 767 elif self.num_channels <= 16: 768 return np.uint16 769 elif self.num_channels <= 32: 770 return np.uint32 771 return np.uint64 772 if self.bits_per_sample <= 8: 773 return np.int8 774 elif self.bits_per_sample <= 16: 775 return np.int16 776 elif self.bits_per_sample <= 32: 777 return np.int32 778 return np.int64
Get the type of numpy data from number of bytes
Returns
- numpy data type: the type of data that is used by the card
781 def data_conversion(self, mode : int = None) -> int: 782 """ 783 Set the data conversion mode (see register `SPC_DATACONVERSION` in the manual) 784 785 Parameters 786 ---------- 787 mode : int 788 the data conversion mode 789 """ 790 791 if mode is not None: 792 self.card.set_i(SPC_DATACONVERSION, mode) 793 mode = self.card.get_i(SPC_DATACONVERSION) 794 self._8bit_mode = (mode == SPCM_DC_12BIT_TO_8BIT or mode == SPCM_DC_14BIT_TO_8BIT or mode == SPCM_DC_16BIT_TO_8BIT) 795 self._12bit_mode = (mode == SPCM_DC_12BIT_TO_12BITPACKED) 796 self._bits_per_sample() 797 self._bytes_per_sample() 798 return mode
Set the data conversion mode (see register SPC_DATACONVERSION
in the manual)
Parameters
- mode (int): the data conversion mode
800 def avail_data_conversion(self) -> int: 801 """ 802 Get the available data conversion modes (see register `SPC_AVAILDATACONVERSION` in the manual) 803 804 Returns 805 ------- 806 int 807 the available data conversion modes 808 """ 809 return self.card.get_i(SPC_AVAILDATACONVERSION)
Get the available data conversion modes (see register SPC_AVAILDATACONVERSION
in the manual)
Returns
- int: the available data conversion modes
821 def verbose(self, verbose : bool = None) -> bool: 822 """ 823 Set or get the verbose mode for the data transfer 824 825 Parameters 826 ---------- 827 verbose : bool = None 828 the verbose mode 829 """ 830 831 if verbose is not None: 832 self._verbose = verbose 833 return self._verbose
Set or get the verbose mode for the data transfer
Parameters
- verbose (bool = None): the verbose mode
835 def to_transfer_samples(self, samples) -> None: 836 """ 837 This method sets the number of samples to transfer 838 839 Parameters 840 ---------- 841 samples : int | pint.Quantity 842 the number of samples to transfer 843 """ 844 845 samples = UnitConversion.convert(samples, units.Sa, int) 846 self._to_transfer_samples = samples
This method sets the number of samples to transfer
Parameters
- samples (int | pint.Quantity): the number of samples to transfer
861 def polling(self, polling : bool = True, timer : float = 0.01) -> None: 862 """ 863 Set the polling mode for the data transfer otherwise wait_dma() is used 864 865 Parameters 866 ---------- 867 polling : bool 868 True to enable polling, False to disable polling 869 timer : float | pint.Quantity 870 the polling timer in seconds 871 """ 872 873 self._polling = polling 874 self._pollng_timer = UnitConversion.convert(timer, units.s, float)
Set the polling mode for the data transfer otherwise wait_dma() is used
Parameters
- polling (bool): True to enable polling, False to disable polling
- timer (float | pint.Quantity): the polling timer in seconds
248class DDS(CardFunctionality): 249 """a higher-level abstraction of the SpcmCardFunctionality class to implement DDS functionality 250 251 The DDS firmware allows the user a certain maximum number of dds cores, that 252 each on it's own generates a sine wave with the following parameters: 253 * static parameters: 254 + frequency 255 + amplitude 256 + phase 257 * dynamic parameters: 258 + frequency_slope 259 changes the active frequency of the dds core with a linear slope 260 + amplitude_slope 261 changes the active amplitude of the dds core with a linear slope 262 Each of these cores can either be added together and outputted, or specific groups 263 of cores can be added together and outputted on a specific hardware output channel. 264 Furthermore, specific dds cores can be connected to input parameters of another dds core. 265 266 For more information about what setups are available, please have a look at the user manual 267 for your specific card. 268 269 Commands 270 --------- 271 The DDS functionality is controlled through commands that are listed and then written to the card. 272 These written lists of commands are collected in a shadow register and are transferred to 273 the active register when a trigger is received. 274 275 There are three different trigger sources, that can be set with the method 'trg_source()': 276 * SPCM_DDS_TRG_SRC_NONE = 0 277 no triggers are generated and the commands are only transfered to the active register 278 when a exec_now command is send 279 * SPCM_DDS_TRG_SRC_TIMER = 1 280 the triggers are generated on a timed grid with a period that can be set by the 281 method 'trg_timer()' 282 * SPCM_DDS_TRG_SRC_CARD = 2 283 the triggers come from the card internal trigger logic (for more information, 284 see our product's user manual on how to setup the different triggers). In the DDS-mode 285 multiple triggers can be processed, as with the mode SPC_STD_REP_SINGLERESTART. 286 287 Note 288 ---- 289 also the trigger source setting happens when a trigger comes. Hence a change of 290 the trigger mode only happens after an 'arm()' command was send and an internal trigger was 291 received. 292 293 """ 294 295 cores : list[DDSCore] = [] 296 channels : Channels = None 297 298 check_features : bool = False 299 300 _current_core : int = -1 301 _channel_from_core : dict[int, int] = {} 302 303 def __init__(self, *args, **kwargs) -> None: 304 super().__init__(*args, **kwargs) 305 self.channels = kwargs.get("channels", None) 306 self.check_features = kwargs.get("check_features", False) 307 self.cores = [] 308 self.load_cores() 309 # Check if DDS feature is installed 310 if self.check_features: 311 features = self.card.ext_features() 312 if not ((features & SPCM_FEAT_EXTFW_DDS20) or (features & SPCM_FEAT_EXTFW_DDS50)): 313 raise SpcmException("The DDS feature is not installed on the card") 314 315 def load_cores(self): 316 """ 317 load the cores of the DDS functionality 318 """ 319 320 self.cores = [] 321 num_cores = self.num_cores() 322 323 if self.channels is not None: 324 for channel in self.channels: 325 cores_on_channel = self.get_cores_on_channel(channel.index) 326 for core in range(num_cores): 327 if cores_on_channel & (1 << core): 328 self._channel_from_core[core] = channel 329 330 for core in range(num_cores): 331 if core in self._channel_from_core: 332 self.cores.append(DDSCore(core, self, channel=self._channel_from_core[core])) 333 else: 334 self.cores.append(DDSCore(core, self)) 335 336 def __len__(self) -> int: 337 """ 338 get the number of cores 339 340 Returns 341 ------- 342 int 343 the number of cores 344 """ 345 return len(self.cores) 346 347 def __iter__(self): 348 """ 349 make the class iterable 350 351 Returns 352 ------- 353 self 354 """ 355 return self 356 357 def __next__(self): 358 """ 359 get the next core 360 361 Returns 362 ------- 363 DDSCore 364 the next core 365 """ 366 367 self._current_core += 1 368 if self._current_core < len(self.cores): 369 return self.cores[self._current_core] 370 else: 371 self._current_core = -1 372 raise StopIteration 373 374 def __getitem__(self, index : int) -> DDSCore: 375 """ 376 get a specific core 377 378 Parameters 379 ---------- 380 index : int 381 the index of the core 382 383 Returns 384 ------- 385 DDSCore 386 the specific core 387 """ 388 389 return self.cores[index] 390 391 def set_i(self, reg : int, value : int) -> None: 392 """ 393 set an integer value to a register 394 395 Parameters 396 ---------- 397 reg : int 398 the register to be changed 399 value : int 400 the value to be set 401 402 Raises 403 ------ 404 SpcmException 405 if the command list is full 406 """ 407 408 self.card.set_i(reg, value) 409 410 def set_d(self, reg : int, value : float) -> None: 411 """ 412 set a double value to a register 413 414 Parameters 415 ---------- 416 reg : int 417 the register to be changed 418 value : float 419 the value to be set 420 """ 421 422 self.card.set_d(reg, value) 423 424 def reset(self) -> None: 425 """ 426 Resets the DDS specific part of the firmware (see register `SPC_DDS_CMD` in the manual) 427 """ 428 429 self.cmd(SPCM_DDS_CMD_RESET) 430 431 # DDS information 432 def num_cores(self) -> int: 433 """ 434 get the total num of available cores on the card. (see register `SPC_DDS_NUM_CORES` in the manual) 435 436 Returns 437 ------- 438 int 439 the available number of dds cores 440 """ 441 return self.card.get_i(SPC_DDS_NUM_CORES) 442 443 def queue_cmd_max(self): 444 """ 445 get the total number of commands that can be hold by the queue. (see register `SPC_DDS_QUEUE_CMD_MAX` in the manual) 446 447 Returns 448 ------- 449 int 450 the total number of commands 451 """ 452 return self.card.get_i(SPC_DDS_QUEUE_CMD_MAX) 453 454 def queue_cmd_count(self): 455 """ 456 get the current number of commands that are in the queue. (see register `SPC_DDS_QUEUE_CMD_COUNT` in the manual) 457 458 Returns 459 ------- 460 int 461 the current number of commands 462 """ 463 return self.card.get_i(SPC_DDS_QUEUE_CMD_COUNT) 464 465 def status(self): 466 return self.card.get_i(SPC_DDS_STATUS) 467 468 # DDS setup settings 469 def data_transfer_mode(self, mode : int) -> None: 470 """ 471 set the data transfer mode for the DDS functionality (see register `SPC_DDS_DATA_TRANSFER_MODE` in the manual) 472 473 Parameters 474 ---------- 475 mode : int 476 the data transfer mode: 477 * SPCM_DDS_DTM_SINGLE = 0 478 the data is transferred using single commands (with lower latency) 479 * SPCM_DDS_DTM_DMA = 1 480 the data is transferred using DMA (with higher bandwidth) 481 """ 482 483 self._dtm = mode 484 self.set_i(SPC_DDS_DATA_TRANSFER_MODE, mode) 485 486 def get_data_transfer_mode(self) -> int: 487 """ 488 get the data transfer mode for the DDS functionality (see register `SPC_DDS_DATA_TRANSFER_MODE` in the manual) 489 490 Returns 491 ------- 492 int 493 the data transfer mode: 494 * SPCM_DDS_DTM_SINGLE = 0 495 the data is transferred using single commands (with lower latency) 496 * SPCM_DDS_DTM_DMA = 1 497 the data is transferred using DMA (with higher bandwidth) 498 """ 499 500 self._dtm = self.card.get_i(SPC_DDS_DATA_TRANSFER_MODE) 501 return self._dtm 502 503 def phase_behaviour(self, behaviour : int) -> None: 504 """ 505 set the phase behaviour of the DDS cores (see register `SPC_DDS_PHASE_BEHAVIOUR` in the manual) 506 507 Parameters 508 ---------- 509 behaviour : int 510 the phase behaviour 511 """ 512 513 self.set_i(SPC_DDS_PHASE_BEHAVIOUR, behaviour) 514 515 def get_phase_behaviour(self) -> int: 516 """ 517 get the phase behaviour of the DDS cores (see register `SPC_DDS_PHASE_BEHAVIOUR` in the manual) 518 519 Returns 520 ------- 521 int 522 the phase behaviour 523 """ 524 525 return self.card.get_i(SPC_DDS_PHASE_BEHAVIOUR) 526 527 def cores_on_channel(self, channel : int, *args) -> None: 528 """ 529 setup the cores that are connected to a specific channel (see register `SPC_DDS_CORES_ON_CH0` in the manual) 530 531 Parameters 532 ---------- 533 channel : int 534 the channel number 535 *args : int 536 the cores that are connected to the channel 537 538 TODO: change the channel associated with each core 539 """ 540 541 mask = 0 542 for core in args: 543 mask |= core 544 self.set_i(SPC_DDS_CORES_ON_CH0 + channel, mask) 545 546 def get_cores_on_channel(self, channel : int) -> int: 547 """ 548 get the cores that are connected to a specific channel (see register `SPC_DDS_CORES_ON_CH0` in the manual) 549 550 Parameters 551 ---------- 552 channel : int 553 the channel number 554 555 Returns 556 ------- 557 int 558 the cores that are connected to the channel 559 """ 560 561 return self.card.get_i(SPC_DDS_CORES_ON_CH0 + channel) 562 563 def trg_src(self, src : int) -> None: 564 """ 565 setup the source of where the trigger is coming from (see register `SPC_DDS_TRG_SRC` in the manual) 566 567 NOTE 568 --- 569 the trigger source is also set using the shadow register, hence only after an exec_at_trig or exec_now -- 570 571 Parameters 572 ---------- 573 src : int 574 set the trigger source: 575 * SPCM_DDS_TRG_SRC_NONE = 0 576 no trigger source set, only exec_now changes what is output by the cores 577 * SPCM_DDS_TRG_SRC_TIMER = 1 578 an internal timer sends out triggers with a period defined by `trg_timer(period)` 579 * SPCM_DDS_TRG_SRC_CARD = 2 580 use the trigger engine of the card (see the user manual for more information about setting up the trigger engine) 581 """ 582 583 self.set_i(SPC_DDS_TRG_SRC, src) 584 585 def get_trg_src(self) -> int: 586 """ 587 get the source of where the trigger is coming from (see register `SPC_DDS_TRG_SRC` in the manual) 588 589 NOTE 590 ---- 591 the trigger source is also set using the shadow register, hence only after an exec_at_trig or exec_now -- 592 593 Returns 594 ---------- 595 int 596 get one of the trigger source: 597 * SPCM_DDS_TRG_SRC_NONE = 0 598 no trigger source set, only exec_now changes what is output by the cores 599 * SPCM_DDS_TRG_SRC_TIMER = 1 600 an internal timer sends out triggers with a period defined by `trg_timer(period)` 601 * SPCM_DDS_TRG_SRC_CARD = 2 602 use the trigger engine of the card (see the user manual for more information about setting up the trigger engine) 603 """ 604 605 return self.card.get_i(SPC_DDS_TRG_SRC) 606 607 def trg_timer(self, period : float) -> None: 608 """ 609 set the period at which the timer should raise DDS trigger events. (see register `SPC_DDS_TRG_TIMER` in the manual) 610 611 NOTE 612 ---- 613 only used in conjecture with the trigger source set to SPCM_DDS_TRG_SRC_TIMER --- 614 615 Parameters 616 ---------- 617 period : float | pint.Quantity 618 the time between DDS trigger events in seconds 619 """ 620 621 period = UnitConversion.convert(period, units.s, float, rounding=None) 622 self.set_d(SPC_DDS_TRG_TIMER, float(period)) 623 624 def get_trg_timer(self, return_unit = None) -> float: 625 """ 626 get the period at which the timer should raise DDS trigger events. (see register `SPC_DDS_TRG_TIMER` in the manual) 627 628 NOTE 629 ---- 630 only used in conjecture with the trigger source set to SPCM_DDS_TRG_SRC_TIMER --- 631 632 Parameters 633 ---------- 634 return_unit : pint.Unit = None 635 the unit of the returned time between DDS trigger events, by default None 636 637 Returns 638 ---------- 639 float 640 the time between DDS trigger events in seconds 641 """ 642 643 return_value = self.card.get_d(SPC_DDS_TRG_TIMER) 644 if return_unit is not None: return_value = UnitConversion.to_unit(return_value * units.s, return_unit) 645 return return_value 646 647 def x_mode(self, xio : int, mode : int) -> None: 648 """ 649 setup the kind of output that the XIO outputs will give (see register `SPC_DDS_X0_MODE` in the manual) 650 651 Parameters 652 ---------- 653 xio : int 654 the XIO channel number 655 mode : int 656 the mode that the channel needs to run in 657 """ 658 659 self.set_i(SPC_DDS_X0_MODE + xio, mode) 660 661 def get_x_mode(self, xio : int) -> int: 662 """ 663 get the kind of output that the XIO outputs will give (see register `SPC_DDS_X0_MODE` in the manual) 664 665 Parameters 666 ---------- 667 xio : int 668 the XIO channel number 669 670 Returns 671 ------- 672 int 673 the mode that the channel needs to run in 674 SPC_DDS_XIO_SEQUENCE = 0 675 turn on and off the XIO channels using commands in the DDS cmd queue 676 SPC_DDS_XIO_ARM = 1 677 when the DDS firmware is waiting for a trigger to come this signal is high 678 SPC_DDS_XIO_LATCH = 2 679 when the DDS firmware starts executing a change this signal is high 680 """ 681 682 return self.card.get_i(SPC_DDS_X0_MODE + xio) 683 684 def freq_ramp_stepsize(self, divider : int) -> None: 685 """ 686 number of timesteps before the frequency is changed during a frequency ramp. (see register `SPC_DDS_FREQ_RAMP_STEPSIZE` in the manual) 687 688 NOTES 689 ----- 690 - this is a global setting for all cores 691 - internally the time divider is used to calculate the amount of change per event using a given frequency slope, please set the time divider before setting the frequency slope 692 693 Parameters 694 ---------- 695 divider : int 696 the number of DDS timesteps that a value is kept constant during a frequency ramp 697 """ 698 699 self.set_i(SPC_DDS_FREQ_RAMP_STEPSIZE, int(divider)) 700 701 def get_freq_ramp_stepsize(self) -> int: 702 """ 703 get the number of timesteps before the frequency is changed during a frequency ramp. (see register `SPC_DDS_FREQ_RAMP_STEPSIZE` in the manual) 704 705 NOTES 706 ----- 707 - this is a global setting for all cores 708 - internally the time divider is used to calculate the amount of change per event using a given frequency slope, please set the time divider before setting the frequency slope 709 710 Returns 711 ---------- 712 divider : int 713 the number of DDS timesteps that a value is kept constant during a frequency ramp 714 """ 715 716 return self.card.get_i(SPC_DDS_FREQ_RAMP_STEPSIZE) 717 718 def amp_ramp_stepsize(self, divider : int) -> None: 719 """ 720 number of timesteps before the amplitude is changed during a frequency ramp. (see register `SPC_DDS_AMP_RAMP_STEPSIZE` in the manual) 721 722 NOTES 723 ----- 724 - this is a global setting for all cores 725 - internally the time divider is used to calculate the amount of change per event using a given amplitude slope, 726 please set the time divider before setting the amplitude slope 727 728 Parameters 729 ---------- 730 divider : int 731 the number of DDS timesteps that a value is kept constant during an amplitude ramp 732 """ 733 734 self.set_i(SPC_DDS_AMP_RAMP_STEPSIZE, int(divider)) 735 736 def get_amp_ramp_stepsize(self) -> int: 737 """ 738 get the number of timesteps before the amplitude is changed during a frequency ramp. (see register `SPC_DDS_AMP_RAMP_STEPSIZE` in the manual) 739 740 NOTES 741 ----- 742 - this is a global setting for all cores 743 - internally the time divider is used to calculate the amount of change per event using a given amplitude slope, 744 please set the time divider before setting the amplitude slope 745 746 Returns 747 ---------- 748 divider : int 749 the number of DDS timesteps that a value is kept constant during an amplitude ramp 750 """ 751 752 return self.card.get_i(SPC_DDS_AMP_RAMP_STEPSIZE) 753 754 # DDS "static" parameters 755 # def amp(self, core_index : int, amplitude : float) -> None: 756 def amp(self, *args) -> None: 757 """ 758 set the amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP` in the manual) 759 760 Parameters 761 ---------- 762 core_index : int (optional) 763 the index of the core to be changed 764 amplitude : float 765 the value between 0 and 1 corresponding to the amplitude 766 """ 767 768 if len(args) == 1: 769 amplitude = args[0] 770 for core in self.cores: 771 core.amp(amplitude) 772 elif len(args) == 2: 773 core_index, amplitude = args 774 self.cores[core_index].amp(amplitude) 775 else: 776 raise TypeError("amp() takes 1 or 2 positional arguments ({} given)".format(len(args) + 1)) 777 # self.set_d(SPC_DDS_CORE0_AMP + core_index, float(amplitude)) 778 # aliases 779 amplitude = amp 780 781 def get_amp(self, core_index : int, return_unit = None) -> float: 782 """ 783 gets the amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP` in the manual) 784 785 Parameters 786 ---------- 787 core_index : int 788 the index of the core to be changed 789 return_unit : pint.Unit = None 790 the unit of the returned amplitude, by default None 791 792 Returns 793 ------- 794 float | pint.Quantity 795 the value between 0 and 1 corresponding to the amplitude of the specific core or in the specified unit 796 """ 797 798 return self.cores[core_index].get_amp(return_unit) 799 # return self.card.get_d(SPC_DDS_CORE0_AMP + core_index) 800 # aliases 801 get_amplitude = get_amp 802 803 def avail_amp_min(self) -> float: 804 """ 805 get the minimum available amplitude (see register `SPC_DDS_AVAIL_AMP_MIN` in the manual) 806 807 Returns 808 ------- 809 float 810 the minimum available amplitude 811 812 TODO: unitize! 813 """ 814 815 return self.card.get_d(SPC_DDS_AVAIL_AMP_MIN) 816 817 def avail_amp_max(self) -> float: 818 """ 819 get the maximum available amplitude (see register `SPC_DDS_AVAIL_AMP_MAX` in the manual) 820 821 Returns 822 ------- 823 float 824 the maximum available amplitude 825 826 TODO: unitize! 827 """ 828 829 return self.card.get_d(SPC_DDS_AVAIL_AMP_MAX) 830 831 def avail_amp_step(self) -> float: 832 """ 833 get the step size of the available amplitudes (see register `SPC_DDS_AVAIL_AMP_STEP` in the manual) 834 835 Returns 836 ------- 837 float 838 the step size of the available amplitudes 839 840 TODO: unitize! 841 """ 842 843 return self.card.get_d(SPC_DDS_AVAIL_AMP_STEP) 844 845 # def freq(self, core_index : int, frequency : float) -> None: 846 def freq(self, *args) -> None: 847 """ 848 set the frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ` in the manual) 849 850 Parameters 851 ---------- 852 core_index : int (optional) 853 the index of the core to be changed 854 frequency : float 855 the value of the frequency in Hz 856 """ 857 858 if len(args) == 1: 859 frequency = args[0] 860 for core in self.cores: 861 core.freq(frequency) 862 elif len(args) == 2: 863 core_index, frequency = args 864 self.cores[core_index].freq(frequency) 865 else: 866 raise TypeError("freq() takes 1 or 2 positional arguments ({} given)".format(len(args) + 1)) 867 # self.set_d(SPC_DDS_CORE0_FREQ + core_index, float(frequency)) 868 # aliases 869 frequency = freq 870 871 def get_freq(self, core_index : int, return_unit = None) -> float: 872 """ 873 gets the frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ` in the manual) 874 875 Parameters 876 ---------- 877 core_index : int 878 the index of the core to be changed 879 return_unit : pint.Unit = None 880 the unit of the returned frequency, by default None 881 882 Returns 883 ------- 884 float | pint.Quantity 885 the value of the frequency in Hz the specific core or in the specified unit 886 """ 887 888 return self.cores[core_index].get_freq(return_unit) 889 # aliases 890 get_frequency = get_freq 891 892 def avail_freq_min(self) -> float: 893 """ 894 get the minimum available frequency (see register `SPC_DDS_AVAIL_FREQ_MIN` in the manual) 895 896 Returns 897 ------- 898 float 899 the minimum available frequency 900 901 TODO: unitize! 902 """ 903 904 return self.card.get_d(SPC_DDS_AVAIL_FREQ_MIN) 905 906 def avail_freq_max(self) -> float: 907 """ 908 get the maximum available frequency (see register `SPC_DDS_AVAIL_FREQ_MAX` in the manual) 909 910 Returns 911 ------- 912 float 913 the maximum available frequency 914 915 TODO: unitize! 916 """ 917 918 return self.card.get_d(SPC_DDS_AVAIL_FREQ_MAX) 919 920 def avail_freq_step(self) -> float: 921 """ 922 get the step size of the available frequencies (see register `SPC_DDS_AVAIL_FREQ_STEP` in the manual) 923 924 Returns 925 ------- 926 float 927 the step size of the available frequencies 928 929 TODO: unitize! 930 """ 931 932 return self.card.get_d(SPC_DDS_AVAIL_FREQ_STEP) 933 934 # def phase(self, core_index : int, phase : float) -> None: 935 def phase(self, *args) -> None: 936 """ 937 set the phase of the sine wave of a specific core (see register `SPC_DDS_CORE0_PHASE` in the manual) 938 939 Parameters 940 ---------- 941 core_index : int (optional) 942 the index of the core to be changed 943 phase : float 944 the value between 0 and 360 degrees of the phase 945 """ 946 947 if len(args) == 1: 948 phase = args[0] 949 for core in self.cores: 950 core.phase(phase) 951 elif len(args) == 2: 952 core_index, phase = args 953 self.cores[core_index].phase(phase) 954 else: 955 raise TypeError("phase() takes 1 or 2 positional arguments ({} given)".format(len(args) + 1)) 956 # self.set_d(SPC_DDS_CORE0_PHASE + core_index, float(phase)) 957 958 def get_phase(self, core_index : int, return_unit = None) -> float: 959 """ 960 gets the phase of the sine wave of a specific core (see register `SPC_DDS_CORE0_PHASE` in the manual) 961 962 Parameters 963 ---------- 964 core_index : int 965 the index of the core to be changed 966 return_unit : pint.Unit = None 967 the unit of the returned phase, by default None 968 969 Returns 970 ------- 971 float 972 the value between 0 and 360 degrees of the phase 973 """ 974 975 return self.cores[core_index].get_phase(return_unit) 976 977 def avail_phase_min(self) -> float: 978 """ 979 get the minimum available phase (see register `SPC_DDS_AVAIL_PHASE_MIN` in the manual) 980 981 Returns 982 ------- 983 float 984 the minimum available phase 985 986 TODO: unitize! 987 """ 988 989 return self.card.get_d(SPC_DDS_AVAIL_PHASE_MIN) 990 991 def avail_phase_max(self) -> float: 992 """ 993 get the maximum available phase (see register `SPC_DDS_AVAIL_PHASE_MAX` in the manual) 994 995 Returns 996 ------- 997 float 998 the maximum available phase 999 1000 TODO: unitize! 1001 """ 1002 1003 return self.card.get_d(SPC_DDS_AVAIL_PHASE_MAX) 1004 1005 def avail_phase_step(self) -> float: 1006 """ 1007 get the step size of the available phases (see register `SPC_DDS_AVAIL_PHASE_STEP` in the manual) 1008 1009 Returns 1010 ------- 1011 float 1012 the step size of the available phases 1013 1014 TODO: unitize! 1015 """ 1016 1017 return self.card.get_d(SPC_DDS_AVAIL_PHASE_STEP) 1018 1019 def x_manual_output(self, state_mask : int) -> None: 1020 """ 1021 set the output of the xio channels using a bit mask (see register `SPC_DDS_X_MANUAL_OUTPUT` in the manual) 1022 1023 Parameters 1024 ---------- 1025 state_mask : int 1026 bit mask where the bits correspond to specific channels and 1 to on and 0 to off. 1027 """ 1028 1029 self.set_i(SPC_DDS_X_MANUAL_OUTPUT, state_mask) 1030 1031 def get_x_manual_output(self) -> int: 1032 """ 1033 get the output of the xio channels using a bit mask (see register `SPC_DDS_X_MANUAL_OUTPUT` in the manual) 1034 1035 Returns 1036 ---------- 1037 int 1038 bit mask where the bits correspond to specific channels and 1 to on and 0 to off. 1039 """ 1040 1041 return self.card.get_i(SPC_DDS_X_MANUAL_OUTPUT) 1042 1043 # DDS dynamic parameters 1044 # def freq_slope(self, core_index : int, slope : float) -> None: 1045 def freq_slope(self, *args) -> None: 1046 """ 1047 set the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ_SLOPE` in the manual) 1048 1049 Parameters 1050 ---------- 1051 core_index : int (optional) 1052 the index of the core to be changed 1053 slope : float 1054 the rate of frequency change in Hz/s 1055 """ 1056 1057 if len(args) == 1: 1058 slope = args[0] 1059 for core in self.cores: 1060 core.freq_slope(slope) 1061 elif len(args) == 2: 1062 core_index, slope = args 1063 self.cores[core_index].freq_slope(slope) 1064 else: 1065 raise TypeError("freq_slope() takes 1 or 2 positional arguments ({} given)".format(len(args) + 1)) 1066 # self.set_d(SPC_DDS_CORE0_FREQ_SLOPE + core_index, float(slope)) 1067 # aliases 1068 frequency_slope = freq_slope 1069 1070 def get_freq_slope(self, core_index : int, return_unit=None) -> float: 1071 """ 1072 get the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ_SLOPE` in the manual) 1073 1074 Parameters 1075 ---------- 1076 core_index : int 1077 the index of the core to be changed 1078 return_unit : pint.Unit = None 1079 the unit of the returned frequency slope, by default None 1080 1081 Returns 1082 ------- 1083 float 1084 the rate of frequency change in Hz/s 1085 """ 1086 1087 return self.cores[core_index].get_freq_slope(return_unit) 1088 # aliases 1089 get_frequency_slope = get_freq_slope 1090 1091 def avail_freq_slope_min(self) -> float: 1092 """ 1093 get the minimum available frequency slope (see register `SPC_DDS_AVAIL_FREQ_SLOPE_MIN` in the manual) 1094 1095 Returns 1096 ------- 1097 float 1098 the minimum available frequency slope 1099 1100 TODO: unitize! 1101 """ 1102 1103 return self.card.get_d(SPC_DDS_AVAIL_FREQ_SLOPE_MIN) 1104 1105 def avail_freq_slope_max(self) -> float: 1106 """ 1107 get the maximum available frequency slope (see register `SPC_DDS_AVAIL_FREQ_SLOPE_MAX` in the manual) 1108 1109 Returns 1110 ------- 1111 float 1112 the maximum available frequency slope 1113 1114 TODO: unitize! 1115 """ 1116 1117 return self.card.get_d(SPC_DDS_AVAIL_FREQ_SLOPE_MAX) 1118 1119 def avail_freq_slope_step(self) -> float: 1120 """ 1121 get the step size of the available frequency slopes (see register `SPC_DDS_AVAIL_FREQ_SLOPE_STEP` in the manual) 1122 1123 Returns 1124 ------- 1125 float 1126 the step size of the available frequency slopes 1127 1128 TODO: unitize! 1129 """ 1130 1131 return self.card.get_d(SPC_DDS_AVAIL_FREQ_SLOPE_STEP) 1132 1133 # def amp_slope(self, core_index : int, slope : float) -> None: 1134 def amp_slope(self, *args) -> None: 1135 """ 1136 set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP_SLOPE` in the manual) 1137 1138 Parameters 1139 ---------- 1140 core_index : int (optional) 1141 the index of the core to be changed 1142 slope : float 1143 the rate of amplitude change in 1/s 1144 """ 1145 1146 if len(args) == 1: 1147 slope = args[0] 1148 for core in self.cores: 1149 core.amp_slope(slope) 1150 elif len(args) == 2: 1151 core_index, slope = args 1152 self.cores[core_index].amp_slope(slope) 1153 else: 1154 raise TypeError("amp_slope() takes 1 or 2 positional arguments ({} given)".format(len(args) + 1)) 1155 # self.set_d(SPC_DDS_CORE0_AMP_SLOPE + core_index, float(slope)) 1156 # aliases 1157 amplitude_slope = amp_slope 1158 1159 def get_amp_slope(self, core_index : int, return_unit = None) -> float: 1160 """ 1161 set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP_SLOPE` in the manual) 1162 1163 Parameters 1164 ---------- 1165 core_index : int 1166 the index of the core to be changed 1167 return_unit : pint.Unit = None 1168 the unit of the returned amplitude slope, by default None 1169 1170 Returns 1171 ------- 1172 float 1173 the rate of amplitude change in 1/s 1174 """ 1175 1176 return self.cores[core_index].get_amp_slope(return_unit) 1177 # aliases 1178 amplitude_slope = amp_slope 1179 1180 def avail_amp_slope_min(self) -> float: 1181 """ 1182 get the minimum available amplitude slope (see register `SPC_DDS_AVAIL_AMP_SLOPE_MIN` in the manual) 1183 1184 Returns 1185 ------- 1186 float 1187 the minimum available amplitude slope 1188 1189 TODO: unitize! 1190 """ 1191 1192 return self.card.get_d(SPC_DDS_AVAIL_AMP_SLOPE_MIN) 1193 1194 def avail_amp_slope_max(self) -> float: 1195 """ 1196 get the maximum available amplitude slope (see register `SPC_DDS_AVAIL_AMP_SLOPE_MAX` in the manual) 1197 1198 Returns 1199 ------- 1200 float 1201 the maximum available amplitude slope 1202 1203 TODO: unitize! 1204 """ 1205 1206 return self.card.get_d(SPC_DDS_AVAIL_AMP_SLOPE_MAX) 1207 1208 def avail_amp_slope_step(self) -> float: 1209 """ 1210 get the step size of the available amplitude slopes (see register `SPC_DDS_AVAIL_AMP_SLOPE_STEP` in the manual) 1211 1212 Returns 1213 ------- 1214 float 1215 the step size of the available amplitude slopes 1216 1217 TODO: unitize! 1218 """ 1219 1220 return self.card.get_d(SPC_DDS_AVAIL_AMP_SLOPE_STEP) 1221 1222 # DDS control 1223 def cmd(self, command : int) -> None: 1224 """ 1225 execute a DDS specific control flow command (see register `SPC_DDS_CMD` in the manual) 1226 1227 Parameters 1228 ---------- 1229 command : int 1230 DDS specific command 1231 """ 1232 1233 self.set_i(SPC_DDS_CMD, command) 1234 1235 def exec_at_trg(self) -> None: 1236 """ 1237 execute the commands in the shadow register at the next trigger event (see register `SPC_DDS_CMD` in the manual) 1238 """ 1239 self.cmd(SPCM_DDS_CMD_EXEC_AT_TRG) 1240 # aliases 1241 arm = exec_at_trg 1242 wait_for_trg = exec_at_trg 1243 1244 def exec_now(self) -> None: 1245 """ 1246 execute the commands in the shadow register as soon as possible (see register `SPC_DDS_CMD` in the manual) 1247 """ 1248 1249 self.cmd(SPCM_DDS_CMD_EXEC_NOW) 1250 # aliases 1251 direct_latch = exec_now 1252 1253 def trg_count(self) -> int: 1254 """ 1255 get the number of trigger exec_at_trg and exec_now command that have been executed (see register `SPC_DDS_TRG_COUNT` in the manual) 1256 1257 Returns 1258 ------- 1259 int 1260 the number of trigger exec_at_trg and exec_now command that have been executed 1261 """ 1262 1263 return self.card.get_i(SPC_DDS_TRG_COUNT) 1264 1265 def write_to_card(self, flags=0) -> None: 1266 """ 1267 send a list of all the commands that came after the last write_list and send them to the card (see register `SPC_DDS_CMD` in the manual) 1268 """ 1269 1270 self.cmd(SPCM_DDS_CMD_WRITE_TO_CARD | flags) 1271 1272 # DDS helper functions 1273 def kwargs2mask(self, kwargs : dict[str, bool], prefix : str = "") -> int: 1274 """ 1275 DDS helper: transform a dictionary with keys with a specific prefix to a bitmask 1276 1277 Parameters 1278 ---------- 1279 kwargs : dict 1280 dictonary with keys with a specific prefix and values given by bools 1281 prefix : str 1282 a prefix for the key names 1283 1284 Returns 1285 ------- 1286 int 1287 bit mask 1288 1289 Example 1290 ------- 1291 ['core_0' = True, 'core_2' = False, 'core_3' = True] => 0b1001 = 9 1292 """ 1293 1294 mask = 0 1295 for keyword, value in kwargs.items(): 1296 bit = int(keyword[len(prefix)+1:]) 1297 if value: 1298 mask |= 1 << bit 1299 else: 1300 mask &= ~(1 << bit) 1301 return mask 1302 # aliases 1303 k2m = kwargs2mask
a higher-level abstraction of the SpcmCardFunctionality class to implement DDS functionality
The DDS firmware allows the user a certain maximum number of dds cores, that each on it's own generates a sine wave with the following parameters:
- static parameters:
- frequency
- amplitude
- phase
- dynamic parameters:
- frequency_slope changes the active frequency of the dds core with a linear slope
- amplitude_slope changes the active amplitude of the dds core with a linear slope Each of these cores can either be added together and outputted, or specific groups of cores can be added together and outputted on a specific hardware output channel. Furthermore, specific dds cores can be connected to input parameters of another dds core.
For more information about what setups are available, please have a look at the user manual for your specific card.
Commands
The DDS functionality is controlled through commands that are listed and then written to the card. These written lists of commands are collected in a shadow register and are transferred to the active register when a trigger is received.
There are three different trigger sources, that can be set with the method 'trg_source()':
- SPCM_DDS_TRG_SRC_NONE = 0 no triggers are generated and the commands are only transfered to the active register when a exec_now command is send
- SPCM_DDS_TRG_SRC_TIMER = 1 the triggers are generated on a timed grid with a period that can be set by the method 'trg_timer()'
- SPCM_DDS_TRG_SRC_CARD = 2 the triggers come from the card internal trigger logic (for more information, see our product's user manual on how to setup the different triggers). In the DDS-mode multiple triggers can be processed, as with the mode SPC_STD_REP_SINGLERESTART.
Note
also the trigger source setting happens when a trigger comes. Hence a change of the trigger mode only happens after an 'arm()' command was send and an internal trigger was received.
303 def __init__(self, *args, **kwargs) -> None: 304 super().__init__(*args, **kwargs) 305 self.channels = kwargs.get("channels", None) 306 self.check_features = kwargs.get("check_features", False) 307 self.cores = [] 308 self.load_cores() 309 # Check if DDS feature is installed 310 if self.check_features: 311 features = self.card.ext_features() 312 if not ((features & SPCM_FEAT_EXTFW_DDS20) or (features & SPCM_FEAT_EXTFW_DDS50)): 313 raise SpcmException("The DDS feature is not installed on the card")
Takes a Card object that is used by the functionality
Parameters
- card (Card): a Card object on which the functionality works
315 def load_cores(self): 316 """ 317 load the cores of the DDS functionality 318 """ 319 320 self.cores = [] 321 num_cores = self.num_cores() 322 323 if self.channels is not None: 324 for channel in self.channels: 325 cores_on_channel = self.get_cores_on_channel(channel.index) 326 for core in range(num_cores): 327 if cores_on_channel & (1 << core): 328 self._channel_from_core[core] = channel 329 330 for core in range(num_cores): 331 if core in self._channel_from_core: 332 self.cores.append(DDSCore(core, self, channel=self._channel_from_core[core])) 333 else: 334 self.cores.append(DDSCore(core, self))
load the cores of the DDS functionality
391 def set_i(self, reg : int, value : int) -> None: 392 """ 393 set an integer value to a register 394 395 Parameters 396 ---------- 397 reg : int 398 the register to be changed 399 value : int 400 the value to be set 401 402 Raises 403 ------ 404 SpcmException 405 if the command list is full 406 """ 407 408 self.card.set_i(reg, value)
set an integer value to a register
Parameters
- reg (int): the register to be changed
- value (int): the value to be set
Raises
- SpcmException: if the command list is full
410 def set_d(self, reg : int, value : float) -> None: 411 """ 412 set a double value to a register 413 414 Parameters 415 ---------- 416 reg : int 417 the register to be changed 418 value : float 419 the value to be set 420 """ 421 422 self.card.set_d(reg, value)
set a double value to a register
Parameters
- reg (int): the register to be changed
- value (float): the value to be set
424 def reset(self) -> None: 425 """ 426 Resets the DDS specific part of the firmware (see register `SPC_DDS_CMD` in the manual) 427 """ 428 429 self.cmd(SPCM_DDS_CMD_RESET)
Resets the DDS specific part of the firmware (see register SPC_DDS_CMD
in the manual)
432 def num_cores(self) -> int: 433 """ 434 get the total num of available cores on the card. (see register `SPC_DDS_NUM_CORES` in the manual) 435 436 Returns 437 ------- 438 int 439 the available number of dds cores 440 """ 441 return self.card.get_i(SPC_DDS_NUM_CORES)
get the total num of available cores on the card. (see register SPC_DDS_NUM_CORES
in the manual)
Returns
- int: the available number of dds cores
443 def queue_cmd_max(self): 444 """ 445 get the total number of commands that can be hold by the queue. (see register `SPC_DDS_QUEUE_CMD_MAX` in the manual) 446 447 Returns 448 ------- 449 int 450 the total number of commands 451 """ 452 return self.card.get_i(SPC_DDS_QUEUE_CMD_MAX)
get the total number of commands that can be hold by the queue. (see register SPC_DDS_QUEUE_CMD_MAX
in the manual)
Returns
- int: the total number of commands
454 def queue_cmd_count(self): 455 """ 456 get the current number of commands that are in the queue. (see register `SPC_DDS_QUEUE_CMD_COUNT` in the manual) 457 458 Returns 459 ------- 460 int 461 the current number of commands 462 """ 463 return self.card.get_i(SPC_DDS_QUEUE_CMD_COUNT)
get the current number of commands that are in the queue. (see register SPC_DDS_QUEUE_CMD_COUNT
in the manual)
Returns
- int: the current number of commands
469 def data_transfer_mode(self, mode : int) -> None: 470 """ 471 set the data transfer mode for the DDS functionality (see register `SPC_DDS_DATA_TRANSFER_MODE` in the manual) 472 473 Parameters 474 ---------- 475 mode : int 476 the data transfer mode: 477 * SPCM_DDS_DTM_SINGLE = 0 478 the data is transferred using single commands (with lower latency) 479 * SPCM_DDS_DTM_DMA = 1 480 the data is transferred using DMA (with higher bandwidth) 481 """ 482 483 self._dtm = mode 484 self.set_i(SPC_DDS_DATA_TRANSFER_MODE, mode)
set the data transfer mode for the DDS functionality (see register SPC_DDS_DATA_TRANSFER_MODE
in the manual)
Parameters
- mode (int):
the data transfer mode:
- SPCM_DDS_DTM_SINGLE = 0 the data is transferred using single commands (with lower latency)
- SPCM_DDS_DTM_DMA = 1 the data is transferred using DMA (with higher bandwidth)
486 def get_data_transfer_mode(self) -> int: 487 """ 488 get the data transfer mode for the DDS functionality (see register `SPC_DDS_DATA_TRANSFER_MODE` in the manual) 489 490 Returns 491 ------- 492 int 493 the data transfer mode: 494 * SPCM_DDS_DTM_SINGLE = 0 495 the data is transferred using single commands (with lower latency) 496 * SPCM_DDS_DTM_DMA = 1 497 the data is transferred using DMA (with higher bandwidth) 498 """ 499 500 self._dtm = self.card.get_i(SPC_DDS_DATA_TRANSFER_MODE) 501 return self._dtm
get the data transfer mode for the DDS functionality (see register SPC_DDS_DATA_TRANSFER_MODE
in the manual)
Returns
- int: the data transfer mode:
- SPCM_DDS_DTM_SINGLE = 0 the data is transferred using single commands (with lower latency)
- SPCM_DDS_DTM_DMA = 1 the data is transferred using DMA (with higher bandwidth)
503 def phase_behaviour(self, behaviour : int) -> None: 504 """ 505 set the phase behaviour of the DDS cores (see register `SPC_DDS_PHASE_BEHAVIOUR` in the manual) 506 507 Parameters 508 ---------- 509 behaviour : int 510 the phase behaviour 511 """ 512 513 self.set_i(SPC_DDS_PHASE_BEHAVIOUR, behaviour)
set the phase behaviour of the DDS cores (see register SPC_DDS_PHASE_BEHAVIOUR
in the manual)
Parameters
- behaviour (int): the phase behaviour
515 def get_phase_behaviour(self) -> int: 516 """ 517 get the phase behaviour of the DDS cores (see register `SPC_DDS_PHASE_BEHAVIOUR` in the manual) 518 519 Returns 520 ------- 521 int 522 the phase behaviour 523 """ 524 525 return self.card.get_i(SPC_DDS_PHASE_BEHAVIOUR)
get the phase behaviour of the DDS cores (see register SPC_DDS_PHASE_BEHAVIOUR
in the manual)
Returns
- int: the phase behaviour
527 def cores_on_channel(self, channel : int, *args) -> None: 528 """ 529 setup the cores that are connected to a specific channel (see register `SPC_DDS_CORES_ON_CH0` in the manual) 530 531 Parameters 532 ---------- 533 channel : int 534 the channel number 535 *args : int 536 the cores that are connected to the channel 537 538 TODO: change the channel associated with each core 539 """ 540 541 mask = 0 542 for core in args: 543 mask |= core 544 self.set_i(SPC_DDS_CORES_ON_CH0 + channel, mask)
setup the cores that are connected to a specific channel (see register SPC_DDS_CORES_ON_CH0
in the manual)
Parameters
- channel (int): the channel number
- *args (int): the cores that are connected to the channel
- TODO (change the channel associated with each core):
546 def get_cores_on_channel(self, channel : int) -> int: 547 """ 548 get the cores that are connected to a specific channel (see register `SPC_DDS_CORES_ON_CH0` in the manual) 549 550 Parameters 551 ---------- 552 channel : int 553 the channel number 554 555 Returns 556 ------- 557 int 558 the cores that are connected to the channel 559 """ 560 561 return self.card.get_i(SPC_DDS_CORES_ON_CH0 + channel)
get the cores that are connected to a specific channel (see register SPC_DDS_CORES_ON_CH0
in the manual)
Parameters
- channel (int): the channel number
Returns
- int: the cores that are connected to the channel
563 def trg_src(self, src : int) -> None: 564 """ 565 setup the source of where the trigger is coming from (see register `SPC_DDS_TRG_SRC` in the manual) 566 567 NOTE 568 --- 569 the trigger source is also set using the shadow register, hence only after an exec_at_trig or exec_now -- 570 571 Parameters 572 ---------- 573 src : int 574 set the trigger source: 575 * SPCM_DDS_TRG_SRC_NONE = 0 576 no trigger source set, only exec_now changes what is output by the cores 577 * SPCM_DDS_TRG_SRC_TIMER = 1 578 an internal timer sends out triggers with a period defined by `trg_timer(period)` 579 * SPCM_DDS_TRG_SRC_CARD = 2 580 use the trigger engine of the card (see the user manual for more information about setting up the trigger engine) 581 """ 582 583 self.set_i(SPC_DDS_TRG_SRC, src)
setup the source of where the trigger is coming from (see register SPC_DDS_TRG_SRC
in the manual)
NOTE
the trigger source is also set using the shadow register, hence only after an exec_at_trig or exec_now --
Parameters
- src (int):
set the trigger source:
- SPCM_DDS_TRG_SRC_NONE = 0 no trigger source set, only exec_now changes what is output by the cores
- SPCM_DDS_TRG_SRC_TIMER = 1
an internal timer sends out triggers with a period defined by
trg_timer(period)
- SPCM_DDS_TRG_SRC_CARD = 2 use the trigger engine of the card (see the user manual for more information about setting up the trigger engine)
585 def get_trg_src(self) -> int: 586 """ 587 get the source of where the trigger is coming from (see register `SPC_DDS_TRG_SRC` in the manual) 588 589 NOTE 590 ---- 591 the trigger source is also set using the shadow register, hence only after an exec_at_trig or exec_now -- 592 593 Returns 594 ---------- 595 int 596 get one of the trigger source: 597 * SPCM_DDS_TRG_SRC_NONE = 0 598 no trigger source set, only exec_now changes what is output by the cores 599 * SPCM_DDS_TRG_SRC_TIMER = 1 600 an internal timer sends out triggers with a period defined by `trg_timer(period)` 601 * SPCM_DDS_TRG_SRC_CARD = 2 602 use the trigger engine of the card (see the user manual for more information about setting up the trigger engine) 603 """ 604 605 return self.card.get_i(SPC_DDS_TRG_SRC)
get the source of where the trigger is coming from (see register SPC_DDS_TRG_SRC
in the manual)
NOTE
the trigger source is also set using the shadow register, hence only after an exec_at_trig or exec_now --
Returns
- int: get one of the trigger source:
- SPCM_DDS_TRG_SRC_NONE = 0 no trigger source set, only exec_now changes what is output by the cores
- SPCM_DDS_TRG_SRC_TIMER = 1
an internal timer sends out triggers with a period defined by
trg_timer(period)
- SPCM_DDS_TRG_SRC_CARD = 2 use the trigger engine of the card (see the user manual for more information about setting up the trigger engine)
607 def trg_timer(self, period : float) -> None: 608 """ 609 set the period at which the timer should raise DDS trigger events. (see register `SPC_DDS_TRG_TIMER` in the manual) 610 611 NOTE 612 ---- 613 only used in conjecture with the trigger source set to SPCM_DDS_TRG_SRC_TIMER --- 614 615 Parameters 616 ---------- 617 period : float | pint.Quantity 618 the time between DDS trigger events in seconds 619 """ 620 621 period = UnitConversion.convert(period, units.s, float, rounding=None) 622 self.set_d(SPC_DDS_TRG_TIMER, float(period))
set the period at which the timer should raise DDS trigger events. (see register SPC_DDS_TRG_TIMER
in the manual)
NOTE
only used in conjecture with the trigger source set to SPCM_DDS_TRG_SRC_TIMER ---
Parameters
- period (float | pint.Quantity): the time between DDS trigger events in seconds
624 def get_trg_timer(self, return_unit = None) -> float: 625 """ 626 get the period at which the timer should raise DDS trigger events. (see register `SPC_DDS_TRG_TIMER` in the manual) 627 628 NOTE 629 ---- 630 only used in conjecture with the trigger source set to SPCM_DDS_TRG_SRC_TIMER --- 631 632 Parameters 633 ---------- 634 return_unit : pint.Unit = None 635 the unit of the returned time between DDS trigger events, by default None 636 637 Returns 638 ---------- 639 float 640 the time between DDS trigger events in seconds 641 """ 642 643 return_value = self.card.get_d(SPC_DDS_TRG_TIMER) 644 if return_unit is not None: return_value = UnitConversion.to_unit(return_value * units.s, return_unit) 645 return return_value
get the period at which the timer should raise DDS trigger events. (see register SPC_DDS_TRG_TIMER
in the manual)
NOTE
only used in conjecture with the trigger source set to SPCM_DDS_TRG_SRC_TIMER ---
Parameters
- return_unit (pint.Unit = None): the unit of the returned time between DDS trigger events, by default None
Returns
- float: the time between DDS trigger events in seconds
647 def x_mode(self, xio : int, mode : int) -> None: 648 """ 649 setup the kind of output that the XIO outputs will give (see register `SPC_DDS_X0_MODE` in the manual) 650 651 Parameters 652 ---------- 653 xio : int 654 the XIO channel number 655 mode : int 656 the mode that the channel needs to run in 657 """ 658 659 self.set_i(SPC_DDS_X0_MODE + xio, mode)
setup the kind of output that the XIO outputs will give (see register SPC_DDS_X0_MODE
in the manual)
Parameters
- xio (int): the XIO channel number
- mode (int): the mode that the channel needs to run in
661 def get_x_mode(self, xio : int) -> int: 662 """ 663 get the kind of output that the XIO outputs will give (see register `SPC_DDS_X0_MODE` in the manual) 664 665 Parameters 666 ---------- 667 xio : int 668 the XIO channel number 669 670 Returns 671 ------- 672 int 673 the mode that the channel needs to run in 674 SPC_DDS_XIO_SEQUENCE = 0 675 turn on and off the XIO channels using commands in the DDS cmd queue 676 SPC_DDS_XIO_ARM = 1 677 when the DDS firmware is waiting for a trigger to come this signal is high 678 SPC_DDS_XIO_LATCH = 2 679 when the DDS firmware starts executing a change this signal is high 680 """ 681 682 return self.card.get_i(SPC_DDS_X0_MODE + xio)
get the kind of output that the XIO outputs will give (see register SPC_DDS_X0_MODE
in the manual)
Parameters
- xio (int): the XIO channel number
Returns
- int: the mode that the channel needs to run in SPC_DDS_XIO_SEQUENCE = 0 turn on and off the XIO channels using commands in the DDS cmd queue SPC_DDS_XIO_ARM = 1 when the DDS firmware is waiting for a trigger to come this signal is high SPC_DDS_XIO_LATCH = 2 when the DDS firmware starts executing a change this signal is high
684 def freq_ramp_stepsize(self, divider : int) -> None: 685 """ 686 number of timesteps before the frequency is changed during a frequency ramp. (see register `SPC_DDS_FREQ_RAMP_STEPSIZE` in the manual) 687 688 NOTES 689 ----- 690 - this is a global setting for all cores 691 - internally the time divider is used to calculate the amount of change per event using a given frequency slope, please set the time divider before setting the frequency slope 692 693 Parameters 694 ---------- 695 divider : int 696 the number of DDS timesteps that a value is kept constant during a frequency ramp 697 """ 698 699 self.set_i(SPC_DDS_FREQ_RAMP_STEPSIZE, int(divider))
number of timesteps before the frequency is changed during a frequency ramp. (see register SPC_DDS_FREQ_RAMP_STEPSIZE
in the manual)
NOTES
- this is a global setting for all cores
- internally the time divider is used to calculate the amount of change per event using a given frequency slope, please set the time divider before setting the frequency slope
Parameters
- divider (int): the number of DDS timesteps that a value is kept constant during a frequency ramp
701 def get_freq_ramp_stepsize(self) -> int: 702 """ 703 get the number of timesteps before the frequency is changed during a frequency ramp. (see register `SPC_DDS_FREQ_RAMP_STEPSIZE` in the manual) 704 705 NOTES 706 ----- 707 - this is a global setting for all cores 708 - internally the time divider is used to calculate the amount of change per event using a given frequency slope, please set the time divider before setting the frequency slope 709 710 Returns 711 ---------- 712 divider : int 713 the number of DDS timesteps that a value is kept constant during a frequency ramp 714 """ 715 716 return self.card.get_i(SPC_DDS_FREQ_RAMP_STEPSIZE)
get the number of timesteps before the frequency is changed during a frequency ramp. (see register SPC_DDS_FREQ_RAMP_STEPSIZE
in the manual)
NOTES
- this is a global setting for all cores
- internally the time divider is used to calculate the amount of change per event using a given frequency slope, please set the time divider before setting the frequency slope
Returns
- divider (int): the number of DDS timesteps that a value is kept constant during a frequency ramp
718 def amp_ramp_stepsize(self, divider : int) -> None: 719 """ 720 number of timesteps before the amplitude is changed during a frequency ramp. (see register `SPC_DDS_AMP_RAMP_STEPSIZE` in the manual) 721 722 NOTES 723 ----- 724 - this is a global setting for all cores 725 - internally the time divider is used to calculate the amount of change per event using a given amplitude slope, 726 please set the time divider before setting the amplitude slope 727 728 Parameters 729 ---------- 730 divider : int 731 the number of DDS timesteps that a value is kept constant during an amplitude ramp 732 """ 733 734 self.set_i(SPC_DDS_AMP_RAMP_STEPSIZE, int(divider))
number of timesteps before the amplitude is changed during a frequency ramp. (see register SPC_DDS_AMP_RAMP_STEPSIZE
in the manual)
NOTES
- this is a global setting for all cores
- internally the time divider is used to calculate the amount of change per event using a given amplitude slope, please set the time divider before setting the amplitude slope
Parameters
- divider (int): the number of DDS timesteps that a value is kept constant during an amplitude ramp
736 def get_amp_ramp_stepsize(self) -> int: 737 """ 738 get the number of timesteps before the amplitude is changed during a frequency ramp. (see register `SPC_DDS_AMP_RAMP_STEPSIZE` in the manual) 739 740 NOTES 741 ----- 742 - this is a global setting for all cores 743 - internally the time divider is used to calculate the amount of change per event using a given amplitude slope, 744 please set the time divider before setting the amplitude slope 745 746 Returns 747 ---------- 748 divider : int 749 the number of DDS timesteps that a value is kept constant during an amplitude ramp 750 """ 751 752 return self.card.get_i(SPC_DDS_AMP_RAMP_STEPSIZE)
get the number of timesteps before the amplitude is changed during a frequency ramp. (see register SPC_DDS_AMP_RAMP_STEPSIZE
in the manual)
NOTES
- this is a global setting for all cores
- internally the time divider is used to calculate the amount of change per event using a given amplitude slope, please set the time divider before setting the amplitude slope
Returns
- divider (int): the number of DDS timesteps that a value is kept constant during an amplitude ramp
756 def amp(self, *args) -> None: 757 """ 758 set the amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP` in the manual) 759 760 Parameters 761 ---------- 762 core_index : int (optional) 763 the index of the core to be changed 764 amplitude : float 765 the value between 0 and 1 corresponding to the amplitude 766 """ 767 768 if len(args) == 1: 769 amplitude = args[0] 770 for core in self.cores: 771 core.amp(amplitude) 772 elif len(args) == 2: 773 core_index, amplitude = args 774 self.cores[core_index].amp(amplitude) 775 else: 776 raise TypeError("amp() takes 1 or 2 positional arguments ({} given)".format(len(args) + 1)) 777 # self.set_d(SPC_DDS_CORE0_AMP + core_index, float(amplitude))
set the amplitude of the sine wave of a specific core (see register SPC_DDS_CORE0_AMP
in the manual)
Parameters
- core_index (int (optional)): the index of the core to be changed
- amplitude (float): the value between 0 and 1 corresponding to the amplitude
756 def amp(self, *args) -> None: 757 """ 758 set the amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP` in the manual) 759 760 Parameters 761 ---------- 762 core_index : int (optional) 763 the index of the core to be changed 764 amplitude : float 765 the value between 0 and 1 corresponding to the amplitude 766 """ 767 768 if len(args) == 1: 769 amplitude = args[0] 770 for core in self.cores: 771 core.amp(amplitude) 772 elif len(args) == 2: 773 core_index, amplitude = args 774 self.cores[core_index].amp(amplitude) 775 else: 776 raise TypeError("amp() takes 1 or 2 positional arguments ({} given)".format(len(args) + 1)) 777 # self.set_d(SPC_DDS_CORE0_AMP + core_index, float(amplitude))
set the amplitude of the sine wave of a specific core (see register SPC_DDS_CORE0_AMP
in the manual)
Parameters
- core_index (int (optional)): the index of the core to be changed
- amplitude (float): the value between 0 and 1 corresponding to the amplitude
781 def get_amp(self, core_index : int, return_unit = None) -> float: 782 """ 783 gets the amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP` in the manual) 784 785 Parameters 786 ---------- 787 core_index : int 788 the index of the core to be changed 789 return_unit : pint.Unit = None 790 the unit of the returned amplitude, by default None 791 792 Returns 793 ------- 794 float | pint.Quantity 795 the value between 0 and 1 corresponding to the amplitude of the specific core or in the specified unit 796 """ 797 798 return self.cores[core_index].get_amp(return_unit) 799 # return self.card.get_d(SPC_DDS_CORE0_AMP + core_index)
gets the amplitude of the sine wave of a specific core (see register SPC_DDS_CORE0_AMP
in the manual)
Parameters
- core_index (int): the index of the core to be changed
- return_unit (pint.Unit = None): the unit of the returned amplitude, by default None
Returns
- float | pint.Quantity: the value between 0 and 1 corresponding to the amplitude of the specific core or in the specified unit
781 def get_amp(self, core_index : int, return_unit = None) -> float: 782 """ 783 gets the amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP` in the manual) 784 785 Parameters 786 ---------- 787 core_index : int 788 the index of the core to be changed 789 return_unit : pint.Unit = None 790 the unit of the returned amplitude, by default None 791 792 Returns 793 ------- 794 float | pint.Quantity 795 the value between 0 and 1 corresponding to the amplitude of the specific core or in the specified unit 796 """ 797 798 return self.cores[core_index].get_amp(return_unit) 799 # return self.card.get_d(SPC_DDS_CORE0_AMP + core_index)
gets the amplitude of the sine wave of a specific core (see register SPC_DDS_CORE0_AMP
in the manual)
Parameters
- core_index (int): the index of the core to be changed
- return_unit (pint.Unit = None): the unit of the returned amplitude, by default None
Returns
- float | pint.Quantity: the value between 0 and 1 corresponding to the amplitude of the specific core or in the specified unit
803 def avail_amp_min(self) -> float: 804 """ 805 get the minimum available amplitude (see register `SPC_DDS_AVAIL_AMP_MIN` in the manual) 806 807 Returns 808 ------- 809 float 810 the minimum available amplitude 811 812 TODO: unitize! 813 """ 814 815 return self.card.get_d(SPC_DDS_AVAIL_AMP_MIN)
get the minimum available amplitude (see register SPC_DDS_AVAIL_AMP_MIN
in the manual)
Returns
- float: the minimum available amplitude
- TODO (unitize!):
817 def avail_amp_max(self) -> float: 818 """ 819 get the maximum available amplitude (see register `SPC_DDS_AVAIL_AMP_MAX` in the manual) 820 821 Returns 822 ------- 823 float 824 the maximum available amplitude 825 826 TODO: unitize! 827 """ 828 829 return self.card.get_d(SPC_DDS_AVAIL_AMP_MAX)
get the maximum available amplitude (see register SPC_DDS_AVAIL_AMP_MAX
in the manual)
Returns
- float: the maximum available amplitude
- TODO (unitize!):
831 def avail_amp_step(self) -> float: 832 """ 833 get the step size of the available amplitudes (see register `SPC_DDS_AVAIL_AMP_STEP` in the manual) 834 835 Returns 836 ------- 837 float 838 the step size of the available amplitudes 839 840 TODO: unitize! 841 """ 842 843 return self.card.get_d(SPC_DDS_AVAIL_AMP_STEP)
get the step size of the available amplitudes (see register SPC_DDS_AVAIL_AMP_STEP
in the manual)
Returns
- float: the step size of the available amplitudes
- TODO (unitize!):
846 def freq(self, *args) -> None: 847 """ 848 set the frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ` in the manual) 849 850 Parameters 851 ---------- 852 core_index : int (optional) 853 the index of the core to be changed 854 frequency : float 855 the value of the frequency in Hz 856 """ 857 858 if len(args) == 1: 859 frequency = args[0] 860 for core in self.cores: 861 core.freq(frequency) 862 elif len(args) == 2: 863 core_index, frequency = args 864 self.cores[core_index].freq(frequency) 865 else: 866 raise TypeError("freq() takes 1 or 2 positional arguments ({} given)".format(len(args) + 1)) 867 # self.set_d(SPC_DDS_CORE0_FREQ + core_index, float(frequency))
set the frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ
in the manual)
Parameters
- core_index (int (optional)): the index of the core to be changed
- frequency (float): the value of the frequency in Hz
846 def freq(self, *args) -> None: 847 """ 848 set the frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ` in the manual) 849 850 Parameters 851 ---------- 852 core_index : int (optional) 853 the index of the core to be changed 854 frequency : float 855 the value of the frequency in Hz 856 """ 857 858 if len(args) == 1: 859 frequency = args[0] 860 for core in self.cores: 861 core.freq(frequency) 862 elif len(args) == 2: 863 core_index, frequency = args 864 self.cores[core_index].freq(frequency) 865 else: 866 raise TypeError("freq() takes 1 or 2 positional arguments ({} given)".format(len(args) + 1)) 867 # self.set_d(SPC_DDS_CORE0_FREQ + core_index, float(frequency))
set the frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ
in the manual)
Parameters
- core_index (int (optional)): the index of the core to be changed
- frequency (float): the value of the frequency in Hz
871 def get_freq(self, core_index : int, return_unit = None) -> float: 872 """ 873 gets the frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ` in the manual) 874 875 Parameters 876 ---------- 877 core_index : int 878 the index of the core to be changed 879 return_unit : pint.Unit = None 880 the unit of the returned frequency, by default None 881 882 Returns 883 ------- 884 float | pint.Quantity 885 the value of the frequency in Hz the specific core or in the specified unit 886 """ 887 888 return self.cores[core_index].get_freq(return_unit)
gets the frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ
in the manual)
Parameters
- core_index (int): the index of the core to be changed
- return_unit (pint.Unit = None): the unit of the returned frequency, by default None
Returns
- float | pint.Quantity: the value of the frequency in Hz the specific core or in the specified unit
871 def get_freq(self, core_index : int, return_unit = None) -> float: 872 """ 873 gets the frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ` in the manual) 874 875 Parameters 876 ---------- 877 core_index : int 878 the index of the core to be changed 879 return_unit : pint.Unit = None 880 the unit of the returned frequency, by default None 881 882 Returns 883 ------- 884 float | pint.Quantity 885 the value of the frequency in Hz the specific core or in the specified unit 886 """ 887 888 return self.cores[core_index].get_freq(return_unit)
gets the frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ
in the manual)
Parameters
- core_index (int): the index of the core to be changed
- return_unit (pint.Unit = None): the unit of the returned frequency, by default None
Returns
- float | pint.Quantity: the value of the frequency in Hz the specific core or in the specified unit
892 def avail_freq_min(self) -> float: 893 """ 894 get the minimum available frequency (see register `SPC_DDS_AVAIL_FREQ_MIN` in the manual) 895 896 Returns 897 ------- 898 float 899 the minimum available frequency 900 901 TODO: unitize! 902 """ 903 904 return self.card.get_d(SPC_DDS_AVAIL_FREQ_MIN)
get the minimum available frequency (see register SPC_DDS_AVAIL_FREQ_MIN
in the manual)
Returns
- float: the minimum available frequency
- TODO (unitize!):
906 def avail_freq_max(self) -> float: 907 """ 908 get the maximum available frequency (see register `SPC_DDS_AVAIL_FREQ_MAX` in the manual) 909 910 Returns 911 ------- 912 float 913 the maximum available frequency 914 915 TODO: unitize! 916 """ 917 918 return self.card.get_d(SPC_DDS_AVAIL_FREQ_MAX)
get the maximum available frequency (see register SPC_DDS_AVAIL_FREQ_MAX
in the manual)
Returns
- float: the maximum available frequency
- TODO (unitize!):
920 def avail_freq_step(self) -> float: 921 """ 922 get the step size of the available frequencies (see register `SPC_DDS_AVAIL_FREQ_STEP` in the manual) 923 924 Returns 925 ------- 926 float 927 the step size of the available frequencies 928 929 TODO: unitize! 930 """ 931 932 return self.card.get_d(SPC_DDS_AVAIL_FREQ_STEP)
get the step size of the available frequencies (see register SPC_DDS_AVAIL_FREQ_STEP
in the manual)
Returns
- float: the step size of the available frequencies
- TODO (unitize!):
935 def phase(self, *args) -> None: 936 """ 937 set the phase of the sine wave of a specific core (see register `SPC_DDS_CORE0_PHASE` in the manual) 938 939 Parameters 940 ---------- 941 core_index : int (optional) 942 the index of the core to be changed 943 phase : float 944 the value between 0 and 360 degrees of the phase 945 """ 946 947 if len(args) == 1: 948 phase = args[0] 949 for core in self.cores: 950 core.phase(phase) 951 elif len(args) == 2: 952 core_index, phase = args 953 self.cores[core_index].phase(phase) 954 else: 955 raise TypeError("phase() takes 1 or 2 positional arguments ({} given)".format(len(args) + 1)) 956 # self.set_d(SPC_DDS_CORE0_PHASE + core_index, float(phase))
set the phase of the sine wave of a specific core (see register SPC_DDS_CORE0_PHASE
in the manual)
Parameters
- core_index (int (optional)): the index of the core to be changed
- phase (float): the value between 0 and 360 degrees of the phase
958 def get_phase(self, core_index : int, return_unit = None) -> float: 959 """ 960 gets the phase of the sine wave of a specific core (see register `SPC_DDS_CORE0_PHASE` in the manual) 961 962 Parameters 963 ---------- 964 core_index : int 965 the index of the core to be changed 966 return_unit : pint.Unit = None 967 the unit of the returned phase, by default None 968 969 Returns 970 ------- 971 float 972 the value between 0 and 360 degrees of the phase 973 """ 974 975 return self.cores[core_index].get_phase(return_unit)
gets the phase of the sine wave of a specific core (see register SPC_DDS_CORE0_PHASE
in the manual)
Parameters
- core_index (int): the index of the core to be changed
- return_unit (pint.Unit = None): the unit of the returned phase, by default None
Returns
- float: the value between 0 and 360 degrees of the phase
977 def avail_phase_min(self) -> float: 978 """ 979 get the minimum available phase (see register `SPC_DDS_AVAIL_PHASE_MIN` in the manual) 980 981 Returns 982 ------- 983 float 984 the minimum available phase 985 986 TODO: unitize! 987 """ 988 989 return self.card.get_d(SPC_DDS_AVAIL_PHASE_MIN)
get the minimum available phase (see register SPC_DDS_AVAIL_PHASE_MIN
in the manual)
Returns
- float: the minimum available phase
- TODO (unitize!):
991 def avail_phase_max(self) -> float: 992 """ 993 get the maximum available phase (see register `SPC_DDS_AVAIL_PHASE_MAX` in the manual) 994 995 Returns 996 ------- 997 float 998 the maximum available phase 999 1000 TODO: unitize! 1001 """ 1002 1003 return self.card.get_d(SPC_DDS_AVAIL_PHASE_MAX)
get the maximum available phase (see register SPC_DDS_AVAIL_PHASE_MAX
in the manual)
Returns
- float: the maximum available phase
- TODO (unitize!):
1005 def avail_phase_step(self) -> float: 1006 """ 1007 get the step size of the available phases (see register `SPC_DDS_AVAIL_PHASE_STEP` in the manual) 1008 1009 Returns 1010 ------- 1011 float 1012 the step size of the available phases 1013 1014 TODO: unitize! 1015 """ 1016 1017 return self.card.get_d(SPC_DDS_AVAIL_PHASE_STEP)
get the step size of the available phases (see register SPC_DDS_AVAIL_PHASE_STEP
in the manual)
Returns
- float: the step size of the available phases
- TODO (unitize!):
1019 def x_manual_output(self, state_mask : int) -> None: 1020 """ 1021 set the output of the xio channels using a bit mask (see register `SPC_DDS_X_MANUAL_OUTPUT` in the manual) 1022 1023 Parameters 1024 ---------- 1025 state_mask : int 1026 bit mask where the bits correspond to specific channels and 1 to on and 0 to off. 1027 """ 1028 1029 self.set_i(SPC_DDS_X_MANUAL_OUTPUT, state_mask)
set the output of the xio channels using a bit mask (see register SPC_DDS_X_MANUAL_OUTPUT
in the manual)
Parameters
- state_mask (int): bit mask where the bits correspond to specific channels and 1 to on and 0 to off.
1031 def get_x_manual_output(self) -> int: 1032 """ 1033 get the output of the xio channels using a bit mask (see register `SPC_DDS_X_MANUAL_OUTPUT` in the manual) 1034 1035 Returns 1036 ---------- 1037 int 1038 bit mask where the bits correspond to specific channels and 1 to on and 0 to off. 1039 """ 1040 1041 return self.card.get_i(SPC_DDS_X_MANUAL_OUTPUT)
get the output of the xio channels using a bit mask (see register SPC_DDS_X_MANUAL_OUTPUT
in the manual)
Returns
- int: bit mask where the bits correspond to specific channels and 1 to on and 0 to off.
1045 def freq_slope(self, *args) -> None: 1046 """ 1047 set the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ_SLOPE` in the manual) 1048 1049 Parameters 1050 ---------- 1051 core_index : int (optional) 1052 the index of the core to be changed 1053 slope : float 1054 the rate of frequency change in Hz/s 1055 """ 1056 1057 if len(args) == 1: 1058 slope = args[0] 1059 for core in self.cores: 1060 core.freq_slope(slope) 1061 elif len(args) == 2: 1062 core_index, slope = args 1063 self.cores[core_index].freq_slope(slope) 1064 else: 1065 raise TypeError("freq_slope() takes 1 or 2 positional arguments ({} given)".format(len(args) + 1)) 1066 # self.set_d(SPC_DDS_CORE0_FREQ_SLOPE + core_index, float(slope))
set the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ_SLOPE
in the manual)
Parameters
- core_index (int (optional)): the index of the core to be changed
- slope (float): the rate of frequency change in Hz/s
1045 def freq_slope(self, *args) -> None: 1046 """ 1047 set the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ_SLOPE` in the manual) 1048 1049 Parameters 1050 ---------- 1051 core_index : int (optional) 1052 the index of the core to be changed 1053 slope : float 1054 the rate of frequency change in Hz/s 1055 """ 1056 1057 if len(args) == 1: 1058 slope = args[0] 1059 for core in self.cores: 1060 core.freq_slope(slope) 1061 elif len(args) == 2: 1062 core_index, slope = args 1063 self.cores[core_index].freq_slope(slope) 1064 else: 1065 raise TypeError("freq_slope() takes 1 or 2 positional arguments ({} given)".format(len(args) + 1)) 1066 # self.set_d(SPC_DDS_CORE0_FREQ_SLOPE + core_index, float(slope))
set the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ_SLOPE
in the manual)
Parameters
- core_index (int (optional)): the index of the core to be changed
- slope (float): the rate of frequency change in Hz/s
1070 def get_freq_slope(self, core_index : int, return_unit=None) -> float: 1071 """ 1072 get the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ_SLOPE` in the manual) 1073 1074 Parameters 1075 ---------- 1076 core_index : int 1077 the index of the core to be changed 1078 return_unit : pint.Unit = None 1079 the unit of the returned frequency slope, by default None 1080 1081 Returns 1082 ------- 1083 float 1084 the rate of frequency change in Hz/s 1085 """ 1086 1087 return self.cores[core_index].get_freq_slope(return_unit)
get the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ_SLOPE
in the manual)
Parameters
- core_index (int): the index of the core to be changed
- return_unit (pint.Unit = None): the unit of the returned frequency slope, by default None
Returns
- float: the rate of frequency change in Hz/s
1070 def get_freq_slope(self, core_index : int, return_unit=None) -> float: 1071 """ 1072 get the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ_SLOPE` in the manual) 1073 1074 Parameters 1075 ---------- 1076 core_index : int 1077 the index of the core to be changed 1078 return_unit : pint.Unit = None 1079 the unit of the returned frequency slope, by default None 1080 1081 Returns 1082 ------- 1083 float 1084 the rate of frequency change in Hz/s 1085 """ 1086 1087 return self.cores[core_index].get_freq_slope(return_unit)
get the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ_SLOPE
in the manual)
Parameters
- core_index (int): the index of the core to be changed
- return_unit (pint.Unit = None): the unit of the returned frequency slope, by default None
Returns
- float: the rate of frequency change in Hz/s
1091 def avail_freq_slope_min(self) -> float: 1092 """ 1093 get the minimum available frequency slope (see register `SPC_DDS_AVAIL_FREQ_SLOPE_MIN` in the manual) 1094 1095 Returns 1096 ------- 1097 float 1098 the minimum available frequency slope 1099 1100 TODO: unitize! 1101 """ 1102 1103 return self.card.get_d(SPC_DDS_AVAIL_FREQ_SLOPE_MIN)
get the minimum available frequency slope (see register SPC_DDS_AVAIL_FREQ_SLOPE_MIN
in the manual)
Returns
- float: the minimum available frequency slope
- TODO (unitize!):
1105 def avail_freq_slope_max(self) -> float: 1106 """ 1107 get the maximum available frequency slope (see register `SPC_DDS_AVAIL_FREQ_SLOPE_MAX` in the manual) 1108 1109 Returns 1110 ------- 1111 float 1112 the maximum available frequency slope 1113 1114 TODO: unitize! 1115 """ 1116 1117 return self.card.get_d(SPC_DDS_AVAIL_FREQ_SLOPE_MAX)
get the maximum available frequency slope (see register SPC_DDS_AVAIL_FREQ_SLOPE_MAX
in the manual)
Returns
- float: the maximum available frequency slope
- TODO (unitize!):
1119 def avail_freq_slope_step(self) -> float: 1120 """ 1121 get the step size of the available frequency slopes (see register `SPC_DDS_AVAIL_FREQ_SLOPE_STEP` in the manual) 1122 1123 Returns 1124 ------- 1125 float 1126 the step size of the available frequency slopes 1127 1128 TODO: unitize! 1129 """ 1130 1131 return self.card.get_d(SPC_DDS_AVAIL_FREQ_SLOPE_STEP)
get the step size of the available frequency slopes (see register SPC_DDS_AVAIL_FREQ_SLOPE_STEP
in the manual)
Returns
- float: the step size of the available frequency slopes
- TODO (unitize!):
1134 def amp_slope(self, *args) -> None: 1135 """ 1136 set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP_SLOPE` in the manual) 1137 1138 Parameters 1139 ---------- 1140 core_index : int (optional) 1141 the index of the core to be changed 1142 slope : float 1143 the rate of amplitude change in 1/s 1144 """ 1145 1146 if len(args) == 1: 1147 slope = args[0] 1148 for core in self.cores: 1149 core.amp_slope(slope) 1150 elif len(args) == 2: 1151 core_index, slope = args 1152 self.cores[core_index].amp_slope(slope) 1153 else: 1154 raise TypeError("amp_slope() takes 1 or 2 positional arguments ({} given)".format(len(args) + 1)) 1155 # self.set_d(SPC_DDS_CORE0_AMP_SLOPE + core_index, float(slope))
set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register SPC_DDS_CORE0_AMP_SLOPE
in the manual)
Parameters
- core_index (int (optional)): the index of the core to be changed
- slope (float): the rate of amplitude change in 1/s
1134 def amp_slope(self, *args) -> None: 1135 """ 1136 set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP_SLOPE` in the manual) 1137 1138 Parameters 1139 ---------- 1140 core_index : int (optional) 1141 the index of the core to be changed 1142 slope : float 1143 the rate of amplitude change in 1/s 1144 """ 1145 1146 if len(args) == 1: 1147 slope = args[0] 1148 for core in self.cores: 1149 core.amp_slope(slope) 1150 elif len(args) == 2: 1151 core_index, slope = args 1152 self.cores[core_index].amp_slope(slope) 1153 else: 1154 raise TypeError("amp_slope() takes 1 or 2 positional arguments ({} given)".format(len(args) + 1)) 1155 # self.set_d(SPC_DDS_CORE0_AMP_SLOPE + core_index, float(slope))
set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register SPC_DDS_CORE0_AMP_SLOPE
in the manual)
Parameters
- core_index (int (optional)): the index of the core to be changed
- slope (float): the rate of amplitude change in 1/s
1159 def get_amp_slope(self, core_index : int, return_unit = None) -> float: 1160 """ 1161 set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP_SLOPE` in the manual) 1162 1163 Parameters 1164 ---------- 1165 core_index : int 1166 the index of the core to be changed 1167 return_unit : pint.Unit = None 1168 the unit of the returned amplitude slope, by default None 1169 1170 Returns 1171 ------- 1172 float 1173 the rate of amplitude change in 1/s 1174 """ 1175 1176 return self.cores[core_index].get_amp_slope(return_unit)
set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register SPC_DDS_CORE0_AMP_SLOPE
in the manual)
Parameters
- core_index (int): the index of the core to be changed
- return_unit (pint.Unit = None): the unit of the returned amplitude slope, by default None
Returns
- float: the rate of amplitude change in 1/s
1180 def avail_amp_slope_min(self) -> float: 1181 """ 1182 get the minimum available amplitude slope (see register `SPC_DDS_AVAIL_AMP_SLOPE_MIN` in the manual) 1183 1184 Returns 1185 ------- 1186 float 1187 the minimum available amplitude slope 1188 1189 TODO: unitize! 1190 """ 1191 1192 return self.card.get_d(SPC_DDS_AVAIL_AMP_SLOPE_MIN)
get the minimum available amplitude slope (see register SPC_DDS_AVAIL_AMP_SLOPE_MIN
in the manual)
Returns
- float: the minimum available amplitude slope
- TODO (unitize!):
1194 def avail_amp_slope_max(self) -> float: 1195 """ 1196 get the maximum available amplitude slope (see register `SPC_DDS_AVAIL_AMP_SLOPE_MAX` in the manual) 1197 1198 Returns 1199 ------- 1200 float 1201 the maximum available amplitude slope 1202 1203 TODO: unitize! 1204 """ 1205 1206 return self.card.get_d(SPC_DDS_AVAIL_AMP_SLOPE_MAX)
get the maximum available amplitude slope (see register SPC_DDS_AVAIL_AMP_SLOPE_MAX
in the manual)
Returns
- float: the maximum available amplitude slope
- TODO (unitize!):
1208 def avail_amp_slope_step(self) -> float: 1209 """ 1210 get the step size of the available amplitude slopes (see register `SPC_DDS_AVAIL_AMP_SLOPE_STEP` in the manual) 1211 1212 Returns 1213 ------- 1214 float 1215 the step size of the available amplitude slopes 1216 1217 TODO: unitize! 1218 """ 1219 1220 return self.card.get_d(SPC_DDS_AVAIL_AMP_SLOPE_STEP)
get the step size of the available amplitude slopes (see register SPC_DDS_AVAIL_AMP_SLOPE_STEP
in the manual)
Returns
- float: the step size of the available amplitude slopes
- TODO (unitize!):
1223 def cmd(self, command : int) -> None: 1224 """ 1225 execute a DDS specific control flow command (see register `SPC_DDS_CMD` in the manual) 1226 1227 Parameters 1228 ---------- 1229 command : int 1230 DDS specific command 1231 """ 1232 1233 self.set_i(SPC_DDS_CMD, command)
execute a DDS specific control flow command (see register SPC_DDS_CMD
in the manual)
Parameters
- command (int): DDS specific command
1235 def exec_at_trg(self) -> None: 1236 """ 1237 execute the commands in the shadow register at the next trigger event (see register `SPC_DDS_CMD` in the manual) 1238 """ 1239 self.cmd(SPCM_DDS_CMD_EXEC_AT_TRG)
execute the commands in the shadow register at the next trigger event (see register SPC_DDS_CMD
in the manual)
1235 def exec_at_trg(self) -> None: 1236 """ 1237 execute the commands in the shadow register at the next trigger event (see register `SPC_DDS_CMD` in the manual) 1238 """ 1239 self.cmd(SPCM_DDS_CMD_EXEC_AT_TRG)
execute the commands in the shadow register at the next trigger event (see register SPC_DDS_CMD
in the manual)
1235 def exec_at_trg(self) -> None: 1236 """ 1237 execute the commands in the shadow register at the next trigger event (see register `SPC_DDS_CMD` in the manual) 1238 """ 1239 self.cmd(SPCM_DDS_CMD_EXEC_AT_TRG)
execute the commands in the shadow register at the next trigger event (see register SPC_DDS_CMD
in the manual)
1244 def exec_now(self) -> None: 1245 """ 1246 execute the commands in the shadow register as soon as possible (see register `SPC_DDS_CMD` in the manual) 1247 """ 1248 1249 self.cmd(SPCM_DDS_CMD_EXEC_NOW)
execute the commands in the shadow register as soon as possible (see register SPC_DDS_CMD
in the manual)
1244 def exec_now(self) -> None: 1245 """ 1246 execute the commands in the shadow register as soon as possible (see register `SPC_DDS_CMD` in the manual) 1247 """ 1248 1249 self.cmd(SPCM_DDS_CMD_EXEC_NOW)
execute the commands in the shadow register as soon as possible (see register SPC_DDS_CMD
in the manual)
1253 def trg_count(self) -> int: 1254 """ 1255 get the number of trigger exec_at_trg and exec_now command that have been executed (see register `SPC_DDS_TRG_COUNT` in the manual) 1256 1257 Returns 1258 ------- 1259 int 1260 the number of trigger exec_at_trg and exec_now command that have been executed 1261 """ 1262 1263 return self.card.get_i(SPC_DDS_TRG_COUNT)
get the number of trigger exec_at_trg and exec_now command that have been executed (see register SPC_DDS_TRG_COUNT
in the manual)
Returns
- int: the number of trigger exec_at_trg and exec_now command that have been executed
1265 def write_to_card(self, flags=0) -> None: 1266 """ 1267 send a list of all the commands that came after the last write_list and send them to the card (see register `SPC_DDS_CMD` in the manual) 1268 """ 1269 1270 self.cmd(SPCM_DDS_CMD_WRITE_TO_CARD | flags)
send a list of all the commands that came after the last write_list and send them to the card (see register SPC_DDS_CMD
in the manual)
1273 def kwargs2mask(self, kwargs : dict[str, bool], prefix : str = "") -> int: 1274 """ 1275 DDS helper: transform a dictionary with keys with a specific prefix to a bitmask 1276 1277 Parameters 1278 ---------- 1279 kwargs : dict 1280 dictonary with keys with a specific prefix and values given by bools 1281 prefix : str 1282 a prefix for the key names 1283 1284 Returns 1285 ------- 1286 int 1287 bit mask 1288 1289 Example 1290 ------- 1291 ['core_0' = True, 'core_2' = False, 'core_3' = True] => 0b1001 = 9 1292 """ 1293 1294 mask = 0 1295 for keyword, value in kwargs.items(): 1296 bit = int(keyword[len(prefix)+1:]) 1297 if value: 1298 mask |= 1 << bit 1299 else: 1300 mask &= ~(1 << bit) 1301 return mask
DDS helper: transform a dictionary with keys with a specific prefix to a bitmask
Parameters
- kwargs (dict): dictonary with keys with a specific prefix and values given by bools
- prefix (str): a prefix for the key names
Returns
- int: bit mask
Example
['core_0' = True, 'core_2' = False, 'core_3' = True] => 0b1001 = 9
1273 def kwargs2mask(self, kwargs : dict[str, bool], prefix : str = "") -> int: 1274 """ 1275 DDS helper: transform a dictionary with keys with a specific prefix to a bitmask 1276 1277 Parameters 1278 ---------- 1279 kwargs : dict 1280 dictonary with keys with a specific prefix and values given by bools 1281 prefix : str 1282 a prefix for the key names 1283 1284 Returns 1285 ------- 1286 int 1287 bit mask 1288 1289 Example 1290 ------- 1291 ['core_0' = True, 'core_2' = False, 'core_3' = True] => 0b1001 = 9 1292 """ 1293 1294 mask = 0 1295 for keyword, value in kwargs.items(): 1296 bit = int(keyword[len(prefix)+1:]) 1297 if value: 1298 mask |= 1 << bit 1299 else: 1300 mask &= ~(1 << bit) 1301 return mask
DDS helper: transform a dictionary with keys with a specific prefix to a bitmask
Parameters
- kwargs (dict): dictonary with keys with a specific prefix and values given by bools
- prefix (str): a prefix for the key names
Returns
- int: bit mask
Example
['core_0' = True, 'core_2' = False, 'core_3' = True] => 0b1001 = 9
13class DDSCore: 14 """ 15 a class for controlling a single DDS core 16 """ 17 18 dds : "DDS" 19 index : int 20 channel : Channel 21 22 def __init__(self, core_index, dds, *args, **kwargs) -> None: 23 self.dds = dds 24 self.index = core_index 25 self.channel = kwargs.get("channel", None) 26 27 def __int__(self) -> int: 28 """ 29 get the index of the core 30 31 Returns 32 ------- 33 int 34 the index of the core 35 """ 36 return self.index 37 __index__ = __int__ 38 39 def __str__(self) -> str: 40 """ 41 get the string representation of the core 42 43 Returns 44 ------- 45 str 46 the string representation of the core 47 """ 48 return f"Core {self.index}" 49 __repr__ = __str__ 50 51 def __add__(self, other) -> int: 52 """ 53 add the index of the core to another index 54 55 Parameters 56 ---------- 57 other : int 58 the other index 59 60 Returns 61 ------- 62 int 63 the sum of the two indices 64 """ 65 return self.index + other 66 67 # DDS "static" parameters 68 def amp(self, amplitude : float) -> None: 69 """ 70 set the amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP` in the manual) 71 72 Parameters 73 ---------- 74 amplitude : float | pint.Quantity 75 the value between 0 and 1 corresponding to the amplitude 76 """ 77 78 if self.channel is not None: 79 amplitude = self.channel.to_amplitude_fraction(amplitude) 80 elif isinstance(amplitude, units.Quantity) and amplitude.check("[]"): 81 amplitude = UnitConversion.convert(amplitude, units.fraction, float, rounding=None) 82 self.dds.set_d(SPC_DDS_CORE0_AMP + self.index, float(amplitude)) 83 # aliases 84 amplitude = amp 85 86 def get_amp(self, return_unit = None) -> float: 87 """ 88 gets the amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP` in the manual) 89 90 Parameters 91 ---------- 92 return_unit : pint.Unit = None 93 the unit of the returned amplitude, by default None 94 95 Returns 96 ------- 97 float 98 the value between 0 and 1 corresponding to the amplitude 99 """ 100 101 return_value = self.dds.card.get_d(SPC_DDS_CORE0_AMP + self.index) 102 if self.channel is not None: 103 return_value = self.channel.from_amplitude_fraction(return_value, return_unit) 104 else: 105 return_value = UnitConversion.to_unit(return_value, return_unit) 106 return return_value 107 # aliases 108 get_amplitude = get_amp 109 110 def freq(self, frequency : float) -> None: 111 """ 112 set the frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ` in the manual) 113 114 Parameters 115 ---------- 116 frequency : float | pint.Quantity 117 the value of the frequency in Hz 118 """ 119 120 frequency = UnitConversion.convert(frequency, units.Hz, float, rounding=None) 121 self.dds.set_d(SPC_DDS_CORE0_FREQ + self.index, float(frequency)) 122 # aliases 123 frequency = freq 124 125 def get_freq(self, return_unit = None) -> float: 126 """ 127 gets the frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ` in the manual) 128 129 Parameters 130 ---------- 131 return_unit : pint.Unit = None 132 the unit of the returned frequency, by default None 133 134 Returns 135 ------- 136 float | pint.Quantity 137 the value of the frequency in Hz the specific core 138 """ 139 140 return_value = self.dds.card.get_d(SPC_DDS_CORE0_FREQ + self.index) 141 if return_unit is not None: return_value = UnitConversion.to_unit(return_value * units.Hz, return_unit) 142 return return_value 143 # aliases 144 get_frequency = get_freq 145 146 def phase(self, phase : float) -> None: 147 """ 148 set the phase of the sine wave of a specific core (see register `SPC_DDS_CORE0_PHASE` in the manual) 149 150 Parameters 151 ---------- 152 phase : float | pint.Quantity 153 the value between 0 and 360 degrees of the phase 154 """ 155 156 phase = UnitConversion.convert(phase, units.deg, float, rounding=None) 157 self.dds.set_d(SPC_DDS_CORE0_PHASE + self.index, float(phase)) 158 159 def get_phase(self, return_unit = None) -> float: 160 """ 161 gets the phase of the sine wave of a specific core (see register `SPC_DDS_CORE0_PHASE` in the manual) 162 163 Returns 164 ------- 165 float 166 the value between 0 and 360 degrees of the phase 167 """ 168 169 return_value = self.dds.card.get_d(SPC_DDS_CORE0_PHASE + self.index) 170 if return_unit is not None: return_value = UnitConversion.to_unit(return_value * units.deg, return_unit) 171 return return_value 172 173 # DDS dynamic parameters 174 def freq_slope(self, slope : float) -> None: 175 """ 176 set the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ_SLOPE` in the manual) 177 178 Parameters 179 ---------- 180 slope : float | pint.Quantity 181 the rate of frequency change in Hz/s (positive or negative) or specified unit 182 """ 183 184 slope = UnitConversion.convert(slope, units.Hz/units.s, float, rounding=None) 185 self.dds.set_d(SPC_DDS_CORE0_FREQ_SLOPE + self.index, float(slope)) 186 # aliases 187 frequency_slope = freq_slope 188 189 def get_freq_slope(self, return_unit = None) -> float: 190 """ 191 get the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ_SLOPE` in the manual) 192 193 Parameters 194 ---------- 195 return_unit : pint.Unit = None 196 the unit of the returned frequency slope, by default None 197 198 Returns 199 ------- 200 float 201 the rate of frequency change in Hz/s 202 """ 203 204 return_value = self.dds.card.get_d(SPC_DDS_CORE0_FREQ_SLOPE + self.index) 205 if return_unit is not None: return_value = UnitConversion.to_unit(return_value * units.Hz/units.s, return_unit) 206 return return_value 207 # aliases 208 get_frequency_slope = get_freq_slope 209 210 def amp_slope(self, slope : float) -> None: 211 """ 212 set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP_SLOPE` in the manual) 213 214 Parameters 215 ---------- 216 slope : float | pint.Quantity 217 the rate of amplitude change in 1/s (positive or negative) or specified unit 218 """ 219 220 slope = UnitConversion.convert(slope, 1/units.s, float, rounding=None) 221 self.dds.set_d(SPC_DDS_CORE0_AMP_SLOPE + self.index, float(slope)) 222 # aliases 223 amplitude_slope = amp_slope 224 225 def get_amp_slope(self, return_unit = None) -> float: 226 """ 227 set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP_SLOPE` in the manual) 228 229 Parameters 230 ---------- 231 return_unit : pint.Unit = None 232 the unit of the returned amplitude slope, by default None 233 234 Returns 235 ------- 236 float 237 the rate of amplitude change in 1/s 238 """ 239 240 241 return_value = self.dds.card.get_d(SPC_DDS_CORE0_AMP_SLOPE + self.index) 242 if return_unit is not None: return_value = UnitConversion.to_unit(return_value / units.s, return_unit) 243 return return_value 244 # aliases 245 amplitude_slope = amp_slope
a class for controlling a single DDS core
68 def amp(self, amplitude : float) -> None: 69 """ 70 set the amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP` in the manual) 71 72 Parameters 73 ---------- 74 amplitude : float | pint.Quantity 75 the value between 0 and 1 corresponding to the amplitude 76 """ 77 78 if self.channel is not None: 79 amplitude = self.channel.to_amplitude_fraction(amplitude) 80 elif isinstance(amplitude, units.Quantity) and amplitude.check("[]"): 81 amplitude = UnitConversion.convert(amplitude, units.fraction, float, rounding=None) 82 self.dds.set_d(SPC_DDS_CORE0_AMP + self.index, float(amplitude))
set the amplitude of the sine wave of a specific core (see register SPC_DDS_CORE0_AMP
in the manual)
Parameters
- amplitude (float | pint.Quantity): the value between 0 and 1 corresponding to the amplitude
68 def amp(self, amplitude : float) -> None: 69 """ 70 set the amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP` in the manual) 71 72 Parameters 73 ---------- 74 amplitude : float | pint.Quantity 75 the value between 0 and 1 corresponding to the amplitude 76 """ 77 78 if self.channel is not None: 79 amplitude = self.channel.to_amplitude_fraction(amplitude) 80 elif isinstance(amplitude, units.Quantity) and amplitude.check("[]"): 81 amplitude = UnitConversion.convert(amplitude, units.fraction, float, rounding=None) 82 self.dds.set_d(SPC_DDS_CORE0_AMP + self.index, float(amplitude))
set the amplitude of the sine wave of a specific core (see register SPC_DDS_CORE0_AMP
in the manual)
Parameters
- amplitude (float | pint.Quantity): the value between 0 and 1 corresponding to the amplitude
86 def get_amp(self, return_unit = None) -> float: 87 """ 88 gets the amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP` in the manual) 89 90 Parameters 91 ---------- 92 return_unit : pint.Unit = None 93 the unit of the returned amplitude, by default None 94 95 Returns 96 ------- 97 float 98 the value between 0 and 1 corresponding to the amplitude 99 """ 100 101 return_value = self.dds.card.get_d(SPC_DDS_CORE0_AMP + self.index) 102 if self.channel is not None: 103 return_value = self.channel.from_amplitude_fraction(return_value, return_unit) 104 else: 105 return_value = UnitConversion.to_unit(return_value, return_unit) 106 return return_value
gets the amplitude of the sine wave of a specific core (see register SPC_DDS_CORE0_AMP
in the manual)
Parameters
- return_unit (pint.Unit = None): the unit of the returned amplitude, by default None
Returns
- float: the value between 0 and 1 corresponding to the amplitude
86 def get_amp(self, return_unit = None) -> float: 87 """ 88 gets the amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP` in the manual) 89 90 Parameters 91 ---------- 92 return_unit : pint.Unit = None 93 the unit of the returned amplitude, by default None 94 95 Returns 96 ------- 97 float 98 the value between 0 and 1 corresponding to the amplitude 99 """ 100 101 return_value = self.dds.card.get_d(SPC_DDS_CORE0_AMP + self.index) 102 if self.channel is not None: 103 return_value = self.channel.from_amplitude_fraction(return_value, return_unit) 104 else: 105 return_value = UnitConversion.to_unit(return_value, return_unit) 106 return return_value
gets the amplitude of the sine wave of a specific core (see register SPC_DDS_CORE0_AMP
in the manual)
Parameters
- return_unit (pint.Unit = None): the unit of the returned amplitude, by default None
Returns
- float: the value between 0 and 1 corresponding to the amplitude
110 def freq(self, frequency : float) -> None: 111 """ 112 set the frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ` in the manual) 113 114 Parameters 115 ---------- 116 frequency : float | pint.Quantity 117 the value of the frequency in Hz 118 """ 119 120 frequency = UnitConversion.convert(frequency, units.Hz, float, rounding=None) 121 self.dds.set_d(SPC_DDS_CORE0_FREQ + self.index, float(frequency))
set the frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ
in the manual)
Parameters
- frequency (float | pint.Quantity): the value of the frequency in Hz
110 def freq(self, frequency : float) -> None: 111 """ 112 set the frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ` in the manual) 113 114 Parameters 115 ---------- 116 frequency : float | pint.Quantity 117 the value of the frequency in Hz 118 """ 119 120 frequency = UnitConversion.convert(frequency, units.Hz, float, rounding=None) 121 self.dds.set_d(SPC_DDS_CORE0_FREQ + self.index, float(frequency))
set the frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ
in the manual)
Parameters
- frequency (float | pint.Quantity): the value of the frequency in Hz
125 def get_freq(self, return_unit = None) -> float: 126 """ 127 gets the frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ` in the manual) 128 129 Parameters 130 ---------- 131 return_unit : pint.Unit = None 132 the unit of the returned frequency, by default None 133 134 Returns 135 ------- 136 float | pint.Quantity 137 the value of the frequency in Hz the specific core 138 """ 139 140 return_value = self.dds.card.get_d(SPC_DDS_CORE0_FREQ + self.index) 141 if return_unit is not None: return_value = UnitConversion.to_unit(return_value * units.Hz, return_unit) 142 return return_value
gets the frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ
in the manual)
Parameters
- return_unit (pint.Unit = None): the unit of the returned frequency, by default None
Returns
- float | pint.Quantity: the value of the frequency in Hz the specific core
125 def get_freq(self, return_unit = None) -> float: 126 """ 127 gets the frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ` in the manual) 128 129 Parameters 130 ---------- 131 return_unit : pint.Unit = None 132 the unit of the returned frequency, by default None 133 134 Returns 135 ------- 136 float | pint.Quantity 137 the value of the frequency in Hz the specific core 138 """ 139 140 return_value = self.dds.card.get_d(SPC_DDS_CORE0_FREQ + self.index) 141 if return_unit is not None: return_value = UnitConversion.to_unit(return_value * units.Hz, return_unit) 142 return return_value
gets the frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ
in the manual)
Parameters
- return_unit (pint.Unit = None): the unit of the returned frequency, by default None
Returns
- float | pint.Quantity: the value of the frequency in Hz the specific core
146 def phase(self, phase : float) -> None: 147 """ 148 set the phase of the sine wave of a specific core (see register `SPC_DDS_CORE0_PHASE` in the manual) 149 150 Parameters 151 ---------- 152 phase : float | pint.Quantity 153 the value between 0 and 360 degrees of the phase 154 """ 155 156 phase = UnitConversion.convert(phase, units.deg, float, rounding=None) 157 self.dds.set_d(SPC_DDS_CORE0_PHASE + self.index, float(phase))
set the phase of the sine wave of a specific core (see register SPC_DDS_CORE0_PHASE
in the manual)
Parameters
- phase (float | pint.Quantity): the value between 0 and 360 degrees of the phase
159 def get_phase(self, return_unit = None) -> float: 160 """ 161 gets the phase of the sine wave of a specific core (see register `SPC_DDS_CORE0_PHASE` in the manual) 162 163 Returns 164 ------- 165 float 166 the value between 0 and 360 degrees of the phase 167 """ 168 169 return_value = self.dds.card.get_d(SPC_DDS_CORE0_PHASE + self.index) 170 if return_unit is not None: return_value = UnitConversion.to_unit(return_value * units.deg, return_unit) 171 return return_value
gets the phase of the sine wave of a specific core (see register SPC_DDS_CORE0_PHASE
in the manual)
Returns
- float: the value between 0 and 360 degrees of the phase
174 def freq_slope(self, slope : float) -> None: 175 """ 176 set the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ_SLOPE` in the manual) 177 178 Parameters 179 ---------- 180 slope : float | pint.Quantity 181 the rate of frequency change in Hz/s (positive or negative) or specified unit 182 """ 183 184 slope = UnitConversion.convert(slope, units.Hz/units.s, float, rounding=None) 185 self.dds.set_d(SPC_DDS_CORE0_FREQ_SLOPE + self.index, float(slope))
set the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ_SLOPE
in the manual)
Parameters
- slope (float | pint.Quantity): the rate of frequency change in Hz/s (positive or negative) or specified unit
174 def freq_slope(self, slope : float) -> None: 175 """ 176 set the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ_SLOPE` in the manual) 177 178 Parameters 179 ---------- 180 slope : float | pint.Quantity 181 the rate of frequency change in Hz/s (positive or negative) or specified unit 182 """ 183 184 slope = UnitConversion.convert(slope, units.Hz/units.s, float, rounding=None) 185 self.dds.set_d(SPC_DDS_CORE0_FREQ_SLOPE + self.index, float(slope))
set the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ_SLOPE
in the manual)
Parameters
- slope (float | pint.Quantity): the rate of frequency change in Hz/s (positive or negative) or specified unit
189 def get_freq_slope(self, return_unit = None) -> float: 190 """ 191 get the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ_SLOPE` in the manual) 192 193 Parameters 194 ---------- 195 return_unit : pint.Unit = None 196 the unit of the returned frequency slope, by default None 197 198 Returns 199 ------- 200 float 201 the rate of frequency change in Hz/s 202 """ 203 204 return_value = self.dds.card.get_d(SPC_DDS_CORE0_FREQ_SLOPE + self.index) 205 if return_unit is not None: return_value = UnitConversion.to_unit(return_value * units.Hz/units.s, return_unit) 206 return return_value
get the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ_SLOPE
in the manual)
Parameters
- return_unit (pint.Unit = None): the unit of the returned frequency slope, by default None
Returns
- float: the rate of frequency change in Hz/s
189 def get_freq_slope(self, return_unit = None) -> float: 190 """ 191 get the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ_SLOPE` in the manual) 192 193 Parameters 194 ---------- 195 return_unit : pint.Unit = None 196 the unit of the returned frequency slope, by default None 197 198 Returns 199 ------- 200 float 201 the rate of frequency change in Hz/s 202 """ 203 204 return_value = self.dds.card.get_d(SPC_DDS_CORE0_FREQ_SLOPE + self.index) 205 if return_unit is not None: return_value = UnitConversion.to_unit(return_value * units.Hz/units.s, return_unit) 206 return return_value
get the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ_SLOPE
in the manual)
Parameters
- return_unit (pint.Unit = None): the unit of the returned frequency slope, by default None
Returns
- float: the rate of frequency change in Hz/s
210 def amp_slope(self, slope : float) -> None: 211 """ 212 set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP_SLOPE` in the manual) 213 214 Parameters 215 ---------- 216 slope : float | pint.Quantity 217 the rate of amplitude change in 1/s (positive or negative) or specified unit 218 """ 219 220 slope = UnitConversion.convert(slope, 1/units.s, float, rounding=None) 221 self.dds.set_d(SPC_DDS_CORE0_AMP_SLOPE + self.index, float(slope))
set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register SPC_DDS_CORE0_AMP_SLOPE
in the manual)
Parameters
- slope (float | pint.Quantity): the rate of amplitude change in 1/s (positive or negative) or specified unit
210 def amp_slope(self, slope : float) -> None: 211 """ 212 set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP_SLOPE` in the manual) 213 214 Parameters 215 ---------- 216 slope : float | pint.Quantity 217 the rate of amplitude change in 1/s (positive or negative) or specified unit 218 """ 219 220 slope = UnitConversion.convert(slope, 1/units.s, float, rounding=None) 221 self.dds.set_d(SPC_DDS_CORE0_AMP_SLOPE + self.index, float(slope))
set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register SPC_DDS_CORE0_AMP_SLOPE
in the manual)
Parameters
- slope (float | pint.Quantity): the rate of amplitude change in 1/s (positive or negative) or specified unit
225 def get_amp_slope(self, return_unit = None) -> float: 226 """ 227 set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP_SLOPE` in the manual) 228 229 Parameters 230 ---------- 231 return_unit : pint.Unit = None 232 the unit of the returned amplitude slope, by default None 233 234 Returns 235 ------- 236 float 237 the rate of amplitude change in 1/s 238 """ 239 240 241 return_value = self.dds.card.get_d(SPC_DDS_CORE0_AMP_SLOPE + self.index) 242 if return_unit is not None: return_value = UnitConversion.to_unit(return_value / units.s, return_unit) 243 return return_value
set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register SPC_DDS_CORE0_AMP_SLOPE
in the manual)
Parameters
- return_unit (pint.Unit = None): the unit of the returned amplitude slope, by default None
Returns
- float: the rate of amplitude change in 1/s
13class DDSCommandList(DDS): 14 """Abstraction of the set_ptr and register `SPC_REGISTER_LIST` for command streaming in the DDS functionality""" 15 16 class WRITE_MODE(IntEnum): 17 NO_CHECK = 0 18 EXCEPTION_IF_FULL = 1 19 WAIT_IF_FULL = 2 20 21 mode : int = WRITE_MODE.NO_CHECK 22 23 command_list : ctypes._Pointer = None 24 commands_transfered : int = 0 25 current_index : int = 0 26 27 _dtm : int = SPCM_DDS_DTM_SINGLE 28 _list_size : int = KIBI(16) 29 30 def __init__(self, *args, **kwargs) -> None: 31 super().__init__(*args, **kwargs) 32 33 self.command_list = None 34 self.current_index = 0 35 36 self._dtm = SPCM_DDS_DTM_SINGLE 37 38 self.list_size = self.default_size() 39 40 def data_transfer_mode(self, mode : int) -> None: 41 """ 42 set the data transfer mode of the DDS 43 44 Parameters 45 ---------- 46 mode : int 47 the data transfer mode 48 """ 49 50 self._dtm = mode 51 self.card.set_i(SPC_DDS_DATA_TRANSFER_MODE, mode) 52 self.card.set_i(SPC_DDS_CMD, SPCM_DDS_CMD_WRITE_TO_CARD) 53 self.list_size = self.default_size() 54 55 def default_size(self) -> int: 56 """ 57 automatically determine the size of the commands list 58 """ 59 60 if self._dtm == SPCM_DDS_DTM_SINGLE: 61 return self.card.get_i(SPC_DDS_QUEUE_CMD_MAX) // 2 62 elif self._dtm == SPCM_DDS_DTM_DMA: 63 return KIBI(16) 64 raise SpcmException(text="Data transfer mode not supported.") 65 66 def allocate(self) -> None: 67 """ 68 allocate memory for the commands list 69 """ 70 if self.command_list is not None: 71 del self.command_list 72 elems = (ST_LIST_PARAM * (self._list_size + 1))() # +1 for the write to card command at the end 73 self.command_list = ctypes.cast(elems, ctypes.POINTER(ST_LIST_PARAM)) 74 self.current_index = 0 75 76 def load(self, data : dict, exec_mode : int = SPCM_DDS_CMD_EXEC_AT_TRG, repeat : int = 1) -> None: 77 """ 78 preload the command list with data 79 80 Parameters 81 ---------- 82 data : dict 83 the data to be preloaded 84 mode : int = SPCM_DDS_CMD_EXEC_AT_TRG 85 the mode of execution 86 repeat : int = 1 87 the number of times to repeat the data, if 0 is given the buffer is filled up with the maximal number of blocks that fit in. 88 89 TODO make this possible for multiple different keys 90 """ 91 92 key = list(data.keys())[0] 93 value_list = data[key] # For now only take the first key 94 size = len(value_list) 95 index = 0 96 if repeat == 0: 97 # repeat the data until the block is full 98 repeat = self.list_size // (2*size) 99 for _ in range(repeat): 100 for value in value_list: 101 # Write value 102 self.command_list[index].lReg = key 103 self.command_list[index].lType = TYPE_DOUBLE 104 self.command_list[index].dValue = value 105 index += 1 106 # Write trigger mode 107 self.command_list[index].lReg = SPC_DDS_CMD 108 self.command_list[index].lType = TYPE_INT64 109 self.command_list[index].llValue = exec_mode 110 index += 1 111 self.write_to_card() 112 self.current_index = index 113 114 def write_to_card(self) -> None: 115 """ 116 write the command list to the card 117 """ 118 119 self.command_list[self.current_index].lReg = SPC_DDS_CMD 120 self.command_list[self.current_index].lType = TYPE_INT64 121 self.command_list[self.current_index].llValue = SPCM_DDS_CMD_WRITE_TO_CARD 122 self.current_index += 1 123 124 def write(self) -> None: 125 """ 126 send the currently loaded data to the card 127 """ 128 129 if self.mode == self.WRITE_MODE.EXCEPTION_IF_FULL: 130 if self.avail_user_len() < (self.current_index) * ctypes.sizeof(ST_LIST_PARAM): 131 raise SpcmException(text="Buffer is full") 132 elif self.mode == self.WRITE_MODE.WAIT_IF_FULL: 133 timer = 0 134 while self.avail_user_len() < (self.current_index) * ctypes.sizeof(ST_LIST_PARAM): 135 print("Waiting for buffer to empty {}".format("."*(timer//100)), end="\r") 136 timer = (timer + 1) % 400 137 self.card.set_ptr(SPC_REGISTER_LIST, self.command_list, (self.current_index) * ctypes.sizeof(ST_LIST_PARAM)) 138 139 def avail_user_len(self) -> int: 140 """ 141 get the available space for commands in the hardware queue 142 """ 143 144 if self._dtm == SPCM_DDS_DTM_SINGLE: 145 return self._command_max - self.card.get_i(SPC_DDS_QUEUE_CMD_COUNT) 146 elif self._dtm == SPCM_DDS_DTM_DMA: 147 return self.card.get_i(SPC_DATA_AVAIL_USER_LEN) 148 else: 149 raise SpcmException(text="Data transfer mode not supported.") 150 151 152 @property 153 def list_size(self) -> int: 154 """ 155 get the size of the command list 156 """ 157 158 return self._list_size 159 160 @list_size.setter 161 def list_size(self, size : int) -> None: 162 """ 163 set the size of the command list 164 165 Parameters 166 ---------- 167 size : int 168 the size of the command list 169 """ 170 171 self._list_size = size 172 self.allocate() 173 174 def reset(self) -> None: 175 """ 176 reset the dds firmware 177 """ 178 179 # The reset shouldn't be queued! 180 self.card.set_i(SPC_DDS_CMD, SPCM_DDS_CMD_RESET)
Abstraction of the set_ptr and register SPC_REGISTER_LIST
for command streaming in the DDS functionality
30 def __init__(self, *args, **kwargs) -> None: 31 super().__init__(*args, **kwargs) 32 33 self.command_list = None 34 self.current_index = 0 35 36 self._dtm = SPCM_DDS_DTM_SINGLE 37 38 self.list_size = self.default_size()
Takes a Card object that is used by the functionality
Parameters
- card (Card): a Card object on which the functionality works
152 @property 153 def list_size(self) -> int: 154 """ 155 get the size of the command list 156 """ 157 158 return self._list_size
get the size of the command list
40 def data_transfer_mode(self, mode : int) -> None: 41 """ 42 set the data transfer mode of the DDS 43 44 Parameters 45 ---------- 46 mode : int 47 the data transfer mode 48 """ 49 50 self._dtm = mode 51 self.card.set_i(SPC_DDS_DATA_TRANSFER_MODE, mode) 52 self.card.set_i(SPC_DDS_CMD, SPCM_DDS_CMD_WRITE_TO_CARD) 53 self.list_size = self.default_size()
set the data transfer mode of the DDS
Parameters
- mode (int): the data transfer mode
55 def default_size(self) -> int: 56 """ 57 automatically determine the size of the commands list 58 """ 59 60 if self._dtm == SPCM_DDS_DTM_SINGLE: 61 return self.card.get_i(SPC_DDS_QUEUE_CMD_MAX) // 2 62 elif self._dtm == SPCM_DDS_DTM_DMA: 63 return KIBI(16) 64 raise SpcmException(text="Data transfer mode not supported.")
automatically determine the size of the commands list
66 def allocate(self) -> None: 67 """ 68 allocate memory for the commands list 69 """ 70 if self.command_list is not None: 71 del self.command_list 72 elems = (ST_LIST_PARAM * (self._list_size + 1))() # +1 for the write to card command at the end 73 self.command_list = ctypes.cast(elems, ctypes.POINTER(ST_LIST_PARAM)) 74 self.current_index = 0
allocate memory for the commands list
76 def load(self, data : dict, exec_mode : int = SPCM_DDS_CMD_EXEC_AT_TRG, repeat : int = 1) -> None: 77 """ 78 preload the command list with data 79 80 Parameters 81 ---------- 82 data : dict 83 the data to be preloaded 84 mode : int = SPCM_DDS_CMD_EXEC_AT_TRG 85 the mode of execution 86 repeat : int = 1 87 the number of times to repeat the data, if 0 is given the buffer is filled up with the maximal number of blocks that fit in. 88 89 TODO make this possible for multiple different keys 90 """ 91 92 key = list(data.keys())[0] 93 value_list = data[key] # For now only take the first key 94 size = len(value_list) 95 index = 0 96 if repeat == 0: 97 # repeat the data until the block is full 98 repeat = self.list_size // (2*size) 99 for _ in range(repeat): 100 for value in value_list: 101 # Write value 102 self.command_list[index].lReg = key 103 self.command_list[index].lType = TYPE_DOUBLE 104 self.command_list[index].dValue = value 105 index += 1 106 # Write trigger mode 107 self.command_list[index].lReg = SPC_DDS_CMD 108 self.command_list[index].lType = TYPE_INT64 109 self.command_list[index].llValue = exec_mode 110 index += 1 111 self.write_to_card() 112 self.current_index = index
preload the command list with data
Parameters
- data (dict): the data to be preloaded
- mode (int = SPCM_DDS_CMD_EXEC_AT_TRG): the mode of execution
- repeat (int = 1): the number of times to repeat the data, if 0 is given the buffer is filled up with the maximal number of blocks that fit in.
- TODO make this possible for multiple different keys
114 def write_to_card(self) -> None: 115 """ 116 write the command list to the card 117 """ 118 119 self.command_list[self.current_index].lReg = SPC_DDS_CMD 120 self.command_list[self.current_index].lType = TYPE_INT64 121 self.command_list[self.current_index].llValue = SPCM_DDS_CMD_WRITE_TO_CARD 122 self.current_index += 1
write the command list to the card
124 def write(self) -> None: 125 """ 126 send the currently loaded data to the card 127 """ 128 129 if self.mode == self.WRITE_MODE.EXCEPTION_IF_FULL: 130 if self.avail_user_len() < (self.current_index) * ctypes.sizeof(ST_LIST_PARAM): 131 raise SpcmException(text="Buffer is full") 132 elif self.mode == self.WRITE_MODE.WAIT_IF_FULL: 133 timer = 0 134 while self.avail_user_len() < (self.current_index) * ctypes.sizeof(ST_LIST_PARAM): 135 print("Waiting for buffer to empty {}".format("."*(timer//100)), end="\r") 136 timer = (timer + 1) % 400 137 self.card.set_ptr(SPC_REGISTER_LIST, self.command_list, (self.current_index) * ctypes.sizeof(ST_LIST_PARAM))
send the currently loaded data to the card
139 def avail_user_len(self) -> int: 140 """ 141 get the available space for commands in the hardware queue 142 """ 143 144 if self._dtm == SPCM_DDS_DTM_SINGLE: 145 return self._command_max - self.card.get_i(SPC_DDS_QUEUE_CMD_COUNT) 146 elif self._dtm == SPCM_DDS_DTM_DMA: 147 return self.card.get_i(SPC_DATA_AVAIL_USER_LEN) 148 else: 149 raise SpcmException(text="Data transfer mode not supported.")
get the available space for commands in the hardware queue
An enumeration.
8class DDSCommandQueue(DDSCommandList): 9 """ 10 Abstraction class of the set_ptr and register `SPC_REGISTER_LIST` for command streaming in the DDS functionality. 11 This class is used to write commands to the card in a more efficient way using a queuing mechanism that writes 12 to the card when the queue is filled-up. 13 """ 14 15 def __init__(self, *args, **kwargs) -> None: 16 super().__init__(*args, **kwargs) 17 self.mode = self.WRITE_MODE.NO_CHECK 18 19 def set_i(self, reg : int, value : int) -> None: 20 """ 21 set an integer value to a register 22 23 Parameters 24 ---------- 25 reg : int 26 the register to be changed 27 value : int 28 the value to be set 29 """ 30 31 self.command_list[self.current_index].lReg = reg 32 self.command_list[self.current_index].lType = TYPE_INT64 33 self.command_list[self.current_index].llValue = value 34 self.current_index += 1 35 36 if self.current_index >= self.list_size: 37 self.write_to_card() 38 39 def set_d(self, reg : int, value) -> None: 40 """ 41 set a double value to a register 42 43 Parameters 44 ---------- 45 reg : int 46 the register to be changed 47 value : np._float64 48 the value to be set 49 """ 50 51 self.command_list[self.current_index].lReg = reg 52 self.command_list[self.current_index].lType = TYPE_DOUBLE 53 self.command_list[self.current_index].dValue = value 54 self.current_index += 1 55 56 if self.current_index >= self.list_size: 57 self.write_to_card() 58 59 def write_to_card(self) -> None: 60 """ 61 write the current list of commands to the card 62 """ 63 64 super().write_to_card() 65 self.write() 66 67 def write(self) -> None: 68 """ 69 write the current list of commands to the card and reset the current command index 70 """ 71 72 super().write() 73 self.current_index = 0 74 75 # DDS "static" parameters 76 def amp(self, index : int, amplitude : float) -> None: 77 """ 78 set the amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP` in the manual) 79 80 Parameters 81 ---------- 82 index : int 83 the core index 84 amplitude : float 85 the value between 0 and 1 corresponding to the amplitude 86 """ 87 88 self.set_d(SPC_DDS_CORE0_AMP + index, amplitude) 89 90 def freq(self, index : int, frequency : float) -> None: 91 """ 92 set the frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ` in the manual) 93 94 Parameters 95 ---------- 96 index : int 97 the core index 98 frequency : float 99 the value of the frequency in Hz 100 """ 101 102 self.set_d(SPC_DDS_CORE0_FREQ + index, frequency) 103 104 def phase(self, index : int, phase : float) -> None: 105 """ 106 set the phase of the sine wave of a specific core (see register `SPC_DDS_CORE0_PHASE` in the manual) 107 108 Parameters 109 ---------- 110 core_index : int 111 the index of the core to be changed 112 phase : float 113 the value between 0 and 360 degrees of the phase 114 """ 115 116 self.set_d(SPC_DDS_CORE0_PHASE + index, phase) 117 118 def freq_slope(self, core_index : int, slope : float) -> None: 119 """ 120 set the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ_SLOPE` in the manual) 121 122 Parameters 123 ---------- 124 core_index : int 125 the index of the core to be changed 126 slope : float 127 the rate of frequency change in Hz/s 128 """ 129 130 self.set_d(SPC_DDS_CORE0_FREQ_SLOPE + core_index, slope) 131 132 def amp_slope(self, core_index : int, slope : float) -> None: 133 """ 134 set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP_SLOPE` in the manual) 135 136 Parameters 137 ---------- 138 core_index : int 139 the index of the core to be changed 140 slope : float 141 the rate of amplitude change in 1/s 142 """ 143 144 self.set_d(SPC_DDS_CORE0_AMP_SLOPE + core_index, slope)
Abstraction class of the set_ptr and register SPC_REGISTER_LIST
for command streaming in the DDS functionality.
This class is used to write commands to the card in a more efficient way using a queuing mechanism that writes
to the card when the queue is filled-up.
15 def __init__(self, *args, **kwargs) -> None: 16 super().__init__(*args, **kwargs) 17 self.mode = self.WRITE_MODE.NO_CHECK
Takes a Card object that is used by the functionality
Parameters
- card (Card): a Card object on which the functionality works
19 def set_i(self, reg : int, value : int) -> None: 20 """ 21 set an integer value to a register 22 23 Parameters 24 ---------- 25 reg : int 26 the register to be changed 27 value : int 28 the value to be set 29 """ 30 31 self.command_list[self.current_index].lReg = reg 32 self.command_list[self.current_index].lType = TYPE_INT64 33 self.command_list[self.current_index].llValue = value 34 self.current_index += 1 35 36 if self.current_index >= self.list_size: 37 self.write_to_card()
set an integer value to a register
Parameters
- reg (int): the register to be changed
- value (int): the value to be set
39 def set_d(self, reg : int, value) -> None: 40 """ 41 set a double value to a register 42 43 Parameters 44 ---------- 45 reg : int 46 the register to be changed 47 value : np._float64 48 the value to be set 49 """ 50 51 self.command_list[self.current_index].lReg = reg 52 self.command_list[self.current_index].lType = TYPE_DOUBLE 53 self.command_list[self.current_index].dValue = value 54 self.current_index += 1 55 56 if self.current_index >= self.list_size: 57 self.write_to_card()
set a double value to a register
Parameters
- reg (int): the register to be changed
- value (np._float64): the value to be set
59 def write_to_card(self) -> None: 60 """ 61 write the current list of commands to the card 62 """ 63 64 super().write_to_card() 65 self.write()
write the current list of commands to the card
67 def write(self) -> None: 68 """ 69 write the current list of commands to the card and reset the current command index 70 """ 71 72 super().write() 73 self.current_index = 0
write the current list of commands to the card and reset the current command index
76 def amp(self, index : int, amplitude : float) -> None: 77 """ 78 set the amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP` in the manual) 79 80 Parameters 81 ---------- 82 index : int 83 the core index 84 amplitude : float 85 the value between 0 and 1 corresponding to the amplitude 86 """ 87 88 self.set_d(SPC_DDS_CORE0_AMP + index, amplitude)
set the amplitude of the sine wave of a specific core (see register SPC_DDS_CORE0_AMP
in the manual)
Parameters
- index (int): the core index
- amplitude (float): the value between 0 and 1 corresponding to the amplitude
90 def freq(self, index : int, frequency : float) -> None: 91 """ 92 set the frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ` in the manual) 93 94 Parameters 95 ---------- 96 index : int 97 the core index 98 frequency : float 99 the value of the frequency in Hz 100 """ 101 102 self.set_d(SPC_DDS_CORE0_FREQ + index, frequency)
set the frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ
in the manual)
Parameters
- index (int): the core index
- frequency (float): the value of the frequency in Hz
104 def phase(self, index : int, phase : float) -> None: 105 """ 106 set the phase of the sine wave of a specific core (see register `SPC_DDS_CORE0_PHASE` in the manual) 107 108 Parameters 109 ---------- 110 core_index : int 111 the index of the core to be changed 112 phase : float 113 the value between 0 and 360 degrees of the phase 114 """ 115 116 self.set_d(SPC_DDS_CORE0_PHASE + index, phase)
set the phase of the sine wave of a specific core (see register SPC_DDS_CORE0_PHASE
in the manual)
Parameters
- core_index (int): the index of the core to be changed
- phase (float): the value between 0 and 360 degrees of the phase
118 def freq_slope(self, core_index : int, slope : float) -> None: 119 """ 120 set the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register `SPC_DDS_CORE0_FREQ_SLOPE` in the manual) 121 122 Parameters 123 ---------- 124 core_index : int 125 the index of the core to be changed 126 slope : float 127 the rate of frequency change in Hz/s 128 """ 129 130 self.set_d(SPC_DDS_CORE0_FREQ_SLOPE + core_index, slope)
set the frequency slope of the linearly changing frequency of the sine wave of a specific core (see register SPC_DDS_CORE0_FREQ_SLOPE
in the manual)
Parameters
- core_index (int): the index of the core to be changed
- slope (float): the rate of frequency change in Hz/s
132 def amp_slope(self, core_index : int, slope : float) -> None: 133 """ 134 set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register `SPC_DDS_CORE0_AMP_SLOPE` in the manual) 135 136 Parameters 137 ---------- 138 core_index : int 139 the index of the core to be changed 140 slope : float 141 the rate of amplitude change in 1/s 142 """ 143 144 self.set_d(SPC_DDS_CORE0_AMP_SLOPE + core_index, slope)
set the amplitude slope of the linearly changing amplitude of the sine wave of a specific core (see register SPC_DDS_CORE0_AMP_SLOPE
in the manual)
Parameters
- core_index (int): the index of the core to be changed
- slope (float): the rate of amplitude change in 1/s
16class PulseGenerator: 17 """ 18 a class to implement a single pulse generator 19 20 Parameters 21 ---------- 22 card : Card 23 the card object that is used by the functionality 24 pg_index : int 25 the index of the used pulse generator 26 """ 27 28 card : Card 29 pg_index : int 30 """The index of the pulse generator""" 31 32 _reg_distance : int = 100 33 34 def __init__(self, card : Card, pg_index : int, *args, **kwargs) -> None: 35 """ 36 The constructor of the PulseGenerator class 37 38 Parameters 39 ---------- 40 card : Card 41 the card object that is used by the functionality 42 pg_index : int 43 the index of the used pulse generator 44 """ 45 46 self.card = card 47 self.pg_index = pg_index 48 49 def __str__(self) -> str: 50 """ 51 String representation of the PulseGenerator class 52 53 Returns 54 ------- 55 str 56 String representation of the PulseGenerator class 57 """ 58 59 return f"PulseGenerator(card={self.card}, pg_index={self.pg_index})" 60 61 __repr__ = __str__ 62 63 # The trigger behavior of the pulse generator 64 def mode(self, mode : int = None) -> int: 65 """ 66 Set the trigger mode of the pulse generator (see register 'SPC_XIO_PULSEGEN0_MODE' in chapter `Pulse Generator` in the manual) 67 68 Parameters 69 ---------- 70 mode : int 71 The trigger mode 72 73 Returns 74 ------- 75 int 76 The trigger mode 77 """ 78 79 if mode is not None: 80 self.card.set_i(SPC_XIO_PULSEGEN0_MODE + self._reg_distance*self.pg_index, mode) 81 return self.card.get_i(SPC_XIO_PULSEGEN0_MODE + self._reg_distance*self.pg_index) 82 83 # The duration of a single period 84 def period_length(self, length : int = None) -> int: 85 """ 86 Set the period length of the pulse generator (see register 'SPC_XIO_PULSEGEN0_LEN' in chapter `Pulse Generator` in the manual) 87 88 Parameters 89 ---------- 90 length : int 91 The period length in clock cycles 92 93 Returns 94 ------- 95 int 96 The period length in clock cycles 97 """ 98 99 if length is not None: 100 self.card.set_i(SPC_XIO_PULSEGEN0_LEN + self._reg_distance*self.pg_index, length) 101 return self.card.get_i(SPC_XIO_PULSEGEN0_LEN + self._reg_distance*self.pg_index) 102 103 def avail_length_min(self) -> int: 104 """ 105 Returns the minimum length (period) of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILLEN_MIN' in chapter `Pulse Generator` in the manual) 106 107 Returns 108 ------- 109 int 110 The available minimal length in clock cycles 111 """ 112 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILLEN_MIN) 113 114 def avail_length_max(self) -> int: 115 """ 116 Returns the maximum length (period) of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILLEN_MAX' in chapter `Pulse Generator` in the manual) 117 118 Returns 119 ------- 120 int 121 The available maximal length in clock cycles 122 """ 123 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILLEN_MAX) 124 125 def avail_length_step(self) -> int: 126 """ 127 Returns the step size of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILLEN_STEP' in chapter `Pulse Generator` in the manual) 128 129 Returns 130 ------- 131 int 132 The available step size in clock cycles 133 """ 134 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILLEN_STEP) 135 136 # The time that the signal is high during one period 137 def high_length(self, length : int = None) -> int: 138 """ 139 Set the high length of the pulse generator (see register 'SPC_XIO_PULSEGEN0_HIGH' in chapter `Pulse Generator` in the manual) 140 141 Parameters 142 ---------- 143 pg_index : int 144 The index of the pulse generator 145 length : int 146 The high length in clock cycles 147 148 Returns 149 ------- 150 int 151 The high length in clock cycles 152 """ 153 154 if length is not None: 155 self.card.set_i(SPC_XIO_PULSEGEN0_HIGH + self._reg_distance*self.pg_index, length) 156 return self.card.get_i(SPC_XIO_PULSEGEN0_HIGH + self._reg_distance*self.pg_index) 157 158 def avail_high_min(self) -> int: 159 """ 160 Returns the minimum high length of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILHIGH_MIN' in chapter `Pulse Generator` in the manual) 161 162 Returns 163 ------- 164 int 165 The available minimal high length in clock cycles 166 """ 167 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILHIGH_MIN) 168 169 def avail_high_max(self) -> int: 170 """ 171 Returns the maximum high length of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILHIGH_MAX' in chapter `Pulse Generator` in the manual) 172 173 Returns 174 ------- 175 int 176 The available maximal high length in clock cycles 177 """ 178 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILHIGH_MAX) 179 180 def avail_high_step(self) -> int: 181 """ 182 Returns the step size of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILHIGH_STEP' in chapter `Pulse Generator` in the manual) 183 184 Returns 185 ------- 186 int 187 The available step size in clock cycles 188 """ 189 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILHIGH_STEP) 190 191 # The number of times that a single period is repeated 192 def num_loops(self, loops : int = None) -> int: 193 """ 194 Set the number of loops of a single period on the pulse generator (see register 'SPC_XIO_PULSEGEN0_LOOPS' in chapter `Pulse Generator` in the manual) 195 196 Parameters 197 ---------- 198 loops : int 199 The number of loops 200 201 Returns 202 ------- 203 int 204 The number of loops 205 """ 206 207 if loops is not None: 208 self.card.set_i(SPC_XIO_PULSEGEN0_LOOPS + self._reg_distance*self.pg_index, loops) 209 return self.card.get_i(SPC_XIO_PULSEGEN0_LOOPS + self._reg_distance*self.pg_index) 210 211 def avail_loops_min(self) -> int: 212 """ 213 Returns the minimum number of loops of the pulse generator’s output pulses. (see register 'SPC_XIO_PULSEGEN_AVAILLOOPS_MIN' in chapter `Pulse Generator` in the manual) 214 215 Returns 216 ------- 217 int 218 The available minimal number of loops 219 """ 220 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILLOOPS_MIN) 221 222 def avail_loops_max(self) -> int: 223 """ 224 Returns the maximum number of loops of the pulse generator’s output pulses. (see register 'SPC_XIO_PULSEGEN_AVAILLOOPS_MAX' in chapter `Pulse Generator` in the manual) 225 226 Returns 227 ------- 228 int 229 The available maximal number of loops 230 """ 231 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILLOOPS_MAX) 232 233 def avail_loops_step(self) -> int: 234 """ 235 Returns the step size of the pulse generator’s output pulses. (see register 'SPC_XIO_PULSEGEN_AVAILLOOPS_STEP' in chapter `Pulse Generator` in the manual) 236 237 Returns 238 ------- 239 int 240 Returns the step size when defining the repetition of pulse generator’s output. 241 """ 242 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILLOOPS_STEP) 243 244 # The delay between the start of the pulse generator and the first pulse 245 def delay(self, delay : int = None) -> int: 246 """ 247 Set the delay of the pulse generator (see register 'SPC_XIO_PULSEGEN0_DELAY' in chapter `Pulse Generator` in the manual) 248 249 Parameters 250 ---------- 251 delay : int 252 The delay in clock cycles 253 254 Returns 255 ------- 256 int 257 The delay in clock cycles 258 """ 259 260 if delay is not None: 261 self.card.set_i(SPC_XIO_PULSEGEN0_DELAY + self._reg_distance*self.pg_index, delay) 262 return self.card.get_i(SPC_XIO_PULSEGEN0_DELAY + self._reg_distance*self.pg_index) 263 264 def avail_delay_min(self) -> int: 265 """ 266 Returns the minimum delay of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILDELAY_MIN' in chapter `Pulse Generator` in the manual) 267 268 Returns 269 ------- 270 int 271 The available minimal delay in clock cycles 272 """ 273 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILDELAY_MIN) 274 275 def avail_delay_max(self) -> int: 276 """ 277 Returns the maximum delay of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILDELAY_MAX' in chapter `Pulse Generator` in the manual) 278 279 Returns 280 ------- 281 int 282 The available maximal delay in clock cycles 283 """ 284 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILDELAY_MAX) 285 286 def avail_delay_step(self) -> int: 287 """ 288 Returns the step size of the delay of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILDELAY_STEP' in chapter `Pulse Generator` in the manual) 289 290 Returns 291 ------- 292 int 293 The available step size of the delay in clock cycles 294 """ 295 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILDELAY_STEP) 296 297 # Trigger muxes 298 def mux1(self, mux : int = None) -> int: 299 """ 300 Set the trigger mux 1 of the pulse generator (see register 'SPC_XIO_PULSEGEN0_MUX1_SRC' in chapter `Pulse Generator` in the manual) 301 302 Parameters 303 ---------- 304 mux : int 305 The trigger mux 1 306 307 Returns 308 ------- 309 int 310 The trigger mux 1 311 """ 312 313 if mux is not None: 314 self.card.set_i(SPC_XIO_PULSEGEN0_MUX1_SRC + self._reg_distance*self.pg_index, mux) 315 return self.card.get_i(SPC_XIO_PULSEGEN0_MUX1_SRC + self._reg_distance*self.pg_index) 316 317 def mux2(self, mux : int = None) -> int: 318 """ 319 Set the trigger mux 2 of the pulse generator (see register 'SPC_XIO_PULSEGEN0_MUX2_SRC' in chapter `Pulse Generator` in the manual) 320 321 Parameters 322 ---------- 323 mux : int 324 The trigger mux 2 325 326 Returns 327 ------- 328 int 329 The trigger mux 2 330 """ 331 332 if mux is not None: 333 self.card.set_i(SPC_XIO_PULSEGEN0_MUX2_SRC + self._reg_distance*self.pg_index, mux) 334 return self.card.get_i(SPC_XIO_PULSEGEN0_MUX2_SRC + self._reg_distance*self.pg_index) 335 336 def config(self, config : int = None) -> int: 337 """ 338 Set the configuration of the pulse generator (see register 'SPC_XIO_PULSEGEN0_CONFIG' in chapter `Pulse Generator` in the manual) 339 340 Parameters 341 ---------- 342 config : int 343 The configuration of the pulse generator 344 345 Returns 346 ------- 347 int 348 The configuration of the pulse generator 349 """ 350 351 if config is not None: 352 self.card.set_i(SPC_XIO_PULSEGEN0_CONFIG + self._reg_distance*self.pg_index, config) 353 return self.card.get_i(SPC_XIO_PULSEGEN0_CONFIG + self._reg_distance*self.pg_index) 354 355 def _get_clock(self, return_unit : pint.Unit = None) -> int: 356 """ 357 Get the clock rate of the pulse generator (see register 'SPC_XIO_PULSEGEN_CLOCK' in chapter `Pulse Generator` in the manual) 358 359 Returns 360 ------- 361 int 362 The clock rate in Hz 363 """ 364 365 return_value = self.card.get_i(SPC_XIO_PULSEGEN_CLOCK) 366 return_value = UnitConversion.to_unit(return_value * units.Hz, return_unit) 367 return return_value 368 369 # Higher abtraction functions 370 371 def pulse_period(self, period : pint.Quantity = None, return_unit : pint.Unit = units.s) -> pint.Quantity: 372 """ 373 Set the period length of the pulse generator signal in a time unit 374 375 Parameters 376 ---------- 377 period : pint.Quantity 378 The period length in seconds 379 380 Returns 381 ------- 382 pint.Quantity 383 The period length in seconds 384 """ 385 386 if period is not None: 387 if isinstance(period, pint.Quantity): 388 period = int((period * self._get_clock(units.Hz)).to_base_units().magnitude) 389 else: 390 raise ValueError("The period must be a pint.Quantity") 391 self.period_length(period) 392 return_value = self.period_length() 393 return_value = UnitConversion.to_unit((return_value / self._get_clock(units.Hz)), return_unit) 394 return return_value 395 396 def repetition_rate(self, rate : pint.Quantity = None, return_unit : pint.Unit = units.Hz) -> pint.Quantity: 397 """ 398 Set the repetition rate of the pulse generator signal in a frequency unit 399 400 Parameters 401 ---------- 402 rate : pint.Quantity 403 The repetition rate in Hz 404 405 Returns 406 ------- 407 pint.Quantity 408 The repetition rate in Hz 409 """ 410 411 if rate is not None: 412 if isinstance(rate, pint.Quantity): 413 period = int(np.rint((self._get_clock(units.Hz) / rate).to_base_units().magnitude)) 414 else: 415 raise ValueError("The rate must be a pint.Quantity") 416 self.period_length(period) 417 return_value = self.period_length() 418 return_value = UnitConversion.to_unit((self._get_clock(units.Hz) / return_value), return_unit) 419 return return_value 420 421 def pulse_length(self, length : pint.Quantity, return_unit : pint.Unit = units.s) -> pint.Quantity: 422 """ 423 Set the pulse length of the pulse generator signal in a time unit 424 425 Parameters 426 ---------- 427 length : pint.Quantity 428 The pulse length in seconds 429 430 Returns 431 ------- 432 pint.Quantity 433 The pulse length in seconds 434 """ 435 436 if length is not None: 437 if isinstance(length, pint.Quantity): 438 length = int((length * self._get_clock(units.Hz)).to_base_units().magnitude) 439 else: 440 raise ValueError("The length must be a pint.Quantity") 441 self.high_length(length) 442 return_value = self.high_length() 443 return_value = UnitConversion.to_unit((return_value / self._get_clock(units.Hz)), return_unit) 444 return return_value 445 446 def duty_cycle(self, duty_cycle : pint.Quantity = None, return_unit : pint.Unit = units.percent) -> pint.Quantity: 447 """ 448 Set the duty cycle of the pulse generator signal in a percentage unit 449 450 Parameters 451 ---------- 452 duty_cycle : pint.Quantity 453 The duty cycle in percentage 454 455 Returns 456 ------- 457 pint.Quantity 458 The duty cycle in percentage 459 """ 460 461 period_length = self.period_length() 462 if duty_cycle is not None: 463 if isinstance(duty_cycle, pint.Quantity): 464 high_length = int(np.rint(period_length * duty_cycle)) 465 else: 466 raise ValueError("The cycle must be a pint.Quantity") 467 self.high_length(high_length) 468 return_value = self.high_length() 469 return_value = UnitConversion.to_unit((return_value / period_length) * 100 * units.percent, return_unit) 470 return return_value 471 472 def start_delay(self, delay : pint.Unit = None, return_unit : pint.Unit = units.s) -> pint.Unit: 473 """ 474 Set the start delay of the pulse generator signal in a time unit 475 476 Parameters 477 ---------- 478 delay : pint.Unit 479 The start delay in a pint quantity with time unit 480 481 Returns 482 ------- 483 pint.Unit 484 The start delay in a pint quantity with time unit 485 """ 486 487 if delay is not None: 488 if isinstance(delay, pint.Quantity): 489 delay = int((delay * self._get_clock(units.Hz)).to_base_units().magnitude) 490 else: 491 raise ValueError("The delay must be a pint.Quantity") 492 return_value = self.delay(delay) 493 return_value = UnitConversion.to_unit((return_value / self._get_clock(units.Hz)), return_unit) 494 return return_value 495 496 repetitions = num_loops 497 498 def start_condition_state_signal(self, signal : int = 0, invert : bool = False) -> int: 499 """ 500 Set the start condition state signal of the pulse generator (see register 'SPC_XIO_PULSEGEN0_MUX1' in chapter `Pulse Generator` in the manual) 501 502 NOTE 503 ---- 504 The Pulse Generator is started when the combined signal of both start condition signals are true and a rising edge 505 is detected. The invert parameter inverts the start condition state signal. 506 507 Parameters 508 ---------- 509 signal : int 510 The start condition state signal 511 invert : bool 512 Invert the start condition state signal 513 514 Returns 515 ------- 516 int 517 The start condition state signal 518 """ 519 520 return_signal = self.mux1(signal) 521 return_invert = self.config() 522 if invert: 523 return_invert |= SPCM_PULSEGEN_CONFIG_MUX1_INVERT 524 else: 525 return_invert &= ~SPCM_PULSEGEN_CONFIG_MUX1_INVERT 526 return_invert = self.config(return_invert) 527 return return_signal, ((return_invert & SPCM_PULSEGEN_CONFIG_MUX1_INVERT) != 0) 528 529 def start_condition_trigger_signal(self, signal : int = 0, invert : bool = False) -> int: 530 """ 531 Set the start condition trigger signal of the pulse generator (see register 'SPC_XIO_PULSEGEN0_MUX2' in chapter `Pulse Generator` in the manual) 532 533 NOTE 534 ---- 535 The Pulse Generator is started when the combined signal of both start condition signals are true and a rising edge 536 is detected. The invert parameter inverts the start condition state signal. 537 538 Parameters 539 ---------- 540 signal : int 541 The start condition trigger signal 542 invert : bool 543 Invert the start condition trigger signal 544 545 Returns 546 ------- 547 int 548 The start condition trigger signal 549 """ 550 551 return_signal = self.mux2(signal) 552 return_invert = self.config() 553 if invert: 554 return_invert |= SPCM_PULSEGEN_CONFIG_MUX2_INVERT 555 else: 556 return_invert &= ~SPCM_PULSEGEN_CONFIG_MUX2_INVERT 557 return_invert = self.config(return_invert) 558 return return_signal, ((return_invert & SPCM_PULSEGEN_CONFIG_MUX2_INVERT) != 0) 559 560 def invert_start_condition(self, invert : bool = None) -> bool: 561 """ 562 Invert the start condition of the pulse generator 563 564 Parameters 565 ---------- 566 invert : bool 567 Invert the start condition 568 569 Returns 570 ------- 571 bool 572 The start condition inversion 573 """ 574 575 if invert is not None: 576 return_invert = self.config() 577 if invert: 578 return_invert |= SPCM_PULSEGEN_CONFIG_INVERT 579 else: 580 return_invert &= ~SPCM_PULSEGEN_CONFIG_INVERT 581 self.config(return_invert) 582 return ((self.config() & SPCM_PULSEGEN_CONFIG_INVERT) != 0)
a class to implement a single pulse generator
Parameters
- card (Card): the card object that is used by the functionality
- pg_index (int): the index of the used pulse generator
34 def __init__(self, card : Card, pg_index : int, *args, **kwargs) -> None: 35 """ 36 The constructor of the PulseGenerator class 37 38 Parameters 39 ---------- 40 card : Card 41 the card object that is used by the functionality 42 pg_index : int 43 the index of the used pulse generator 44 """ 45 46 self.card = card 47 self.pg_index = pg_index
The constructor of the PulseGenerator class
Parameters
- card (Card): the card object that is used by the functionality
- pg_index (int): the index of the used pulse generator
64 def mode(self, mode : int = None) -> int: 65 """ 66 Set the trigger mode of the pulse generator (see register 'SPC_XIO_PULSEGEN0_MODE' in chapter `Pulse Generator` in the manual) 67 68 Parameters 69 ---------- 70 mode : int 71 The trigger mode 72 73 Returns 74 ------- 75 int 76 The trigger mode 77 """ 78 79 if mode is not None: 80 self.card.set_i(SPC_XIO_PULSEGEN0_MODE + self._reg_distance*self.pg_index, mode) 81 return self.card.get_i(SPC_XIO_PULSEGEN0_MODE + self._reg_distance*self.pg_index)
Set the trigger mode of the pulse generator (see register 'SPC_XIO_PULSEGEN0_MODE' in chapter Pulse Generator
in the manual)
Parameters
- mode (int): The trigger mode
Returns
- int: The trigger mode
84 def period_length(self, length : int = None) -> int: 85 """ 86 Set the period length of the pulse generator (see register 'SPC_XIO_PULSEGEN0_LEN' in chapter `Pulse Generator` in the manual) 87 88 Parameters 89 ---------- 90 length : int 91 The period length in clock cycles 92 93 Returns 94 ------- 95 int 96 The period length in clock cycles 97 """ 98 99 if length is not None: 100 self.card.set_i(SPC_XIO_PULSEGEN0_LEN + self._reg_distance*self.pg_index, length) 101 return self.card.get_i(SPC_XIO_PULSEGEN0_LEN + self._reg_distance*self.pg_index)
Set the period length of the pulse generator (see register 'SPC_XIO_PULSEGEN0_LEN' in chapter Pulse Generator
in the manual)
Parameters
- length (int): The period length in clock cycles
Returns
- int: The period length in clock cycles
103 def avail_length_min(self) -> int: 104 """ 105 Returns the minimum length (period) of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILLEN_MIN' in chapter `Pulse Generator` in the manual) 106 107 Returns 108 ------- 109 int 110 The available minimal length in clock cycles 111 """ 112 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILLEN_MIN)
Returns the minimum length (period) of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILLEN_MIN' in chapter Pulse Generator
in the manual)
Returns
- int: The available minimal length in clock cycles
114 def avail_length_max(self) -> int: 115 """ 116 Returns the maximum length (period) of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILLEN_MAX' in chapter `Pulse Generator` in the manual) 117 118 Returns 119 ------- 120 int 121 The available maximal length in clock cycles 122 """ 123 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILLEN_MAX)
Returns the maximum length (period) of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILLEN_MAX' in chapter Pulse Generator
in the manual)
Returns
- int: The available maximal length in clock cycles
125 def avail_length_step(self) -> int: 126 """ 127 Returns the step size of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILLEN_STEP' in chapter `Pulse Generator` in the manual) 128 129 Returns 130 ------- 131 int 132 The available step size in clock cycles 133 """ 134 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILLEN_STEP)
Returns the step size of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILLEN_STEP' in chapter Pulse Generator
in the manual)
Returns
- int: The available step size in clock cycles
137 def high_length(self, length : int = None) -> int: 138 """ 139 Set the high length of the pulse generator (see register 'SPC_XIO_PULSEGEN0_HIGH' in chapter `Pulse Generator` in the manual) 140 141 Parameters 142 ---------- 143 pg_index : int 144 The index of the pulse generator 145 length : int 146 The high length in clock cycles 147 148 Returns 149 ------- 150 int 151 The high length in clock cycles 152 """ 153 154 if length is not None: 155 self.card.set_i(SPC_XIO_PULSEGEN0_HIGH + self._reg_distance*self.pg_index, length) 156 return self.card.get_i(SPC_XIO_PULSEGEN0_HIGH + self._reg_distance*self.pg_index)
Set the high length of the pulse generator (see register 'SPC_XIO_PULSEGEN0_HIGH' in chapter Pulse Generator
in the manual)
Parameters
- pg_index (int): The index of the pulse generator
- length (int): The high length in clock cycles
Returns
- int: The high length in clock cycles
158 def avail_high_min(self) -> int: 159 """ 160 Returns the minimum high length of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILHIGH_MIN' in chapter `Pulse Generator` in the manual) 161 162 Returns 163 ------- 164 int 165 The available minimal high length in clock cycles 166 """ 167 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILHIGH_MIN)
Returns the minimum high length of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILHIGH_MIN' in chapter Pulse Generator
in the manual)
Returns
- int: The available minimal high length in clock cycles
169 def avail_high_max(self) -> int: 170 """ 171 Returns the maximum high length of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILHIGH_MAX' in chapter `Pulse Generator` in the manual) 172 173 Returns 174 ------- 175 int 176 The available maximal high length in clock cycles 177 """ 178 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILHIGH_MAX)
Returns the maximum high length of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILHIGH_MAX' in chapter Pulse Generator
in the manual)
Returns
- int: The available maximal high length in clock cycles
180 def avail_high_step(self) -> int: 181 """ 182 Returns the step size of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILHIGH_STEP' in chapter `Pulse Generator` in the manual) 183 184 Returns 185 ------- 186 int 187 The available step size in clock cycles 188 """ 189 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILHIGH_STEP)
Returns the step size of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILHIGH_STEP' in chapter Pulse Generator
in the manual)
Returns
- int: The available step size in clock cycles
192 def num_loops(self, loops : int = None) -> int: 193 """ 194 Set the number of loops of a single period on the pulse generator (see register 'SPC_XIO_PULSEGEN0_LOOPS' in chapter `Pulse Generator` in the manual) 195 196 Parameters 197 ---------- 198 loops : int 199 The number of loops 200 201 Returns 202 ------- 203 int 204 The number of loops 205 """ 206 207 if loops is not None: 208 self.card.set_i(SPC_XIO_PULSEGEN0_LOOPS + self._reg_distance*self.pg_index, loops) 209 return self.card.get_i(SPC_XIO_PULSEGEN0_LOOPS + self._reg_distance*self.pg_index)
Set the number of loops of a single period on the pulse generator (see register 'SPC_XIO_PULSEGEN0_LOOPS' in chapter Pulse Generator
in the manual)
Parameters
- loops (int): The number of loops
Returns
- int: The number of loops
211 def avail_loops_min(self) -> int: 212 """ 213 Returns the minimum number of loops of the pulse generator’s output pulses. (see register 'SPC_XIO_PULSEGEN_AVAILLOOPS_MIN' in chapter `Pulse Generator` in the manual) 214 215 Returns 216 ------- 217 int 218 The available minimal number of loops 219 """ 220 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILLOOPS_MIN)
Returns the minimum number of loops of the pulse generator’s output pulses. (see register 'SPC_XIO_PULSEGEN_AVAILLOOPS_MIN' in chapter Pulse Generator
in the manual)
Returns
- int: The available minimal number of loops
222 def avail_loops_max(self) -> int: 223 """ 224 Returns the maximum number of loops of the pulse generator’s output pulses. (see register 'SPC_XIO_PULSEGEN_AVAILLOOPS_MAX' in chapter `Pulse Generator` in the manual) 225 226 Returns 227 ------- 228 int 229 The available maximal number of loops 230 """ 231 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILLOOPS_MAX)
Returns the maximum number of loops of the pulse generator’s output pulses. (see register 'SPC_XIO_PULSEGEN_AVAILLOOPS_MAX' in chapter Pulse Generator
in the manual)
Returns
- int: The available maximal number of loops
233 def avail_loops_step(self) -> int: 234 """ 235 Returns the step size of the pulse generator’s output pulses. (see register 'SPC_XIO_PULSEGEN_AVAILLOOPS_STEP' in chapter `Pulse Generator` in the manual) 236 237 Returns 238 ------- 239 int 240 Returns the step size when defining the repetition of pulse generator’s output. 241 """ 242 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILLOOPS_STEP)
Returns the step size of the pulse generator’s output pulses. (see register 'SPC_XIO_PULSEGEN_AVAILLOOPS_STEP' in chapter Pulse Generator
in the manual)
Returns
- int: Returns the step size when defining the repetition of pulse generator’s output.
245 def delay(self, delay : int = None) -> int: 246 """ 247 Set the delay of the pulse generator (see register 'SPC_XIO_PULSEGEN0_DELAY' in chapter `Pulse Generator` in the manual) 248 249 Parameters 250 ---------- 251 delay : int 252 The delay in clock cycles 253 254 Returns 255 ------- 256 int 257 The delay in clock cycles 258 """ 259 260 if delay is not None: 261 self.card.set_i(SPC_XIO_PULSEGEN0_DELAY + self._reg_distance*self.pg_index, delay) 262 return self.card.get_i(SPC_XIO_PULSEGEN0_DELAY + self._reg_distance*self.pg_index)
Set the delay of the pulse generator (see register 'SPC_XIO_PULSEGEN0_DELAY' in chapter Pulse Generator
in the manual)
Parameters
- delay (int): The delay in clock cycles
Returns
- int: The delay in clock cycles
264 def avail_delay_min(self) -> int: 265 """ 266 Returns the minimum delay of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILDELAY_MIN' in chapter `Pulse Generator` in the manual) 267 268 Returns 269 ------- 270 int 271 The available minimal delay in clock cycles 272 """ 273 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILDELAY_MIN)
Returns the minimum delay of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILDELAY_MIN' in chapter Pulse Generator
in the manual)
Returns
- int: The available minimal delay in clock cycles
275 def avail_delay_max(self) -> int: 276 """ 277 Returns the maximum delay of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILDELAY_MAX' in chapter `Pulse Generator` in the manual) 278 279 Returns 280 ------- 281 int 282 The available maximal delay in clock cycles 283 """ 284 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILDELAY_MAX)
Returns the maximum delay of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILDELAY_MAX' in chapter Pulse Generator
in the manual)
Returns
- int: The available maximal delay in clock cycles
286 def avail_delay_step(self) -> int: 287 """ 288 Returns the step size of the delay of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILDELAY_STEP' in chapter `Pulse Generator` in the manual) 289 290 Returns 291 ------- 292 int 293 The available step size of the delay in clock cycles 294 """ 295 return self.card.get_i(SPC_XIO_PULSEGEN_AVAILDELAY_STEP)
Returns the step size of the delay of the pulse generator’s output pulses in clock cycles. (see register 'SPC_XIO_PULSEGEN_AVAILDELAY_STEP' in chapter Pulse Generator
in the manual)
Returns
- int: The available step size of the delay in clock cycles
298 def mux1(self, mux : int = None) -> int: 299 """ 300 Set the trigger mux 1 of the pulse generator (see register 'SPC_XIO_PULSEGEN0_MUX1_SRC' in chapter `Pulse Generator` in the manual) 301 302 Parameters 303 ---------- 304 mux : int 305 The trigger mux 1 306 307 Returns 308 ------- 309 int 310 The trigger mux 1 311 """ 312 313 if mux is not None: 314 self.card.set_i(SPC_XIO_PULSEGEN0_MUX1_SRC + self._reg_distance*self.pg_index, mux) 315 return self.card.get_i(SPC_XIO_PULSEGEN0_MUX1_SRC + self._reg_distance*self.pg_index)
Set the trigger mux 1 of the pulse generator (see register 'SPC_XIO_PULSEGEN0_MUX1_SRC' in chapter Pulse Generator
in the manual)
Parameters
- mux (int): The trigger mux 1
Returns
- int: The trigger mux 1
317 def mux2(self, mux : int = None) -> int: 318 """ 319 Set the trigger mux 2 of the pulse generator (see register 'SPC_XIO_PULSEGEN0_MUX2_SRC' in chapter `Pulse Generator` in the manual) 320 321 Parameters 322 ---------- 323 mux : int 324 The trigger mux 2 325 326 Returns 327 ------- 328 int 329 The trigger mux 2 330 """ 331 332 if mux is not None: 333 self.card.set_i(SPC_XIO_PULSEGEN0_MUX2_SRC + self._reg_distance*self.pg_index, mux) 334 return self.card.get_i(SPC_XIO_PULSEGEN0_MUX2_SRC + self._reg_distance*self.pg_index)
Set the trigger mux 2 of the pulse generator (see register 'SPC_XIO_PULSEGEN0_MUX2_SRC' in chapter Pulse Generator
in the manual)
Parameters
- mux (int): The trigger mux 2
Returns
- int: The trigger mux 2
336 def config(self, config : int = None) -> int: 337 """ 338 Set the configuration of the pulse generator (see register 'SPC_XIO_PULSEGEN0_CONFIG' in chapter `Pulse Generator` in the manual) 339 340 Parameters 341 ---------- 342 config : int 343 The configuration of the pulse generator 344 345 Returns 346 ------- 347 int 348 The configuration of the pulse generator 349 """ 350 351 if config is not None: 352 self.card.set_i(SPC_XIO_PULSEGEN0_CONFIG + self._reg_distance*self.pg_index, config) 353 return self.card.get_i(SPC_XIO_PULSEGEN0_CONFIG + self._reg_distance*self.pg_index)
Set the configuration of the pulse generator (see register 'SPC_XIO_PULSEGEN0_CONFIG' in chapter Pulse Generator
in the manual)
Parameters
- config (int): The configuration of the pulse generator
Returns
- int: The configuration of the pulse generator
371 def pulse_period(self, period : pint.Quantity = None, return_unit : pint.Unit = units.s) -> pint.Quantity: 372 """ 373 Set the period length of the pulse generator signal in a time unit 374 375 Parameters 376 ---------- 377 period : pint.Quantity 378 The period length in seconds 379 380 Returns 381 ------- 382 pint.Quantity 383 The period length in seconds 384 """ 385 386 if period is not None: 387 if isinstance(period, pint.Quantity): 388 period = int((period * self._get_clock(units.Hz)).to_base_units().magnitude) 389 else: 390 raise ValueError("The period must be a pint.Quantity") 391 self.period_length(period) 392 return_value = self.period_length() 393 return_value = UnitConversion.to_unit((return_value / self._get_clock(units.Hz)), return_unit) 394 return return_value
Set the period length of the pulse generator signal in a time unit
Parameters
- period (pint.Quantity): The period length in seconds
Returns
- pint.Quantity: The period length in seconds
396 def repetition_rate(self, rate : pint.Quantity = None, return_unit : pint.Unit = units.Hz) -> pint.Quantity: 397 """ 398 Set the repetition rate of the pulse generator signal in a frequency unit 399 400 Parameters 401 ---------- 402 rate : pint.Quantity 403 The repetition rate in Hz 404 405 Returns 406 ------- 407 pint.Quantity 408 The repetition rate in Hz 409 """ 410 411 if rate is not None: 412 if isinstance(rate, pint.Quantity): 413 period = int(np.rint((self._get_clock(units.Hz) / rate).to_base_units().magnitude)) 414 else: 415 raise ValueError("The rate must be a pint.Quantity") 416 self.period_length(period) 417 return_value = self.period_length() 418 return_value = UnitConversion.to_unit((self._get_clock(units.Hz) / return_value), return_unit) 419 return return_value
Set the repetition rate of the pulse generator signal in a frequency unit
Parameters
- rate (pint.Quantity): The repetition rate in Hz
Returns
- pint.Quantity: The repetition rate in Hz
421 def pulse_length(self, length : pint.Quantity, return_unit : pint.Unit = units.s) -> pint.Quantity: 422 """ 423 Set the pulse length of the pulse generator signal in a time unit 424 425 Parameters 426 ---------- 427 length : pint.Quantity 428 The pulse length in seconds 429 430 Returns 431 ------- 432 pint.Quantity 433 The pulse length in seconds 434 """ 435 436 if length is not None: 437 if isinstance(length, pint.Quantity): 438 length = int((length * self._get_clock(units.Hz)).to_base_units().magnitude) 439 else: 440 raise ValueError("The length must be a pint.Quantity") 441 self.high_length(length) 442 return_value = self.high_length() 443 return_value = UnitConversion.to_unit((return_value / self._get_clock(units.Hz)), return_unit) 444 return return_value
Set the pulse length of the pulse generator signal in a time unit
Parameters
- length (pint.Quantity): The pulse length in seconds
Returns
- pint.Quantity: The pulse length in seconds
446 def duty_cycle(self, duty_cycle : pint.Quantity = None, return_unit : pint.Unit = units.percent) -> pint.Quantity: 447 """ 448 Set the duty cycle of the pulse generator signal in a percentage unit 449 450 Parameters 451 ---------- 452 duty_cycle : pint.Quantity 453 The duty cycle in percentage 454 455 Returns 456 ------- 457 pint.Quantity 458 The duty cycle in percentage 459 """ 460 461 period_length = self.period_length() 462 if duty_cycle is not None: 463 if isinstance(duty_cycle, pint.Quantity): 464 high_length = int(np.rint(period_length * duty_cycle)) 465 else: 466 raise ValueError("The cycle must be a pint.Quantity") 467 self.high_length(high_length) 468 return_value = self.high_length() 469 return_value = UnitConversion.to_unit((return_value / period_length) * 100 * units.percent, return_unit) 470 return return_value
Set the duty cycle of the pulse generator signal in a percentage unit
Parameters
- duty_cycle (pint.Quantity): The duty cycle in percentage
Returns
- pint.Quantity: The duty cycle in percentage
472 def start_delay(self, delay : pint.Unit = None, return_unit : pint.Unit = units.s) -> pint.Unit: 473 """ 474 Set the start delay of the pulse generator signal in a time unit 475 476 Parameters 477 ---------- 478 delay : pint.Unit 479 The start delay in a pint quantity with time unit 480 481 Returns 482 ------- 483 pint.Unit 484 The start delay in a pint quantity with time unit 485 """ 486 487 if delay is not None: 488 if isinstance(delay, pint.Quantity): 489 delay = int((delay * self._get_clock(units.Hz)).to_base_units().magnitude) 490 else: 491 raise ValueError("The delay must be a pint.Quantity") 492 return_value = self.delay(delay) 493 return_value = UnitConversion.to_unit((return_value / self._get_clock(units.Hz)), return_unit) 494 return return_value
Set the start delay of the pulse generator signal in a time unit
Parameters
- delay (pint.Unit): The start delay in a pint quantity with time unit
Returns
- pint.Unit: The start delay in a pint quantity with time unit
192 def num_loops(self, loops : int = None) -> int: 193 """ 194 Set the number of loops of a single period on the pulse generator (see register 'SPC_XIO_PULSEGEN0_LOOPS' in chapter `Pulse Generator` in the manual) 195 196 Parameters 197 ---------- 198 loops : int 199 The number of loops 200 201 Returns 202 ------- 203 int 204 The number of loops 205 """ 206 207 if loops is not None: 208 self.card.set_i(SPC_XIO_PULSEGEN0_LOOPS + self._reg_distance*self.pg_index, loops) 209 return self.card.get_i(SPC_XIO_PULSEGEN0_LOOPS + self._reg_distance*self.pg_index)
Set the number of loops of a single period on the pulse generator (see register 'SPC_XIO_PULSEGEN0_LOOPS' in chapter Pulse Generator
in the manual)
Parameters
- loops (int): The number of loops
Returns
- int: The number of loops
498 def start_condition_state_signal(self, signal : int = 0, invert : bool = False) -> int: 499 """ 500 Set the start condition state signal of the pulse generator (see register 'SPC_XIO_PULSEGEN0_MUX1' in chapter `Pulse Generator` in the manual) 501 502 NOTE 503 ---- 504 The Pulse Generator is started when the combined signal of both start condition signals are true and a rising edge 505 is detected. The invert parameter inverts the start condition state signal. 506 507 Parameters 508 ---------- 509 signal : int 510 The start condition state signal 511 invert : bool 512 Invert the start condition state signal 513 514 Returns 515 ------- 516 int 517 The start condition state signal 518 """ 519 520 return_signal = self.mux1(signal) 521 return_invert = self.config() 522 if invert: 523 return_invert |= SPCM_PULSEGEN_CONFIG_MUX1_INVERT 524 else: 525 return_invert &= ~SPCM_PULSEGEN_CONFIG_MUX1_INVERT 526 return_invert = self.config(return_invert) 527 return return_signal, ((return_invert & SPCM_PULSEGEN_CONFIG_MUX1_INVERT) != 0)
Set the start condition state signal of the pulse generator (see register 'SPC_XIO_PULSEGEN0_MUX1' in chapter Pulse Generator
in the manual)
NOTE
The Pulse Generator is started when the combined signal of both start condition signals are true and a rising edge is detected. The invert parameter inverts the start condition state signal.
Parameters
- signal (int): The start condition state signal
- invert (bool): Invert the start condition state signal
Returns
- int: The start condition state signal
529 def start_condition_trigger_signal(self, signal : int = 0, invert : bool = False) -> int: 530 """ 531 Set the start condition trigger signal of the pulse generator (see register 'SPC_XIO_PULSEGEN0_MUX2' in chapter `Pulse Generator` in the manual) 532 533 NOTE 534 ---- 535 The Pulse Generator is started when the combined signal of both start condition signals are true and a rising edge 536 is detected. The invert parameter inverts the start condition state signal. 537 538 Parameters 539 ---------- 540 signal : int 541 The start condition trigger signal 542 invert : bool 543 Invert the start condition trigger signal 544 545 Returns 546 ------- 547 int 548 The start condition trigger signal 549 """ 550 551 return_signal = self.mux2(signal) 552 return_invert = self.config() 553 if invert: 554 return_invert |= SPCM_PULSEGEN_CONFIG_MUX2_INVERT 555 else: 556 return_invert &= ~SPCM_PULSEGEN_CONFIG_MUX2_INVERT 557 return_invert = self.config(return_invert) 558 return return_signal, ((return_invert & SPCM_PULSEGEN_CONFIG_MUX2_INVERT) != 0)
Set the start condition trigger signal of the pulse generator (see register 'SPC_XIO_PULSEGEN0_MUX2' in chapter Pulse Generator
in the manual)
NOTE
The Pulse Generator is started when the combined signal of both start condition signals are true and a rising edge is detected. The invert parameter inverts the start condition state signal.
Parameters
- signal (int): The start condition trigger signal
- invert (bool): Invert the start condition trigger signal
Returns
- int: The start condition trigger signal
560 def invert_start_condition(self, invert : bool = None) -> bool: 561 """ 562 Invert the start condition of the pulse generator 563 564 Parameters 565 ---------- 566 invert : bool 567 Invert the start condition 568 569 Returns 570 ------- 571 bool 572 The start condition inversion 573 """ 574 575 if invert is not None: 576 return_invert = self.config() 577 if invert: 578 return_invert |= SPCM_PULSEGEN_CONFIG_INVERT 579 else: 580 return_invert &= ~SPCM_PULSEGEN_CONFIG_INVERT 581 self.config(return_invert) 582 return ((self.config() & SPCM_PULSEGEN_CONFIG_INVERT) != 0)
Invert the start condition of the pulse generator
Parameters
- invert (bool): Invert the start condition
Returns
- bool: The start condition inversion
584class PulseGenerators(CardFunctionality): 585 """ 586 a higher-level abstraction of the CardFunctionality class to implement Pulse generator functionality 587 588 Parameters 589 ---------- 590 generators : list[PulseGenerator] 591 a list of pulse generators 592 num_generators : int 593 the number of pulse generators on the card 594 """ 595 596 generators : list[PulseGenerator] 597 num_generators = 4 598 599 def __init__(self, card : Card, enable : int = 0, *args, **kwargs) -> None: 600 """ 601 The constructor of the PulseGenerators class 602 603 Parameters 604 ---------- 605 card : Card 606 the card object that is used by the functionality 607 enable : int or bool 608 Enable or disable (all) the different pulse generators, by default all are turned off 609 610 Raises 611 ------ 612 SpcmException 613 """ 614 615 super().__init__(card, *args, **kwargs) 616 # Check for the pulse generator option on the card 617 features = self.card.get_i(SPC_PCIEXTFEATURES) 618 if features & SPCM_FEAT_EXTFW_PULSEGEN: 619 self.card._print(f"Pulse generator option available") 620 else: 621 raise SpcmException(text="This card doesn't have the pulse generator functionality installed. Please contact sales@spec.de to get more information about this functionality.") 622 623 self.load() 624 self.enable(enable) 625 626 def load(self) -> None: 627 """Load the pulse generators""" 628 self.generators = [PulseGenerator(self.card, i) for i in range(self.num_generators)] 629 630 # TODO in the next driver release there will be a register to get the number of pulse generators 631 def get_num_generators(self) -> int: 632 """ 633 Get the number of pulse generators on the card 634 635 Returns 636 ------- 637 int 638 The number of pulse generators 639 """ 640 641 return self.num_generators 642 643 def __str__(self) -> str: 644 """ 645 String representation of the PulseGenerators class 646 647 Returns 648 ------- 649 str 650 String representation of the PulseGenerators class 651 """ 652 653 return f"PulseGenerators(card={self.card})" 654 655 __repr__ = __str__ 656 657 658 def __iter__(self) -> "PulseGenerators": 659 """Define this class as an iterator""" 660 return self 661 662 def __getitem__(self, index : int) -> PulseGenerator: 663 """ 664 Get the pulse generator at the given index 665 666 Parameters 667 ---------- 668 index : int 669 The index of the pulse generator 670 671 Returns 672 ------- 673 PulseGenerator 674 The pulse generator at the given index 675 """ 676 677 return self.generators[index] 678 679 _generator_iterator_index = -1 680 def __next__(self) -> PulseGenerator: 681 """ 682 This method is called when the next element is requested from the iterator 683 684 Returns 685 ------- 686 PulseGenerator 687 the next available pulse generator 688 689 Raises 690 ------ 691 StopIteration 692 """ 693 self._generator_iterator_index += 1 694 if self._generator_iterator_index >= len(self.channels): 695 self._generator_iterator_index = -1 696 raise StopIteration 697 return self.generators[self._generator_iterator_index] 698 699 def __len__(self) -> int: 700 """Returns the number of available pulse generators""" 701 return len(self.generators) 702 703 def write_setup(self) -> None: 704 """Write the setup to the card""" 705 self.card.write_setup() 706 707 # The pulse generator can be enabled or disabled 708 def enable(self, enable : int = None) -> int: 709 """ 710 Enable or disable (all) the pulse generators (see register 'SPC_XIO_PULSEGEN_ENABLE' in chapter `Pulse Generator` in the manual) 711 712 Parameters 713 ---------- 714 enable : int or bool 715 Enable or disable (all) the different pulse generators, by default all are turned off 716 717 Returns 718 ------- 719 int 720 The enable state of the pulse generators 721 """ 722 723 724 if isinstance(enable, bool): 725 enable = (1 << self.num_generators) - 1 if enable else 0 726 if enable is not None: 727 self.card.set_i(SPC_XIO_PULSEGEN_ENABLE, enable) 728 return self.card.get_i(SPC_XIO_PULSEGEN_ENABLE) 729 730 def cmd(self, cmd : int) -> None: 731 """ 732 Execute a command on the pulse generator (see register 'SPC_XIO_PULSEGEN_COMMAND' in chapter `Pulse Generator` in the manual) 733 734 Parameters 735 ---------- 736 cmd : int 737 The command to execute 738 """ 739 self.card.set_i(SPC_XIO_PULSEGEN_COMMAND, cmd) 740 741 def force(self) -> None: 742 """ 743 Generate a single rising edge, that is common for all pulse generator engines. This allows to start/trigger the output 744 of all enabled pulse generators synchronously by issuing a software command. (see register 'SPC_XIO_PULSEGEN_COMMAND' in chapter `Pulse Generator` in the manual) 745 """ 746 self.cmd(SPCM_PULSEGEN_CMD_FORCE) 747 748 def write_setup(self) -> None: 749 """Write the setup of the pulse generator to the card""" 750 self.card.write_setup() 751 752 # The clock rate in Hz of the pulse generator 753 def get_clock(self) -> int: 754 """ 755 Get the clock rate of the pulse generator (see register 'SPC_XIO_PULSEGEN_CLOCK' in chapter `Pulse Generator` in the manual) 756 757 Returns 758 ------- 759 int 760 The clock rate in Hz 761 """ 762 return self.card.get_i(SPC_XIO_PULSEGEN_CLOCK)
a higher-level abstraction of the CardFunctionality class to implement Pulse generator functionality
Parameters
- generators (list[PulseGenerator]): a list of pulse generators
- num_generators (int): the number of pulse generators on the card
599 def __init__(self, card : Card, enable : int = 0, *args, **kwargs) -> None: 600 """ 601 The constructor of the PulseGenerators class 602 603 Parameters 604 ---------- 605 card : Card 606 the card object that is used by the functionality 607 enable : int or bool 608 Enable or disable (all) the different pulse generators, by default all are turned off 609 610 Raises 611 ------ 612 SpcmException 613 """ 614 615 super().__init__(card, *args, **kwargs) 616 # Check for the pulse generator option on the card 617 features = self.card.get_i(SPC_PCIEXTFEATURES) 618 if features & SPCM_FEAT_EXTFW_PULSEGEN: 619 self.card._print(f"Pulse generator option available") 620 else: 621 raise SpcmException(text="This card doesn't have the pulse generator functionality installed. Please contact sales@spec.de to get more information about this functionality.") 622 623 self.load() 624 self.enable(enable)
The constructor of the PulseGenerators class
Parameters
- card (Card): the card object that is used by the functionality
- enable (int or bool): Enable or disable (all) the different pulse generators, by default all are turned off
Raises
- SpcmException
626 def load(self) -> None: 627 """Load the pulse generators""" 628 self.generators = [PulseGenerator(self.card, i) for i in range(self.num_generators)]
Load the pulse generators
631 def get_num_generators(self) -> int: 632 """ 633 Get the number of pulse generators on the card 634 635 Returns 636 ------- 637 int 638 The number of pulse generators 639 """ 640 641 return self.num_generators
Get the number of pulse generators on the card
Returns
- int: The number of pulse generators
748 def write_setup(self) -> None: 749 """Write the setup of the pulse generator to the card""" 750 self.card.write_setup()
Write the setup of the pulse generator to the card
708 def enable(self, enable : int = None) -> int: 709 """ 710 Enable or disable (all) the pulse generators (see register 'SPC_XIO_PULSEGEN_ENABLE' in chapter `Pulse Generator` in the manual) 711 712 Parameters 713 ---------- 714 enable : int or bool 715 Enable or disable (all) the different pulse generators, by default all are turned off 716 717 Returns 718 ------- 719 int 720 The enable state of the pulse generators 721 """ 722 723 724 if isinstance(enable, bool): 725 enable = (1 << self.num_generators) - 1 if enable else 0 726 if enable is not None: 727 self.card.set_i(SPC_XIO_PULSEGEN_ENABLE, enable) 728 return self.card.get_i(SPC_XIO_PULSEGEN_ENABLE)
Enable or disable (all) the pulse generators (see register 'SPC_XIO_PULSEGEN_ENABLE' in chapter Pulse Generator
in the manual)
Parameters
- enable (int or bool): Enable or disable (all) the different pulse generators, by default all are turned off
Returns
- int: The enable state of the pulse generators
730 def cmd(self, cmd : int) -> None: 731 """ 732 Execute a command on the pulse generator (see register 'SPC_XIO_PULSEGEN_COMMAND' in chapter `Pulse Generator` in the manual) 733 734 Parameters 735 ---------- 736 cmd : int 737 The command to execute 738 """ 739 self.card.set_i(SPC_XIO_PULSEGEN_COMMAND, cmd)
Execute a command on the pulse generator (see register 'SPC_XIO_PULSEGEN_COMMAND' in chapter Pulse Generator
in the manual)
Parameters
- cmd (int): The command to execute
741 def force(self) -> None: 742 """ 743 Generate a single rising edge, that is common for all pulse generator engines. This allows to start/trigger the output 744 of all enabled pulse generators synchronously by issuing a software command. (see register 'SPC_XIO_PULSEGEN_COMMAND' in chapter `Pulse Generator` in the manual) 745 """ 746 self.cmd(SPCM_PULSEGEN_CMD_FORCE)
Generate a single rising edge, that is common for all pulse generator engines. This allows to start/trigger the output
of all enabled pulse generators synchronously by issuing a software command. (see register 'SPC_XIO_PULSEGEN_COMMAND' in chapter Pulse Generator
in the manual)
753 def get_clock(self) -> int: 754 """ 755 Get the clock rate of the pulse generator (see register 'SPC_XIO_PULSEGEN_CLOCK' in chapter `Pulse Generator` in the manual) 756 757 Returns 758 ------- 759 int 760 The clock rate in Hz 761 """ 762 return self.card.get_i(SPC_XIO_PULSEGEN_CLOCK)
Get the clock rate of the pulse generator (see register 'SPC_XIO_PULSEGEN_CLOCK' in chapter Pulse Generator
in the manual)
Returns
- int: The clock rate in Hz
16class Multi(DataTransfer): 17 """a high-level class to control Multiple Recording and Replay functionality on Spectrum Instrumentation cards 18 19 For more information about what setups are available, please have a look at the user manual 20 for your specific card. 21 22 """ 23 24 # Private 25 _segment_size : int 26 _num_segments : int 27 28 def __init__(self, card, *args, **kwargs) -> None: 29 super().__init__(card, *args, **kwargs) 30 self.pre_trigger = None 31 self._segment_size = 0 32 self._num_segments = 0 33 34 def segment_samples(self, segment_size : int = None) -> None: 35 """ 36 Sets the memory size in samples per channel. The memory size setting must be set before transferring 37 data to the card. (see register `SPC_MEMSIZE` in the manual) 38 39 Parameters 40 ---------- 41 segment_size : int | pint.Quantity 42 the size of a single segment in memory in Samples 43 """ 44 45 if segment_size is not None: 46 segment_size = UnitConversion.convert(segment_size, units.S, int) 47 self.card.set_i(SPC_SEGMENTSIZE, segment_size) 48 segment_size = self.card.get_i(SPC_SEGMENTSIZE) 49 self._segment_size = segment_size 50 51 def post_trigger(self, num_samples : int = None) -> int: 52 """ 53 Set the number of post trigger samples (see register `SPC_POSTTRIGGER` in the manual) 54 55 Parameters 56 ---------- 57 num_samples : int | pint.Quantity 58 the number of post trigger samples 59 60 Returns 61 ------- 62 int 63 the number of post trigger samples 64 """ 65 66 post_trigger = super().post_trigger(num_samples) 67 self._pre_trigger = self._segment_size - post_trigger 68 return post_trigger 69 70 def allocate_buffer(self, segment_samples : int, num_segments : int = None) -> None: 71 """ 72 Memory allocation for the buffer that is used for communicating with the card 73 74 Parameters 75 ---------- 76 segment_samples : int | pint.Quantity 77 use the number of samples and get the number of active channels and bytes per samples directly from the card 78 num_segments : int = None 79 the number of segments that are used for the multiple recording mode 80 """ 81 82 segment_samples = UnitConversion.convert(segment_samples, units.S, int) 83 num_segments = UnitConversion.convert(num_segments, units.S, int) 84 self.segment_samples(segment_samples) 85 if num_segments is None: 86 self._num_segments = self._memory_size // segment_samples 87 else: 88 self._num_segments = num_segments 89 super().allocate_buffer(segment_samples * self._num_segments) 90 num_channels = self.card.active_channels() 91 if self.bits_per_sample > 1 and not self._12bit_mode: 92 self.buffer = self.buffer.reshape((self._num_segments, segment_samples, num_channels), order='C') # index definition: [segment, sample, channel] ! 93 94 def time_data(self, total_num_samples : int = None) -> npt.NDArray: 95 """ 96 Get the time array for the data buffer 97 98 Returns 99 ------- 100 numpy array 101 the time array 102 """ 103 104 sample_rate = self._sample_rate() 105 if total_num_samples is None: 106 total_num_samples = self._buffer_samples // self._num_segments 107 total_num_samples = UnitConversion.convert(total_num_samples, units.Sa, int) 108 return (np.arange(total_num_samples) - self._pre_trigger) / sample_rate 109 110 def unpack_12bit_buffer(self) -> npt.NDArray[np.int_]: 111 """ 112 Unpacks the 12-bit packed data to 16-bit data 113 114 Returns 115 ------- 116 npt.NDArray[np.int_] 117 the unpacked data 118 """ 119 buffer_12bit = super().unpack_12bit_buffer() 120 return buffer_12bit.reshape((self._num_segments, self.num_channels, self._segment_size), order='C') 121 122 123 def __next__(self) -> npt.ArrayLike: 124 """ 125 This method is called when the next element is requested from the iterator 126 127 Returns 128 ------- 129 npt.ArrayLike 130 the next data block 131 132 Raises 133 ------ 134 StopIteration 135 """ 136 137 timeout_counter = 0 138 # notify the card that data is available or read, but only after the first block 139 if self._current_samples >= self._notify_samples: 140 self.avail_card_len(self._notify_samples) 141 while True: 142 try: 143 self.wait_dma() 144 except SpcmTimeout: 145 self.card._print("... Timeout ({})".format(timeout_counter), end='\r') 146 timeout_counter += 1 147 if timeout_counter > self._max_timeout: 148 raise StopIteration 149 else: 150 user_len = self.avail_user_len() 151 user_pos = self.avail_user_pos() 152 153 current_segment = user_pos // self._segment_size 154 current_pos_in_segment = user_pos % self._segment_size 155 final_segment = ((user_pos+self._notify_samples) // self._segment_size) 156 final_pos_in_segment = (user_pos+self._notify_samples) % self._segment_size 157 158 self.card._print("NumSamples = {}, CurrentSegment = {}, CurrentPos = {}, FinalSegment = {}, FinalPos = {}, UserLen = {}".format(self._notify_samples, current_segment, current_pos_in_segment, final_segment, final_pos_in_segment, user_len)) 159 160 self._current_samples += self._notify_samples 161 if self._to_transfer_samples != 0 and self._to_transfer_samples < self._current_samples: 162 raise StopIteration 163 164 fill_size = self.fill_size_promille() 165 self.card._print("Fill size: {}% Pos:{:08x} Len:{:08x} Total:{:.2f} MiS / {:.2f} MiS".format(fill_size/10, user_pos, user_len, self._current_samples / MEBI(1), self._to_transfer_samples / MEBI(1)), end='\r') 166 167 return self.buffer[current_segment:final_segment, :, :]
a high-level class to control Multiple Recording and Replay functionality on Spectrum Instrumentation cards
For more information about what setups are available, please have a look at the user manual for your specific card.
28 def __init__(self, card, *args, **kwargs) -> None: 29 super().__init__(card, *args, **kwargs) 30 self.pre_trigger = None 31 self._segment_size = 0 32 self._num_segments = 0
Initialize the DataTransfer object with a card object and additional arguments
Parameters
- card (Card): the card object that is used for the data transfer
- *args (list): list of additional arguments
- **kwargs (dict): dictionary of additional keyword arguments
332 def pre_trigger(self, num_samples : int = None) -> int: 333 """ 334 Set the number of pre trigger samples (see register `SPC_PRETRIGGER` in the manual) 335 336 Parameters 337 ---------- 338 num_samples : int | pint.Quantity 339 the number of pre trigger samples 340 341 Returns 342 ------- 343 int 344 the number of pre trigger samples 345 """ 346 347 if num_samples is not None: 348 num_samples = UnitConversion.convert(num_samples, units.Sa, int) 349 self.card.set_i(SPC_PRETRIGGER, num_samples) 350 self._pre_trigger = self.card.get_i(SPC_PRETRIGGER) 351 return self._pre_trigger
Set the number of pre trigger samples (see register SPC_PRETRIGGER
in the manual)
Parameters
- num_samples (int | pint.Quantity): the number of pre trigger samples
Returns
- int: the number of pre trigger samples
34 def segment_samples(self, segment_size : int = None) -> None: 35 """ 36 Sets the memory size in samples per channel. The memory size setting must be set before transferring 37 data to the card. (see register `SPC_MEMSIZE` in the manual) 38 39 Parameters 40 ---------- 41 segment_size : int | pint.Quantity 42 the size of a single segment in memory in Samples 43 """ 44 45 if segment_size is not None: 46 segment_size = UnitConversion.convert(segment_size, units.S, int) 47 self.card.set_i(SPC_SEGMENTSIZE, segment_size) 48 segment_size = self.card.get_i(SPC_SEGMENTSIZE) 49 self._segment_size = segment_size
Sets the memory size in samples per channel. The memory size setting must be set before transferring
data to the card. (see register SPC_MEMSIZE
in the manual)
Parameters
- segment_size (int | pint.Quantity): the size of a single segment in memory in Samples
51 def post_trigger(self, num_samples : int = None) -> int: 52 """ 53 Set the number of post trigger samples (see register `SPC_POSTTRIGGER` in the manual) 54 55 Parameters 56 ---------- 57 num_samples : int | pint.Quantity 58 the number of post trigger samples 59 60 Returns 61 ------- 62 int 63 the number of post trigger samples 64 """ 65 66 post_trigger = super().post_trigger(num_samples) 67 self._pre_trigger = self._segment_size - post_trigger 68 return post_trigger
Set the number of post trigger samples (see register SPC_POSTTRIGGER
in the manual)
Parameters
- num_samples (int | pint.Quantity): the number of post trigger samples
Returns
- int: the number of post trigger samples
70 def allocate_buffer(self, segment_samples : int, num_segments : int = None) -> None: 71 """ 72 Memory allocation for the buffer that is used for communicating with the card 73 74 Parameters 75 ---------- 76 segment_samples : int | pint.Quantity 77 use the number of samples and get the number of active channels and bytes per samples directly from the card 78 num_segments : int = None 79 the number of segments that are used for the multiple recording mode 80 """ 81 82 segment_samples = UnitConversion.convert(segment_samples, units.S, int) 83 num_segments = UnitConversion.convert(num_segments, units.S, int) 84 self.segment_samples(segment_samples) 85 if num_segments is None: 86 self._num_segments = self._memory_size // segment_samples 87 else: 88 self._num_segments = num_segments 89 super().allocate_buffer(segment_samples * self._num_segments) 90 num_channels = self.card.active_channels() 91 if self.bits_per_sample > 1 and not self._12bit_mode: 92 self.buffer = self.buffer.reshape((self._num_segments, segment_samples, num_channels), order='C') # index definition: [segment, sample, channel] !
Memory allocation for the buffer that is used for communicating with the card
Parameters
- segment_samples (int | pint.Quantity): use the number of samples and get the number of active channels and bytes per samples directly from the card
- num_segments (int = None): the number of segments that are used for the multiple recording mode
94 def time_data(self, total_num_samples : int = None) -> npt.NDArray: 95 """ 96 Get the time array for the data buffer 97 98 Returns 99 ------- 100 numpy array 101 the time array 102 """ 103 104 sample_rate = self._sample_rate() 105 if total_num_samples is None: 106 total_num_samples = self._buffer_samples // self._num_segments 107 total_num_samples = UnitConversion.convert(total_num_samples, units.Sa, int) 108 return (np.arange(total_num_samples) - self._pre_trigger) / sample_rate
Get the time array for the data buffer
Returns
- numpy array: the time array
110 def unpack_12bit_buffer(self) -> npt.NDArray[np.int_]: 111 """ 112 Unpacks the 12-bit packed data to 16-bit data 113 114 Returns 115 ------- 116 npt.NDArray[np.int_] 117 the unpacked data 118 """ 119 buffer_12bit = super().unpack_12bit_buffer() 120 return buffer_12bit.reshape((self._num_segments, self.num_channels, self._segment_size), order='C')
Unpacks the 12-bit packed data to 16-bit data
Returns
- npt.NDArray[np.int_]: the unpacked data
12class TimeStamp(DataTransfer): 13 """a class to control Spectrum Instrumentation cards with the timestamp functionality 14 15 For more information about what setups are available, please have a look at the user manual 16 for your specific card 17 18 Parameters 19 ---------- 20 ts_mode : int 21 transfer_mode : int 22 bits_per_ts : int = 0 23 bytes_per_ts : int = 16 24 """ 25 ts_mode : int 26 transfer_mode : int 27 28 bits_per_ts : int = 0 29 bytes_per_ts : int = 16 30 31 _notify_timestamps : int = 0 32 _to_transfer_timestamps : int = 0 33 34 def __init__(self, card, *args, **kwargs) -> None: 35 """ 36 Initialize the TimeStamp object with a card object 37 38 Parameters 39 ---------- 40 card : Card 41 a card object that is used to control the card 42 """ 43 44 super().__init__(card, *args, **kwargs) 45 self.buffer_type = SPCM_BUF_TIMESTAMP 46 self.bits_per_ts = self.bytes_per_ts * 8 47 48 def cmd(self, *args) -> None: 49 """ 50 Execute spcm timestamp commands (see register 'SPC_TIMESTAMP_CMD' in chapter `Timestamp` in the manual) 51 52 Parameters 53 ---------- 54 *args : int 55 The different timestamp command flags to be executed. 56 """ 57 58 cmd = 0 59 for arg in args: 60 cmd |= arg 61 self.card.set_i(SPC_TIMESTAMP_CMD, cmd) 62 63 def reset(self) -> None: 64 """Reset the timestamp counter (see command 'SPC_TS_RESET' in chapter `Timestamp` in the manual)""" 65 self.cmd(SPC_TS_RESET) 66 67 def mode(self, mode : int, *args : list[int]) -> None: 68 """ 69 Set the mode of the timestamp counter (see register 'SPC_TIMESTAMP_CMD' in chapter `Timestamp` in the manual) 70 71 Parameters 72 ---------- 73 mode : int 74 The mode of the timestamp counter 75 *args : list[int] 76 List of additional commands send with setting the mode 77 """ 78 self.ts_mode = mode 79 self.cmd(self.ts_mode, *args) 80 81 def notify_timestamps(self, notify_timestamps : int) -> None: 82 """ 83 Set the number of timestamps to notify the user about 84 85 Parameters 86 ---------- 87 notify_timestamps : int 88 the number of timestamps to notify the user about 89 """ 90 self._notify_timestamps = notify_timestamps 91 92 def allocate_buffer(self, num_timestamps : int) -> None: 93 """ 94 Allocate the buffer for the timestamp data transfer 95 96 Parameters 97 ---------- 98 num_timestamps : int 99 The number of timestamps to be allocated 100 """ 101 102 self.buffer_size = num_timestamps * self.bytes_per_ts 103 104 dwMask = self._buffer_alignment - 1 105 106 sample_type = np.int64 107 item_size = sample_type(0).itemsize 108 # allocate a buffer (numpy array) for DMA transfer: a little bigger one to have room for address alignment 109 databuffer_unaligned = np.empty(((self._buffer_alignment + self.buffer_size) // item_size, ), dtype = sample_type) # half byte count at int16 sample (// = integer division) 110 # two numpy-arrays may share the same memory: skip the begin up to the alignment boundary (ArrayVariable[SKIP_VALUE:]) 111 # Address of data-memory from numpy-array: ArrayVariable.__array_interface__['data'][0] 112 start_pos_samples = ((self._buffer_alignment - (databuffer_unaligned.__array_interface__['data'][0] & dwMask)) // item_size) 113 self.buffer = databuffer_unaligned[start_pos_samples:start_pos_samples + (self.buffer_size // item_size)] # byte address but int16 sample: therefore / 2 114 self.buffer = self.buffer.reshape((num_timestamps, 2), order='C') # array items per timestamp, because the maximum item size is 8 bytes = 64 bits 115 116 def start_buffer_transfer(self, *args, direction=SPCM_DIR_CARDTOPC, notify_timestamps=0, transfer_offset=0, transfer_length=None) -> None: 117 """ 118 Start the transfer of the timestamp data to the card 119 120 Parameters 121 ---------- 122 *args : list 123 list of additonal arguments that are added as flags to the start dma command 124 """ 125 126 notify_size = 0 127 if notify_timestamps: 128 self._notify_timestamps = notify_timestamps 129 if self._notify_timestamps: 130 notify_size = self._notify_timestamps * self.bytes_per_ts 131 132 if transfer_offset: 133 transfer_offset_bytes = transfer_offset * self.bytes_per_ts 134 else: 135 transfer_offset_bytes = 0 136 137 if transfer_length is not None: 138 transfer_length_bytes = transfer_length * self.bytes_per_ts 139 else: 140 transfer_length_bytes = self.buffer_size 141 142 143 # we define the buffer for transfer and start the DMA transfer 144 self.card._print("Starting the Timestamp transfer and waiting until data is in board memory") 145 self._c_buffer = self.buffer.ctypes.data_as(c_void_p) 146 spcm_dwDefTransfer_i64(self.card._handle, self.buffer_type, direction, notify_size, self._c_buffer, transfer_offset_bytes, transfer_length_bytes) 147 cmd = 0 148 for arg in args: 149 cmd |= arg 150 self.card.cmd(cmd) 151 self.card._print("... timestamp data transfer started") 152 153 def avail_card_len(self, num_timestamps : int) -> None: 154 """ 155 Set the amount of timestamps that is available for reading of the timestamp buffer (see register 'SPC_TS_AVAIL_CARD_LEN' in chapter `Timestamp` in the manual) 156 157 Parameters 158 ---------- 159 num_timestamps : int 160 the amount of timestamps that is available for reading 161 """ 162 card_len = num_timestamps * self.bytes_per_ts 163 self.card.set_i(SPC_TS_AVAIL_CARD_LEN, card_len) 164 165 def avail_user_pos(self) -> int: 166 """ 167 Get the current position of the pointer in the timestamp buffer (see register 'SPC_TS_AVAIL_USER_POS' in chapter `Timestamp` in the manual) 168 169 Returns 170 ------- 171 int 172 pointer position in timestamps 173 """ 174 return self.card.get_i(SPC_TS_AVAIL_USER_POS) // self.bytes_per_ts 175 176 def avail_user_len(self) -> int: 177 """ 178 Get the current length of the data in timestamps in the timestamp buffer (see register 'SPC_TS_AVAIL_USER_LEN' in chapter `Timestamp` in the manual) 179 180 Returns 181 ------- 182 int 183 data length available in number of timestamps 184 """ 185 return self.card.get_i(SPC_TS_AVAIL_USER_LEN) // self.bytes_per_ts 186 187 188 # Iterator methods 189 _max_polling = 64 190 191 def to_transfer_timestamps(self, timestamps: int) -> None: 192 """ 193 This method sets the number of timestamps to transfer 194 195 Parameters 196 ---------- 197 timestamps : int 198 the number of timestamps to transfer 199 """ 200 self._to_transfer_timestamps = timestamps 201 202 def poll(self) -> npt.ArrayLike: 203 """ 204 This method is called when polling for timestamps 205 206 Returns 207 ------- 208 npt.ArrayLike 209 the next data block 210 """ 211 while True: 212 user_len = self.avail_user_len() 213 if user_len >= 1: 214 user_pos = self.avail_user_pos() 215 self.avail_card_len(user_len) 216 return self.buffer[user_pos:user_pos+user_len, :]
a class to control Spectrum Instrumentation cards with the timestamp functionality
For more information about what setups are available, please have a look at the user manual for your specific card
Parameters
ts_mode (int):
transfer_mode (int):
bits_per_ts (int = 0):
bytes_per_ts (int = 16):
34 def __init__(self, card, *args, **kwargs) -> None: 35 """ 36 Initialize the TimeStamp object with a card object 37 38 Parameters 39 ---------- 40 card : Card 41 a card object that is used to control the card 42 """ 43 44 super().__init__(card, *args, **kwargs) 45 self.buffer_type = SPCM_BUF_TIMESTAMP 46 self.bits_per_ts = self.bytes_per_ts * 8
Initialize the TimeStamp object with a card object
Parameters
- card (Card): a card object that is used to control the card
48 def cmd(self, *args) -> None: 49 """ 50 Execute spcm timestamp commands (see register 'SPC_TIMESTAMP_CMD' in chapter `Timestamp` in the manual) 51 52 Parameters 53 ---------- 54 *args : int 55 The different timestamp command flags to be executed. 56 """ 57 58 cmd = 0 59 for arg in args: 60 cmd |= arg 61 self.card.set_i(SPC_TIMESTAMP_CMD, cmd)
Execute spcm timestamp commands (see register 'SPC_TIMESTAMP_CMD' in chapter Timestamp
in the manual)
Parameters
- *args (int): The different timestamp command flags to be executed.
63 def reset(self) -> None: 64 """Reset the timestamp counter (see command 'SPC_TS_RESET' in chapter `Timestamp` in the manual)""" 65 self.cmd(SPC_TS_RESET)
Reset the timestamp counter (see command 'SPC_TS_RESET' in chapter Timestamp
in the manual)
67 def mode(self, mode : int, *args : list[int]) -> None: 68 """ 69 Set the mode of the timestamp counter (see register 'SPC_TIMESTAMP_CMD' in chapter `Timestamp` in the manual) 70 71 Parameters 72 ---------- 73 mode : int 74 The mode of the timestamp counter 75 *args : list[int] 76 List of additional commands send with setting the mode 77 """ 78 self.ts_mode = mode 79 self.cmd(self.ts_mode, *args)
Set the mode of the timestamp counter (see register 'SPC_TIMESTAMP_CMD' in chapter Timestamp
in the manual)
Parameters
- mode (int): The mode of the timestamp counter
- *args (list[int]): List of additional commands send with setting the mode
81 def notify_timestamps(self, notify_timestamps : int) -> None: 82 """ 83 Set the number of timestamps to notify the user about 84 85 Parameters 86 ---------- 87 notify_timestamps : int 88 the number of timestamps to notify the user about 89 """ 90 self._notify_timestamps = notify_timestamps
Set the number of timestamps to notify the user about
Parameters
- notify_timestamps (int): the number of timestamps to notify the user about
92 def allocate_buffer(self, num_timestamps : int) -> None: 93 """ 94 Allocate the buffer for the timestamp data transfer 95 96 Parameters 97 ---------- 98 num_timestamps : int 99 The number of timestamps to be allocated 100 """ 101 102 self.buffer_size = num_timestamps * self.bytes_per_ts 103 104 dwMask = self._buffer_alignment - 1 105 106 sample_type = np.int64 107 item_size = sample_type(0).itemsize 108 # allocate a buffer (numpy array) for DMA transfer: a little bigger one to have room for address alignment 109 databuffer_unaligned = np.empty(((self._buffer_alignment + self.buffer_size) // item_size, ), dtype = sample_type) # half byte count at int16 sample (// = integer division) 110 # two numpy-arrays may share the same memory: skip the begin up to the alignment boundary (ArrayVariable[SKIP_VALUE:]) 111 # Address of data-memory from numpy-array: ArrayVariable.__array_interface__['data'][0] 112 start_pos_samples = ((self._buffer_alignment - (databuffer_unaligned.__array_interface__['data'][0] & dwMask)) // item_size) 113 self.buffer = databuffer_unaligned[start_pos_samples:start_pos_samples + (self.buffer_size // item_size)] # byte address but int16 sample: therefore / 2 114 self.buffer = self.buffer.reshape((num_timestamps, 2), order='C') # array items per timestamp, because the maximum item size is 8 bytes = 64 bits
Allocate the buffer for the timestamp data transfer
Parameters
- num_timestamps (int): The number of timestamps to be allocated
116 def start_buffer_transfer(self, *args, direction=SPCM_DIR_CARDTOPC, notify_timestamps=0, transfer_offset=0, transfer_length=None) -> None: 117 """ 118 Start the transfer of the timestamp data to the card 119 120 Parameters 121 ---------- 122 *args : list 123 list of additonal arguments that are added as flags to the start dma command 124 """ 125 126 notify_size = 0 127 if notify_timestamps: 128 self._notify_timestamps = notify_timestamps 129 if self._notify_timestamps: 130 notify_size = self._notify_timestamps * self.bytes_per_ts 131 132 if transfer_offset: 133 transfer_offset_bytes = transfer_offset * self.bytes_per_ts 134 else: 135 transfer_offset_bytes = 0 136 137 if transfer_length is not None: 138 transfer_length_bytes = transfer_length * self.bytes_per_ts 139 else: 140 transfer_length_bytes = self.buffer_size 141 142 143 # we define the buffer for transfer and start the DMA transfer 144 self.card._print("Starting the Timestamp transfer and waiting until data is in board memory") 145 self._c_buffer = self.buffer.ctypes.data_as(c_void_p) 146 spcm_dwDefTransfer_i64(self.card._handle, self.buffer_type, direction, notify_size, self._c_buffer, transfer_offset_bytes, transfer_length_bytes) 147 cmd = 0 148 for arg in args: 149 cmd |= arg 150 self.card.cmd(cmd) 151 self.card._print("... timestamp data transfer started")
Start the transfer of the timestamp data to the card
Parameters
- *args (list): list of additonal arguments that are added as flags to the start dma command
153 def avail_card_len(self, num_timestamps : int) -> None: 154 """ 155 Set the amount of timestamps that is available for reading of the timestamp buffer (see register 'SPC_TS_AVAIL_CARD_LEN' in chapter `Timestamp` in the manual) 156 157 Parameters 158 ---------- 159 num_timestamps : int 160 the amount of timestamps that is available for reading 161 """ 162 card_len = num_timestamps * self.bytes_per_ts 163 self.card.set_i(SPC_TS_AVAIL_CARD_LEN, card_len)
Set the amount of timestamps that is available for reading of the timestamp buffer (see register 'SPC_TS_AVAIL_CARD_LEN' in chapter Timestamp
in the manual)
Parameters
- num_timestamps (int): the amount of timestamps that is available for reading
165 def avail_user_pos(self) -> int: 166 """ 167 Get the current position of the pointer in the timestamp buffer (see register 'SPC_TS_AVAIL_USER_POS' in chapter `Timestamp` in the manual) 168 169 Returns 170 ------- 171 int 172 pointer position in timestamps 173 """ 174 return self.card.get_i(SPC_TS_AVAIL_USER_POS) // self.bytes_per_ts
Get the current position of the pointer in the timestamp buffer (see register 'SPC_TS_AVAIL_USER_POS' in chapter Timestamp
in the manual)
Returns
- int: pointer position in timestamps
176 def avail_user_len(self) -> int: 177 """ 178 Get the current length of the data in timestamps in the timestamp buffer (see register 'SPC_TS_AVAIL_USER_LEN' in chapter `Timestamp` in the manual) 179 180 Returns 181 ------- 182 int 183 data length available in number of timestamps 184 """ 185 return self.card.get_i(SPC_TS_AVAIL_USER_LEN) // self.bytes_per_ts
Get the current length of the data in timestamps in the timestamp buffer (see register 'SPC_TS_AVAIL_USER_LEN' in chapter Timestamp
in the manual)
Returns
- int: data length available in number of timestamps
191 def to_transfer_timestamps(self, timestamps: int) -> None: 192 """ 193 This method sets the number of timestamps to transfer 194 195 Parameters 196 ---------- 197 timestamps : int 198 the number of timestamps to transfer 199 """ 200 self._to_transfer_timestamps = timestamps
This method sets the number of timestamps to transfer
Parameters
- timestamps (int): the number of timestamps to transfer
202 def poll(self) -> npt.ArrayLike: 203 """ 204 This method is called when polling for timestamps 205 206 Returns 207 ------- 208 npt.ArrayLike 209 the next data block 210 """ 211 while True: 212 user_len = self.avail_user_len() 213 if user_len >= 1: 214 user_pos = self.avail_user_pos() 215 self.avail_card_len(user_len) 216 return self.buffer[user_pos:user_pos+user_len, :]
This method is called when polling for timestamps
Returns
- npt.ArrayLike: the next data block
11class Sequence(DataTransfer): 12 """ 13 a high-level class to control the sequence mode on Spectrum Instrumentation cards 14 15 For more information about what setups are available, please have a look at the user manual 16 for your specific card. 17 18 """ 19 20 def __init__(self, card, *args, **kwargs) -> None: 21 super().__init__(card, *args, **kwargs) 22 23 def max_segments(self, max_segments : int = 0) -> int: 24 """ 25 Set the maximum number of segments that can be used in the sequence mode (see register 'SPC_SEQMODE_MAXSEGMENTS' in chapter `Sequence Mode` in the manual) 26 27 Parameters 28 ---------- 29 max_segments : int 30 The maximum number of segments that can be used in the sequence mode 31 32 Returns 33 ------- 34 max_segments : int 35 The actual maximum number of segments that can be used in the sequence mode 36 """ 37 if max_segments: 38 self.card.set_i(SPC_SEQMODE_MAXSEGMENTS, max_segments) 39 return self.card.get_i(SPC_SEQMODE_MAXSEGMENTS) 40 41 def write_segment(self, segment : int = None) -> int: 42 """ 43 Defines the current segment to be addressed by the user. Must be programmed prior to changing any segment parameters. (see register 'SPC_SEQMODE_WRITESEGMENT' in chapter `Sequence Mode` in the manual) 44 45 Parameters 46 ---------- 47 segment : int 48 The segment to be addresses 49 50 Returns 51 ------- 52 segment : int 53 The segment to be addresses 54 """ 55 56 if segment is not None: 57 self.card.set_i(SPC_SEQMODE_WRITESEGMENT, segment) 58 return self.card.get_i(SPC_SEQMODE_WRITESEGMENT) 59 60 def segment_size(self, segment_size : int = None, return_unit = None) -> int: 61 """ 62 Defines the number of valid/to be replayed samples for the current selected memory segment in samples per channel. (see register 'SPC_SEQMODE_SEGMENTSIZE' in chapter `Sequence Mode` in the manual) 63 64 Parameters 65 ---------- 66 segment_size : int | pint.Quantity 67 The size of the segment in samples 68 69 Returns 70 ------- 71 segment_size : int 72 The size of the segment in samples 73 """ 74 75 if segment_size is not None: 76 segment_size = UnitConversion.convert(segment_size, units.Sa, int) 77 self.card.set_i(SPC_SEQMODE_SEGMENTSIZE, segment_size) 78 return_value = self.card.get_i(SPC_SEQMODE_SEGMENTSIZE) 79 if return_unit is not None: return UnitConversion.to_unit(return_value, return_unit) 80 return return_value 81 82 def step_memory(self, step_index : int, next_step_index : int = None, segment_index : int = None, loops : int = None, flags : int = None) -> tuple[int, int, int, int]: 83 """ 84 Defines the step memory for the current selected memory segment. (see register 'SPC_SEQMODE_STEPMEM0' in chapter `Sequence Mode` in the manual) 85 86 Parameters 87 ---------- 88 step_index : int 89 The index of the current step 90 next_step_index : int 91 The index of the next step in the sequence 92 segment_index : int 93 The index of the segment associated to the step 94 loops : int 95 The number of times the segment is looped 96 flags : int 97 The flags for the step 98 99 Returns 100 ------- 101 next_step_index : int 102 The index of the next step in the sequence 103 segment_index : int 104 The index of the segment associated to the step 105 loops : int 106 The number of times the segment is looped 107 flags : int 108 The flags for the step 109 110 """ 111 qwSequenceEntry = 0 112 113 # setup register value 114 if next_step_index is not None and segment_index is not None and loops is not None and flags is not None: 115 qwSequenceEntry = (flags & ~SPCSEQ_LOOPMASK) | (loops & SPCSEQ_LOOPMASK) 116 qwSequenceEntry <<= 32 117 qwSequenceEntry |= ((next_step_index << 16) & SPCSEQ_NEXTSTEPMASK) | (int(segment_index) & SPCSEQ_SEGMENTMASK) 118 self.card.set_i(SPC_SEQMODE_STEPMEM0 + step_index, qwSequenceEntry) 119 120 qwSequenceEntry = self.card.get_i(SPC_SEQMODE_STEPMEM0 + step_index) 121 return (qwSequenceEntry & SPCSEQ_NEXTSTEPMASK) >> 16, qwSequenceEntry & SPCSEQ_SEGMENTMASK, (qwSequenceEntry >> 32) & SPCSEQ_LOOPMASK, (qwSequenceEntry >> 32) & ~SPCSEQ_LOOPMASK 122 123 124 def start_step(self, start_step_index : int = None) -> int: 125 """ 126 Defines which of all defined steps in the sequence memory will be used first directly after the card start. (see register 'SPC_SEQMODE_STARTSTEP' in chapter `Sequence Mode` in the manual) 127 128 Parameters 129 ---------- 130 start_step_index : int 131 The index of the start step 132 133 Returns 134 ------- 135 start_step_index : int 136 The index of the start step 137 """ 138 139 if start_step_index is not None: 140 self.card.set_i(SPC_SEQMODE_STARTSTEP, start_step_index) 141 return self.card.get_i(SPC_SEQMODE_STARTSTEP) 142 143 def status(self) -> int: 144 """ 145 Reads the status of the sequence mode. (see register 'SPC_SEQMODE_STATUS' in chapter `Sequence Mode` in the manual) 146 147 Returns 148 ------- 149 status : int 150 The status of the sequence mode 151 152 """ 153 return self.card.get_i(SPC_SEQMODE_STATUS)
a high-level class to control the sequence mode on Spectrum Instrumentation cards
For more information about what setups are available, please have a look at the user manual for your specific card.
Initialize the DataTransfer object with a card object and additional arguments
Parameters
- card (Card): the card object that is used for the data transfer
- *args (list): list of additional arguments
- **kwargs (dict): dictionary of additional keyword arguments
23 def max_segments(self, max_segments : int = 0) -> int: 24 """ 25 Set the maximum number of segments that can be used in the sequence mode (see register 'SPC_SEQMODE_MAXSEGMENTS' in chapter `Sequence Mode` in the manual) 26 27 Parameters 28 ---------- 29 max_segments : int 30 The maximum number of segments that can be used in the sequence mode 31 32 Returns 33 ------- 34 max_segments : int 35 The actual maximum number of segments that can be used in the sequence mode 36 """ 37 if max_segments: 38 self.card.set_i(SPC_SEQMODE_MAXSEGMENTS, max_segments) 39 return self.card.get_i(SPC_SEQMODE_MAXSEGMENTS)
Set the maximum number of segments that can be used in the sequence mode (see register 'SPC_SEQMODE_MAXSEGMENTS' in chapter Sequence Mode
in the manual)
Parameters
- max_segments (int): The maximum number of segments that can be used in the sequence mode
Returns
- max_segments (int): The actual maximum number of segments that can be used in the sequence mode
41 def write_segment(self, segment : int = None) -> int: 42 """ 43 Defines the current segment to be addressed by the user. Must be programmed prior to changing any segment parameters. (see register 'SPC_SEQMODE_WRITESEGMENT' in chapter `Sequence Mode` in the manual) 44 45 Parameters 46 ---------- 47 segment : int 48 The segment to be addresses 49 50 Returns 51 ------- 52 segment : int 53 The segment to be addresses 54 """ 55 56 if segment is not None: 57 self.card.set_i(SPC_SEQMODE_WRITESEGMENT, segment) 58 return self.card.get_i(SPC_SEQMODE_WRITESEGMENT)
Defines the current segment to be addressed by the user. Must be programmed prior to changing any segment parameters. (see register 'SPC_SEQMODE_WRITESEGMENT' in chapter Sequence Mode
in the manual)
Parameters
- segment (int): The segment to be addresses
Returns
- segment (int): The segment to be addresses
60 def segment_size(self, segment_size : int = None, return_unit = None) -> int: 61 """ 62 Defines the number of valid/to be replayed samples for the current selected memory segment in samples per channel. (see register 'SPC_SEQMODE_SEGMENTSIZE' in chapter `Sequence Mode` in the manual) 63 64 Parameters 65 ---------- 66 segment_size : int | pint.Quantity 67 The size of the segment in samples 68 69 Returns 70 ------- 71 segment_size : int 72 The size of the segment in samples 73 """ 74 75 if segment_size is not None: 76 segment_size = UnitConversion.convert(segment_size, units.Sa, int) 77 self.card.set_i(SPC_SEQMODE_SEGMENTSIZE, segment_size) 78 return_value = self.card.get_i(SPC_SEQMODE_SEGMENTSIZE) 79 if return_unit is not None: return UnitConversion.to_unit(return_value, return_unit) 80 return return_value
Defines the number of valid/to be replayed samples for the current selected memory segment in samples per channel. (see register 'SPC_SEQMODE_SEGMENTSIZE' in chapter Sequence Mode
in the manual)
Parameters
- segment_size (int | pint.Quantity): The size of the segment in samples
Returns
- segment_size (int): The size of the segment in samples
82 def step_memory(self, step_index : int, next_step_index : int = None, segment_index : int = None, loops : int = None, flags : int = None) -> tuple[int, int, int, int]: 83 """ 84 Defines the step memory for the current selected memory segment. (see register 'SPC_SEQMODE_STEPMEM0' in chapter `Sequence Mode` in the manual) 85 86 Parameters 87 ---------- 88 step_index : int 89 The index of the current step 90 next_step_index : int 91 The index of the next step in the sequence 92 segment_index : int 93 The index of the segment associated to the step 94 loops : int 95 The number of times the segment is looped 96 flags : int 97 The flags for the step 98 99 Returns 100 ------- 101 next_step_index : int 102 The index of the next step in the sequence 103 segment_index : int 104 The index of the segment associated to the step 105 loops : int 106 The number of times the segment is looped 107 flags : int 108 The flags for the step 109 110 """ 111 qwSequenceEntry = 0 112 113 # setup register value 114 if next_step_index is not None and segment_index is not None and loops is not None and flags is not None: 115 qwSequenceEntry = (flags & ~SPCSEQ_LOOPMASK) | (loops & SPCSEQ_LOOPMASK) 116 qwSequenceEntry <<= 32 117 qwSequenceEntry |= ((next_step_index << 16) & SPCSEQ_NEXTSTEPMASK) | (int(segment_index) & SPCSEQ_SEGMENTMASK) 118 self.card.set_i(SPC_SEQMODE_STEPMEM0 + step_index, qwSequenceEntry) 119 120 qwSequenceEntry = self.card.get_i(SPC_SEQMODE_STEPMEM0 + step_index) 121 return (qwSequenceEntry & SPCSEQ_NEXTSTEPMASK) >> 16, qwSequenceEntry & SPCSEQ_SEGMENTMASK, (qwSequenceEntry >> 32) & SPCSEQ_LOOPMASK, (qwSequenceEntry >> 32) & ~SPCSEQ_LOOPMASK
Defines the step memory for the current selected memory segment. (see register 'SPC_SEQMODE_STEPMEM0' in chapter Sequence Mode
in the manual)
Parameters
- step_index (int): The index of the current step
- next_step_index (int): The index of the next step in the sequence
- segment_index (int): The index of the segment associated to the step
- loops (int): The number of times the segment is looped
- flags (int): The flags for the step
Returns
- next_step_index (int): The index of the next step in the sequence
- segment_index (int): The index of the segment associated to the step
- loops (int): The number of times the segment is looped
- flags (int): The flags for the step
124 def start_step(self, start_step_index : int = None) -> int: 125 """ 126 Defines which of all defined steps in the sequence memory will be used first directly after the card start. (see register 'SPC_SEQMODE_STARTSTEP' in chapter `Sequence Mode` in the manual) 127 128 Parameters 129 ---------- 130 start_step_index : int 131 The index of the start step 132 133 Returns 134 ------- 135 start_step_index : int 136 The index of the start step 137 """ 138 139 if start_step_index is not None: 140 self.card.set_i(SPC_SEQMODE_STARTSTEP, start_step_index) 141 return self.card.get_i(SPC_SEQMODE_STARTSTEP)
Defines which of all defined steps in the sequence memory will be used first directly after the card start. (see register 'SPC_SEQMODE_STARTSTEP' in chapter Sequence Mode
in the manual)
Parameters
- start_step_index (int): The index of the start step
Returns
- start_step_index (int): The index of the start step
143 def status(self) -> int: 144 """ 145 Reads the status of the sequence mode. (see register 'SPC_SEQMODE_STATUS' in chapter `Sequence Mode` in the manual) 146 147 Returns 148 ------- 149 status : int 150 The status of the sequence mode 151 152 """ 153 return self.card.get_i(SPC_SEQMODE_STATUS)
Reads the status of the sequence mode. (see register 'SPC_SEQMODE_STATUS' in chapter Sequence Mode
in the manual)
Returns
- status (int): The status of the sequence mode
11class BlockAverage(Multi): 12 """a high-level class to control Block Average functionality on Spectrum Instrumentation cards 13 14 For more information about what setups are available, please have a look at the user manual 15 for your specific card. 16 17 """ 18 19 def __init__(self, card, *args, **kwargs) -> None: 20 super().__init__(card, *args, **kwargs) 21 22 def averages(self, num_averages : int = None) -> int: 23 """Sets the number of averages for the block averaging functionality (see hardware reference manual register 'SPC_AVERAGES') 24 25 Parameters 26 ---------- 27 num_averages : int 28 the number of averages for the boxcar functionality 29 30 Returns 31 ------- 32 int 33 the number of averages for the block averaging functionality 34 """ 35 if num_averages is not None: 36 self.card.set_i(SPC_AVERAGES, num_averages) 37 return self.card.get_i(SPC_AVERAGES) 38 39 def bits_per_sample(self) -> int: 40 """ 41 Get the number of bits per sample 42 43 Returns 44 ------- 45 int 46 number of bits per sample 47 """ 48 return super().bits_per_sample * 2 49 50 def bytes_per_sample(self) -> int: 51 """ 52 Get the number of bytes per sample 53 54 Returns 55 ------- 56 int 57 number of bytes per sample 58 """ 59 return super().bytes_per_sample * 2 60 61 def numpy_type(self) -> npt.NDArray[np.int_]: 62 """ 63 Get the type of numpy data from number of bytes 64 65 Returns 66 ------- 67 numpy data type 68 the type of data that is used by the card 69 """ 70 if self.bytes_per_sample == 2: 71 return np.int16 72 return np.int32
a high-level class to control Block Average functionality on Spectrum Instrumentation cards
For more information about what setups are available, please have a look at the user manual for your specific card.
Initialize the DataTransfer object with a card object and additional arguments
Parameters
- card (Card): the card object that is used for the data transfer
- *args (list): list of additional arguments
- **kwargs (dict): dictionary of additional keyword arguments
22 def averages(self, num_averages : int = None) -> int: 23 """Sets the number of averages for the block averaging functionality (see hardware reference manual register 'SPC_AVERAGES') 24 25 Parameters 26 ---------- 27 num_averages : int 28 the number of averages for the boxcar functionality 29 30 Returns 31 ------- 32 int 33 the number of averages for the block averaging functionality 34 """ 35 if num_averages is not None: 36 self.card.set_i(SPC_AVERAGES, num_averages) 37 return self.card.get_i(SPC_AVERAGES)
Sets the number of averages for the block averaging functionality (see hardware reference manual register 'SPC_AVERAGES')
Parameters
- num_averages (int): the number of averages for the boxcar functionality
Returns
- int: the number of averages for the block averaging functionality
39 def bits_per_sample(self) -> int: 40 """ 41 Get the number of bits per sample 42 43 Returns 44 ------- 45 int 46 number of bits per sample 47 """ 48 return super().bits_per_sample * 2
Get the number of bits per sample
Returns
- int: number of bits per sample
50 def bytes_per_sample(self) -> int: 51 """ 52 Get the number of bytes per sample 53 54 Returns 55 ------- 56 int 57 number of bytes per sample 58 """ 59 return super().bytes_per_sample * 2
Get the number of bytes per sample
Returns
- int: number of bytes per sample
61 def numpy_type(self) -> npt.NDArray[np.int_]: 62 """ 63 Get the type of numpy data from number of bytes 64 65 Returns 66 ------- 67 numpy data type 68 the type of data that is used by the card 69 """ 70 if self.bytes_per_sample == 2: 71 return np.int16 72 return np.int32
Get the type of numpy data from number of bytes
Returns
- numpy data type: the type of data that is used by the card
11class Boxcar(Multi): 12 """a high-level class to control Boxcar functionality on Spectrum Instrumentation cards 13 14 For more information about what setups are available, please have a look at the user manual 15 for your specific card. 16 17 """ 18 19 def __init__(self, card, *args, **kwargs) -> None: 20 super().__init__(card, *args, **kwargs) 21 22 def box_averages(self, num_averages : int = None) -> int: 23 """Sets the number of averages for the boxcar functionality (see hardware reference manual register 'SPC_BOX_AVERAGES') 24 25 Parameters 26 ---------- 27 num_averages : int 28 the number of averages for the boxcar functionality 29 30 Returns 31 ------- 32 int 33 the number of averages for the boxcar functionality 34 """ 35 if num_averages is not None: 36 self.card.set_i(SPC_BOX_AVERAGES, num_averages) 37 return self.card.get_i(SPC_BOX_AVERAGES) 38 39 def bits_per_sample(self) -> int: 40 """ 41 Get the number of bits per sample 42 43 Returns 44 ------- 45 int 46 number of bits per sample 47 """ 48 return 32 49 50 def bytes_per_sample(self) -> int: 51 """ 52 Get the number of bytes per sample 53 54 Returns 55 ------- 56 int 57 number of bytes per sample 58 """ 59 return 4 60 61 def numpy_type(self) -> npt.NDArray[np.int_]: 62 """ 63 Get the type of numpy data from number of bytes 64 65 Returns 66 ------- 67 numpy data type 68 the type of data that is used by the card 69 """ 70 return np.int32
a high-level class to control Boxcar functionality on Spectrum Instrumentation cards
For more information about what setups are available, please have a look at the user manual for your specific card.
Initialize the DataTransfer object with a card object and additional arguments
Parameters
- card (Card): the card object that is used for the data transfer
- *args (list): list of additional arguments
- **kwargs (dict): dictionary of additional keyword arguments
22 def box_averages(self, num_averages : int = None) -> int: 23 """Sets the number of averages for the boxcar functionality (see hardware reference manual register 'SPC_BOX_AVERAGES') 24 25 Parameters 26 ---------- 27 num_averages : int 28 the number of averages for the boxcar functionality 29 30 Returns 31 ------- 32 int 33 the number of averages for the boxcar functionality 34 """ 35 if num_averages is not None: 36 self.card.set_i(SPC_BOX_AVERAGES, num_averages) 37 return self.card.get_i(SPC_BOX_AVERAGES)
Sets the number of averages for the boxcar functionality (see hardware reference manual register 'SPC_BOX_AVERAGES')
Parameters
- num_averages (int): the number of averages for the boxcar functionality
Returns
- int: the number of averages for the boxcar functionality
39 def bits_per_sample(self) -> int: 40 """ 41 Get the number of bits per sample 42 43 Returns 44 ------- 45 int 46 number of bits per sample 47 """ 48 return 32
Get the number of bits per sample
Returns
- int: number of bits per sample
50 def bytes_per_sample(self) -> int: 51 """ 52 Get the number of bytes per sample 53 54 Returns 55 ------- 56 int 57 number of bytes per sample 58 """ 59 return 4
Get the number of bytes per sample
Returns
- int: number of bytes per sample
61 def numpy_type(self) -> npt.NDArray[np.int_]: 62 """ 63 Get the type of numpy data from number of bytes 64 65 Returns 66 ------- 67 numpy data type 68 the type of data that is used by the card 69 """ 70 return np.int32
Get the type of numpy data from number of bytes
Returns
- numpy data type: the type of data that is used by the card
100class SpcmException(Exception): 101 """a container class for handling driver level errors 102 103 Examples 104 ---------- 105 ```python 106 raise SpcmException(handle=card.handle()) 107 raise SpcmException(register=0, value=0, text="Some weird error") 108 ``` 109 110 Parameters 111 --------- 112 error : SpcmError 113 the error that induced the raising of the exception 114 115 """ 116 error = None 117 118 def __init__(self, error = None, register = None, value = None, text = None) -> None: 119 """ 120 Constructs exception object and an associated error object, either by getting 121 the last error from the card specified by the handle or using the information 122 coming from the parameters register, value and text 123 124 Parameters 125 ---------- 126 handle : drv_handle (optional) 127 a card handle to obtain the last error 128 register, value and text : int, int, str (optional) 129 parameters to define an error that is not raised by a driver error 130 """ 131 if error: self.error = error 132 if register or value or text: 133 self.error = SpcmError(register=register, value=value, text=text) 134 135 136 def __str__(self) -> str: 137 """ 138 Returns a human-readable text of the last error connected to the exception 139 140 Class Parameters 141 ---------- 142 self.error 143 144 Returns 145 ------- 146 str 147 the human-readable text as return by the error 148 """ 149 150 return str(self.error)
a container class for handling driver level errors
Examples
raise SpcmException(handle=card.handle())
raise SpcmException(register=0, value=0, text="Some weird error")
Parameters
- error (SpcmError): the error that induced the raising of the exception
118 def __init__(self, error = None, register = None, value = None, text = None) -> None: 119 """ 120 Constructs exception object and an associated error object, either by getting 121 the last error from the card specified by the handle or using the information 122 coming from the parameters register, value and text 123 124 Parameters 125 ---------- 126 handle : drv_handle (optional) 127 a card handle to obtain the last error 128 register, value and text : int, int, str (optional) 129 parameters to define an error that is not raised by a driver error 130 """ 131 if error: self.error = error 132 if register or value or text: 133 self.error = SpcmError(register=register, value=value, text=text)
Constructs exception object and an associated error object, either by getting the last error from the card specified by the handle or using the information coming from the parameters register, value and text
Parameters
- handle (drv_handle (optional)): a card handle to obtain the last error
- register, value and text (int, int, str (optional)): parameters to define an error that is not raised by a driver error
152class SpcmTimeout(Exception): 153 """a container class for handling specific timeout exceptions""" 154 pass
a container class for handling specific timeout exceptions
156class SpcmDeviceNotFound(SpcmException): 157 """a container class for handling specific device not found exceptions""" 158 pass
a container class for handling specific device not found exceptions
10class SpcmError(): 11 """a container class for handling driver level errors 12 13 Examples 14 ---------- 15 ```python 16 error = SpcmError(handle=card.handle()) 17 error = SpcmError(register=0, value=0, text="Some weird error") 18 ``` 19 20 Parameters 21 --------- 22 register : int 23 the register address that triggered the error 24 25 value : int 26 the value that was written to the register address 27 28 text : str 29 the human-readable text associated with the error 30 31 """ 32 33 register : int = 0 34 value : int = 0 35 text : str = "" 36 _handle = None 37 38 def __init__(self, handle = None, register = None, value = None, text = None) -> None: 39 """ 40 Constructs an error object, either by getting the last error from the card specified by the handle 41 or using the information coming from the parameters register, value and text 42 43 Parameters 44 ---------- 45 handle : pyspcm.drv_handle (optional) 46 a card handle to obtain the last error 47 register, value and text : int, int, str (optional) 48 parameters to define an error that is not raised by a driver error 49 """ 50 if handle: 51 self._handle = handle 52 self.get_info() 53 if register: self.register = register 54 if value: self.value = value 55 if text: self.text = text 56 57 def get_info(self) -> int: 58 """ 59 Gets the last error registered by the card and puts it in the object 60 61 Class Parameters 62 ---------- 63 self.register 64 self.value 65 self.text 66 67 Returns 68 ------- 69 int 70 Error number of the spcm_dwGetErrorInfo_i32 class 71 """ 72 73 register = uint32(0) 74 value = int32(0) 75 text = create_string_buffer(ERRORTEXTLEN) 76 dwErr = spcm_dwGetErrorInfo_i32(self._handle, byref(register), byref(value), byref(text)) 77 self.register = register.value 78 self.value = value.value 79 self.text = text.value.decode('utf-8') 80 return dwErr 81 82 def __str__(self) -> str: 83 """ 84 Returns a human-readable text of the last error 85 86 Class Parameters 87 ---------- 88 self.register 89 self.value 90 self.text 91 92 Returns 93 ------- 94 str 95 the human-readable text as saved in self.text. 96 """ 97 98 return str(self.text)
a container class for handling driver level errors
Examples
error = SpcmError(handle=card.handle())
error = SpcmError(register=0, value=0, text="Some weird error")
Parameters
- register (int): the register address that triggered the error
- value (int): the value that was written to the register address
- text (str): the human-readable text associated with the error
38 def __init__(self, handle = None, register = None, value = None, text = None) -> None: 39 """ 40 Constructs an error object, either by getting the last error from the card specified by the handle 41 or using the information coming from the parameters register, value and text 42 43 Parameters 44 ---------- 45 handle : pyspcm.drv_handle (optional) 46 a card handle to obtain the last error 47 register, value and text : int, int, str (optional) 48 parameters to define an error that is not raised by a driver error 49 """ 50 if handle: 51 self._handle = handle 52 self.get_info() 53 if register: self.register = register 54 if value: self.value = value 55 if text: self.text = text
Constructs an error object, either by getting the last error from the card specified by the handle or using the information coming from the parameters register, value and text
Parameters
- handle (pyspcm.drv_handle (optional)): a card handle to obtain the last error
- register, value and text (int, int, str (optional)): parameters to define an error that is not raised by a driver error
57 def get_info(self) -> int: 58 """ 59 Gets the last error registered by the card and puts it in the object 60 61 Class Parameters 62 ---------- 63 self.register 64 self.value 65 self.text 66 67 Returns 68 ------- 69 int 70 Error number of the spcm_dwGetErrorInfo_i32 class 71 """ 72 73 register = uint32(0) 74 value = int32(0) 75 text = create_string_buffer(ERRORTEXTLEN) 76 dwErr = spcm_dwGetErrorInfo_i32(self._handle, byref(register), byref(value), byref(text)) 77 self.register = register.value 78 self.value = value.value 79 self.text = text.value.decode('utf-8') 80 return dwErr
Gets the last error registered by the card and puts it in the object
Class Parameters
self.register self.value self.text
Returns
- int: Error number of the spcm_dwGetErrorInfo_i32 class
47class SCAPPTransfer(DataTransfer): 48 """ 49 Class for data transfer between the card and the host using the SCAPP API. 50 51 Parameters 52 ---------- 53 direction : Direction = Direction.Acquisition 54 Direction of the data transfer. 55 """ 56 57 direction : Direction = None 58 59 def __init__(self, card : Card, direction : Direction = Direction.Acquisition): 60 if not _cuda_support: 61 raise ImportError("CUDA support is not available. Please install the cupy and cuda-python packages.") 62 super().__init__(card) 63 self.direction = direction 64 self.iterator_index = 0 65 66 def allocate_buffer(self, num_samples : int) -> None: 67 """ 68 Memory allocation for the buffer that is used for communicating with the card 69 70 Parameters 71 ---------- 72 num_samples : int | pint.Quantity = None 73 use the number of samples an get the number of active channels and bytes per samples directly from the card 74 """ 75 76 self.buffer_samples = UnitConversion.convert(num_samples, units.Sa, int) 77 # Allocate RDMA buffer 78 self.buffer = cp.empty((self.num_channels, self.buffer_samples), dtype = self.numpy_type(), order='F') 79 flag = 1 80 checkCudaErrors(cuda.cuPointerSetAttribute(flag, cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_SYNC_MEMOPS, self.buffer.data.ptr)) 81 82 def start_buffer_transfer(self, *args, notify_samples = None, transfer_length = None) -> None: 83 """ 84 Setup an RDMA transfer. 85 86 Parameters 87 ---------- 88 args : int 89 Additional commands that are send to the card. 90 notify_samples : int 91 Size of the part of the buffer that is used for notifications. 92 transfer_length : int 93 Total length of the transfer buffer. 94 """ 95 96 # self.notify_samples(notify_samples) 97 # only change this locally 98 if notify_samples is not None: 99 notify_size = notify_samples * self.num_channels * self.bytes_per_sample 100 else: 101 notify_size = self.notify_size 102 # print("Notify size: ", self.notify_size) 103 self.buffer_samples = transfer_length 104 105 # Define transfer CUDA buffers 106 if self.direction == Direction.Acquisition: 107 direction = SPCM_DIR_CARDTOGPU 108 else: 109 direction = SPCM_DIR_GPUTOCARD 110 self.card._check_error(spcm_dwDefTransfer_i64(self.card._handle, SPCM_BUF_DATA, direction, notify_size, c_void_p(self.buffer.data.ptr), 0, self.buffer_size)) 111 112 # Execute additional commands if available 113 if args: 114 cmd = 0 115 for arg in args: 116 cmd |= arg 117 self.card.cmd(cmd) 118 self.card._print("... CUDA data transfer started") 119 120 _auto_avail_card_len = True 121 def auto_avail_card_len(self, value : bool = None) -> bool: 122 """ 123 Enable or disable the automatic sending of the number of samples that the card can now use for sample data transfer again 124 125 Parameters 126 ---------- 127 value : bool = None 128 True to enable, False to disable and None to get the current status 129 130 Returns 131 ------- 132 bool 133 the current status 134 """ 135 if value is not None: 136 self._auto_avail_card_len = value 137 return self._auto_avail_card_len 138 139 def __next__(self) -> tuple: 140 """ 141 This method is called when the next element is requested from the iterator 142 143 Returns 144 ------- 145 npt.ArrayLike 146 the next data block 147 148 Raises 149 ------ 150 StopIteration 151 """ 152 timeout_counter = 0 153 154 if self.iterator_index != 0 and self._auto_avail_card_len: 155 self.avail_card_len(self._notify_samples) 156 157 while True: 158 try: 159 if not self._polling: 160 self.wait_dma() 161 else: 162 user_len = self.avail_user_len() 163 if user_len >= self._notify_samples: 164 break 165 time.sleep(0.01) 166 except SpcmTimeout: 167 self.card._print("... Timeout ({})".format(timeout_counter), end='\r') 168 timeout_counter += 1 169 if timeout_counter > self._max_timeout: 170 self.iterator_index = 0 171 raise StopIteration 172 else: 173 if not self._polling: 174 break 175 176 self.iterator_index += 1 177 178 self._current_samples += self._notify_samples 179 if self._to_transfer_samples != 0 and self._to_transfer_samples < self._current_samples: 180 self.iterator_index = 0 181 raise StopIteration 182 183 user_pos = self.avail_user_pos() 184 fill_size = self.fill_size_promille() 185 186 self.card._print("Fill size: {}% Pos:{:08x} Total:{:.2f} MiS / {:.2f} MiS".format(fill_size/10, user_pos, self._current_samples / MEBI(1), self._to_transfer_samples / MEBI(1)), end='\r', verbose=self._verbose) 187 188 return self.buffer[:, user_pos:user_pos+self._notify_samples]
Class for data transfer between the card and the host using the SCAPP API.
Parameters
- direction (Direction = Direction.Acquisition): Direction of the data transfer.
59 def __init__(self, card : Card, direction : Direction = Direction.Acquisition): 60 if not _cuda_support: 61 raise ImportError("CUDA support is not available. Please install the cupy and cuda-python packages.") 62 super().__init__(card) 63 self.direction = direction 64 self.iterator_index = 0
Initialize the DataTransfer object with a card object and additional arguments
Parameters
- card (Card): the card object that is used for the data transfer
- *args (list): list of additional arguments
- **kwargs (dict): dictionary of additional keyword arguments
66 def allocate_buffer(self, num_samples : int) -> None: 67 """ 68 Memory allocation for the buffer that is used for communicating with the card 69 70 Parameters 71 ---------- 72 num_samples : int | pint.Quantity = None 73 use the number of samples an get the number of active channels and bytes per samples directly from the card 74 """ 75 76 self.buffer_samples = UnitConversion.convert(num_samples, units.Sa, int) 77 # Allocate RDMA buffer 78 self.buffer = cp.empty((self.num_channels, self.buffer_samples), dtype = self.numpy_type(), order='F') 79 flag = 1 80 checkCudaErrors(cuda.cuPointerSetAttribute(flag, cuda.CUpointer_attribute.CU_POINTER_ATTRIBUTE_SYNC_MEMOPS, self.buffer.data.ptr))
Memory allocation for the buffer that is used for communicating with the card
Parameters
- num_samples (int | pint.Quantity = None): use the number of samples an get the number of active channels and bytes per samples directly from the card
82 def start_buffer_transfer(self, *args, notify_samples = None, transfer_length = None) -> None: 83 """ 84 Setup an RDMA transfer. 85 86 Parameters 87 ---------- 88 args : int 89 Additional commands that are send to the card. 90 notify_samples : int 91 Size of the part of the buffer that is used for notifications. 92 transfer_length : int 93 Total length of the transfer buffer. 94 """ 95 96 # self.notify_samples(notify_samples) 97 # only change this locally 98 if notify_samples is not None: 99 notify_size = notify_samples * self.num_channels * self.bytes_per_sample 100 else: 101 notify_size = self.notify_size 102 # print("Notify size: ", self.notify_size) 103 self.buffer_samples = transfer_length 104 105 # Define transfer CUDA buffers 106 if self.direction == Direction.Acquisition: 107 direction = SPCM_DIR_CARDTOGPU 108 else: 109 direction = SPCM_DIR_GPUTOCARD 110 self.card._check_error(spcm_dwDefTransfer_i64(self.card._handle, SPCM_BUF_DATA, direction, notify_size, c_void_p(self.buffer.data.ptr), 0, self.buffer_size)) 111 112 # Execute additional commands if available 113 if args: 114 cmd = 0 115 for arg in args: 116 cmd |= arg 117 self.card.cmd(cmd) 118 self.card._print("... CUDA data transfer started")
Setup an RDMA transfer.
Parameters
- args (int): Additional commands that are send to the card.
- notify_samples (int): Size of the part of the buffer that is used for notifications.
- transfer_length (int): Total length of the transfer buffer.
121 def auto_avail_card_len(self, value : bool = None) -> bool: 122 """ 123 Enable or disable the automatic sending of the number of samples that the card can now use for sample data transfer again 124 125 Parameters 126 ---------- 127 value : bool = None 128 True to enable, False to disable and None to get the current status 129 130 Returns 131 ------- 132 bool 133 the current status 134 """ 135 if value is not None: 136 self._auto_avail_card_len = value 137 return self._auto_avail_card_len
Enable or disable the automatic sending of the number of samples that the card can now use for sample data transfer again
Parameters
- value (bool = None): True to enable, False to disable and None to get the current status
Returns
- bool: the current status