Skip to content

Quam classes

ParentDescriptor

Descriptor for the parent attribute of QuamBase.

This descriptor is used to ensure that the parent attribute of a QuamBase object is not overwritten. This is to prevent the following situation:

parent1 = QuamBase()
parent2 = QuamBase()

child = QuamBase()
child.parent = parent1  # This is fine
child.parent = parent2  # This raises an AttributeError
Source code in quam/core/quam_classes.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
class ParentDescriptor:
    """Descriptor for the parent attribute of QuamBase.

    This descriptor is used to ensure that the parent attribute of a QuamBase
    object is not overwritten. This is to prevent the following situation:

    ```
    parent1 = QuamBase()
    parent2 = QuamBase()

    child = QuamBase()
    child.parent = parent1  # This is fine
    child.parent = parent2  # This raises an AttributeError
    ```
    """

    def __get__(self, instance, owner):
        if instance is None:
            return self

        if "parent" in instance.__dict__:
            return instance.__dict__["parent"]
        return None

    def __set__(self, instance, value):
        if value is None:
            instance.__dict__.pop("parent", None)
            return

        if "parent" in instance.__dict__ and instance.__dict__["parent"] is not value:
            cls = instance.__class__.__name__
            raise AttributeError(
                f"Cannot overwrite parent attribute of {cls}. "
                f"To modify {cls}.parent, first set {cls}.parent = None"
            )
        instance.__dict__["parent"] = value

QuamBase

Bases: ReferenceClass

Base class for any QuAM component class.

Parameters:

Name Type Description Default
parent

The parent of this object. This is automatically set when adding this object to another QuamBase object.

required
config_settings

A dictionary of configuration settings for this object. This is used by QuamRoot.generate_config to determine the order in which to add the components to the QUA config. Keys are "before" and "after", and the values are a list of QuamComponents

required
Note

This class should not be used directly, but should generally be subclassed. The subclasses should be dataclasses.

Source code in quam/core/quam_classes.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
class QuamBase(ReferenceClass):
    """Base class for any QuAM component class.

    args:
        parent: The parent of this object. This is automatically set when adding
            this object to another QuamBase object.
        config_settings: A dictionary of configuration settings for this object.
            This is used by [`QuamRoot.generate_config`][quam.core.quam_classes.QuamRoot.generate_config]
            to determine the order in which to add the components to the QUA config.
            Keys are "before" and "after", and the values are a list of QuamComponents

    Note:
        This class should not be used directly, but should generally be subclassed.
        The subclasses should be dataclasses.
    """

    parent: ClassVar["QuamBase"] = ParentDescriptor()
    _last_instantiated_root: ClassVar[Optional["QuamRoot"]] = None
    config_settings: ClassVar[Dict[str, Any]] = None

    def __init__(self):
        # This prohibits instantiating without it being a dataclass
        # This means that we have to subclass this class and make it a dataclass
        if not is_dataclass(self):
            if type(self) in [QuamBase, QuamComponent, QuamRoot]:
                raise TypeError(
                    f"Cannot instantiate {self.__class__.__name__} directly. "
                    "Please create a subclass and make it a dataclass."
                )
            else:
                raise TypeError(
                    f"Cannot instantiate {self.__class__.__name__}. "
                    "Please make it a dataclass."
                )

    def _get_attr_names(self) -> List[str]:
        """Get names of all dataclass attributes of this object.

        Returns:
            List of attribute names.

        Raises:
            AssertionError if not a dataclass.
        """
        assert is_dataclass(self)
        return [data_field.name for data_field in fields(self)]

    def get_root(self) -> Optional[QuamRoot]:
        """Get the QuamRoot object of this object.

        This function recursively searches the parent chain for a QuamRoot object.
        If no QuamRoot object is found, it will return the last instantiated QuamRoot
        if it exists, else None.

        Returns:
            The root of this object, or None if no root is found.
        """
        if self.parent is not None:
            return self.parent.get_root()

        if self._last_instantiated_root is not None:
            warnings.warn(
                f"This component is not part of any QuamRoot, using last "
                f"instantiated QuamRoot. This is not recommended as it may lead to "
                f"unexpected behaviour. Component: {self.__class__.__name__}"
            )
            return self._last_instantiated_root
        return None

    def get_attr_name(self, attr_val: Any) -> str:
        """Get the name of an attribute that matches the value.

        Args:
            attr_val: The value of the attribute.

        Returns:
            The name of the attribute.

        Raises:
            AttributeError if not found.
        """
        for attr_name in self._get_attr_names():
            if getattr(self, attr_name) is attr_val:
                return attr_name
        else:
            raise AttributeError(
                "Could not find name corresponding to attribute.\n"
                f"attribute: {attr_val}\n"
                f"obj: {self}"
            )

    def _attr_val_is_default(self, attr: str, val: Any) -> bool:
        """Check whether the value of an attribute is the default value.

        Args:
            attr: The name of the attribute.
            val: The value of the attribute.

        Returns:
            True if the value is the default value, False otherwise.
            False is also returned if the parent is not a dataclass
        """
        if not is_dataclass(self):
            return False

        dataclass_fields = fields(self)
        if not any(field.name == attr for field in dataclass_fields):
            return False

        field = next(field for field in dataclass_fields if field.name == attr)
        if field.default is not MISSING:
            return val == field.default
        elif field.default_factory is not MISSING:
            try:
                default_val = field.default_factory()
                return val == default_val
            except TypeError:
                return False

        return False

    @classmethod
    def _val_matches_attr_annotation(cls, attr: str, val: Any) -> bool:
        """Check whether the type of an attribute matches the annotation.

        The attribute type must exactly match the annotation.
        For dict and list, no additional type check of args is performed.
        """
        annotated_attrs = get_dataclass_attr_annotations(cls)
        if attr not in annotated_attrs["allowed"]:
            return False

        required_type = annotated_attrs["allowed"][attr]
        if type_is_optional(required_type):
            required_type = get_args(required_type)[0]

        if required_type == dict or get_origin(required_type) == dict:
            return isinstance(val, (dict, QuamDict))
        elif required_type == list or get_origin(required_type) == list:
            return isinstance(val, (list, QuamList))
        return type(val) == required_type

    def get_reference(
        self, attr: Optional[str] = None, relative_path: Optional[str] = None
    ) -> Optional[str]:
        """Get the reference path of this object.

        Args:
            attr: The optional attribute to get the reference path for.
                If None, the reference path of the object itself is returned.
            relative_path: The optional relative path to join with the reference path.

        Returns:
            The reference path of this object.

        Examples:
            We assume a QuamRoot object with a component "elem".
            - elem.get_reference() == "#/elem"
            - elem.get_reference(attr="child") == "#/elem/child"
            - elem.get_reference(relative_path="#./child") == "#/elem/child"
            - elem.get_reference(relative_path="#../child") == "#/child"
            - elem.get_reference(relative_path="#./child/grandchild") == "#/elem/child/grandchild"
        """

        if attr is not None and relative_path is not None:
            raise ValueError(
                "Cannot specify both attr and relative_path. "
                "Please specify only one of them."
            )

        if self.parent is None:
            raise AttributeError(
                "Unable to extract reference path for {self}: No parent defined"
            )

        try:
            base_reference = self.parent.get_reference()
            if base_reference == "#/":
                base_reference = "#"
        except AttributeError:
            raise AttributeError(
                f"Unable to extract reference path for {self}: Could not get "
                f"reference path for parent {self.parent}"
            )

        try:
            attr_name = self.parent.get_attr_name(self)
        except AttributeError:
            raise AttributeError(
                f"Unable to extract reference path for {self}: Could not get "
                f"attribute name from parent {self.parent}"
            )

        reference = f"{base_reference}/{attr_name}"

        if relative_path is not None:
            if not string_reference.is_reference(relative_path):
                raise ValueError(
                    f"Unable to extract reference path for {self}: "
                    f"relative_path {relative_path} is not a reference"
                )

            reference = string_reference.join_references(reference, relative_path)
        elif attr is not None:
            reference = f"{reference}/{attr}"

        return reference

    def get_attrs(
        self, follow_references: bool = False, include_defaults: bool = True
    ) -> Dict[str, Any]:
        """Get all attributes and corresponding values of this object.

        Args:
            follow_references: Whether to follow references when getting the value.
                If False, the reference will be returned as a string.
            include_defaults: Whether to include attributes that have the default
                value.

        Returns:
            A dictionary of attribute names and values.

        """
        attr_names = self._get_attr_names()

        skip_attrs = getattr(self, "_skip_attrs", [])
        attr_names = [attr for attr in attr_names if attr not in skip_attrs]

        if not follow_references:
            attrs = {attr: self.get_unreferenced_value(attr) for attr in attr_names}
        else:
            attrs = {attr: getattr(self, attr) for attr in attr_names}

        if not include_defaults:
            attrs = {
                attr: val
                for attr, val in attrs.items()
                if not self._attr_val_is_default(attr, val)
            }
        return attrs

    def to_dict(
        self, follow_references: bool = False, include_defaults: bool = False
    ) -> Dict[str, Any]:
        """Convert this object to a dictionary.

        Args:
            follow_references: Whether to follow references when getting the value.
                If False, the reference will be returned as a string.
            include_defaults: Whether to include attributes that have the default

        Returns:
            A dictionary representation of this object.
            Any QuamBase objects will be recursively converted to dictionaries.

        Note:
            If the value of an attribute does not match the annotation, the
            `"__class__"` key will be added to the dictionary. This is to ensure
            that the object can be reconstructed when loading from a file.
        """
        attrs = self.get_attrs(
            follow_references=follow_references, include_defaults=include_defaults
        )
        quam_dict = {}
        for attr, val in attrs.items():
            if isinstance(val, QuamBase):
                quam_dict[attr] = val.to_dict(
                    follow_references=follow_references,
                    include_defaults=include_defaults,
                )
                val_is_list = isinstance(val, (list, UserList))
                if not self._val_matches_attr_annotation(attr, val) and not val_is_list:
                    quam_dict[attr]["__class__"] = get_full_class_path(val)
            else:
                quam_dict[attr] = val
        return quam_dict

    def iterate_components(
        self, skip_elems: Optional[Sequence["QuamBase"]] = None
    ) -> Generator["QuamBase", None, None]:
        """Iterate over all QuamBase objects in this object, including nested objects.

        Args:
            skip_elems: A list of QuamBase objects to skip.
                This is used to prevent infinite loops when iterating over nested
                objects.

        Returns:
            A generator of QuamBase objects.
        """
        if skip_elems is None:
            skip_elems = []

        # We don't use "self in skip_elems" because we want to check for identity,
        # not equality. The reason is that you would otherwise have to instantiate
        # dataclasses using @dataclass(eq=False)
        in_skip_elems = any(self is elem for elem in skip_elems)
        if isinstance(self, QuamComponent) and not in_skip_elems:
            skip_elems.append(self)
            yield self

        attrs = self.get_attrs(follow_references=False, include_defaults=True)

        for attr_val in attrs.values():
            if any(attr_val is elem for elem in skip_elems):
                continue

            if isinstance(attr_val, QuamBase):
                yield from attr_val.iterate_components(skip_elems=skip_elems)

    def _is_reference(self, attr: str) -> bool:
        """Check whether an attribute is a reference.

        Args:
            attr: The name of the attribute.

        Returns:
            True if the attribute is a reference, False otherwise.

        Note:
            This function is used from the ReferenceClass class.
        """
        return string_reference.is_reference(attr)

    def _get_referenced_value(self, reference: str) -> Any:
        """Get the value of an attribute by reference

        Args:
            reference: The reference to the attribute.

        Returns:
            The value of the attribute, or the reference if it is not a reference

        Note:
            This function is used from the ReferenceClass class.
        """
        if not string_reference.is_reference(reference):
            return reference

        if (
            string_reference.is_absolute_reference(reference)
            and self.get_root() is None
        ):
            warnings.warn(
                f"No QuamRoot initialized, cannot retrieve reference {reference}"
                f" from {self.__class__.__name__}"
            )
            return reference

        try:
            return string_reference.get_referenced_value(
                self, reference, root=self.get_root()
            )
        except ValueError as e:
            try:
                ref = f"{self.__class__.__name__}: {self.get_reference()}"
            except Exception:
                ref = self.__class__.__name__
            warnings.warn(f"Could not get reference {reference} from {ref}.\n{str(e)}")
            return reference

    def print_summary(self, indent: int = 0):
        """Print a summary of the QuamBase object.

        Args:
            indent: The number of spaces to indent the summary.
        """
        if self.get_root() is self:
            full_name = "QuAM:"
        elif self.parent is None:
            full_name = f"{self.__class__.__name__} (parent unknown):"
        else:
            try:
                attr_name = self.parent.get_attr_name(self)
                full_name = f"{attr_name}: {self.__class__.__name__}"
            except AttributeError:
                full_name = f"{self.__class__.__name__}:"

        if not self.get_attrs():
            print(" " * indent + f"{full_name} Empty")
            return

        print(" " * indent + f"{full_name}")
        for attr, val in self.get_attrs().items():
            if isinstance(val, str):
                val = f'"{val}"'
            if isinstance(val, QuamBase):
                val.print_summary(indent=indent + 2)
            else:
                print(" " * (indent + 2) + f"{attr}: {val}")

    def set_at_reference(
        self, attr: str, value: Any, allow_non_reference: bool = False
    ):
        """Follow the reference of an attribute and set the value at the reference

        Args:
            attr: The attribute to set the value at the reference of.
            value: The value to set.
            allow_non_reference: Whether to allow the attribute to be a non-reference.
                If False, the attribute must be a reference or an error is raised.

        Raises:
            ValueError: If the attribute is not a reference and `allow_non_reference` is
                False.
            ValueError: If the reference is invalid, e.g. "#./" since it has no
                attribute.
        """
        raw_value = self.get_unreferenced_value(attr)
        if not string_reference.is_reference(raw_value):
            if not allow_non_reference:
                raise ValueError(
                    f"Cannot set at reference because attr '{attr}' is not a reference. "
                    f"'{attr}' = {raw_value}"
                )
            else:
                setattr(self, attr, value)
                return

        parent_reference, ref_attr = string_reference.split_reference(raw_value)
        if not ref_attr:
            raise ValueError(
                f"Unsuccessful attempt to set the value at reference {raw_value} for "
                f"attribute {attr} because the reference is invalid as it has no "
                "attribute"
            )

        parent_obj = self._get_referenced_value(parent_reference)
        raw_referenced_value = parent_obj.get_unreferenced_value(ref_attr)
        if string_reference.is_reference(raw_referenced_value) and isinstance(
            parent_obj, QuamBase
        ):
            parent_obj.set_at_reference(ref_attr, value)
        else:
            setattr(parent_obj, ref_attr, value)

