SettingNode#
Module: exa.common.data.setting_node
- class SettingNode(name, settings=None, subtrees=None, *, path='', align_name=True, generate_paths=None)#
Bases:
BaseModelA tree-structured
Settingcontainer.Each child of the node is a
Setting, or anotherSettingNode. Iterating over the node returns all children, recursively. Settings can be accessed by dictionary syntax or attribute syntax:>>> from exa.common.data.parameter import Parameter >>> from exa.common.data.setting_node import SettingNode >>> p1 = Parameter("voltage", "Voltage") >>> f1 = Parameter("frequency", "Frequency") >>> sub = SettingNode("sub", frequency=f1) >>> settings = SettingNode('name', voltage=p1) >>> settings.voltage.parameter is p1 True >>> settings['voltage'].parameter is p1 True >>> settings.voltage.value is None True >>> settings.voltage = 7 # updates to Setting(p1, 7) >>> settings.voltage.value 7 >>> settings["sub.frequency"] = 8 >>> settings["sub.frequency"].value 8
- Parameters:
name (str) – Name of the node.
settings (dict[str, Any] | None) – Dict of setting path fraqment names (usually the same as the setting name) to the settings. Mostly used when deserialising and otherwise left empty.
subtrees (dict[str, Any] | None) – Dict of child node path fraqment names (usually the same as the child node name) to the settings. Mostly used when deserialising and otherwise left empty.
path (str) – Optionally give a path for the node, by default empty.
align_name (bool) – Whether to align node.name = node.path in this node and all of its child nodes, by default True.
generate_paths (bool | None) – If set
True, all subnodes will get their paths autogenerated correctly. Only set toFalseif the subnodes already have correct paths set (e.g. when deserialising).kwargs – The children given as keyword arguments. Each argument must be a
Setting,Parameter, or aSettingNode. The keywords are used as the names of the nodes. Parameters will be cast into Settings with the valueNone.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
Attributes
Yields all
Settinginstances inside this node, recursively.ItemsView of immediate child nodes of this node.
ItemsView of settings of this node.
Dictionary of immediate child nodes of this node.
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
namesettingssubtreespathalign_nameMethods
Add nodes to
selfwhile creating the missing nodes in-between.Recursive diff between two SettingNodes.
Fast construction alternative to __init__ from trusted serialized dict using model_construct.
Find first occurrence of Setting or SettingNode by name, by iterating recursively through all children.
Get the default implementation name for a given gate and locus.
Get the gate calibration sub-node for the locus given as a parameter if it exists in the settings tree.
Get the gate characterization sub-node for the locus given as a parameter if it exists in the settings tree.
Get all the gate locus node paths for a given
gate.Return the node corresponding to the given path.
Get the first SettingNode that has a Setting named name.
Recursively combine the tree structures and values of two SettingNodes.
Recursively combine the values from another
SettingNodeto this one.Copy the model.
Yields all nodes, filtered by given node_types.
Print a tree representation of the contents of this node.
Recursively delete all branches from this SettingNode that are not found in
other.Recursively set values to Settings, taking values from a dictionary that has similar tree structure.
Set
playlist_repeatsandaveraging_binsunderself.controllers.options.Set source recursively to all Settings in
self.Get a copy of a setting with its name replaced with the path name.
Reduce any subclass of SettingNode and it's contents into instances of cls.
Update an existing Setting in this tree.
- classmethod fast_construct(name, settings=None, subtrees=None, *, path='', align_name=True, generate_paths=False, **kwargs)#
Fast construction alternative to __init__ from trusted serialized dict using model_construct.
This is the “middle ground” between
__init__(full validation and normalization) andBaseModel.model_construct(no normalization).The key purpose is performance: when loading large trees (e.g. tens of thousands of settings) that were already validated before being written to the database, re-running Pydantic validation and index construction in
__init__is unnecessary and expensive.fast_constructlets us reuse that trusted data as-is and skip the extra work.This must only be used with already validated / trusted data (DB rows, internal API payloads, etc.). It intentionally skips Pydantic validation and coercion, so untrusted input should always go through the normal constructor instead.
- model_copy(*, update=None, deep=True)#
Copy the model.
deep=Trueand noupdate→ use fast tree clone (_fast_deep_copy).deep=Falseand noupdate→ returnself(no copy).Any
update→ fall back to Pydantic’smodel_copyfor correct update handling.
- nodes_by_type(node_types=None, recursive=False)#
Yields all nodes, filtered by given node_types.
Used to find and iterate over nodes of specific types.
- Parameters:
node_types (type | tuple[type, ...] | None) – when iterating over the tree, yields only instances that match this type or any of the types in the tuple. By default, yields Settings and SettingNodes.
recursive (bool) – If True, the search is carried recursively. If False, the search is limited to immediate child nodes.
- Returns:
Iterator that yields the filtered nodes.
- Return type:
- update_setting(setting)#
Update an existing Setting in this tree.
- Parameters:
setting (Setting) – Setting that will replace an existing Setting with the same name. Or if the setting is an element-wise setting (i.e. it has a non-empty value of
setting.element_indices), the corresponding element will be updated in the collection.- Raises:
UnknownSettingError – If no setting is found in the children of this tree.
- Return type:
None
- property all_settings: Generator[Setting]#
Yields all
Settinginstances inside this node, recursively.
- property children: dict[str, Setting | SettingNode]#
Dictionary of immediate child nodes of this node.
- property child_nodes: ItemsView[str, SettingNode]#
ItemsView of immediate child nodes of this node.
- get_parent_of(name)#
Get the first SettingNode that has a Setting named name.
- Parameters:
name (str) – Name of the setting to look for.
- Returns:
A SettingNode that has a child name.
- Return type:
- find_by_name(name)#
Find first occurrence of Setting or SettingNode by name, by iterating recursively through all children.
- Parameters:
name (str) – Name of the Setting or SettingNode to look for.
- Returns:
First found item, or None if nothing is found.
- Return type:
SettingNode | Setting | None
- static merge(first, second, merge_nones=False, align_name=True, deep_copy=True)#
Recursively combine the tree structures and values of two SettingNodes.
In case of conflicting nodes,values in first take priority regardless of the replaced content in second. None values are not prioritized unless
merge_nonesis set toTrue.- Parameters:
first (SettingNode) – SettingNode to merge, whose values and structure take priority
second (SettingNode) – SettingNode to merge.
merge_nones (bool) – Whether to merge also
Nonevalues fromfirsttosecond.align_name (bool) – Whether to align the paths (and also names if
seconddoes not usealign_name==False) when merging the nodes. Should never be setFalseunless the paths infirstalready align with what they should be insecond(setting itFalsein such cases can improve performance).deep_copy (bool) – Whether to deepcopy or just shallow copy all the sub-nodes. Set to
Falsewith high caution and understand the consequences.
- Returns:
A new SettingNode constructed from arguments.
- Return type:
- merge_values(other, prioritize_other=False)#
Recursively combine the values from another
SettingNodeto this one.The resulting tree structure the same as that of self.
- Parameters:
other (SettingNode) – SettingNode to merge.
prioritize_other (bool) – If True, will prioritize values in other. If False (default), only None values in self will be replaced.
- prune(other)#
Recursively delete all branches from this SettingNode that are not found in
other.- Parameters:
other (SettingNode)
- Return type:
None
- print_tree(levels=5)#
Print a tree representation of the contents of this node.
- Parameters:
levels (int) – display this many levels, starting from the root.
- Return type:
None
- classmethod transform_node_types(node)#
Reduce any subclass of SettingNode and it’s contents into instances of cls.
- Parameters:
node (SettingNode) – node to transform.
- Returns:
A new SettingNode with the same structure as the original, but where node instances are of type cls.
- Return type:
- set_from_dict(dct, strict=False, source=None)#
Recursively set values to Settings, taking values from a dictionary that has similar tree structure. Keys that are not found in self are ignored, unless
strictis True.- Parameters:
- Raises:
UnknownSettingError – If the condition of
stricthappens.- Return type:
None
- setting_with_path_name(setting)#
Get a copy of a setting with its name replaced with the path name.
- diff(other, *, path='')#
Recursive diff between two SettingNodes.
This function is meant to produce human-readable output, e.g. for debugging purposes. It returns the differences in a list of strings, each string detailing one specific difference. The diff is non-symmetric.
- Parameters:
other (SettingNode) – second node to compare
selftopath (str) – node path to the currently compared nodes (used in printing the results)
- Returns:
differences from
selftoother, in depth-first order- Return type:
- get_node_for_path(path)#
Return the node corresponding to the given path.
- Parameters:
path (str) – The path.
- Returns:
The node at
pathin self.- Raises:
ValueError – If the given path cannot be found in self.
- Return type:
- add_for_path(nodes, path, override_values=None, override_source=None)#
Add nodes to
selfwhile creating the missing nodes in-between.Whether the names and paths are aligned is determined by the attribute
align_nameof the current node (self). All the created missing nodes will use this samealign_namevalue, which determines whether their names will align with their paths.- Parameters:
nodes (Iterable[Setting | Parameter | SettingNode] | dict[str, Setting | Parameter | SettingNode]) – Nodes to add as new leaves/branches of
path. If of typedict, maps the keys used inself.settingsorself.subtreesto the nodes themselves. Ifalign_name=False, the key and the node name can differ, but otherwise the names will be replaced by the path anyways).path (str) – Path in
selfto whichnodeswill be added. If the path or any part (suffix) of it is not found in self, the associated nodes will be created automatically.override_values (dict[str, Any] | None) – Optionally override the values for the Settings corresponding to
nodes. This dict should have the same structure asnodes, including matching names. NOTE: If an override’s value is None, it is ignored.override_source (None | BaseModel | dict[str, Any]) – Optionally override the source for the
Settingscorresponding tonodes. All the settings will then have this same source.
- Return type:
None
- get_default_implementation_name(gate, locus)#
Get the default implementation name for a given gate and locus.
Takes into account the global default implementation and a possible locus specific implementation and also the symmetry properties of the gate.
NOTE: using this method requires the standard EXA settings tree structure.
- get_gate_node_for_locus(gate, locus, implementation=None)#
Get the gate calibration sub-node for the locus given as a parameter if it exists in the settings tree.
NOTE: using this method requires the standard EXA settings tree structure.
- Parameters:
- Returns:
The settings of the specified locus and gate.
- Return type:
- get_locus_node_paths_for(gate, implementations=None)#
Get all the gate locus node paths for a given
gate.NOTE: using this method requires the standard EXA settings tree structure.
- get_gate_properties_for_locus(gate, locus, implementation=None)#
Get the gate characterization sub-node for the locus given as a parameter if it exists in the settings tree.
NOTE: using this method requires the standard EXA settings tree structure.
- Parameters:
- Returns:
The settings of the specified locus and gate.
- Return type:
- set_shots(shots, averaging_bins=None)#
Set
playlist_repeatsandaveraging_binsunderself.controllers.options.
- set_source(source, ignore_nones=True, ignore_populated=False)#
Set source recursively to all Settings in
self.
- model_config = {'extra': 'ignore', 'frozen': True, 'ser_json_inf_nan': 'constants', 'validate_assignment': True, 'validate_default': False}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
Inheritance
