"""Validated, thread-safe store for live updates of mutable arguments.
The store holds the current host-native value of every argument that may change while a scan runs. Writers call
``ArgumentOverrideStore.update`` from any thread. The scan reads a consistent copy with
``ArgumentOverrideStore.snapshot`` at each chunk fetch.
"""
import copy
import math
import threading
import numpy as np
from atomiq.point_schema import kernel_type_of
_KIND_BOOL = "bool"
_KIND_ENUM = "enumeration"
_KIND_INT = "int"
_KIND_FLOAT = "float"
_INT64_MIN = -(2**63)
_INT64_MAX = 2**63 - 1
[docs]
def _type_name(value: object) -> str:
"""Get a readable type name of a value, with the module for types that are not builtin.
Args:
value: Any object.
Returns:
The qualified type name, for example ``int`` or ``numpy.bool``.
"""
value_type = type(value)
prefix = "" if value_type.__module__ == "builtins" else f"{value_type.__module__}."
return prefix + value_type.__qualname__
[docs]
def _kind_from_seed(definition: dict, seed: object) -> str | None:
"""Get the kind of an argument, using the same rule as the point schema.
Args:
definition: Argument definition dict.
seed: Submitted value of the argument.
Returns:
``"enumeration"`` if the definition has ``options`` that are not ``None``, else the kind of the kernel type of the seed value: one of
``"bool"``, ``"int"`` and ``"float"``. ``None`` if the argument cannot be updated: a string without options, or
a seed without a kernel type.
"""
if definition.get("options") is not None:
return _KIND_ENUM
try:
kernel_type = kernel_type_of(seed)
except TypeError:
return None
return {bool: _KIND_BOOL, np.int64: _KIND_INT, float: _KIND_FLOAT}.get(kernel_type)
[docs]
class ArgumentOverrideStore:
"""Holds the live values of the mutable arguments of a run.
The store is seeded with the submitted values. ``update`` validates a batch of new values against the argument
definitions and applies it atomically. ``snapshot`` returns a copy of all values. A lock guards both methods, so a
snapshot never contains part of a batch.
The kind of an argument is fixed at construction, by the same rule as the point schema: an argument whose
definition has ``options`` is an enumeration, every other kind comes from the kernel type of the seed value. The
caller must pass seeds that are consistent with the schema. In particular the seed of a ``Scannable``-derived
argument is a float and the seed of an int argument is an int. An argument whose seed has no kernel type, or is a
string without options, cannot be updated.
Values are host-native. Numbers are compared with ``min`` and ``max`` of the definition as they are, in base units:
ARTIQ divides ``min``, ``max`` and ``step`` by ``scale`` only to display them in the GUI, while the value passed to
the experiment is already multiplied by ``scale``. For an argument with ``unit="us"`` and ``scale=1e-6``, a value
of ``5e-6`` is valid and a value of ``5`` is not. The bounds are enforced for every numeric argument that has them
in its definition, including ``Scannable``-derived ones, although the argument builder does not pass them to
``Scannable`` and the GUI does not enforce them.
A bool argument accepts only a Python ``bool``. ``numpy.bool_`` and ints are rejected, like on the RPC wire. An int
argument accepts an int or a ``numpy`` integer that is not a bool and fits in 64 bits signed. It must be a multiple
of ``step`` counted from ``min``, or from 0 when there is no ``min``. A float argument accepts a finite int or float
that is not a bool and stores it as float. A number that is too large for a float is a ``ValueError``. The
``step`` of a float argument is not checked. An enumeration accepts a string that is one of ``options`` and stores
it as a plain ``str``.
Args:
definitions: Argument definitions, keyed by argument name. They are deep copied, so later changes to the
passed dicts have no effect.
values: Submitted host-native values, keyed by argument name. They seed the store.
mutable: Names of the arguments that may be updated.
active_axes: Names of the arguments that are active scan axes. They cannot be updated.
"""
def __init__(self, definitions: dict, values: dict, mutable: set, active_axes: set):
self._definitions = copy.deepcopy(definitions)
self._values = dict(values)
self._kinds = {name: _kind_from_seed(definition, values.get(name)) for name, definition in definitions.items()}
self._mutable = frozenset(mutable)
self._active_axes = frozenset(active_axes)
self._lock = threading.Lock()
[docs]
def update(self, values: dict) -> dict:
"""Validate a batch of new values and apply it.
Every entry is validated first. If one is invalid, the exception is raised and no value changes.
Args:
values: New host-native values, keyed by argument name.
Returns:
dict of the values of the batch as stored, keyed by argument name. A value is a ``bool``, ``int``,
``float`` or ``str``. A number for a float argument comes back as ``float``.
Raises:
TypeError: If ``values`` is not a dict, a key is not a string, or a value has the wrong type for its
argument.
KeyError: If a name is not a known argument.
ValueError: If an argument is not mutable, is an active scan axis, is out of range, is off its step, or is an
enumeration value that is not in the options.
"""
if not isinstance(values, dict):
msg = f"update needs a dict, got {_type_name(values)}"
raise TypeError(msg)
with self._lock:
checked = {name: self._validate(name, value) for name, value in values.items()}
self._values.update(checked)
return dict(checked)
[docs]
def snapshot(self) -> dict:
"""Get a copy of the current values.
Returns:
dict of all values, keyed by argument name.
"""
with self._lock:
return dict(self._values)
[docs]
def _validate(self, name: str, value: object) -> object:
"""Check one value against its definition.
Args:
name: Name of the argument.
value: New host-native value.
Returns:
The value in its stored form, a ``bool``, ``int``, ``float`` or ``str``.
Raises:
TypeError: If the name is not a string or the value has the wrong type.
KeyError: If the name is not a known argument.
ValueError: If the argument is not mutable, is an active scan axis, or the value is invalid.
"""
if not isinstance(name, str):
msg = f"argument names must be str, got {_type_name(name)}"
raise TypeError(msg)
if name not in self._definitions:
msg = f"unknown argument '{name}'"
raise KeyError(msg)
if name not in self._mutable:
msg = f"argument '{name}' is not mutable"
raise ValueError(msg)
if name in self._active_axes:
msg = f"argument '{name}' is an active scan axis and cannot be updated"
raise ValueError(msg)
definition = self._definitions[name]
kind = self._kinds[name]
if kind == _KIND_BOOL:
if not isinstance(value, bool):
msg = f"argument '{name}' needs a bool, got {_type_name(value)}"
raise TypeError(msg)
return value
if kind == _KIND_ENUM:
if not isinstance(value, str):
msg = f"argument '{name}' needs a str, got {_type_name(value)}"
raise TypeError(msg)
if value not in definition["options"]:
msg = f"'{value}' is not in the options of argument '{name}': {list(definition['options'])}"
raise ValueError(msg)
return str(value)
if kind == _KIND_INT:
if isinstance(value, bool | np.bool_) or not isinstance(value, int | np.integer):
msg = f"argument '{name}' needs an int, got {_type_name(value)}"
raise TypeError(msg)
number = int(value)
if not _INT64_MIN <= number <= _INT64_MAX:
msg = f"argument '{name}' must fit in 64 bits signed, got {number}"
raise ValueError(msg)
elif kind == _KIND_FLOAT:
if isinstance(value, bool | np.bool_) or not isinstance(value, int | float | np.integer | np.floating):
msg = f"argument '{name}' needs a number, got {_type_name(value)}"
raise TypeError(msg)
try:
number = float(value)
except OverflowError as ex:
msg = f"argument '{name}' is too large for a float"
raise ValueError(msg) from ex
if not math.isfinite(number):
msg = f"argument '{name}' needs a finite number, got {number}"
raise ValueError(msg)
else:
msg = f"argument '{name}' has a type that cannot be updated"
raise TypeError(msg)
self._check_range(name, number, definition, kind)
return number
[docs]
@staticmethod
def _check_range(name: str, number: float, definition: dict, kind: str) -> None:
"""Check a number against ``min``, ``max`` and, for ints, ``step``.
Args:
name: Name of the argument.
number: Value to check.
definition: Argument definition.
kind: Kind of the argument, ``"int"`` or ``"float"``.
Raises:
ValueError: If the number is below ``min``, above ``max``, or an int that is off its step.
"""
minimum = definition.get("min")
maximum = definition.get("max")
if minimum is not None and number < minimum:
msg = f"argument '{name}' must be >= {minimum}, got {number}"
raise ValueError(msg)
if maximum is not None and number > maximum:
msg = f"argument '{name}' must be <= {maximum}, got {number}"
raise ValueError(msg)
if kind == _KIND_INT:
step = int(definition.get("step", 1))
offset = 0 if minimum is None else minimum
if step > 0 and (number - offset) % step != 0:
msg = f"argument '{name}' must be a multiple of step {step} from {offset}, got {number}"
raise ValueError(msg)