_attr_val_is_default(attr, val)

Check whether the value of an attribute is the default value.

Parameters:

Name Type Description Default
attr str

The name of the attribute.

required
val Any

The value of the attribute.

required

Returns:

Type Description
bool

True if the value is the default value, False otherwise.

bool

False is also returned if the parent is not a dataclass

Source code in quam/core/quam_classes.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
def _attr_val_is_default(self, attr: str, val: Any) -> bool:
    """Check whether the value of an attribute is the default value.

    Args:
        attr: The name of the attribute.
        val: The value of the attribute.

    Returns:
        True if the value is the default value, False otherwise.
        False is also returned if the parent is not a dataclass
    """
    if not is_dataclass(self):
        return False

    dataclass_fields = fields(self)
    if not any(field.name == attr for field in dataclass_fields):
        return False

    field = next(field for field in dataclass_fields if field.name == attr)
    if field.default is not MISSING:
        return val == field.default
    elif field.default_factory is not MISSING:
        try:
            default_val = field.default_factory()
            return val == default_val
        except TypeError:
            return False

    return False

_get_attr_names()

Get names of all dataclass attributes of this object.

Returns:

Type Description
List[str]

List of attribute names.

Source code in quam/core/quam_classes.py
260
261
262
263
264
265
266
267
268
269
270
def _get_attr_names(self) -> List[str]:
    """Get names of all dataclass attributes of this object.

    Returns:
        List of attribute names.

    Raises:
        AssertionError if not a dataclass.
    """
    assert is_dataclass(self)
    return [data_field.name for data_field in fields(self)]

_get_referenced_value(reference)

Get the value of an attribute by reference

Parameters:

Name Type Description Default
reference str

The reference to the attribute.

required

Returns:

Type Description
Any

The value of the attribute, or the reference if it is not a reference

Note

This function is used from the ReferenceClass class.

Source code in quam/core/quam_classes.py
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
def _get_referenced_value(self, reference: str) -> Any:
    """Get the value of an attribute by reference

    Args:
        reference: The reference to the attribute.

    Returns:
        The value of the attribute, or the reference if it is not a reference

    Note:
        This function is used from the ReferenceClass class.
    """
    if not string_reference.is_reference(reference):
        return reference

    if (
        string_reference.is_absolute_reference(reference)
        and self.get_root() is None
    ):
        warnings.warn(
            f"No QuamRoot initialized, cannot retrieve reference {reference}"
            f" from {self.__class__.__name__}"
        )
        return reference

    try:
        return string_reference.get_referenced_value(
            self, reference, root=self.get_root()
        )
    except ValueError as e:
        try:
            ref = f"{self.__class__.__name__}: {self.get_reference()}"
        except Exception:
            ref = self.__class__.__name__
        warnings.warn(f"Could not get reference {reference} from {ref}.\n{str(e)}")
        return reference

_is_reference(attr)

Check whether an attribute is a reference.

Parameters:

Name Type Description Default
attr str

The name of the attribute.

required

Returns:

Type Description
bool

True if the attribute is a reference, False otherwise.

Note

This function is used from the ReferenceClass class.

