Skip to content

QuAM Classes API

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
_root

The QuamRoot object. This is automatically set when instantiating a QuamRoot 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
222
223
224
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
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.
        _root: The QuamRoot object. This is automatically set when instantiating
            a QuamRoot 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()
    _root: ClassVar["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_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=None) -> Optional[str]:
        """Get the reference path of this object.

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

        Returns:
            The reference path of this object.
        """

        if self.parent is None:
            raise AttributeError(
                "Unable to extract reference path. Parent must be defined for {self}"
            )
        reference = f"{self.parent.get_reference()}/{self.parent.get_attr_name(self)}"
        if 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: bool = 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._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._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._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}")

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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
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
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
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)

Get the reference path of this object.

Parameters:

Name Type Description Default
attr

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

None

Returns:

Type Description
Optional[str]

The reference path of this object.

Source code in quam/core/quam_classes.py
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
def get_reference(self, attr=None) -> Optional[str]:
    """Get the reference path of this object.

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

    Returns:
        The reference path of this object.
    """

    if self.parent is None:
        raise AttributeError(
            "Unable to extract reference path. Parent must be defined for {self}"
        )
    reference = f"{self.parent.get_reference()}/{self.parent.get_attr_name(self)}"
    if attr is not None:
        reference = f"{reference}/{attr}"
    return reference

iterate_components(skip_elems=None)

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

Parameters:

Name Type Description Default
skip_elems bool

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

None

Returns:

Type Description
Generator[QuamBase, None, None]

A generator of QuamBase objects.

Source code in quam/core/quam_classes.py
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
def iterate_components(
    self, skip_elems: bool = 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
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
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._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}")

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
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
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

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.

Note

Upon instantiating a QuamRoot object, it sets the class attribute QuamBase._root to itself. This is used such that any references with an absolute path are resolved from the root.

Source code in quam/core/quam_classes.py
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
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.

    Note:
        Upon instantiating a `QuamRoot` object, it sets the class attribute
        `QuamBase._root` to itself. This is used such that any references with an
        absolute path are resolved from the root.
    """

    serialiser: AbstractSerialiser = JSONSerialiser

    def __post_init__(self):
        QuamBase._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):
        return "#"

    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) -> Dict[str, Any]:
        """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

    def get_unreferenced_value(self, attr: str):
        return getattr(self, attr)

generate_config()

Generate the QUA configuration from the QuAM object.

Returns:

Type Description
Dict[str, Any]

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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
def generate_config(self) -> Dict[str, Any]:
    """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

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
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
660
661
@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
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
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
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

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
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
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
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
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
821
822
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
856
857
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
@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)

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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
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
Generator[QuamBase, None, None]

A generator of QuamBase objects.

Source code in quam/core/quam_classes.py
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
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
 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
1043
1044
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
@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):
            # 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}")

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
Generator[QuamBase, None, None]

A generator of QuamBase objects.

Source code in quam/core/quam_classes.py
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
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
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
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
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
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