Source code in quam/core/quam_classes.py
535
536
537
538
539
540
541
542
543
544
545
546
547
def _is_reference(self, attr: str) -> bool:
    """Check whether an attribute is a reference.

    Args:
        attr: The name of the attribute.

    Returns:
        True if the attribute is a reference, False otherwise.

    Note:
        This function is used from the ReferenceClass class.
    """
    return string_reference.is_reference(attr)

_val_matches_attr_annotation(attr, val) classmethod

Check whether the type of an attribute matches the annotation.

The attribute type must exactly match the annotation. For dict and list, no additional type check of args is performed.

Source code in quam/core/quam_classes.py
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
@classmethod
def _val_matches_attr_annotation(cls, attr: str, val: Any) -> bool:
    """Check whether the type of an attribute matches the annotation.

    The attribute type must exactly match the annotation.
    For dict and list, no additional type check of args is performed.
    """
    annotated_attrs = get_dataclass_attr_annotations(cls)
    if attr not in annotated_attrs["allowed"]:
        return False

    required_type = annotated_attrs["allowed"][attr]
    if type_is_optional(required_type):
        required_type = get_args(required_type)[0]

    if required_type == dict or get_origin(required_type) == dict:
        return isinstance(val, (dict, QuamDict))
    elif required_type == list or get_origin(required_type) == list:
        return isinstance(val, (list, QuamList))
    return type(val) == required_type

get_attr_name(attr_val)

Get the name of an attribute that matches the value.

Parameters:

Name Type Description Default
attr_val Any

The value of the attribute.

required

Returns:

Type Description
str

The name of the attribute.

Source code in quam/core/quam_classes.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
def get_attr_name(self, attr_val: Any) -> str:
    """Get the name of an attribute that matches the value.

    Args:
        attr_val: The value of the attribute.

    Returns:
        The name of the attribute.

    Raises:
        AttributeError if not found.
    """
    for attr_name in self._get_attr_names():
        if getattr(self, attr_name) is attr_val:
            return attr_name
    else:
        raise AttributeError(
            "Could not find name corresponding to attribute.\n"
            f"attribute: {attr_val}\n"
            f"obj: {self}"
        )

get_attrs(follow_references=False, include_defaults=True)

Get all attributes and corresponding values of this object.

Parameters:

Name Type Description Default
follow_references bool

Whether to follow references when getting the value. If False, the reference will be returned as a string.

False
include_defaults bool

Whether to include attributes that have the default value.

True

Returns:

Type Description
Dict[str, Any]

A dictionary of attribute names and values.

Source code in quam/core/quam_classes.py
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
def get_attrs(
    self, follow_references: bool = False, include_defaults: bool = True
) -> Dict[str, Any]:
    """Get all attributes and corresponding values of this object.

    Args:
        follow_references: Whether to follow references when getting the value.
            If False, the reference will be returned as a string.
        include_defaults: Whether to include attributes that have the default
            value.

    Returns:
        A dictionary of attribute names and values.

    """
    attr_names = self._get_attr_names()

    skip_attrs = getattr(self, "_skip_attrs", [])
    attr_names = [attr for attr in attr_names if attr not in skip_attrs]

    if not follow_references:
        attrs = {attr: self.get_unreferenced_value(attr) for attr in attr_names}
    else:
        attrs = {attr: getattr(self, attr) for attr in attr_names}

    if not include_defaults:
        attrs = {
            attr: val
            for attr, val in attrs.items()
            if not self._attr_val_is_default(attr, val)
        }
    return attrs

get_reference(attr=None, relative_path=None)

Get the reference path of this object.

Parameters:

Name Type Description Default
attr Optional[str]

The optional attribute to get the reference path for. If None, the reference path of the object itself is returned.

None
relative_path Optional[str]

The optional relative path to join with the reference path.

None

Returns:

Type Description
Optional[str]

The reference path of this object.

Examples:

We assume a QuamRoot object with a component "elem". - elem.get_reference() == "#/elem" - elem.get_reference(attr="child") == "#/elem/child" - elem.get_reference(relative_path="#./child") == "#/elem/child" - elem.get_reference(relative_path="#../child") == "#/child" - elem.get_reference(relative_path="#./child/grandchild") == "#/elem/child/grandchild"

Source code in quam/core/quam_classes.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
def get_reference(
    self, attr: Optional[str] = None, relative_path: Optional[str] = None
) -> Optional[str]:
    """Get the reference path of this object.

    Args:
        attr: The optional attribute to get the reference path for.
            If None, the reference path of the object itself is returned.
        relative_path: The optional relative path to join with the reference path.

    Returns:
        The reference path of this object.

    Examples:
        We assume a QuamRoot object with a component "elem".
        - elem.get_reference() == "#/elem"
        - elem.get_reference(attr="child") == "#/elem/child"
        - elem.get_reference(relative_path="#./child") == "#/elem/child"
        - elem.get_reference(relative_path="#../child") == "#/child"
        - elem.get_reference(relative_path="#./child/grandchild") == "#/elem/child/grandchild"
    """

    if attr is not None and relative_path is not None:
        raise ValueError(
            "Cannot specify both attr and relative_path. "
            "Please specify only one of them."
        )

    if self.parent is None:
        raise AttributeError(
            "Unable to extract reference path for {self}: No parent defined"
        )

    try:
        base_reference = self.parent.get_reference()
        if base_reference == "#/":
            base_reference = "#"
    except AttributeError:
        raise AttributeError(
            f"Unable to extract reference path for {self}: Could not get "
            f"reference path for parent {self.parent}"
        )

    try:
        attr_name = self.parent.get_attr_name(self)
    except AttributeError:
        raise AttributeError(
            f"Unable to extract reference path for {self}: Could not get "
            f"attribute name from parent {self.parent}"
        )

    reference = f"{base_reference}/{attr_name}"

    if relative_path is not None:
        if not string_reference.is_reference(relative_path):
            raise ValueError(
                f"Unable to extract reference path for {self}: "
                f"relative_path {relative_path} is not a reference"
            )

        reference = string_reference.join_references(reference, relative_path)
    elif attr is not None:
        reference = f"{reference}/{attr}"

    return reference

get_root()

Get the QuamRoot object of this object.

This function recursively searches the parent chain for a QuamRoot object. If no QuamRoot object is found, it will return the last instantiated QuamRoot if it exists, else None.

Returns:

Type Description
Optional[QuamRoot]

The root of this object, or None if no root is found.

Source code in quam/core/quam_classes.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def get_root(self) -> Optional[QuamRoot]:
    """Get the QuamRoot object of this object.

    This function recursively searches the parent chain for a QuamRoot object.
    If no QuamRoot object is found, it will return the last instantiated QuamRoot
    if it exists, else None.

    Returns:
        The root of this object, or None if no root is found.
    """
    if self.parent is not None:
        return self.parent.get_root()

    if self._last_instantiated_root is not None:
        warnings.warn(
            f"This component is not part of any QuamRoot, using last "
            f"instantiated QuamRoot. This is not recommended as it may lead to "
            f"unexpected behaviour. Component: {self.__class__.__name__}"
        )
        return self._last_instantiated_root
    return None

iterate_components(skip_elems=None)

Iterate over all QuamBase objects in this object, including nested objects.

Parameters:

Name Type Description Default
skip_elems Optional[Sequence['QuamBase']]

A list of QuamBase objects to skip. This is used to prevent infinite loops when iterating over nested objects.

None

Returns:

Type Description
None

A generator of QuamBase objects.

Source code in quam/core/quam_classes.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
def iterate_components(
    self, skip_elems: Optional[Sequence["QuamBase"]] = None
) -> Generator["QuamBase", None, None]:
    """Iterate over all QuamBase objects in this object, including nested objects.

    Args:
        skip_elems: A list of QuamBase objects to skip.
            This is used to prevent infinite loops when iterating over nested
            objects.

    Returns:
        A generator of QuamBase objects.
    """
    if skip_elems is None:
        skip_elems = []

    # We don't use "self in skip_elems" because we want to check for identity,
    # not equality. The reason is that you would otherwise have to instantiate
    # dataclasses using @dataclass(eq=False)
    in_skip_elems = any(self is elem for elem in skip_elems)
    if isinstance(self, QuamComponent) and not in_skip_elems:
        skip_elems.append(self)
        yield self

    attrs = self.get_attrs(follow_references=False, include_defaults=True)

    for attr_val in attrs.values():
        if any(attr_val is elem for elem in skip_elems):
            continue

        if isinstance(attr_val, QuamBase):
            yield from attr_val.iterate_components(skip_elems=skip_elems)

print_summary(indent=0)

Print a summary of the QuamBase object.

Parameters:

Name Type Description Default
indent int

The number of spaces to indent the summary.

0
Source code in quam/core/quam_classes.py
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
def print_summary(self, indent: int = 0):
    """Print a summary of the QuamBase object.

    Args:
        indent: The number of spaces to indent the summary.
    """
    if self.get_root() is self:
        full_name = "QuAM:"
    elif self.parent is None:
        full_name = f"{self.__class__.__name__} (parent unknown):"
    else:
        try:
            attr_name = self.parent.get_attr_name(self)
            full_name = f"{attr_name}: {self.__class__.__name__}"
        except AttributeError:
            full_name = f"{self.__class__.__name__}:"

    if not self.get_attrs():
        print(" " * indent + f"{full_name} Empty")
        return

    print(" " * indent + f"{full_name}")
    for attr, val in self.get_attrs().items():
        if isinstance(val, str):
            val = f'"{val}"'
        if isinstance(val, QuamBase):
            val.print_summary(indent=indent + 2)
        else:
            print(" " * (indent + 2) + f"{attr}: {val}")

set_at_reference(attr, value, allow_non_reference=False)

Follow the reference of an attribute and set the value at the reference

Parameters:

Name Type Description Default
attr str

The attribute to set the value at the reference of.

required
value Any

The value to set.

required
allow_non_reference bool

Whether to allow the attribute to be a non-reference. If False, the attribute must be a reference or an error is raised.

False

Raises:

Type Description
ValueError

If the attribute is not a reference and allow_non_reference is False.

ValueError

If the reference is invalid, e.g. "#./" since it has no attribute.

Source code in quam/core/quam_classes.py
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
def set_at_reference(
    self, attr: str, value: Any, allow_non_reference: bool = False
):
    """Follow the reference of an attribute and set the value at the reference

    Args:
        attr: The attribute to set the value at the reference of.
        value: The value to set.
        allow_non_reference: Whether to allow the attribute to be a non-reference.
            If False, the attribute must be a reference or an error is raised.

    Raises:
        ValueError: If the attribute is not a reference and `allow_non_reference` is
            False.
        ValueError: If the reference is invalid, e.g. "#./" since it has no
            attribute.
    """
    raw_value = self.get_unreferenced_value(attr)
    if not string_reference.is_reference(raw_value):
        if not allow_non_reference:
            raise ValueError(
                f"Cannot set at reference because attr '{attr}' is not a reference. "
                f"'{attr}' = {raw_value}"
            )
        else:
            setattr(self, attr, value)
            return

    parent_reference, ref_attr = string_reference.split_reference(raw_value)
    if not ref_attr:
        raise ValueError(
            f"Unsuccessful attempt to set the value at reference {raw_value} for "
            f"attribute {attr} because the reference is invalid as it has no "
            "attribute"
        )

    parent_obj = self._get_referenced_value(parent_reference)
    raw_referenced_value = parent_obj.get_unreferenced_value(ref_attr)
    if string_reference.is_reference(raw_referenced_value) and isinstance(
        parent_obj, QuamBase
    ):
        parent_obj.set_at_reference(ref_attr, value)
    else:
        setattr(parent_obj, ref_attr, value)

to_dict(follow_references=False, include_defaults=False)

Convert this object to a dictionary.

Parameters:

Name Type Description Default
follow_references bool

Whether to follow references when getting the value. If False, the reference will be returned as a string.

False
include_defaults bool

Whether to include attributes that have the default

False

Returns:

Type Description
Dict[str, Any]

A dictionary representation of this object.

Dict[str, Any]

Any QuamBase objects will be recursively converted to dictionaries.

Note

If the value of an attribute does not match the annotation, the "__class__" key will be added to the dictionary. This is to ensure that the object can be reconstructed when loading from a file.

Source code in quam/core/quam_classes.py
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
def to_dict(
    self, follow_references: bool = False, include_defaults: bool = False
) -> Dict[str, Any]:
    """Convert this object to a dictionary.

    Args:
        follow_references: Whether to follow references when getting the value.
            If False, the reference will be returned as a string.
        include_defaults: Whether to include attributes that have the default

    Returns:
        A dictionary representation of this object.
        Any QuamBase objects will be recursively converted to dictionaries.

    Note:
        If the value of an attribute does not match the annotation, the
        `"__class__"` key will be added to the dictionary. This is to ensure
        that the object can be reconstructed when loading from a file.
    """
    attrs = self.get_attrs(
        follow_references=follow_references, include_defaults=include_defaults
    )
    quam_dict = {}
    for attr, val in attrs.items():
        if isinstance(val, QuamBase):
            quam_dict[attr] = val.to_dict(
                follow_references=follow_references,
                include_defaults=include_defaults,
            )
            val_is_list = isinstance(val, (list, UserList))
            if not self._val_matches_attr_annotation(attr, val) and not val_is_list:
                quam_dict[attr]["__class__"] = get_full_class_path(val)
        else:
            quam_dict[attr] = val
    return quam_dict

QuamComponent

Bases: QuamBase

Base class for any QuAM component class.

Examples of QuamComponent classes are Mixer, LocalOscillator, Pulse, etc.

Note

This class should be subclassed and made a dataclass.

Source code in quam/core/quam_classes.py
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
class QuamComponent(QuamBase):
    """Base class for any QuAM component class.

    Examples of QuamComponent classes are [`Mixer`][quam.components.hardware.Mixer],
    [`LocalOscillator`][quam.components.hardware.LocalOscillator],
    [`Pulse`][quam.components.pulses.Pulse], etc.

    Note:
        This class should be subclassed and made a dataclass.
    """

    def __setattr__(self, name, value):
        converted_val = convert_dict_and_list(value, cls_or_obj=self, attr=name)
        super().__setattr__(name, converted_val)

        if isinstance(converted_val, QuamBase) and name != "parent":
            converted_val.parent = self

    def apply_to_config(self, config: dict) -> None:
        """Add information to the QUA configuration, such as pulses and waveforms.

        Args:
            config: The QUA configuration dictionary. Initially this is a nearly empty
                dictionary, but

        Note:
            This function is called by
            [`QuamRoot.generate_config`][quam.core.quam_classes.QuamRoot.generate_config].

        Note:
            The config has a starting template, defined at [`quam.core.qua_config_template`][]
        """
        ...

apply_to_config(config)

Add information to the QUA configuration, such as pulses and waveforms.

Parameters:

Name Type Description Default
config dict

The QUA configuration dictionary. Initially this is a nearly empty dictionary, but

required
Note

This function is called by QuamRoot.generate_config.

Note

The config has a starting template, defined at quam.core.qua_config_template

Source code in quam/core/quam_classes.py
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
def apply_to_config(self, config: dict) -> None:
    """Add information to the QUA configuration, such as pulses and waveforms.

    Args:
        config: The QUA configuration dictionary. Initially this is a nearly empty
            dictionary, but

    Note:
        This function is called by
        [`QuamRoot.generate_config`][quam.core.quam_classes.QuamRoot.generate_config].

    Note:
        The config has a starting template, defined at [`quam.core.qua_config_template`][]
    """
    ...

QuamDict

Bases: UserDict, QuamBase

A QuAM dictionary class.

Any dict added to a QuamBase object is automatically converted to a QuamDict. The QuamDict adds the following functionalities to a dict: - Values can be references (see below) - Keys can also be accessed through attributes (e.g. d.a instead of d["a"])

QuamDict references

QuamDict values can be references, which are strings that start with #. See the documentation for details on references. An example is shown here:

d = QuamDict({"a": 1, "b": "#./a"})
assert d["b"] == 1

Warning

This class is a subclass of QuamBase, but also of UserDict. As a result, it can be used as a normal dictionary, but it is not a subclass of dict.

Source code in quam/core/quam_classes.py
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
@quam_dataclass
class QuamDict(UserDict, QuamBase):
    """A QuAM dictionary class.

    Any dict added to a `QuamBase` object is automatically converted to a `QuamDict`.
    The `QuamDict` adds the following functionalities to a dict:
    - Values can be references (see below)
    - Keys can also be accessed through attributes (e.g. `d.a` instead of `d["a"]`)

    # QuamDict references
    QuamDict values can be references, which are strings that start with `#`. See the
    documentation for details on references. An example is shown here:
    ```
    d = QuamDict({"a": 1, "b": "#./a"})
    assert d["b"] == 1
    ```

    Warning:
        This class is a subclass of `QuamBase`, but also of `UserDict`. As a result,
        it can be used as a normal dictionary, but it is not a subclass of `dict`.
    """

    _value_annotation: ClassVar[type] = None

    def __init__(self, dict=None, /, value_annotation: type = None, **kwargs):
        self.__dict__["data"] = {}
        self.__dict__["_value_annotation"] = value_annotation
        self.__dict__["_initialized"] = True
        super().__init__(dict, **kwargs)

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError as e:
            try:
                repr = f"{self.__class__.__name__}: {self.get_reference()}"
            except Exception:
                repr = self.__class__.__name__
            raise AttributeError(f'{repr} has no attribute "{key}"') from e

    def __setattr__(self, key, value):
        if key in ["data", "parent", "config_settings", "_initialized"]:
            super().__setattr__(key, value)
        else:
            self[key] = value

    def __getitem__(self, i):
        elem = super().__getitem__(i)
        if string_reference.is_reference(elem):
            try:
                elem = self._get_referenced_value(elem)
            except ValueError as e:
                try:
                    repr = f"{self.__class__.__name__}: {self.get_reference()}"
                except Exception:
                    repr = self.__class__.__name__
                raise KeyError(
                    f"Could not get referenced value {elem} from {repr}"
                ) from e
        return elem

    # Overriding methods from UserDict
    def __setitem__(self, key, value):
        value = convert_dict_and_list(value)
        self._is_valid_setattr(key, value, error_on_False=True)
        super().__setitem__(key, value)

        if isinstance(value, QuamBase):
            value.parent = self

    def __eq__(self, other) -> bool:
        if isinstance(other, dict):
            return self.data == other
        return super().__eq__(other)

    def __repr__(self) -> str:
        with warnings.catch_warnings():
            warnings.filterwarnings(
                "ignore",
                message="^Could not get reference*",
                category=UserWarning,
            )
            return super().__repr__()

    # QuAM methods
    def _get_attr_names(self):
        return list(self.data.keys())

    def get_attrs(
        self, follow_references=False, include_defaults=True
    ) -> Dict[str, Any]:
        # TODO implement reference kwargs
        return self.data

    def get_attr_name(self, attr_val: Any) -> Union[str, int]:
        """Get the name of an attribute that matches the value.

        Args:
            attr_val: The value of the attribute.

        Returns:
            The name of the attribute. This can also be an int depending on the dict key

        Raises:
            AttributeError if not found.
        """
        for attr_name in self._get_attr_names():
            if attr_name in self and self[attr_name] is attr_val:
                return attr_name
        else:
            raise AttributeError(
                "Could not find name corresponding to attribute.\n"
                f"attribute: {attr_val}\n"
                f"obj: {self}"
            )

    def _val_matches_attr_annotation(self, attr: str, val: Any) -> bool:
        """Check whether the type of an attribute matches the annotation.

        Called by [`QuamDict.to_dict`][quam.core.quam_classes.QuamDict.to_dict] to
        determine whether to add the __class__ key.

        Args:
            attr: The name of the attribute. Unused but added to match parent signature
            val: The value of the attribute.

        Note:
            The attribute val is compared to `QuamDict._value_annotation`, which is set
            when a dict is converted to a `QuamDict` using `convert_dict_and_list`.
        """
        if isinstance(val, (QuamDict, QuamList)):
            return True
        if self._value_annotation is None:
            return False
        return type(val) == self._value_annotation

    def _attr_val_is_default(self, attr: str, val: Any):
        """Check whether the value of an attribute is the default value.

        Overrides parent method.
        Since a QuamDict does not have any fixed attrs, this is always False.

        """
        return False

    def get_unreferenced_value(self, attr: str) -> bool:
        """Get the value of an attribute without following references.

        Args:
            attr: The name of the attribute.

        Returns:
            The value of the attribute. If the value is a reference, it returns the
            reference string instead of the value it is referencing.
        """
        try:
            return self.__dict__["data"][attr]
        except KeyError as e:
            raise AttributeError(
                "Cannot get unreferenced value from attribute {attr} that does not"
                " exist in {self}"
            ) from e

    def iterate_components(
        self, skip_elems: Sequence[QuamBase] = None
    ) -> Generator["QuamBase", None, None]:
        """Iterate over all QuamBase objects in this object, including nested objects.

        Args:
            skip_elems: A list of QuamBase objects to skip.
                This is used to prevent infinite loops when iterating over nested
                objects.

        Returns:
            A generator of QuamBase objects.
        """
        if skip_elems is None:
            skip_elems = []

        for attr_val in self.data.values():
            if any(attr_val is elem for elem in skip_elems):
                continue

            if isinstance(attr_val, QuamBase):
                yield from attr_val.iterate_components(skip_elems=skip_elems)

_attr_val_is_default(attr, val)

Check whether the value of an attribute is the default value.

Overrides parent method. Since a QuamDict does not have any fixed attrs, this is always False.

Source code in quam/core/quam_classes.py
 994
 995
 996
 997
 998
 999
1000
1001
def _attr_val_is_default(self, attr: str, val: Any):
    """Check whether the value of an attribute is the default value.

    Overrides parent method.
    Since a QuamDict does not have any fixed attrs, this is always False.

    """
    return False

_val_matches_attr_annotation(attr, val)

Check whether the type of an attribute matches the annotation.

Called by QuamDict.to_dict to determine whether to add the class key.

Parameters:

Name Type Description Default
attr str

The name of the attribute. Unused but added to match parent signature

required
val Any

The value of the attribute.

required
Note

The attribute val is compared to QuamDict._value_annotation, which is set when a dict is converted to a QuamDict using convert_dict_and_list.

Source code in quam/core/quam_classes.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
def _val_matches_attr_annotation(self, attr: str, val: Any) -> bool:
    """Check whether the type of an attribute matches the annotation.

    Called by [`QuamDict.to_dict`][quam.core.quam_classes.QuamDict.to_dict] to
    determine whether to add the __class__ key.

    Args:
        attr: The name of the attribute. Unused but added to match parent signature
        val: The value of the attribute.

    Note:
        The attribute val is compared to `QuamDict._value_annotation`, which is set
        when a dict is converted to a `QuamDict` using `convert_dict_and_list`.
    """
    if isinstance(val, (QuamDict, QuamList)):
        return True
    if self._value_annotation is None:
        return False
    return type(val) == self._value_annotation

get_attr_name(attr_val)

Get the name of an attribute that matches the value.

Parameters:

Name Type Description Default
attr_val Any

The value of the attribute.

required

Returns:

Type Description
Union[str, int]

The name of the attribute. This can also be an int depending on the dict key

Source code in quam/core/quam_classes.py
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def get_attr_name(self, attr_val: Any) -> Union[str, int]:
    """Get the name of an attribute that matches the value.

    Args:
        attr_val: The value of the attribute.

    Returns:
        The name of the attribute. This can also be an int depending on the dict key

    Raises:
        AttributeError if not found.
    """
    for attr_name in self._get_attr_names():
        if attr_name in self and self[attr_name] is attr_val:
            return attr_name
    else:
        raise AttributeError(
            "Could not find name corresponding to attribute.\n"
            f"attribute: {attr_val}\n"
            f"obj: {self}"
        )

get_unreferenced_value(attr)

Get the value of an attribute without following references.

Parameters:

Name Type Description Default
attr str

The name of the attribute.

required

Returns:

Type Description
bool

The value of the attribute. If the value is a reference, it returns the

bool

reference string instead of the value it is referencing.

Source code in quam/core/quam_classes.py
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
def get_unreferenced_value(self, attr: str) -> bool:
    """Get the value of an attribute without following references.

    Args:
        attr: The name of the attribute.

    Returns:
        The value of the attribute. If the value is a reference, it returns the
        reference string instead of the value it is referencing.
    """
    try:
        return self.__dict__["data"][attr]
    except KeyError as e:
        raise AttributeError(
            "Cannot get unreferenced value from attribute {attr} that does not"
            " exist in {self}"
        ) from e

iterate_components(skip_elems=None)

Iterate over all QuamBase objects in this object, including nested objects.

Parameters:

Name Type Description Default
skip_elems Sequence[QuamBase]

A list of QuamBase objects to skip. This is used to prevent infinite loops when iterating over nested objects.

None

Returns:

Type Description
None

A generator of QuamBase objects.

Source code in quam/core/quam_classes.py
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
def iterate_components(
    self, skip_elems: Sequence[QuamBase] = None
) -> Generator["QuamBase", None, None]:
    """Iterate over all QuamBase objects in this object, including nested objects.

    Args:
        skip_elems: A list of QuamBase objects to skip.
            This is used to prevent infinite loops when iterating over nested
            objects.

    Returns:
        A generator of QuamBase objects.
    """
    if skip_elems is None:
        skip_elems = []

    for attr_val in self.data.values():
        if any(attr_val is elem for elem in skip_elems):
            continue

        if isinstance(attr_val, QuamBase):
            yield from attr_val.iterate_components(skip_elems=skip_elems)

QuamList

Bases: UserList, QuamBase

A QuAM list class.

Any list added to a QuamBase object is automatically converted to a QuamList. The QuamList adds the following functionalities to a list: - Elements can be references (see below)

QuamList references

QuamList values can be references, which are strings that start with #. See the documentation for details on references. An example is shown here:

d = QuamList([1, "#./0"]])
assert d[1] == 1

Warning

This class is a subclass of QuamBase, but also of UserList. As a result, it can be used as a normal list, but it is not a subclass of list.

Source code in quam/core/quam_classes.py
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
@quam_dataclass
class QuamList(UserList, QuamBase):
    """A QuAM list class.

    Any list added to a `QuamBase` object is automatically converted to a `QuamList`.
    The `QuamList` adds the following functionalities to a list:
    - Elements can be references (see below)

    # QuamList references
    QuamList values can be references, which are strings that start with `#`. See the
    documentation for details on references. An example is shown here:
    ```
    d = QuamList([1, "#./0"]])
    assert d[1] == 1
    ```

    Warning:
        This class is a subclass of `QuamBase`, but also of `UserList`. As a result,
        it can be used as a normal list, but it is not a subclass of `list`.
    """

    _value_annotation: ClassVar[type] = None

    def __init__(self, *args, value_annotation: type = None):
        self._value_annotation = value_annotation

        # We manually add elements using extend instead of passing to super()
        # To ensure that any dicts and lists get converted to QuamDict and QuamList
        super().__init__()
        if args:
            self.extend(*args)

    # Overloading methods from UserList
    def __eq__(self, value: object) -> bool:
        return super().__eq__(value)

    def __repr__(self) -> str:
        with warnings.catch_warnings():
            warnings.filterwarnings(
                "ignore",
                message="^Could not get reference*",
                category=UserWarning,
            )
            return super().__repr__()

    def __getitem__(self, i):
        elem = super().__getitem__(i)
        if isinstance(i, slice):
            if isinstance(elem, QuamList):
                elem.parent = self.parent
            # This automatically gets the referenced values
            return list(elem)

        if string_reference.is_reference(elem):
            elem = self._get_referenced_value(elem)
        return elem

    def __setitem__(self, i, item):
        converted_item = convert_dict_and_list(item)
        super().__setitem__(i, converted_item)

        if isinstance(converted_item, QuamBase):
            converted_item.parent = self

    def __iadd__(self, other: Iterable):
        converted_other = [convert_dict_and_list(elem) for elem in other]
        return super().__iadd__(converted_other)

    def append(self, item: Any) -> None:
        converted_item = convert_dict_and_list(item)

        if isinstance(converted_item, QuamBase):
            converted_item.parent = self

        return super().append(converted_item)

    def insert(self, i: int, item: Any) -> None:
        converted_item = convert_dict_and_list(item)

        if isinstance(converted_item, QuamBase):
            converted_item.parent = self

        return super().insert(i, converted_item)

    def extend(self, iterable: Iterator) -> None:
        converted_iterable = [convert_dict_and_list(elem) for elem in iterable]
        for converted_item in converted_iterable:
            if isinstance(converted_item, QuamBase):
                converted_item.parent = self

        return super().extend(converted_iterable)

    # Quam methods
    def _val_matches_attr_annotation(self, attr: str, val: Any) -> bool:
        """Check whether the type of an attribute matches the annotation.

        Called by QuamList.to_dict to determine whether to add the __class__ key.
        For the QuamList, we compare the type to the _value_annotation.
        """
        if isinstance(val, (QuamDict, QuamList)):
            return True
        if self._value_annotation is None:
            return False
        return type(val) == self._value_annotation

    def get_attr_name(self, attr_val: Any) -> str:
        for k, elem in enumerate(self.data):
            if elem is attr_val:
                return str(k)
        else:
            raise AttributeError(
                "Could not find name corresponding to attribute"
                f"attribute: {attr_val}\n"
                f"obj: {self}"
            )

    def to_dict(
        self, follow_references: bool = False, include_defaults: bool = False
    ) -> list:
        """Convert this object to a list, usually as part of a dictionary representation.

        Args:
            follow_references: Whether to follow references when getting the value.
                If False, the reference will be returned as a string.
            include_defaults: Whether to include attributes that have the default
                value.

        Returns:
            A list with the values of this object. Any QuamBase objects will be
            recursively converted to dictionaries.

        Note:
            If the value of an attribute does not match the annotation of
            `QuamList._value_annotation`, the `"__class__"` key will be added to the
            dictionary. This is to ensure that the object can be reconstructed when
            loading from a file.
        """
        quam_list = []
        for val in self.data:
            if isinstance(val, QuamBase):
                quam_list.append(
                    val.to_dict(
                        follow_references=follow_references,
                        include_defaults=include_defaults,
                    )
                )
                if not self._val_matches_attr_annotation(val=val, attr=None):
                    quam_list[-1]["__class__"] = get_full_class_path(val)
            else:
                quam_list.append(val)
        return quam_list

    def iterate_components(
        self, skip_elems: List[QuamBase] = None
    ) -> Generator["QuamBase", None, None]:
        """Iterate over all QuamBase objects in this object, including nested objects.

        Args:
            skip_elems: A list of QuamBase objects to skip.
                This is used to prevent infinite loops when iterating over nested
                objects.

        Returns:
            A generator of QuamBase objects.
        """
        if skip_elems is None:
            skip_elems = []

        for attr_val in self.data:
            if any(attr_val is elem for elem in skip_elems):
                continue

            if isinstance(attr_val, QuamBase):
                yield from attr_val.iterate_components(skip_elems=skip_elems)

    def get_attrs(
        self, follow_references: bool = False, include_defaults: bool = True
    ) -> Dict[str, Any]:
        raise NotImplementedError("QuamList does not have attributes")

    def print_summary(self, indent: int = 0):
        """Print a summary of the QuamBase object.

        Args:
            indent: The number of spaces to indent the summary.
        """

        if self.parent is None:
            full_name = f"{self.__class__.__name__} (parent unknown):"
        else:
            try:
                attr_name = self.parent.get_attr_name(self)
                full_name = f"{attr_name}: {self.__class__.__name__}"
            except AttributeError:
                full_name = f"{self.__class__.__name__}:"

        if not self.data:
            print(" " * indent + f"{full_name} = []")
            return

        print(" " * indent + f"{full_name}:")
        if len(str(self.data)) + 2 * indent < 80:
            print(" " * (indent + 2) + f"{self.data}")
        else:
            for k, val in enumerate(self.data):
                if isinstance(val, QuamBase):
                    val.print_summary(indent=indent + 2)
                else:
                    print(" " * (indent + 2) + f"{k}: {val}")

_val_matches_attr_annotation(attr, val)

Check whether the type of an attribute matches the annotation.

Called by QuamList.to_dict to determine whether to add the class key. For the QuamList, we compare the type to the _value_annotation.

Source code in quam/core/quam_classes.py
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
def _val_matches_attr_annotation(self, attr: str, val: Any) -> bool:
    """Check whether the type of an attribute matches the annotation.

    Called by QuamList.to_dict to determine whether to add the __class__ key.
    For the QuamList, we compare the type to the _value_annotation.
    """
    if isinstance(val, (QuamDict, QuamList)):
        return True
    if self._value_annotation is None:
        return False
    return type(val) == self._value_annotation

iterate_components(skip_elems=None)

Iterate over all QuamBase objects in this object, including nested objects.

Parameters:

Name Type Description Default
skip_elems List[QuamBase]

A list of QuamBase objects to skip. This is used to prevent infinite loops when iterating over nested objects.

None

Returns:

Type Description
None

A generator of QuamBase objects.

Source code in quam/core/quam_classes.py
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
def iterate_components(
    self, skip_elems: List[QuamBase] = None
) -> Generator["QuamBase", None, None]:
    """Iterate over all QuamBase objects in this object, including nested objects.

    Args:
        skip_elems: A list of QuamBase objects to skip.
            This is used to prevent infinite loops when iterating over nested
            objects.

    Returns:
        A generator of QuamBase objects.
    """
    if skip_elems is None:
        skip_elems = []

    for attr_val in self.data:
        if any(attr_val is elem for elem in skip_elems):
            continue

        if isinstance(attr_val, QuamBase):
            yield from attr_val.iterate_components(skip_elems=skip_elems)

print_summary(indent=0)

Print a summary of the QuamBase object.

Parameters:

Name Type Description Default
indent int

The number of spaces to indent the summary.

0
Source code in quam/core/quam_classes.py
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
def print_summary(self, indent: int = 0):
    """Print a summary of the QuamBase object.

    Args:
        indent: The number of spaces to indent the summary.
    """

    if self.parent is None:
        full_name = f"{self.__class__.__name__} (parent unknown):"
    else:
        try:
            attr_name = self.parent.get_attr_name(self)
            full_name = f"{attr_name}: {self.__class__.__name__}"
        except AttributeError:
            full_name = f"{self.__class__.__name__}:"

    if not self.data:
        print(" " * indent + f"{full_name} = []")
        return

    print(" " * indent + f"{full_name}:")
    if len(str(self.data)) + 2 * indent < 80:
        print(" " * (indent + 2) + f"{self.data}")
    else:
        for k, val in enumerate(self.data):
            if isinstance(val, QuamBase):
                val.print_summary(indent=indent + 2)
            else:
                print(" " * (indent + 2) + f"{k}: {val}")

to_dict(follow_references=False, include_defaults=False)

Convert this object to a list, usually as part of a dictionary representation.

Parameters:

Name Type Description Default
follow_references bool

Whether to follow references when getting the value. If False, the reference will be returned as a string.

False
include_defaults bool

Whether to include attributes that have the default value.

False

Returns:

Type Description
list

A list with the values of this object. Any QuamBase objects will be

list

recursively converted to dictionaries.

Note

If the value of an attribute does not match the annotation of QuamList._value_annotation, the "__class__" key will be added to the dictionary. This is to ensure that the object can be reconstructed when loading from a file.

Source code in quam/core/quam_classes.py
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
def to_dict(
    self, follow_references: bool = False, include_defaults: bool = False
) -> list:
    """Convert this object to a list, usually as part of a dictionary representation.

    Args:
        follow_references: Whether to follow references when getting the value.
            If False, the reference will be returned as a string.
        include_defaults: Whether to include attributes that have the default
            value.

    Returns:
        A list with the values of this object. Any QuamBase objects will be
        recursively converted to dictionaries.

    Note:
        If the value of an attribute does not match the annotation of
        `QuamList._value_annotation`, the `"__class__"` key will be added to the
        dictionary. This is to ensure that the object can be reconstructed when
        loading from a file.
    """
    quam_list = []
    for val in self.data:
        if isinstance(val, QuamBase):
            quam_list.append(
                val.to_dict(
                    follow_references=follow_references,
                    include_defaults=include_defaults,
                )
            )
            if not self._val_matches_attr_annotation(val=val, attr=None):
                quam_list[-1]["__class__"] = get_full_class_path(val)
        else:
            quam_list.append(val)
    return quam_list

QuamRoot

Bases: QuamBase

Base class for the root of a QuAM object.

This class should be subclassed and made a dataclass.

Parameters:

Name Type Description Default
serialiser

The serialiser class to use for saving and loading. The default is to use the JSONSerialiser, but this can be changed.

required
Note

This class should not be used directly, but should generally be subclassed and made a dataclass. The dataclass fields should correspond to the QuAM root structure.

Source code in quam/core/quam_classes.py
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
class QuamRoot(QuamBase):
    """Base class for the root of a QuAM object.

    This class should be subclassed and made a dataclass.

    Args:
        serialiser: The serialiser class to use for saving and loading.
            The default is to use the `JSONSerialiser`, but this can be changed.

    Note:
        This class should not be used directly, but should generally be subclassed and
        made a dataclass. The dataclass fields should correspond to the QuAM root
        structure.
    """

    serialiser: AbstractSerialiser = JSONSerialiser

    def __post_init__(self):
        if QuamBase._last_instantiated_root is not None:
            warnings.warn(
                "Multiple QuamRoot objects were instantiated. Any QuAM component will be "
                "attached to its specific QuamRoot object. Mixing QuAM components belonging "
                "to different QuamRoot objects is not recommended as it may lead to "
                "unexpected results."
            )
        QuamBase._last_instantiated_root = self
        super().__post_init__()

    def __setattr__(self, name, value):
        converted_val = convert_dict_and_list(value, cls_or_obj=self, attr=name)
        super().__setattr__(name, converted_val)

        if isinstance(converted_val, QuamBase) and name != "parent":
            converted_val.parent = self

    def get_reference(
        self, attr: Optional[str] = None, relative_path: Optional[str] = None
    ) -> Optional[str]:
        if attr is not None:
            return f"#/{attr}"

        reference = "#/"
        if relative_path is not None:
            reference = string_reference.join_references(reference, relative_path)
        return reference

    def get_root(self: QuamRootType) -> QuamRootType:
        """Get the QuamRoot object of this object, i.e. the object itself.

        This QuamRoot function overrides the QuamBase function to return the object
        itself, rather than following the parent chain.

        Returns:
            The current QuamRoot object (self).
        """
        return self

    def save(
        self,
        path: Union[Path, str] = None,
        content_mapping: Dict[str, str] = None,
        include_defaults: bool = False,
        ignore: Sequence[str] = None,
    ):
        """Save the entire QuamRoot object to a file. This includes nested objects.

        Args:
            path: The path to save the file to. If None, the path will be saved to
                `state.json`.
            content_mapping: A dictionary of paths to save to and a list of attributes
                to save to that path. This can be used to save different parts of the
                QuamRoot object to different files.
            include_defaults: Whether to include attributes that have the default
                value.
            ignore: A list of attributes to ignore.
        """
        serialiser = self.serialiser()
        serialiser.save(
            quam_obj=self,
            path=path,
            content_mapping=content_mapping,
            include_defaults=include_defaults,
            ignore=ignore,
        )

    def to_dict(
        self, follow_references: bool = False, include_defaults: bool = False
    ) -> Dict[str, Any]:
        """Convert this object to a dictionary.

        Args:
            follow_references: Whether to follow references when getting the value.
                If False, the reference will be returned as a string.
            include_defaults: Whether to include attributes that have the default
                value.
        """
        quam_dict = super().to_dict(follow_references, include_defaults)
        # QuamRoot should always add __class__ because it is generally not
        # quam.components.quam.QuAM
        quam_dict["__class__"] = get_full_class_path(self)
        return quam_dict

    @classmethod
    def load(
        cls: QuamRootType,
        filepath_or_dict: Union[str, Path, dict],
        validate_type: bool = True,
        fix_attrs: bool = True,
    ) -> QuamRootType:
        """Load a QuamRoot object from a file.

        Args:
            filepath_or_dict: The path to the file/folder to load, or a dictionary.
                The dictionary would be the result from a call to `QuamRoot.save()`
            validate_type: Whether to validate the type of all attributes while loading.
            fix_attrs: Whether attributes can be added to QuamBase objects that are not
                defined as dataclass fields.

        Returns:
            A QuamRoot object instantiated from the file/folder/dict.
        """
        if isinstance(filepath_or_dict, dict):
            contents = filepath_or_dict
        else:
            serialiser = cls.serialiser()
            contents, _ = serialiser.load(filepath_or_dict)

        return instantiate_quam_class(
            quam_class=cls,
            contents=contents,
            fix_attrs=fix_attrs,
            validate_type=validate_type,
        )

    def generate_config(self) -> DictQuaConfig:
        """Generate the QUA configuration from the QuAM object.

        Returns:
            A dictionary with the QUA configuration.

        Note:
            This function collects all the nested QuamComponent objects and calls
            `QuamComponent.apply_to_config` on them.
        """
        qua_config = deepcopy(qua_config_template)

        quam_components = list(self.iterate_components())
        sorted_components = sort_quam_components(quam_components)

        for quam_component in sorted_components:
            quam_component.apply_to_config(qua_config)

        generate_config_final_actions(qua_config)

        return qua_config

generate_config()

Generate the QUA configuration from the QuAM object.

Returns:

Type Description
DictQuaConfig

A dictionary with the QUA configuration.

Note

This function collects all the nested QuamComponent objects and calls QuamComponent.apply_to_config on them.

Source code in quam/core/quam_classes.py
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
def generate_config(self) -> DictQuaConfig:
    """Generate the QUA configuration from the QuAM object.

    Returns:
        A dictionary with the QUA configuration.

    Note:
        This function collects all the nested QuamComponent objects and calls
        `QuamComponent.apply_to_config` on them.
    """
    qua_config = deepcopy(qua_config_template)

    quam_components = list(self.iterate_components())
    sorted_components = sort_quam_components(quam_components)

    for quam_component in sorted_components:
        quam_component.apply_to_config(qua_config)

    generate_config_final_actions(qua_config)

    return qua_config

get_root()

Get the QuamRoot object of this object, i.e. the object itself.

This QuamRoot function overrides the QuamBase function to return the object itself, rather than following the parent chain.

Returns:

Type Description
QuamRootType

The current QuamRoot object (self).

Source code in quam/core/quam_classes.py
712
713
714
715
716
717
718
719
720
721
def get_root(self: QuamRootType) -> QuamRootType:
    """Get the QuamRoot object of this object, i.e. the object itself.

    This QuamRoot function overrides the QuamBase function to return the object
    itself, rather than following the parent chain.

    Returns:
        The current QuamRoot object (self).
    """
    return self

load(filepath_or_dict, validate_type=True, fix_attrs=True) classmethod

Load a QuamRoot object from a file.

Parameters:

Name Type Description Default
filepath_or_dict Union[str, Path, dict]

The path to the file/folder to load, or a dictionary. The dictionary would be the result from a call to QuamRoot.save()

required
validate_type bool

Whether to validate the type of all attributes while loading.

True
fix_attrs bool

Whether attributes can be added to QuamBase objects that are not defined as dataclass fields.

True

Returns:

Type Description
QuamRootType

A QuamRoot object instantiated from the file/folder/dict.

Source code in quam/core/quam_classes.py
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
@classmethod
def load(
    cls: QuamRootType,
    filepath_or_dict: Union[str, Path, dict],
    validate_type: bool = True,
    fix_attrs: bool = True,
) -> QuamRootType:
    """Load a QuamRoot object from a file.

    Args:
        filepath_or_dict: The path to the file/folder to load, or a dictionary.
            The dictionary would be the result from a call to `QuamRoot.save()`
        validate_type: Whether to validate the type of all attributes while loading.
        fix_attrs: Whether attributes can be added to QuamBase objects that are not
            defined as dataclass fields.

    Returns:
        A QuamRoot object instantiated from the file/folder/dict.
    """
    if isinstance(filepath_or_dict, dict):
        contents = filepath_or_dict
    else:
        serialiser = cls.serialiser()
        contents, _ = serialiser.load(filepath_or_dict)

    return instantiate_quam_class(
        quam_class=cls,
        contents=contents,
        fix_attrs=fix_attrs,
        validate_type=validate_type,
    )

save(path=None, content_mapping=None, include_defaults=False, ignore=None)

Save the entire QuamRoot object to a file. This includes nested objects.

Parameters:

Name Type Description Default
path Union[Path, str]

The path to save the file to. If None, the path will be saved to state.json.

None
content_mapping Dict[str, str]

A dictionary of paths to save to and a list of attributes to save to that path. This can be used to save different parts of the QuamRoot object to different files.

None
include_defaults bool

Whether to include attributes that have the default value.

False
ignore Sequence[str]

A list of attributes to ignore.

None
Source code in quam/core/quam_classes.py
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
def save(
    self,
    path: Union[Path, str] = None,
    content_mapping: Dict[str, str] = None,
    include_defaults: bool = False,
    ignore: Sequence[str] = None,
):
    """Save the entire QuamRoot object to a file. This includes nested objects.

    Args:
        path: The path to save the file to. If None, the path will be saved to
            `state.json`.
        content_mapping: A dictionary of paths to save to and a list of attributes
            to save to that path. This can be used to save different parts of the
            QuamRoot object to different files.
        include_defaults: Whether to include attributes that have the default
            value.
        ignore: A list of attributes to ignore.
    """
    serialiser = self.serialiser()
    serialiser.save(
        quam_obj=self,
        path=path,
        content_mapping=content_mapping,
        include_defaults=include_defaults,
        ignore=ignore,
    )

to_dict(follow_references=False, include_defaults=False)

Convert this object to a dictionary.

Parameters:

Name Type Description Default
follow_references bool

Whether to follow references when getting the value. If False, the reference will be returned as a string.

False
include_defaults bool

Whether to include attributes that have the default value.

False
Source code in quam/core/quam_classes.py
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
def to_dict(
    self, follow_references: bool = False, include_defaults: bool = False
) -> Dict[str, Any]:
    """Convert this object to a dictionary.

    Args:
        follow_references: Whether to follow references when getting the value.
            If False, the reference will be returned as a string.
        include_defaults: Whether to include attributes that have the default
            value.
    """
    quam_dict = super().to_dict(follow_references, include_defaults)
    # QuamRoot should always add __class__ because it is generally not
    # quam.components.quam.QuAM
    quam_dict["__class__"] = get_full_class_path(self)
    return quam_dict

_get_value_annotation(cls_or_obj, attr)

Get the type annotation for the values in a QuamDict or QuamList.

If the QuamDict is defined as Dict[str, int], this will return int. If the QuamList is defined as List[int], this will return int. In all other cases, this will return None.

Source code in quam/core/quam_classes.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def _get_value_annotation(cls_or_obj: Union[type, object], attr: str) -> type:
    """Get the type annotation for the values in a QuamDict or QuamList.

    If the QuamDict is defined as Dict[str, int], this will return int.
    If the QuamList is defined as List[int], this will return int.
    In all other cases, this will return None.
    """
    if cls_or_obj is None or attr is None:
        return None

    cls = cls_or_obj if isinstance(cls_or_obj, type) else cls_or_obj.__class__

    annotated_attrs = get_type_hints(cls)
    if attr not in annotated_attrs:
        return None

    attr_annotation = annotated_attrs[attr]
    if get_origin(attr_annotation) == dict:
        return get_args(attr_annotation)[1]
    elif get_origin(attr_annotation) == list:
        return get_args(attr_annotation)[0]
    return None

_quam_dataclass(cls=None, **kwargs)

Dataclass for QuAM classes.

This class is used as a patch to maintain compatibility with Python 3.9, as these do not support the dataclass argument kw_only. This argument is needed to ensure inheritance of parent dataclasses is allowed.

Args: - cls: The QuAM class to decorate. - kwargs: The arguments to pass to the dataclass decorator. By default, kw_only=True and eq=False are passed, though they can be overwritten. Notes: - This custom dataclass is no longer necessary once Python 3.9 support is dropped - The actual custom dataclass is quam_dataclass (without the underscore). This function is only used to trick type checkers into recognizing it as a dataclass. - From Python 3.10 onwards, this customized dataclass is no longer needed, as then the following two decorators are equivalent: - @quam_dataclass - @dataclass(eq=False, kw_only=True)

Source code in quam/core/quam_classes.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def _quam_dataclass(cls=None, **kwargs):
    """Dataclass for QuAM classes.

    This class is used as a patch to maintain compatibility with Python 3.9, as
    these do not support the dataclass argument `kw_only`. This argument is needed to
    ensure inheritance of parent dataclasses is allowed.

    Args:
    - cls: The QuAM class to decorate.
    - kwargs: The arguments to pass to the dataclass decorator.
      By default, kw_only=True and eq=False are passed, though they can be overwritten.
    Notes:
    - This custom dataclass is no longer necessary once Python 3.9 support is dropped
    - The actual custom dataclass is `quam_dataclass` (without the underscore). This
      function is only used to trick type checkers into recognizing it as a dataclass.
    - From Python 3.10 onwards, this customized dataclass is no longer needed, as then
      the following two decorators are equivalent:
      - @quam_dataclass
      - @dataclass(eq=False, kw_only=True)
    """
    if cls is None:
        return partial(_quam_dataclass, **kwargs)

    kwargs.setdefault("kw_only", True)
    kwargs.setdefault("eq", False)

    if sys.version_info.minor > 9:
        return dataclass(cls, **kwargs)

    from quam.utils.dataclass import _quam_patched_dataclass

    return _quam_patched_dataclass(cls, **kwargs)

convert_dict_and_list(value, cls_or_obj=None, attr=None)

Convert a dict or list to a QuamDict or QuamList if possible.

Source code in quam/core/quam_classes.py
75
76
77
78
79
80
81
82
83
84
def convert_dict_and_list(value, cls_or_obj=None, attr=None):
    """Convert a dict or list to a QuamDict or QuamList if possible."""
    if isinstance(value, dict):
        value_annotation = _get_value_annotation(cls_or_obj=cls_or_obj, attr=attr)
        return QuamDict(value, value_annotation=value_annotation)
    elif type(value) == list:
        value_annotation = _get_value_annotation(cls_or_obj=cls_or_obj, attr=attr)
        return QuamList(value, value_annotation=value_annotation)
    else:
        return value

sort_quam_components(components, max_attempts=5)

Sort QuamComponent objects based on their config_settings.

Parameters:

Name Type Description Default
components List['QuamComponent']

A list of QuamComponent objects.

required
max_attempts

The maximum number of attempts to sort the components. If the components aren't yet properly sorted after all these attempts, a warning is raised and the components are returned in the final attempted ordering.

5

Returns:

Type Description
List['QuamComponent']

A sorted list of QuamComponent objects.

Note

This function is used by QuamRoot.generate_config to determine the order in which to add the components to the QUA config. This sorting isn't guaranteed to be successful.

Source code in quam/core/quam_classes.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def sort_quam_components(
    components: List["QuamComponent"], max_attempts=5
) -> List["QuamComponent"]:
    """Sort QuamComponent objects based on their config_settings.

    Args:
        components: A list of QuamComponent objects.
        max_attempts: The maximum number of attempts to sort the components.
            If the components aren't yet properly sorted after all these attempts,
            a warning is raised and the components are returned in the final attempted
            ordering.

    Returns:
        A sorted list of QuamComponent objects.

    Note:
        This function is used by
        [`QuamRoot.generate_config`][quam.core.quam_classes.QuamRoot.generate_config]
        to determine the order in which to add the components to the QUA config.
        This sorting isn't guaranteed to be successful.
    """
    sorted_components = components.copy()
    for _ in range(max_attempts):
        adjustments_made = False

        for component in components:
            if component.config_settings is None:
                continue

            component_idx = sorted_components.index(component)

            if "after" in component.config_settings:
                for after_component in component.config_settings["after"]:
                    after_component_idx = sorted_components.index(after_component)
                    if after_component_idx < component_idx:
                        continue
                    sorted_components.remove(after_component)
                    sorted_components.insert(component_idx, after_component)
                    adjustments_made = True

            if "before" in component.config_settings:
                for before_component in component.config_settings["before"]:
                    before_component_idx = sorted_components.index(before_component)
                    if before_component_idx > component_idx:
                        continue
                    sorted_components.remove(before_component)
                    sorted_components.insert(component_idx + 1, before_component)
                    adjustments_made = True

        if not adjustments_made:
            break
    else:
        warnings.warn(
            "Unable to sort QuamComponents based on config_settings. "
            "This may cause issues when generating the QUA config."
        )

    return sorted_components