From e765bceedb2c4948dd4d9c64cf150059d79947ca Mon Sep 17 00:00:00 2001 From: Alexis Gamelin Date: Tue, 10 Nov 2026 18:01:06 +0100 Subject: [PATCH 1/8] Add pint-based unit helpers for SI conversion (#350) New pyaml.common.units module: shared pint registry, multiplicative conversion factors (accelerator notation such as m-1 or T.m supported, offset units and mismatched base units rejected), Quantity stripping for user inputs, and the SI units exposed by PyAML. pint becomes a required dependency. Co-Authored-By: Claude Opus 5.5 --- pyaml/common/units.py | 260 ++++++++++++++++++++++++++++++++++++++++++ pyproject.toml | 3 +- 2 files changed, 262 insertions(+), 1 deletion(-) create mode 100644 pyaml/common/units.py diff --git a/pyaml/common/units.py b/pyaml/common/units.py new file mode 100644 index 00000000..5577931e --- /dev/null +++ b/pyaml/common/units.py @@ -0,0 +1,260 @@ +""" +Unit handling for PyAML. + +PyAML works internally with plain floats expressed in SI units (the energy is +the exception and stays in eV), which is also what the PyAT simulator uses. +`pint `_ is only used at the edges: + +- to convert values read from / written to a control-system device whose unit + is not the SI unit expected by PyAML (see + :class:`~pyaml.control.si_deviceaccess.SIDeviceAccess`); +- to let users pass a :class:`pint.Quantity` to ``set()`` instead of a float + (see :func:`to_magnitude`). + +Conversions are purely multiplicative: offset units such as ``degC`` are +rejected. +""" + +import re +from functools import lru_cache, wraps +from typing import Any + +import numpy as np +import pint + +from .exception import PyAMLConfigException, PyAMLException + +# SI units in which PyAML exposes values, shared by the simulator and the control systems +SI_POSITION = "m" +SI_ANGLE = "rad" +SI_VOLTAGE = "V" +SI_FREQUENCY = "Hz" +SI_TUNE = "1" + +_UREG: pint.UnitRegistry | None = None + +# Strings meaning "no unit": the value is passed through unchanged. +_NO_UNIT = ("", "1", "none", "no unit", "dimensionless") + + +def get_registry() -> pint.UnitRegistry: + """ + Return the application-wide pint unit registry. + + The registry is created on first use and registered with + :func:`pint.set_application_registry`, so that ``pint.Quantity`` objects + built by the user (or unpickled) share the PyAML registry. + + Returns + ------- + pint.UnitRegistry + The shared unit registry. + """ + global _UREG + if _UREG is None: + _UREG = pint.get_application_registry().get() + if not isinstance(_UREG, pint.UnitRegistry): # pragma: no cover - defensive + _UREG = pint.UnitRegistry() + pint.set_application_registry(_UREG) + return _UREG + + +def _is_no_unit(unit: str | None) -> bool: + """Return ``True`` when ``unit`` means that no conversion should be done.""" + return unit is None or str(unit).strip().lower() in _NO_UNIT + + +# "m-1", "m-2" (accelerator notation) -> "m^-1", "m^-2" +_NEG_EXPONENT = re.compile(r"(?<=[A-Za-z\)])(-\d+)") +# "T.m" -> "T*m" +_DOT_PRODUCT = re.compile(r"(?<=[A-Za-z\)])\.(?=[A-Za-z\(])") + + +def normalize_unit(unit: str) -> str: + """ + Rewrite accelerator-style unit strings in a syntax understood by pint. + + ``m-1`` becomes ``m^-1`` and ``T.m`` becomes ``T*m``. Other strings are + returned stripped and otherwise unchanged. + + Parameters + ---------- + unit : str + Unit string from the configuration or a backend. + + Returns + ------- + str + Unit string for pint. + """ + u = str(unit).strip() + u = _NEG_EXPONENT.sub(r"^\1", u) + return _DOT_PRODUCT.sub("*", u) + + +def _parse_unit(unit: str): + """Parse ``unit`` with the PyAML registry, raising a PyAML exception on failure.""" + try: + return get_registry().Unit(normalize_unit(unit)) + except Exception as e: + raise PyAMLConfigException(f"Unknown unit '{unit}': {e}") from e + + +@lru_cache(maxsize=None) +def conversion_factor(src: str | None, dst: str | None) -> float: + """ + Return the factor ``k`` such that ``value_dst = k * value_src``. + + Parameters + ---------- + src : str or None + Unit of the source value (typically the control-system device unit). + dst : str or None + Unit of the destination value (typically the SI unit used by PyAML). + + Returns + ------- + float + Multiplicative conversion factor. ``1.0`` when ``src`` or ``dst`` is + empty, ``None`` or dimensionless (passthrough: the value is assumed to + already be in the expected unit). + + Raises + ------ + PyAMLConfigException + If a unit is unknown to pint, if the two units have different + dimensions, or if the conversion is not purely multiplicative. + """ + if _is_no_unit(src) or _is_no_unit(dst) or str(src).strip() == str(dst).strip(): + return 1.0 + ureg = get_registry() + qsrc = ureg.Quantity(1.0, _parse_unit(src)) + udst = _parse_unit(dst) + # Compare root units rather than dimensions: pint treats rad as dimensionless, + # so a dimension check alone would accept '%' or 'count' for an angle. + if qsrc.to_root_units().units != ureg.Quantity(1.0, udst).to_root_units().units: + raise PyAMLConfigException(f"Unit '{src}' cannot be converted to '{dst}'") + try: + k = qsrc.to(udst).magnitude + # Reject offset units (degC, degF...): conversion of 0 must give 0 + offset = ureg.Quantity(0.0, qsrc.units).to(udst).magnitude + except Exception as e: + raise PyAMLConfigException(f"Unit '{src}' cannot be converted to '{dst}': {e}") from e + if offset != 0.0: + raise PyAMLConfigException(f"Unit conversion '{src}' -> '{dst}' is not multiplicative (offset unit)") + return float(k) + + +def is_quantity(value: Any) -> bool: + """Return ``True`` if ``value`` is a :class:`pint.Quantity`.""" + return isinstance(value, pint.Quantity) + + +def has_quantity(value: Any) -> bool: + """Return ``True`` if ``value`` is a quantity or a list/tuple containing one.""" + return is_quantity(value) or (isinstance(value, (list, tuple)) and any(is_quantity(v) for v in value)) + + +def to_magnitude(value: Any, unit: str | list[str] | None) -> Any: + """ + Strip the unit of a user input, converting it to ``unit`` first. + + Plain numbers and arrays are returned unchanged: they are assumed to be + already expressed in ``unit`` (SI). A :class:`pint.Quantity` (scalar or + array) or a list of quantities is converted to ``unit`` and its magnitude + returned. + + Parameters + ---------- + value : object + User input: float, array-like, :class:`pint.Quantity` or list of + :class:`pint.Quantity`. + unit : str or list of str or None + Unit expected by the accessor (as returned by its ``unit()`` method). + A list gives one unit per element of ``value``. + + Returns + ------- + object + ``value`` expressed as plain number(s) in ``unit``. + + Raises + ------ + PyAMLException + If a quantity cannot be converted to ``unit``. + """ + if not has_quantity(value): + return value + + if isinstance(unit, (list, tuple)) and len(set(unit)) == 1: + unit = unit[0] + + if isinstance(unit, (list, tuple)) or not is_quantity(value): + # One unit per element: convert element-wise (a scalar quantity is broadcast) + units = unit if isinstance(unit, (list, tuple)) else [unit] * len(value) + values = [value] * len(units) if is_quantity(value) and np.ndim(value.magnitude) == 0 else list(value) + if len(units) != len(values): + raise PyAMLException(f"Expected {len(units)} values but got {len(values)}") + return np.array([to_magnitude(v, u) for v, u in zip(values, units, strict=True)], dtype=float) + + if _is_no_unit(unit): + if value.dimensionless: + return value.to("dimensionless").magnitude + raise PyAMLException(f"Cannot assign a value in '{value.units}' to a dimensionless quantity") + _parse_unit(unit) # Check the target unit is valid + try: + # Convert with the quantity's own registry, it may not be the PyAML one + return value.to(normalize_unit(unit)).magnitude + except Exception as e: + raise PyAMLException(f"Cannot convert {value} to '{unit}': {e}") from e + + +def accepts_quantity(method): + """ + Decorate a ``set(self, value, ...)``-like method so that ``value`` may be a quantity. + + When ``value`` is a :class:`pint.Quantity` (or a list of them), it is + converted to ``self.unit()`` and stripped before calling ``method``. Plain + numbers are passed through untouched, without calling ``unit()``. + + Parameters + ---------- + method : callable + Method taking the value to write as first positional argument. + + Returns + ------- + callable + The wrapped method. + """ + if getattr(method, "__pyaml_accepts_quantity__", False): + return method + + @wraps(method) + def wrapper(self, value, *args, **kwargs): + if has_quantity(value): + value = to_magnitude(value, self.unit()) + return method(self, value, *args, **kwargs) + + wrapper.__pyaml_accepts_quantity__ = True + return wrapper + + +class AcceptsQuantity: + """ + Mixin making ``set``/``set_and_wait`` of every subclass accept :class:`pint.Quantity` values. + + Inherited by the PyAML read/write interfaces, so that every implementation + (including the ones of external packages) supports quantities without any + change: the setters defined by a subclass are wrapped with + :func:`accepts_quantity` when the subclass is created. + """ + + _QUANTITY_SETTERS = ("set", "set_and_wait") + + def __init_subclass__(cls, **kwargs): + super().__init_subclass__(**kwargs) + for name in cls._QUANTITY_SETTERS: + method = cls.__dict__.get(name) + if callable(method) and not getattr(method, "__isabstractmethod__", False): + setattr(cls, name, accepts_quantity(method)) diff --git a/pyproject.toml b/pyproject.toml index 81c47797..8bcf9e19 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,7 +30,8 @@ dependencies = [ "pydantic>=2.11.7", "accelerator-commissioning==1.5.3", #pySC "h5py", - "matplotlib" + "matplotlib", + "pint>=0.24" ] [project.optional-dependencies] From 50b44b3eb2cd0c5fcd042479518d730fd7b78c52 Mon Sep 17 00:00:00 2001 From: Alexis Gamelin Date: Tue, 10 Nov 2026 18:01:07 +0100 Subject: [PATCH 2/8] Convert control-system devices to SI units (#350) Live accessors now read and write the same SI units as the simulator: backend devices are wrapped in SIDeviceAccess / SIDeviceAccessList, with the target unit fixed by the accessor (m, rad, V, Hz, magnet hardware unit). Devices without unit are passed through; incompatible units raise at load time. Backend aggregators still receive raw devices. ControlSystem.get_devices_access is replaced by get_si_device_access / get_si_devices_access. Tests using BPMs declared in mm now expect metres. Co-Authored-By: Claude Opus 5.5 --- pyaml/control/abstract_impl.py | 65 ++--- pyaml/control/controlsystem.py | 111 +++++-- pyaml/control/si_deviceaccess.py | 274 ++++++++++++++++++ pyaml/lattice/abstract_impl.py | 21 +- .../diagnostics/bpm/test_bpm_controlsystem.py | 20 +- tests/magnet/test_load_quad.py | 2 +- tests/magnet/test_ranges_cfm_deviceaccess.py | 2 +- tests/test_catalogs.py | 5 +- 8 files changed, 418 insertions(+), 82 deletions(-) create mode 100644 pyaml/control/si_deviceaccess.py diff --git a/pyaml/control/abstract_impl.py b/pyaml/control/abstract_impl.py index 5b110562..33d9fa81 100644 --- a/pyaml/control/abstract_impl.py +++ b/pyaml/control/abstract_impl.py @@ -15,6 +15,7 @@ from .. import PyAMLException from ..common import abstract from ..common.abstract_aggregator import ScalarAggregator +from ..common.units import SI_ANGLE, SI_FREQUENCY, SI_POSITION, SI_TUNE, SI_VOLTAGE from ..control.deviceaccess import DeviceAccess from ..control.deviceaccesslist import DeviceAccessList from ..magnet.magnet import Magnet @@ -403,7 +404,7 @@ class CSStrengthScalarAggregator(CSScalarAggregator): readback() Read back magnet strengths from measured hardware values. unit() - Return the units associated with the underlying devices. + Return the strength unit of each registered magnet. """ def __init__(self, peer: CSScalarAggregator): @@ -414,6 +415,7 @@ def __init__(self, peer: CSScalarAggregator): self.__models: list[MagnetModel] = [] # List of magnet model self.__modelToMagnet: list[list[tuple[int, int]]] = [] # strengths indexing self.__nbMagnet = 0 # Number of magnet strengths + self.__units: list[str] = [] # Strength unit of each magnet def add_magnet(self, magnet: Magnet, devs: list[DeviceAccess]): # Incoming magnet can be a magnet exported from @@ -442,6 +444,7 @@ def add_magnet(self, magnet: Magnet, devs: list[DeviceAccess]): else: index = self.__models.index(magnet.model) self.__modelToMagnet[index].append((self.__nbMagnet, strengthIndex)) + self.__units.append(magnet.strength.unit()) self.__nbMagnet += 1 def set(self, value: NDArray[np.float64]): @@ -519,9 +522,9 @@ def readback(self) -> np.array: hardwareIndex += nbDev return allStrength - def unit(self) -> str: - """Return the units associated with the underlying devices.""" - return self._devs.unit() + def unit(self) -> list[str]: + """Return the strength unit of each registered magnet.""" + return list(self.__units) # ------------------------------------------------------------------------------ @@ -935,7 +938,7 @@ class RBpmArray(abstract.ReadFloatArray): get() Return horizontal and vertical BPM positions (NaN for a missing plane). unit() - Return the unit reported by the BPM device. + Return the SI unit of BPM positions. """ def __init__(self, hDev: DeviceAccess | None, vDev: DeviceAccess | None): @@ -949,11 +952,9 @@ def get(self) -> np.array: """Return horizontal and vertical BPM positions (NaN for a missing plane).""" return np.array([d.get() if d is not None else np.nan for d in (self._hDev, self._vDev)], dtype=float) - # Gets the unit of the value Assume that x and y, offsets and positions - # have the same unit def unit(self) -> str: - """Return the unit reported by the BPM device.""" - return (self._hDev if self._hDev is not None else self._vDev).unit() + """Return the SI unit of BPM positions.""" + return SI_POSITION # ------------------------------------------------------------------------------ @@ -977,7 +978,7 @@ class RWBpmTiltScalar(abstract.ReadFloatScalar): set_and_wait(value) Set the BPM tilt and wait for readback confirmation. unit() - Return the unit shared by the BPM devices. + Return the SI unit of the BPM tilt. """ def __init__(self, dev: DeviceAccess): @@ -997,7 +998,7 @@ def set(self, value: float): Parameters ---------- value : float - BPM tilt value in the device's configured units. + BPM tilt in rad. """ self._dev.set(value) @@ -1019,8 +1020,8 @@ def set_and_wait(self, value: NDArray[np.float64]): # Gets the unit of the value def unit(self) -> str: - """Return the unit shared by the BPM devices.""" - return self._dev.unit() + """Return the SI unit of the BPM tilt.""" + return SI_ANGLE # ------------------------------------------------------------------------------ @@ -1046,7 +1047,7 @@ class RWBpmOffsetArray(abstract.ReadWriteFloatArray): set_and_wait(value) Set BPM offsets and wait for readback confirmation. unit() - Return the unit shared by the BPM offset devices. + Return the SI unit of BPM offsets. """ def __init__(self, hDev: DeviceAccess, vDev: DeviceAccess): @@ -1088,11 +1089,9 @@ def set_and_wait(self, value: NDArray[np.float64]): """ raise NotImplementedError("Not implemented yet.") - # Gets the unit of the value Assume that x and y, offsets and positions - # have the same unit def unit(self) -> str: - """Return the unit shared by the BPM offset devices.""" - return self._hDev.unit() + """Return the SI unit of BPM offsets.""" + return SI_POSITION # ------------------------------------------------------------------------------ @@ -1119,7 +1118,7 @@ class RWRFVoltageScalar(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the cavity voltage and wait for readback confirmation. unit() - Return the configured cavity-voltage unit. + Return the SI unit of the cavity voltage. """ def __init__(self, transmitter: RFTransmitter, dev: DeviceAccess): @@ -1140,7 +1139,7 @@ def set(self, value: float): Parameters ---------- value : float - Cavity-voltage setpoint in the configured voltage unit. + Cavity-voltage setpoint in V. """ self.__dev.set(value) @@ -1161,8 +1160,8 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the configured cavity-voltage unit.""" - return self.__transmitter._cfg.voltage.unit() + """Return the SI unit of the cavity voltage.""" + return SI_VOLTAGE # ------------------------------------------------------------------------------ @@ -1189,7 +1188,7 @@ class RWRFPhaseScalar(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the cavity phase and wait for readback confirmation. unit() - Return the configured cavity-phase unit. + Return the SI unit of the cavity phase. """ def __init__(self, transmitter: RFTransmitter, dev: DeviceAccess): @@ -1210,7 +1209,7 @@ def set(self, value: float): Parameters ---------- value : float - Cavity-phase setpoint in the configured phase unit. + Cavity-phase setpoint in rad. """ self.__dev.set(value) @@ -1231,8 +1230,8 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the configured cavity-phase unit.""" - return self.__transmitter._cfg.phase.unit() + """Return the SI unit of the cavity phase.""" + return SI_ANGLE # ------------------------------------------------------------------------------ @@ -1258,7 +1257,7 @@ class RWRFFrequencyScalar(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the RF frequency and wait for readback confirmation. unit() - Return the configured RF-frequency unit. + Return the SI unit of the RF frequency. """ def __init__(self, rf: RFPlant, dev: DeviceAccess): @@ -1280,7 +1279,7 @@ def set(self, value: float): Parameters ---------- value : float - RF-frequency setpoint in the configured frequency unit. + RF-frequency setpoint in Hz. """ self.__dev.set(value) @@ -1301,8 +1300,8 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the configured RF-frequency unit.""" - return self.__rf._cfg.masterclock.unit() + """Return the SI unit of the RF frequency.""" + return SI_FREQUENCY # ------------------------------------------------------------------------------ @@ -1324,7 +1323,7 @@ class RBetatronTuneArray(abstract.ReadFloatArray): get() Return horizontal and vertical betatron tunes. unit() - Return the configured betatron-tune unit. + Return the betatron-tune unit (dimensionless). """ def __init__(self, tune_monitor, devs: list[DeviceAccess]): @@ -1345,8 +1344,8 @@ def get(self) -> NDArray: ) def unit(self) -> str: - """Return the configured betatron-tune unit.""" - return self.__tune_monitor._cfg.tune_v.unit() + """Return the betatron-tune unit (dimensionless).""" + return SI_TUNE # ------------------------------------------------------------------------------ diff --git a/pyaml/control/controlsystem.py b/pyaml/control/controlsystem.py index 4800f796..02dd553c 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -14,8 +14,9 @@ from ..common.abstract import RWMapper from ..common.abstract_aggregator import ScalarAggregator -from ..common.exception import PyAMLException +from ..common.exception import PyAMLConfigException, PyAMLException from ..common.holders.element_holder import ElementHolder +from ..common.units import SI_ANGLE, SI_FREQUENCY, SI_POSITION, SI_TUNE, SI_VOLTAGE from ..configuration.unbound_element import UnboundElement from ..control.abstract_impl import ( CSScalarAggregator, @@ -45,6 +46,20 @@ from ..tuning_tools.tuning_tool import TuningTool from .deviceaccess import DeviceAccess from .deviceaccesslist import DeviceAccessList +from .si_deviceaccess import SIDeviceAccessList, wrap_si + + +def _hardware_unit(model, index: int = 0) -> str: + """Return the hardware unit of device ``index`` of a magnet model ('' if unknown).""" + # Identity models without power supply still report the unit of the device they read + units = model.get_hardware_units() + if not units: + return "" + if len(units) == 1: # One unit shared by all devices of the model + return units[0] or "" + if index >= len(units): + raise PyAMLConfigException(f"Magnet model declares {len(units)} hardware units but has no unit for device {index}") + return units[index] or "" class ControlSystem(ElementHolder, metaclass=ABCMeta): @@ -67,8 +82,10 @@ class ControlSystem(ElementHolder, metaclass=ABCMeta): Return a device reference for this control system. YAML element configuration passes opaque strings. Public Python APIs may also pass backend ConfigModel instances. Concrete backends own all lookup, parsing and DeviceAccess construction. - get_devices_access(refs) - Resolve a list of backend references into device access objects. + get_si_device_access(ref, si_unit) + Resolve a backend reference into a device read and written in ``si_unit``. + get_si_devices_access(refs, si_units) + Resolve backend references into devices read and written in SI units. create_magnet_strength_aggregator(magnets) Create an aggregator that exposes magnet strengths. create_magnet_hardware_aggregator(magnets) @@ -105,32 +122,73 @@ def get_device_access(self, ref: str | BaseModel | None) -> DeviceAccess: """ pass - def get_devices_access(self, refs: list[str | BaseModel | None]) -> list[DeviceAccess]: + def get_si_device_access(self, ref: str | BaseModel | None, si_unit: str | None) -> DeviceAccess | None: """ - Resolve a list of backend references into device access objects. + Resolve a backend reference into a device read and written in ``si_unit``. + + The backend device unit (``DeviceAccess.unit()``) is converted to + ``si_unit`` with pint. A device without unit is assumed to already be + expressed in ``si_unit``. + + Parameters + ---------- + ref : str or BaseModel or None + Backend-specific device reference. + si_unit : str or None + Unit expected by PyAML for this device. + + Returns + ------- + DeviceAccess or None + The backend device, wrapped in a + :class:`~pyaml.control.si_deviceaccess.SIDeviceAccess` when a + conversion is needed. + + Raises + ------ + PyAMLConfigException + If the device unit cannot be converted to ``si_unit``. + """ + return wrap_si(self.get_device_access(ref), si_unit) + + def get_si_devices_access( + self, refs: list[str | BaseModel | None], si_units: str | list[str] | None + ) -> list[DeviceAccess | None]: + """ + Resolve backend references into devices read and written in SI units. Parameters ---------- refs : list of str or BaseModel or None - Backend-specific device references from the configuration. + Backend-specific device references. + si_units : str or list of str or None + Unit expected by PyAML, either one for all devices or one per device. Returns ------- - list of DeviceAccess - Device access objects in the same order as ``refs``. + list of DeviceAccess or None + Devices in the same order as ``refs``. Raises ------ PyAMLException If ``refs`` is not a list. + PyAMLConfigException + If a device unit cannot be converted to its SI unit. """ if not isinstance(refs, list): - raise PyAMLException(f"get_devices() expect a list as input arguments but got {str(type(refs))}") - return [self.get_device_access(ref) for ref in refs] + raise PyAMLException(f"get_si_devices_access() expects a list as input arguments but got {type(refs)}") + units = si_units if isinstance(si_units, list) else [si_units] * len(refs) + return [self.get_si_device_access(ref, unit) for ref, unit in zip(refs, units, strict=True)] + + def _get_si_aggregator(self) -> SIDeviceAccessList | None: + """Return an empty backend aggregator wrapped for SI conversion, or ``None``.""" + agg = self.get_aggregator() + return None if agg is None else SIDeviceAccessList(agg) def _create_scalar_aggregator(self) -> ScalarAggregator | None: """Create an empty scalar aggregator for this control-system backend.""" - agg = self.get_aggregator() + agg = self._get_si_aggregator() if agg is None: return None return CSScalarAggregator(agg) @@ -155,7 +213,8 @@ def create_magnet_strength_aggregator(self, magnets: list[Magnet]) -> ScalarAggr return None magg = CSStrengthScalarAggregator(agg) for m in magnets: - devs = self.get_devices_access(m.model.get_device_names()) + names = m.model.get_device_names() + devs = self.get_si_devices_access(names, [_hardware_unit(m.model, i) for i in range(len(names))]) magg.add_magnet(m, devs) return magg @@ -184,7 +243,8 @@ def create_magnet_hardware_aggregator(self, magnets: list[Magnet]) -> ScalarAggr if not m.model.has_hardware(): return None psIndex = m.hardware.index() if isinstance(m.hardware, RWMapper) else 0 - agg.add_devices(self.get_devices_access([m.model.get_device_names()[psIndex]])[0]) + ref = m.model.get_device_names()[psIndex] + agg.add_devices(self.get_si_device_access(ref, _hardware_unit(m.model, psIndex))) return agg def create_bpm_aggregators(self, bpms: list[BPM]) -> list[ScalarAggregator | None]: @@ -204,25 +264,26 @@ def create_bpm_aggregators(self, bpms: list[BPM]) -> list[ScalarAggregator | Non vertical-only XBPM) reads NaN, the other devices are still read in one grouped call. """ - aggs = [self.get_aggregator() for _ in range(3)] + aggs = [self._get_si_aggregator() for _ in range(3)] if any(a is None for a in aggs): return [None, None, None] agg, aggh, aggv = (CSSparseScalarAggregator(a) for a in aggs) for b in bpms: - devs = self.get_devices_access(b.get_pos_devices()) + devs = self.get_si_devices_access(b.get_pos_devices(), SI_POSITION) agg.add_devices(devs) aggh.add_devices(devs[0]) aggv.add_devices(devs[1]) return [agg, aggh, aggv] def _fill_magnet(self, magnet: Magnet) -> None: - device = self.get_device_access(magnet.model.get_device_names()[0]) + device = self.get_si_device_access(magnet.model.get_device_names()[0], _hardware_unit(magnet.model)) current = RWHardwareScalar(magnet.model, device) if magnet.model.has_hardware() else None strength = RWStrengthScalar(magnet.model, device) if magnet.model.has_physics() else None self.magnet.add(magnet.attach(self, strength, current)) def _fill_combined_function_magnet(self, magnet: CombinedFunctionMagnet) -> None: - devices = self.get_devices_access(magnet.model.get_device_names()) + names = magnet.model.get_device_names() + devices = self.get_si_devices_access(names, [_hardware_unit(magnet.model, i) for i in range(len(names))]) currents = RWHardwareArray(magnet.model, devices) strengths = RWStrengthArray(magnet.model, devices) attached_magnets = magnet.attach(self, strengths, currents) @@ -232,7 +293,7 @@ def _fill_combined_function_magnet(self, magnet: CombinedFunctionMagnet) -> None def _fill_serialized_magnets(self, magnets: SerializedMagnets) -> None: # All magnets of the group share the same power supply - device = self.get_device_access(magnets.model.get_device_names()[0]) + device = self.get_si_device_access(magnets.model.get_device_names()[0], _hardware_unit(magnets.model)) currents = [] strengths = [] for index in range(magnets.get_nb_magnets()): @@ -245,9 +306,9 @@ def _fill_serialized_magnets(self, magnets: SerializedMagnets) -> None: self.magnet.add(magnet) def _fill_bpm(self, bpm: BPM) -> None: - position_devices = self.get_devices_access(bpm.get_pos_devices()) - tilt_devices = self.get_devices_access([bpm.get_tilt_device()]) - offset_devices = self.get_devices_access(bpm.get_offset_devices()) + position_devices = self.get_si_devices_access(bpm.get_pos_devices(), SI_POSITION) + tilt_devices = self.get_si_devices_access([bpm.get_tilt_device()], SI_ANGLE) + offset_devices = self.get_si_devices_access(bpm.get_offset_devices(), SI_POSITION) positions = RBpmArray(position_devices[0], position_devices[1]) tilt = RWBpmTiltScalar(tilt_devices[0]) offsets = RWBpmOffsetArray(offset_devices[0], offset_devices[1]) @@ -257,20 +318,20 @@ def _fill_rf_plant(self, rf_plant: RFPlant) -> None: attached_transmitters: list[RFTransmitter] = [] if rf_plant.transmitters: for transmitter in rf_plant.transmitters: - voltage_device = self.get_device_access(transmitter.voltage_name) - phase_device = self.get_device_access(transmitter.phase_name) + voltage_device = self.get_si_device_access(transmitter.voltage_name, SI_VOLTAGE) + phase_device = self.get_si_device_access(transmitter.phase_name, SI_ANGLE) voltage = RWRFVoltageScalar(transmitter, voltage_device) phase = RWRFPhaseScalar(transmitter, phase_device) attached_transmitter = transmitter.attach(self, voltage, phase) self.rf.transmitter.add(attached_transmitter) attached_transmitters.append(attached_transmitter) - frequency_device = self.get_device_access(rf_plant.masterclock) + frequency_device = self.get_si_device_access(rf_plant.masterclock, SI_FREQUENCY) frequency = RWRFFrequencyScalar(rf_plant, frequency_device) voltage = RWTotalVoltage(attached_transmitters) if rf_plant.transmitters else None self.rf.add(rf_plant.attach(self, frequency, voltage)) def _fill_betatron_tune_monitor(self, monitor: BetatronTuneMonitor) -> None: - devices = self.get_devices_access([monitor.tune_h, monitor.tune_v]) + devices = self.get_si_devices_access([monitor.tune_h, monitor.tune_v], SI_TUNE) self.add_betatron_tune_monitor(monitor.attach(self, RBetatronTuneArray(monitor, devices))) def _fill_tool(self, tool: TuningTool | MeasurementTool) -> None: diff --git a/pyaml/control/si_deviceaccess.py b/pyaml/control/si_deviceaccess.py new file mode 100644 index 00000000..2113f498 --- /dev/null +++ b/pyaml/control/si_deviceaccess.py @@ -0,0 +1,274 @@ +""" +SI unit conversion of control-system devices. + +Backends expose device values in the unit of the control system (``nm``, +``MHz``, ``mA``...). PyAML works in SI. The wrappers of this module sit between +the backend :class:`~pyaml.control.deviceaccess.DeviceAccess` / +:class:`~pyaml.control.deviceaccesslist.DeviceAccessList` and the PyAML +accessors, and apply the multiplicative factor computed once with pint by +:func:`pyaml.common.units.conversion_factor`. + +The target unit is fixed by the PyAML accessor (``m`` for BPM positions, +``Hz`` for the RF frequency, the model hardware unit for a magnet...), not by +the backend, so that live and design modes return the same quantities. +""" + +from typing import Any + +import numpy as np +import numpy.typing as npt + +from ..common.exception import PyAMLConfigException +from ..common.units import conversion_factor +from .deviceaccess import DeviceAccess +from .deviceaccesslist import DeviceAccessList +from .readback_value import Value + + +def _scale(value: Any, k: float | np.ndarray) -> Any: + """ + Multiply a raw device value by ``k`` (one factor, or one per element). + + Handles scalars, numeric arrays, :class:`Value` objects (metadata kept) and + lists/object arrays of them, as returned by ``readback()``. + """ + if value is None: + return None + if isinstance(value, Value): + return Value(_scale(value.value, k), value.quality, value.timestamp) + if isinstance(value, (list, tuple)) or (isinstance(value, np.ndarray) and value.dtype == object): + ks = np.broadcast_to(k, (len(value),)) + scaled = [_scale(v, kk) for v, kk in zip(value, ks, strict=True)] + return np.array(scaled, dtype=object) if isinstance(value, np.ndarray) else scaled + return value * k + + +def _scale_range(rng: list | None, k: float | np.ndarray) -> list | None: + """Scale a flat ``[min0, max0, min1, max1, ...]`` range, keeping ``None`` bounds (factors are positive).""" + if rng is None: + return None + ks = np.repeat(np.broadcast_to(k, (len(rng) // 2,)), 2) + return [None if b is None else b * kk for b, kk in zip(rng, ks, strict=True)] + + +class SIDeviceAccess(DeviceAccess): + """ + Expose a backend device in the SI unit expected by PyAML. + + Parameters + ---------- + raw : DeviceAccess + Backend device, read and written in its own unit (``raw.unit()``). + si_unit : str + Unit in which values are exposed to PyAML. + + Attributes + ---------- + raw : DeviceAccess + The wrapped backend device. + factor : float + Conversion factor, ``si_value = factor * raw_value``. + + Methods + ------- + name() + Return the backend identifier of the device variable. + measure_name() + Return the identifier of the device's measurement channel. + set(value) + Convert a SI setpoint to the device unit and write it. + set_and_wait(value) + Convert a SI setpoint to the device unit, write it and wait. + get() + Return the current setpoint in SI. + readback() + Return the latest measured value in SI. + unit() + Return the SI unit. + get_range() + Return the device range in SI. + check_device_availability() + Check if the device is available and accessible. + """ + + def __init__(self, raw: DeviceAccess, si_unit: str, factor: float): + self.raw = raw + self.factor = factor + self._si_unit = si_unit + + def name(self) -> str: + """Return the backend identifier of the device variable.""" + return self.raw.name() + + def measure_name(self) -> str: + """Return the identifier of the device's measurement channel.""" + return self.raw.measure_name() + + def set(self, value): + """Convert a SI setpoint to the device unit and write it.""" + self.raw.set(_scale(value, 1.0 / self.factor)) + + def set_and_wait(self, value): + """Convert a SI setpoint to the device unit, write it and wait.""" + self.raw.set_and_wait(_scale(value, 1.0 / self.factor)) + + def get(self): + """Return the current setpoint in SI.""" + return _scale(self.raw.get(), self.factor) + + def readback(self): + """Return the latest measured value in SI.""" + return _scale(self.raw.readback(), self.factor) + + def unit(self) -> str: + """Return the SI unit.""" + return self._si_unit + + def get_range(self) -> list[float]: + """Return the device range in SI.""" + return _scale_range(self.raw.get_range(), self.factor) + + def check_device_availability(self) -> bool: + """Check if the device is available and accessible.""" + return self.raw.check_device_availability() + + def __str__(self): + return str(self.raw) + + def __repr__(self): + return f"SIDeviceAccess({self.raw!r}, si_unit='{self._si_unit}', factor={self.factor:g})" + + +def wrap_si(dev: DeviceAccess | None, si_unit: str | None) -> DeviceAccess | None: + """ + Wrap ``dev`` so that it is read and written in ``si_unit``. + + Parameters + ---------- + dev : DeviceAccess or None + Backend device. ``None`` is returned unchanged (missing device). + si_unit : str or None + Unit expected by the PyAML accessor. + + Returns + ------- + DeviceAccess or None + ``dev`` itself when no conversion is needed (factor 1, empty unit), + otherwise a :class:`SIDeviceAccess`. + + Raises + ------ + PyAMLConfigException + If the device unit cannot be converted to ``si_unit``. + """ + if dev is None or isinstance(dev, SIDeviceAccess): + return dev + dev_unit = dev.unit() + if isinstance(dev_unit, (list, tuple)): # Defensive: some backends may return a list + dev_unit = dev_unit[0] if dev_unit else None + try: + k = conversion_factor(dev_unit, si_unit) + except PyAMLConfigException as e: + raise PyAMLConfigException(f"Device '{dev.name()}': {e}") from e + if k == 1.0: + return dev + return SIDeviceAccess(dev, si_unit, k) + + +class SIDeviceAccessList(DeviceAccessList): + """ + Expose a backend device list in the SI units expected by PyAML. + + The backend list only receives raw backend devices (it may need them to + perform grouped reads); the conversion factor of each device is kept here. + + Parameters + ---------- + raw : DeviceAccessList + Backend device list. + + Attributes + ---------- + raw : DeviceAccessList + The wrapped backend device list. + factors : numpy.ndarray + Conversion factors, one per device (``si_value = factor * raw_value``). + + Methods + ------- + add_devices(devices) + Add raw or SI-wrapped devices. + get_device_at(index) + Return the (SI-wrapped) device at ``index``. + len() + Return the number of devices. + set(value) + Convert SI setpoints to device units and write them. + set_and_wait(value) + Convert SI setpoints to device units, write them and wait. + get() + Return all setpoints in SI. + readback() + Return all readbacks in SI. + unit() + Return the SI unit of each device. + get_range() + Return the ranges in SI. + check_device_availability() + Check if all devices are available. + """ + + def __init__(self, raw: DeviceAccessList): + self.raw = raw + self._items: list[DeviceAccess] = [] + self.factors = np.ones(0) # Conversion factors, one per device + self._passthrough = True # True while all factors are 1 + + def add_devices(self, devices: DeviceAccess | list[DeviceAccess]): + """Add raw or SI-wrapped devices.""" + devs = devices if isinstance(devices, list) else [devices] + raws = [d.raw if isinstance(d, SIDeviceAccess) else d for d in devs] + self.raw.add_devices(raws if isinstance(devices, list) else raws[0]) + self._items.extend(devs) + k = [d.factor if isinstance(d, SIDeviceAccess) else 1.0 for d in devs] + self.factors = np.concatenate([self.factors, k]) + self._passthrough = bool(np.all(self.factors == 1.0)) + + def get_device_at(self, index: int) -> DeviceAccess: + """Return the (SI-wrapped) device at ``index``.""" + return self._items[index] + + def len(self) -> int: + """Return the number of devices.""" + return len(self._items) + + def set(self, value: npt.NDArray[np.float64]): + """Convert SI setpoints to device units and write them.""" + self.raw.set(value if self._passthrough else np.asarray(value, dtype=float) / self.factors) + + def set_and_wait(self, value: npt.NDArray[np.float64]): + """Convert SI setpoints to device units, write them and wait.""" + self.raw.set_and_wait(value if self._passthrough else np.asarray(value, dtype=float) / self.factors) + + def get(self) -> npt.NDArray[np.float64]: + """Return all setpoints in SI.""" + v = self.raw.get() + return v if self._passthrough else np.asarray(v, dtype=float) * self.factors + + def readback(self) -> np.array: + """Return all readbacks in SI.""" + v = self.raw.readback() + return v if self._passthrough or v is None or len(v) == 0 else _scale(v, self.factors) + + def unit(self) -> list[str]: + """Return the SI unit of each device.""" + return [d.unit() for d in self._items] + + def get_range(self) -> list[float]: + """Return the ranges in SI.""" + rng = self.raw.get_range() + return rng if self._passthrough else _scale_range(rng, self.factors) + + def check_device_availability(self) -> bool: + """Check if all devices are available.""" + return self.raw.check_device_availability() diff --git a/pyaml/lattice/abstract_impl.py b/pyaml/lattice/abstract_impl.py index a734a587..5321036e 100644 --- a/pyaml/lattice/abstract_impl.py +++ b/pyaml/lattice/abstract_impl.py @@ -13,6 +13,7 @@ from ..common import abstract from ..common.abstract_aggregator import ScalarAggregator from ..common.exception import PyAMLException +from ..common.units import SI_ANGLE, SI_FREQUENCY, SI_POSITION, SI_TUNE, SI_VOLTAGE from ..magnet.model import MagnetModel from .polynom_info import PolynomInfo @@ -761,7 +762,7 @@ def readback(self) -> np.array: def unit(self) -> str: """Return the value unit.""" - return "m" + return SI_POSITION def _transform(self) -> np.array: """Transform the configured value for the lattice interface.""" @@ -887,7 +888,7 @@ def get(self) -> np.array: # Gets the unit of the value def unit(self) -> str: """Return the value unit.""" - return "m" + return SI_POSITION # ------------------------------------------------------------------------------ @@ -959,7 +960,7 @@ def set_and_wait(self, value: np.array): # Gets the unit of the value def unit(self) -> str: """Return the value unit.""" - return "m" # Assuming all offsets are in m + return SI_POSITION # ------------------------------------------------------------------------------ @@ -1036,7 +1037,7 @@ def set_and_wait(self, value: float): # Gets the unit of the value def unit(self) -> str: """Return the value unit.""" - return "rad" # Assuming BPM tilts are in rad + return SI_ANGLE # ------------------------------------------------------------------------------ @@ -1108,7 +1109,7 @@ def set_and_wait(self, value: float): def unit(self) -> str: """Return the value unit.""" - return "V" + return SI_VOLTAGE # ------------------------------------------------------------------------------ @@ -1183,7 +1184,7 @@ def set_and_wait(self, value: float): def unit(self) -> str: """Return the value unit.""" - return "rad" + return SI_ANGLE # ------------------------------------------------------------------------------ @@ -1254,7 +1255,7 @@ def set_and_wait(self, value: float): def unit(self) -> str: """Return the value unit.""" - return "Hz" + return SI_FREQUENCY # ------------------------------------------------------------------------------ @@ -1323,7 +1324,7 @@ def set_and_wait(self, value: float): def unit(self) -> str: """Return the value unit.""" - return "Hz" + return SI_FREQUENCY # ------------------------------------------------------------------------------ @@ -1392,7 +1393,7 @@ def set_and_wait(self, value: float): def unit(self) -> str: """Return the value unit.""" - return "V" + return SI_VOLTAGE # ------------------------------------------------------------------------------ @@ -1427,7 +1428,7 @@ def get(self) -> float: def unit(self) -> str: """Return the value unit.""" - return "1" + return SI_TUNE # ------------------------------------------------------------------------------ diff --git a/tests/diagnostics/bpm/test_bpm_controlsystem.py b/tests/diagnostics/bpm/test_bpm_controlsystem.py index 54eeb068..845b36a0 100644 --- a/tests/diagnostics/bpm/test_bpm_controlsystem.py +++ b/tests/diagnostics/bpm/test_bpm_controlsystem.py @@ -58,7 +58,7 @@ def test_controlsystem_bpm_position(install_test_package): def test_controlsystem_get_devices_returns_attached_devices(install_test_package): sr: Accelerator = Accelerator.load("tests/config/bpms.yaml") - devs = sr.live.get_devices_access(["srdiag/bpm/c01-01/SA_HPosition", "srdiag/bpm/c01-01/SA_VPosition"]) + devs = [sr.live.get_device_access(name) for name in ["srdiag/bpm/c01-01/SA_HPosition", "srdiag/bpm/c01-01/SA_VPosition"]] assert devs[0].name() == "//ebs-simu-3:10000/srdiag/bpm/c01-01/SA_HPosition" assert devs[1].name() == "//ebs-simu-3:10000/srdiag/bpm/c01-01/SA_VPosition" @@ -93,7 +93,7 @@ def test_controlsystem_bpm_position_indexed(install_test_package): sr: Accelerator = Accelerator.load("tests/config/bpms.yaml") bpm = sr.live.diagnostic.bpm.get("BPM_C01-04") - assert np.allclose(bpm.positions.get(), np.array([0.0, 1.0])) + assert np.allclose(bpm.positions.get(), np.array([0.0, 1.0e-3])) def _single_plane_bpm_config() -> dict: @@ -144,8 +144,8 @@ def test_controlsystem_bpm_single_plane(install_test_package): pos = xbpm.positions.get() assert np.isnan(pos[0]) - assert pos[1] == pytest.approx(0.3) - assert xbpm.positions.unit() == "mm" + assert pos[1] == pytest.approx(0.3e-3) + assert xbpm.positions.unit() == "m" @pytest.mark.parametrize( @@ -164,20 +164,20 @@ def test_controlsystem_bpm_array_with_single_plane_bpm(install_test_package): pos = bpms.positions.get() assert pos.shape == (3, 2) assert np.isnan(pos[2, 0]) - assert np.allclose(pos[:2], [[0.1, -0.1], [0.2, -0.2]]) - assert pos[2, 1] == pytest.approx(0.3) + assert np.allclose(pos[:2], [[0.1e-3, -0.1e-3], [0.2e-3, -0.2e-3]]) + assert pos[2, 1] == pytest.approx(0.3e-3) h = bpms.h.get() - assert np.allclose(h[:2], [0.1, 0.2]) + assert np.allclose(h[:2], [0.1e-3, 0.2e-3]) assert np.isnan(h[2]) - assert np.allclose(bpms.v.get(), [-0.1, -0.2, 0.3]) + assert np.allclose(bpms.v.get(), [-0.1e-3, -0.2e-3, 0.3e-3]) # The missing plane must not disable the grouped reads agg, aggh, aggv = sr.live.create_bpm_aggregators(list(bpms)) assert [agg.nb_device(), aggh.nb_device(), aggv.nb_device()] == [6, 3, 3] assert np.allclose(agg.get(), pos.flatten(), equal_nan=True) assert np.allclose(aggh.get(), h, equal_nan=True) - assert np.allclose(aggv.get(), [-0.1, -0.2, 0.3]) + assert np.allclose(aggv.get(), [-0.1e-3, -0.2e-3, 0.3e-3]) @pytest.mark.parametrize( @@ -195,5 +195,5 @@ def test_controlsystem_bpm_array_without_horizontal_plane(install_test_package): bpms = sr.live.diagnostic.bpms.get("BPM") assert np.isnan(bpms.h.get()).all() - assert np.allclose(bpms.v.get(), [0.3]) + assert np.allclose(bpms.v.get(), [0.3e-3]) assert bpms.positions.get().shape == (1, 2) diff --git a/tests/magnet/test_load_quad.py b/tests/magnet/test_load_quad.py index 386382b4..f104d3c6 100644 --- a/tests/magnet/test_load_quad.py +++ b/tests/magnet/test_load_quad.py @@ -133,7 +133,7 @@ def test_combined_function_magnets(magnet_file, config_root_dir): ) sh: CombinedFunctionMagnet = Factory.build(cfg_sh, False) sh.model.set_magnet_rigidity(6e9 / speed_of_light) - devs = cs.get_devices_access(sh.model.get_device_names()) + devs = [cs.get_device_access(name) for name in sh.model.get_device_names()] currents = RWHardwareArray(sh.model, devs) strengths = RWStrengthArray(sh.model, devs) sUnits = sh.model.get_strength_units() diff --git a/tests/magnet/test_ranges_cfm_deviceaccess.py b/tests/magnet/test_ranges_cfm_deviceaccess.py index 6316cc94..5104b2ab 100644 --- a/tests/magnet/test_ranges_cfm_deviceaccess.py +++ b/tests/magnet/test_ranges_cfm_deviceaccess.py @@ -50,7 +50,7 @@ def test_cfm_ranges_from_yaml_are_propagated_and_enforced(magnet_file, install_t [-1.5, None], ] - devs = sr.live.get_devices_access(dev_names) + devs = [sr.live.get_device_access(name) for name in dev_names] got_ranges = [d.get_range() for d in devs] assert got_ranges == expected_ranges diff --git a/tests/test_catalogs.py b/tests/test_catalogs.py index bbe42f46..4c92bb36 100644 --- a/tests/test_catalogs.py +++ b/tests/test_catalogs.py @@ -186,5 +186,6 @@ def test_indexed_catalog_entry_extracts_scalar_from_vector_attribute(install_tes bpm = sr.live.diagnostic.bpm.get("BPM_TEST") positions = bpm.positions.get() - assert np.isclose(positions[0], 1.5) - assert np.isclose(positions[1], -0.3) + # Device values are in mm, PyAML returns SI (m) + assert np.isclose(positions[0], 1.5e-3) + assert np.isclose(positions[1], -0.3e-3) From c29cd3de5765eab553d3822f109b09b313704943 Mon Sep 17 00:00:00 2001 From: Alexis Gamelin Date: Tue, 10 Nov 2026 18:01:07 +0100 Subject: [PATCH 3/8] Accept pint quantities in set() and set_energy() (#350) Read/write interfaces and scalar aggregators inherit the AcceptsQuantity mixin, so every set()/set_and_wait() implementation, including external ones, converts a pint.Quantity to its unit() before writing. get() still returns plain floats. Add tests for the whole SI conversion feature. Co-Authored-By: Claude Opus 5.5 --- pyaml/accelerator.py | 6 +- pyaml/common/abstract.py | 6 +- pyaml/common/abstract_aggregator.py | 4 +- tests/test_units.py | 364 ++++++++++++++++++++++++++++ 4 files changed, 375 insertions(+), 5 deletions(-) create mode 100644 tests/test_units.py diff --git a/pyaml/accelerator.py b/pyaml/accelerator.py index 0b82df7a..90d83961 100644 --- a/pyaml/accelerator.py +++ b/pyaml/accelerator.py @@ -8,6 +8,7 @@ from .common.element import Element, __pyaml_repr__ from .common.exception import PyAMLConfigException, PyAMLException from .common.holders.element_holder import ElementHolder +from .common.units import to_magnitude from .configuration import ConfigurationManager, UnsupportedConfigurationRootError from .configuration.factory import Factory from .control.controlsystem import ControlSystem @@ -223,9 +224,10 @@ def set_energy(self, E: float): Parameters ---------- - E : float - Energy value to set in eV + E : float or pint.Quantity + Energy value to set in eV (a quantity is converted to eV) """ + E = to_magnitude(E, "eV") self._set_properties("_set_energy", E) self._energy = E diff --git a/pyaml/common/abstract.py b/pyaml/common/abstract.py index 39805038..5b9e484c 100644 --- a/pyaml/common/abstract.py +++ b/pyaml/common/abstract.py @@ -10,10 +10,12 @@ from numpy import array, double +from .units import AcceptsQuantity + # Float ---------------------------------------------------------------- -class ReadFloatScalar(metaclass=ABCMeta): +class ReadFloatScalar(AcceptsQuantity, metaclass=ABCMeta): """ Define read-only access to one floating-point value. @@ -88,7 +90,7 @@ def set_and_wait(self, value: double): pass -class ReadFloatArray(metaclass=ABCMeta): +class ReadFloatArray(AcceptsQuantity, metaclass=ABCMeta): """ Define read-only access to an array of floating-point values. diff --git a/pyaml/common/abstract_aggregator.py b/pyaml/common/abstract_aggregator.py index 7a80d644..38399a74 100644 --- a/pyaml/common/abstract_aggregator.py +++ b/pyaml/common/abstract_aggregator.py @@ -9,8 +9,10 @@ import numpy as np import numpy.typing as npt +from .units import AcceptsQuantity -class ScalarAggregator(metaclass=ABCMeta): + +class ScalarAggregator(AcceptsQuantity, metaclass=ABCMeta): """ Abstract class providing access to a list of scalar variables diff --git a/tests/test_units.py b/tests/test_units.py new file mode 100644 index 00000000..20692f7e --- /dev/null +++ b/tests/test_units.py @@ -0,0 +1,364 @@ +"""Tests of the SI unit conversion (issue #350).""" + +import numpy as np +import pint +import pytest + +from pyaml.accelerator import Accelerator +from pyaml.common.exception import PyAMLConfigException, PyAMLException +from pyaml.common.units import conversion_factor, get_registry, normalize_unit, to_magnitude + +TANGO = pytest.mark.parametrize( + "install_test_package", + [{"name": "tango-pyaml", "path": "tests/dummy_cs/tango-pyaml"}], + indirect=True, +) + +ureg = get_registry() + + +# --------------------------------------------------------------------------- units module + + +@pytest.mark.parametrize( + "src,dst,k", + [ + ("nm", "m", 1e-9), + ("mm", "m", 1e-3), + ("MHz", "Hz", 1e6), + ("kV", "V", 1e3), + ("mrad", "rad", 1e-3), + ("deg", "rad", np.pi / 180), + ("mA", "A", 1e-3), + ("m-1", "1/m", 1.0), + ("T.m", "T*m", 1.0), + ], +) +def test_conversion_factor(src, dst, k): + assert conversion_factor(src, dst) == pytest.approx(k) + + +@pytest.mark.parametrize("src,dst", [("", "m"), (None, "m"), ("mm", ""), ("A", "A"), ("whatever", "whatever")]) +def test_conversion_factor_passthrough(src, dst): + assert conversion_factor(src, dst) == 1.0 + + +@pytest.mark.parametrize("src,dst", [("A", "m"), ("foo", "m"), ("degC", "K"), ("%", "rad"), ("count", "rad")]) +def test_conversion_factor_errors(src, dst): + with pytest.raises(PyAMLConfigException): + conversion_factor(src, dst) + + +def test_normalize_unit(): + assert normalize_unit(" m-2 ") == "m^-2" + assert normalize_unit("T.m") == "T*m" + assert normalize_unit("mm") == "mm" + + +def test_to_magnitude(): + assert to_magnitude(1.5, "m") == 1.5 + assert to_magnitude(3 * ureg.mm, "m") == pytest.approx(3e-3) + assert np.allclose(to_magnitude(np.array([1.0, 2.0]) * ureg.mm, "m"), [1e-3, 2e-3]) + assert np.allclose(to_magnitude([1 * ureg.mm, 2 * ureg.um], ["m", "m"]), [1e-3, 2e-6]) + assert to_magnitude(0.2 * ureg.dimensionless, "1") == pytest.approx(0.2) + # A quantity from another registry is accepted too + assert to_magnitude(pint.UnitRegistry().Quantity(352, "MHz"), "Hz") == pytest.approx(352e6) + with pytest.raises(PyAMLException): + to_magnitude(1 * ureg.A, "Hz") + + +def test_to_magnitude_scalar_quantity_broadcast_to_unit_list(): + assert np.allclose(to_magnitude(2 * ureg.mm, ["m", "km"]), [2e-3, 2e-6]) + with pytest.raises(PyAMLException): + to_magnitude(0.5 / ureg.m, ["1/m", "1/m**2"]) + + +def test_read_write_interfaces_accept_quantity(): + from pyaml.common.abstract import ReadFloatScalar + + class Tilt(ReadFloatScalar): # Read-only interface with a setter, like the BPM tilt + def __init__(self): + self.value = 0.0 + + def get(self): + return self.value + + def set(self, value): + self.value = value + + def unit(self): + return "rad" + + t = Tilt() + t.set(1 * ureg.mrad) + assert t.value == pytest.approx(1e-3) + + +def test_hardware_unit_of_model(): + from pyaml.control.controlsystem import _hardware_unit + + class Model: + def __init__(self, units): + self.units = units + + def get_hardware_units(self): + return self.units + + assert _hardware_unit(Model(["A"]), 2) == "A" # One unit shared by all devices + assert _hardware_unit(Model(["A", "mA"]), 1) == "mA" + assert _hardware_unit(Model([None]), 0) == "" + with pytest.raises(PyAMLConfigException): + _hardware_unit(Model(["A", "A"]), 2) + + +# --------------------------------------------------------------------------- control system + + +def _entry(key: str, unit: str, range=None, read_only=False) -> dict: + device = { + "type": "tango.pyaml.attribute_read_only" if read_only else "tango.pyaml.attribute", + "attribute": f"sr/test/{key}", + "unit": unit, + } + if range is not None: + device["range"] = range + return {"type": "tango.pyaml.static_catalog_entry", "key": key, "device": device} + + +def _quad(name: str, ps: str) -> dict: + return { + "type": "pyaml.magnet.quadrupole", + "name": name, + "model": { + "type": "pyaml.magnet.linear_model", + "calibration_factor": 0.01, + "unit": "1/m", + "hardware_unit": "A", + "powerconverter": ps, + }, + } + + +def _config(bpm_unit="mm", freq_unit="MHz", volt_unit="kV", phase_unit="deg", ps_unit="mA") -> dict: + entries = [ + _entry("bpm1/H", bpm_unit, read_only=True), + _entry("bpm1/V", bpm_unit, read_only=True), + _entry("bpm2/H", bpm_unit, read_only=True), + _entry("bpm2/V", bpm_unit, read_only=True), + _entry("rf/freq", freq_unit, range=[352.0, 353.0]), + _entry("rf/volt", volt_unit), + _entry("rf/phase", phase_unit), + _entry("ps/q1", ps_unit), + _entry("ps/q2", ps_unit), + ] + return { + "type": "pyaml.accelerator", + "facility": "ESRF", + "machine": "sr", + "energy": 6e9, + "data_folder": "/data/store", + "controls": [ + { + "type": "tango.pyaml.controlsystem", + "tango_host": "ebs-simu-3:10000", + "name": "live", + "catalog": {"type": "tango.pyaml.static_catalog", "entries": entries}, + } + ], + "arrays": [ + {"type": "pyaml.arrays.bpm", "name": "BPM", "elements": ["BPM1", "BPM2"]}, + {"type": "pyaml.arrays.magnet", "name": "QUADS", "elements": ["Q1", "Q2"]}, + ], + "devices": [ + {"type": "pyaml.diagnostics.bpm.bpm", "name": "BPM1", "x_pos": "bpm1/H", "y_pos": "bpm1/V"}, + {"type": "pyaml.diagnostics.bpm.bpm", "name": "BPM2", "x_pos": "bpm2/H", "y_pos": "bpm2/V"}, + { + "type": "pyaml.rf.rf_plant", + "name": "RF", + "masterclock": "rf/freq", + "transmitters": [ + { + "type": "pyaml.rf.rf_transmitter", + "name": "RFTRA", + "cavities": ["CAV1"], + "voltage": "rf/volt", + "phase": "rf/phase", + } + ], + }, + _quad("Q1", "ps/q1"), + _quad("Q2", "ps/q2"), + ], + } + + +@TANGO +def test_bpm_positions_are_converted_to_si(install_test_package): + from tango.pyaml.attribute_store import get_attribute, set_attribute + + for key, value in [("bpm1/H", 0.1), ("bpm1/V", -0.2), ("bpm2/H", 0.3), ("bpm2/V", -0.4)]: + set_attribute(f"sr/test/{key}", value, unit="mm") + sr = Accelerator.from_dict(_config()) + + bpm = sr.live.diagnostic.bpm.get("BPM1") + assert np.allclose(bpm.positions.get(), [0.1e-3, -0.2e-3]) + assert bpm.positions.unit() == "m" + + # The grouped read gives the same values as the per-element reads + bpms = sr.live.diagnostic.bpms.get("BPM") + assert np.allclose(bpms.positions.get(), [[0.1e-3, -0.2e-3], [0.3e-3, -0.4e-3]]) + assert np.allclose(bpms.h.get(), [0.1e-3, 0.3e-3]) + assert np.allclose(bpms.v.get(), [-0.2e-3, -0.4e-3]) + + # The raw control-system value is untouched + assert get_attribute("sr/test/bpm1/H") == pytest.approx(0.1) + + +@TANGO +def test_rf_is_converted_to_si(install_test_package): + from tango.pyaml.attribute_store import get_attribute + + sr = Accelerator.from_dict(_config()) + rf = sr.live.rf.get("RF") + tra = sr.live.rf.transmitter.get("RFTRA") + + rf.frequency.set(352.2e6) + assert get_attribute("sr/test/rf/freq") == pytest.approx(352.2) + assert rf.frequency.get() == pytest.approx(352.2e6) + assert rf.frequency.unit() == "Hz" + + tra.voltage.set(1.5e6) + assert get_attribute("sr/test/rf/volt") == pytest.approx(1500.0) + assert tra.voltage.get() == pytest.approx(1.5e6) + assert tra.voltage.unit() == "V" + + tra.phase.set(np.pi / 2) + assert get_attribute("sr/test/rf/phase") == pytest.approx(90.0) + assert tra.phase.get() == pytest.approx(np.pi / 2) + assert tra.phase.unit() == "rad" + + +@TANGO +def test_set_accepts_quantity_on_control_system(install_test_package): + from tango.pyaml.attribute_store import get_attribute + + sr = Accelerator.from_dict(_config()) + rf = sr.live.rf.get("RF") + tra = sr.live.rf.transmitter.get("RFTRA") + + rf.frequency.set(352.3 * ureg.MHz) + assert get_attribute("sr/test/rf/freq") == pytest.approx(352.3) + tra.voltage.set(0.8 * ureg.MV) + assert get_attribute("sr/test/rf/volt") == pytest.approx(800.0) + tra.phase.set(45 * ureg.deg) + assert get_attribute("sr/test/rf/phase") == pytest.approx(45.0) + + q1 = sr.live.magnet.get("Q1") + q1.hardware.set(2 * ureg.A) + assert get_attribute("sr/test/ps/q1") == pytest.approx(2000.0) + + # Arrays and aggregators accept quantities too + quads = sr.live.magnets.get("QUADS") + quads.hardwares.set(np.array([1.0, 3.0]) * ureg.A) + assert get_attribute("sr/test/ps/q1") == pytest.approx(1000.0) + assert get_attribute("sr/test/ps/q2") == pytest.approx(3000.0) + + with pytest.raises(PyAMLException): + rf.frequency.set(1 * ureg.A) + + +@TANGO +def test_range_is_converted_to_si(install_test_package): + sr = Accelerator.from_dict(_config()) + rf = sr.live.rf.get("RF") + rf.frequency.set(352.5e6) # Within [352, 353] MHz + dev_range = sr.live.get_si_device_access("rf/freq", "Hz").get_range() + assert np.allclose(dev_range, [352e6, 353e6]) + + +@TANGO +def test_magnet_device_unit_is_converted_to_model_hardware_unit(install_test_package): + from tango.pyaml.attribute_store import get_attribute, set_attribute + + set_attribute("sr/test/ps/q1", 5000.0, unit="mA") + set_attribute("sr/test/ps/q2", 7000.0, unit="mA") + sr = Accelerator.from_dict(_config()) + + q1 = sr.live.magnet.get("Q1") + assert q1.hardware.get() == pytest.approx(5.0) + assert q1.hardware.unit() == "A" + + # Strength computed from the current in A, same result as a device declared in A + sr_a = Accelerator.from_dict(_config(ps_unit="A")) + set_attribute("sr/test/ps/q1", 5.0) + assert q1.strength.get() == pytest.approx(sr_a.live.magnet.get("Q1").strength.get()) + set_attribute("sr/test/ps/q1", 5000.0) + + # Strength aggregator (grouped access) is consistent with element access + quads = sr.live.magnets.get("QUADS") + strengths = quads.strengths.get() + assert strengths[0] == pytest.approx(q1.strength.get()) + quads.strengths.set(strengths * 2) + assert get_attribute("sr/test/ps/q1") == pytest.approx(10000.0) + assert get_attribute("sr/test/ps/q2") == pytest.approx(14000.0) + assert np.allclose(quads.hardwares.get(), [10.0, 14.0]) + + +@TANGO +def test_strength_aggregator_unit_and_quantity(install_test_package): + from tango.pyaml.attribute_store import get_attribute + + sr = Accelerator.from_dict(_config()) + agg = sr.live.create_magnet_strength_aggregator(list(sr.live.magnets.get("QUADS"))) + assert agg.unit() == ["1/m", "1/m"] + agg.set(np.array([0.01, 0.02]) / ureg.m) + q1, q2 = sr.live.magnet.get("Q1"), sr.live.magnet.get("Q2") + assert [q1.strength.get(), q2.strength.get()] == pytest.approx([0.01, 0.02]) + assert get_attribute("sr/test/ps/q1") == pytest.approx(1000 * q1.hardware.get()) + + +@TANGO +def test_device_unit_error_is_not_swallowed(install_test_package): + from pyaml.control.si_deviceaccess import wrap_si + + sr = Accelerator.from_dict(_config()) + dev = sr.live.get_device_access("bpm1/H") + + def broken_unit(): + raise RuntimeError("device offline") + + dev.unit = broken_unit + with pytest.raises(RuntimeError, match="device offline"): + wrap_si(dev, "m") + + +@TANGO +def test_incompatible_device_unit_raises_at_load(install_test_package): + with pytest.raises(PyAMLConfigException, match="cannot be converted"): + Accelerator.from_dict(_config(bpm_unit="A")) + + +@TANGO +def test_device_without_unit_is_passthrough(install_test_package): + from tango.pyaml.attribute_store import get_attribute + + sr = Accelerator.from_dict(_config(freq_unit="")) + sr.live.rf.get("RF").frequency.set(352.5) + assert get_attribute("sr/test/rf/freq") == pytest.approx(352.5) + + +# --------------------------------------------------------------------------- simulator + + +def test_set_accepts_quantity_on_simulator(): + sr = Accelerator.load("tests/config/EBS_rf.yaml", ignore_external=True) + sr.design.rf.frequency.set(352.3 * ureg.MHz) + assert sr.design.rf.frequency.get() == pytest.approx(352.3e6) + with pytest.raises(PyAMLException): + sr.design.rf.frequency.set(1 * ureg.m) + + +def test_set_energy_accepts_quantity(): + sr = Accelerator.load("tests/config/EBS_rf.yaml", ignore_external=True) + sr.set_energy(6 * ureg.GeV) + assert sr._energy == pytest.approx(6e9) From 130912b30ae3b8db26867abbe04f606a4da0d343 Mon Sep 17 00:00:00 2001 From: Alexis Gamelin Date: Tue, 17 Nov 2026 11:07:16 +0100 Subject: [PATCH 4/8] Fix BESSY II configuration --- examples/use_cases/config/bessy2/bessy2.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/use_cases/config/bessy2/bessy2.yaml b/examples/use_cases/config/bessy2/bessy2.yaml index 8d5d1f35..1271ac4c 100644 --- a/examples/use_cases/config/bessy2/bessy2.yaml +++ b/examples/use_cases/config/bessy2/bessy2.yaml @@ -347,7 +347,7 @@ devices: response_matrix: ${path:orm.json} - class: pyaml.rf.rf_plant.RFPlant name: RF - masterclock: (MCLKHX251C:freq)[KHz] + masterclock: (MCLKHX251C:freq)[kHz] - class: pyaml.magnet.hcorrector.HCorrector name: HS4M2D1R lattice_names: S4M2D1R@0 From 6d3adc079f31021f03fb21344895ee8cbc8116f4 Mon Sep 17 00:00:00 2001 From: Alexis Gamelin Date: Fri, 20 Nov 2026 15:48:10 +0100 Subject: [PATCH 5/8] Address review of SI unit conversion (#350) - Add get(quantity=True) returning a pint.Quantity in unit(), and control_system_unit() reporting the unit of the control-system devices (same as unit() when no device holds the value). - unit()/control_system_unit() return a single unit when all values share it, one unit per value (shaped like get()) only when they differ, e.g. combined-function magnets or mixed magnet families. This changes the return type of the BPM, magnet, CFM and serialized arrays, which always returned one unit per element. - Report units in a canonical form (pint compact format, "1" for dimensionless) so that equivalent spellings compare equal: m-1 -> 1/m, T.m -> m*T. Accepted unit formats are documented in pyaml.common.units. - Fix serialized magnet arrays building unit() by extending a list with a string, which split the unit into characters. - Reject a dimensioned device unit for a dimensionless target (e.g. a tune device declared in Hz or mm) instead of passing it through; fix the tune unit in tests/config/EBSTuneOATango.yaml. - Divide by the conversion factor on write so that setpoints are correctly rounded (352.372e6 Hz is written as 352.372 MHz). - Harmonise unit() and control_system_unit() docstrings. Co-Authored-By: Claude Opus 5.5 --- pyaml/arrays/bpm_array.py | 37 ++- pyaml/arrays/cfm_magnet_array.py | 34 ++- pyaml/arrays/magnet_array.py | 23 +- pyaml/arrays/serialized_magnet_array.py | 29 +-- pyaml/common/abstract.py | 101 +++++++- pyaml/common/abstract_aggregator.py | 34 ++- pyaml/common/units.py | 279 +++++++++++++++++++-- pyaml/control/abstract_impl.py | 150 ++++++++--- pyaml/control/controlsystem.py | 7 +- pyaml/control/deviceaccess.py | 4 +- pyaml/control/deviceaccesslist.py | 6 +- pyaml/control/si_deviceaccess.py | 72 ++++-- pyaml/diagnostics/tune_monitor.py | 4 +- pyaml/lattice/abstract_impl.py | 74 +++--- pyaml/magnet/corrector.py | 6 +- pyaml/magnet/serialized_magnet.py | 14 +- pyaml/rf/rf_plant.py | 7 +- pyaml/tuning_tools/chromaticity_monitor.py | 4 +- tests/arrays/test_arrays.py | 4 +- tests/config/EBSTuneOATango.yaml | 4 +- tests/test_units.py | 237 ++++++++++++++++- tests/tuning_tools/test_tune_hardware.py | 2 +- 22 files changed, 921 insertions(+), 211 deletions(-) diff --git a/pyaml/arrays/bpm_array.py b/pyaml/arrays/bpm_array.py index f3751226..02e5d6f6 100644 --- a/pyaml/arrays/bpm_array.py +++ b/pyaml/arrays/bpm_array.py @@ -9,6 +9,7 @@ from pyaml.diagnostics.bpm import BPM from ..common.abstract import ReadFloatArray +from ..common.units import common_unit, per_value_units from ..control.deviceaccesslist import DeviceAccessList from .element_array import ElementArray @@ -33,7 +34,9 @@ class RWBPMPosition(ReadFloatArray): get() Get BPM positions. unit() - Get the units for BPM positions. + Return the pyAML unit for this quantity, i.e. returned by get(). + control_system_unit() + Return the control-system unit for this quantity. set_aggregator(agg) Set the device access list aggregator for improved performance. """ @@ -63,16 +66,20 @@ def get(self) -> np.array: return self.__aggregator.get().reshape(len(self.__bpms), 2) # Gets the unit of the values - def unit(self) -> list[str]: + def unit(self) -> str | list[list[str]]: """ - Get the units for BPM positions. + Return the pyAML unit for this quantity, i.e. returned by get(). Returns ------- - list[str] - List of unit strings for each BPM + str or list[list[str]] + Unit label, or one per value (shaped like get()) if they differ. """ - return [b.positions.unit() for b in self.__bpms] + return common_unit([per_value_units(b.positions.unit(), 2) for b in self.__bpms]) + + def control_system_unit(self) -> str | list[list[str | None]] | None: + """Return the control-system unit for this quantity.""" + return common_unit([per_value_units(b.positions.control_system_unit(), 2) for b in self.__bpms]) # Set the aggregator (Control system only) def set_aggregator(self, agg: DeviceAccessList): @@ -109,7 +116,9 @@ class RWBPMSinglePosition(ReadFloatArray): get() Get single axis BPM positions. unit() - Get the units for BPM positions. + Return the pyAML unit for this quantity, i.e. returned by get(). + control_system_unit() + Return the control-system unit for this quantity. set_aggregator(agg) Set the device access list aggregator for improved performance. """ @@ -139,16 +148,20 @@ def get(self) -> np.array: return self.__aggregator.get() # Gets the unit of the values - def unit(self) -> list[str]: + def unit(self) -> str | list[str]: """ - Get the units for BPM positions. + Return the pyAML unit for this quantity, i.e. returned by get(). Returns ------- - list[str] - List of unit strings for each BPM + str or list[str] + Unit label, or one per value if they differ. """ - return [b.positions.unit() for b in self.__bpms] + return common_unit([per_value_units(b.positions.unit(), 2)[self.__idx] for b in self.__bpms]) + + def control_system_unit(self) -> str | list[str | None] | None: + """Return the control-system unit for this quantity.""" + return common_unit([per_value_units(b.positions.control_system_unit(), 2)[self.__idx] for b in self.__bpms]) # Set the aggregator (Control system only) def set_aggregator(self, agg: DeviceAccessList): diff --git a/pyaml/arrays/cfm_magnet_array.py b/pyaml/arrays/cfm_magnet_array.py index fcedc5b6..1950b8c0 100644 --- a/pyaml/arrays/cfm_magnet_array.py +++ b/pyaml/arrays/cfm_magnet_array.py @@ -8,6 +8,7 @@ from ..common.abstract import ReadWriteFloatArray from ..common.exception import PyAMLException +from ..common.units import common_unit, per_value_units from ..magnet.cfm_magnet import CombinedFunctionMagnet from .element_array import ElementArray @@ -34,7 +35,7 @@ class RWMagnetStrengths(ReadWriteFloatArray): set_and_wait(value) Set every multipole strength and wait for the readbacks to converge. unit() - Return the strength unit of every multipole. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). """ def __init__(self, name: str, magnets: list[CombinedFunctionMagnet]): @@ -89,12 +90,12 @@ def set_and_wait(self, value: np.array): raise NotImplementedError("Not implemented yet.") # Gets the unit of the values - def unit(self) -> list[str]: - """Return the strength unit of every multipole.""" - r = [] + def unit(self) -> str | list[str]: + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + units = [] for m in self.__magnets: - r.extend(m.strengths.unit()) - return r + units.extend(per_value_units(m.strengths.unit(), len(m.model.get_strength_units()))) + return common_unit(units) class RWMagnetHardwares(ReadWriteFloatArray): @@ -117,7 +118,9 @@ class RWMagnetHardwares(ReadWriteFloatArray): set_and_wait(value) Set every hardware value and wait for the readbacks to converge. unit() - Return the hardware unit of every multipole. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit for this quantity. """ def __init__(self, name: str, magnets: list[CombinedFunctionMagnet]): @@ -172,12 +175,19 @@ def set_and_wait(self, value: np.array): raise NotImplementedError("Not implemented yet.") # Gets the unit of the values - def unit(self) -> list[str]: - """Return the hardware unit of every multipole.""" - r = [] + def unit(self) -> str | list[str]: + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + units = [] for m in self.__magnets: - r.extend(m.hardwares.unit()) - return r + units.extend(per_value_units(m.hardwares.unit(), len(m.model.get_hardware_units()))) + return common_unit(units) + + def control_system_unit(self) -> str | list[str | None] | None: + """Return the control-system unit for this quantity.""" + units = [] + for m in self.__magnets: + units.extend(per_value_units(m.hardwares.control_system_unit(), len(m.model.get_hardware_units()))) + return common_unit(units) class CombinedFunctionMagnetArray(ElementArray): diff --git a/pyaml/arrays/magnet_array.py b/pyaml/arrays/magnet_array.py index 55d6854c..abf03f39 100644 --- a/pyaml/arrays/magnet_array.py +++ b/pyaml/arrays/magnet_array.py @@ -10,6 +10,7 @@ from ..common.abstract import ReadWriteFloatArray from ..common.abstract_aggregator import ScalarAggregator +from ..common.units import common_unit from ..magnet.magnet import Magnet from .element_array import ElementArray @@ -34,7 +35,7 @@ class RWMagnetStrength(ReadWriteFloatArray): set_and_wait(value) Set every strength and wait for the readbacks to converge. unit() - Return the strength unit of every magnet in the array. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). set_aggregator(agg) Install an aggregator so the array is read and written in a single call. """ @@ -99,9 +100,9 @@ def set_and_wait(self, value: np.array): raise NotImplementedError("Not implemented yet.") # Gets the unit of the values - def unit(self) -> list[str]: - """Return the strength unit of every magnet in the array.""" - return [m.strength.unit() for m in self.__magnets] + def unit(self) -> str | list[str]: + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return common_unit([m.strength.unit() for m in self.__magnets]) # Set the aggregator (Control system only) def set_aggregator(self, agg: ScalarAggregator): @@ -137,7 +138,9 @@ class RWMagnetHardware(ReadWriteFloatArray): set_and_wait(value) Set every hardware value and wait for the readbacks to converge. unit() - Return the hardware unit of every magnet in the array. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit for this quantity. set_aggregator(agg) Install an aggregator so the array is read and written in a single call. """ @@ -194,9 +197,13 @@ def set_and_wait(self, value: np.array): raise NotImplementedError("Not implemented yet.") # Gets the unit of the values - def unit(self) -> list[str]: - """Return the hardware unit of every magnet in the array.""" - return [m.hardware.unit() for m in self.__magnets] + def unit(self) -> str | list[str]: + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return common_unit([m.hardware.unit() for m in self.__magnets]) + + def control_system_unit(self) -> str | list[str | None] | None: + """Return the control-system unit for this quantity.""" + return common_unit([m.hardware.control_system_unit() for m in self.__magnets]) # Set the aggregator def set_aggregator(self, agg: ScalarAggregator): diff --git a/pyaml/arrays/serialized_magnet_array.py b/pyaml/arrays/serialized_magnet_array.py index c891e5c6..76b92df0 100644 --- a/pyaml/arrays/serialized_magnet_array.py +++ b/pyaml/arrays/serialized_magnet_array.py @@ -8,6 +8,7 @@ from ..common.abstract import ReadWriteFloatArray from ..common.exception import PyAMLException +from ..common.units import common_unit from ..magnet.serialized_magnet import SerializedMagnets from .element_array import ElementArray @@ -34,7 +35,7 @@ class RWMagnetStrengths(ReadWriteFloatArray): set_and_wait(value) Set every shared strength and wait for the readbacks to converge. unit() - Return the strength unit of every serialized group. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). """ def __init__(self, name: str, magnets: list[SerializedMagnets]): @@ -82,12 +83,9 @@ def set_and_wait(self, value: np.array): raise NotImplementedError("Not implemented yet.") # Gets the unit of the values - def unit(self) -> list[str]: - """Return the strength unit of every serialized group.""" - r = [] - for m in self.__magnets: - r.extend(m.strength.unit()) - return r + def unit(self) -> str | list[str]: + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return common_unit([m.strength.unit() for m in self.__magnets]) class RWMagnetHardwares(ReadWriteFloatArray): @@ -110,7 +108,9 @@ class RWMagnetHardwares(ReadWriteFloatArray): set_and_wait(value) Set every shared hardware value and wait for the readbacks to converge. unit() - Return the hardware unit of every serialized group. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit for this quantity. """ def __init__(self, name: str, magnets: list[SerializedMagnets]): @@ -158,12 +158,13 @@ def set_and_wait(self, value: np.array): raise NotImplementedError("Not implemented yet.") # Gets the unit of the values - def unit(self) -> list[str]: - """Return the hardware unit of every serialized group.""" - r = [] - for m in self.__magnets: - r.extend(m.hardware.unit()) - return r + def unit(self) -> str | list[str]: + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return common_unit([m.hardware.unit() for m in self.__magnets]) + + def control_system_unit(self) -> str | list[str | None] | None: + """Return the control-system unit for this quantity.""" + return common_unit([m.hardware.control_system_unit() for m in self.__magnets]) class SerializedMagnetsArray(ElementArray): diff --git a/pyaml/common/abstract.py b/pyaml/common/abstract.py index 5b9e484c..acd4b453 100644 --- a/pyaml/common/abstract.py +++ b/pyaml/common/abstract.py @@ -21,10 +21,12 @@ class ReadFloatScalar(AcceptsQuantity, metaclass=ABCMeta): Methods ------- - get() + get(quantity=False) Return the current scalar value. unit() - Return the physical unit of the scalar value. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit for this quantity. """ @abstractmethod @@ -32,6 +34,11 @@ def get(self) -> double: """ Return the current scalar value. + Implementations take no argument: every subclass also accepts + ``get(quantity=True)``, which returns the value as a + :class:`pint.Quantity` in ``unit()`` (see + :class:`~pyaml.common.units.AcceptsQuantity`). + Returns ------- float @@ -42,7 +49,10 @@ def get(self) -> double: @abstractmethod def unit(self) -> str: """ - Return the physical unit of the scalar value. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + + A :class:`pint.Quantity` passed to ``set()`` is converted to this unit. + Unit strings use the pyAML canonical format (see :mod:`pyaml.common.units`). Returns ------- @@ -51,6 +61,21 @@ def unit(self) -> str: """ pass + def control_system_unit(self) -> str | None: + """ + Return the control-system unit for this quantity. + + Same as ``unit()`` by default, for values that no control-system + device holds (simulator, computed values). Unit strings use the pyAML + canonical format (see :mod:`pyaml.common.units`). + + Returns + ------- + str or None + Unit label. + """ + return self.unit() + class ReadWriteFloatScalar(ReadFloatScalar): """ @@ -96,22 +121,59 @@ class ReadFloatArray(AcceptsQuantity, metaclass=ABCMeta): Methods ------- - get() + get(quantity=False) Return the current values as an array. unit() - Return the units associated with the array values. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit for this quantity. """ @abstractmethod def get(self) -> array: - """Return the current values as an array.""" + """ + Return the current values as an array. + + Implementations take no argument: every subclass also accepts + ``get(quantity=True)``, which returns the values as a + :class:`pint.Quantity` in ``unit()`` (see + :class:`~pyaml.common.units.AcceptsQuantity`). + """ pass @abstractmethod - def unit(self) -> list[str]: - """Return the units associated with the array values.""" + def unit(self) -> str | list[str]: + """ + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + + A single unit when all values share it, one unit per value (shaped + like ``get()``) only when they differ. Unit strings use the pyAML canonical format + (see :mod:`pyaml.common.units`). + + Returns + ------- + str or list of str + Unit label(s). + """ pass + def control_system_unit(self) -> str | list[str | None] | None: + """ + Return the control-system unit for this quantity. + + A single unit when all devices share it, one unit per value (shaped + like ``get()``) only when they differ. Same as ``unit()`` by default, + for values that no control-system device holds (simulator, computed + values). Unit strings use the pyAML canonical format + (see :mod:`pyaml.common.units`). + + Returns + ------- + str or list of str or None + Unit label(s). + """ + return self.unit() + class ReadWriteFloatArray(ReadFloatScalar): """ @@ -171,7 +233,9 @@ class RWMapper(ReadWriteFloatScalar): set_and_wait(value) Set the value and wait for it to reach the setpoint. unit() - Get the unit for the value. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit for this quantity. index() Get the mapped array index. """ @@ -229,14 +293,27 @@ def set_and_wait(self, value: float): # Return the unit def unit(self) -> str: """ - Get the unit for the value. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). Returns ------- str - Unit string for the value at the mapped index + Unit label of the value at the mapped index. + """ + unit = self.bind.unit() + return unit if isinstance(unit, str) or unit is None else unit[self.idx] + + def control_system_unit(self) -> str | None: + """ + Return the control-system unit for this quantity. + + Returns + ------- + str or None + Unit label of the device at the mapped index. """ - return self.bind.unit()[self.idx] + unit = self.bind.control_system_unit() + return unit if isinstance(unit, str) or unit is None else unit[self.idx] # Return the mapped index def index(self) -> int: diff --git a/pyaml/common/abstract_aggregator.py b/pyaml/common/abstract_aggregator.py index 38399a74..20a50db3 100644 --- a/pyaml/common/abstract_aggregator.py +++ b/pyaml/common/abstract_aggregator.py @@ -22,12 +22,14 @@ class ScalarAggregator(AcceptsQuantity, metaclass=ABCMeta): Write a list of variable set_and_wait(value) Write a list of variable and wait that setpoint are reached - get() + get(quantity=False) Return a list variables readback() Return a list variables (measurements) unit() - Return the variables unit + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit for this quantity. """ @abstractmethod @@ -42,7 +44,12 @@ def set_and_wait(self, value: npt.NDArray[np.float64]): @abstractmethod def get(self) -> npt.NDArray[np.float64]: - """Return a list variables""" + """ + Return a list variables. + + Every subclass also accepts ``get(quantity=True)``, which returns the + values as a :class:`pint.Quantity` in ``unit()``. + """ pass @abstractmethod @@ -51,6 +58,23 @@ def readback(self) -> np.array: pass @abstractmethod - def unit(self) -> str: - """Return the variables unit""" + def unit(self) -> str | list[str]: + """ + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + + A single unit when all values share it, one unit per value only when + they differ. Unit strings use the pyAML canonical format + (see :mod:`pyaml.common.units`). + """ pass + + def control_system_unit(self) -> str | list[str | None] | None: + """ + Return the control-system unit for this quantity. + + A single unit when all devices share it, one unit per value only when + they differ. Same as ``unit()`` by default, for values that no + control-system device holds. Unit strings use the pyAML canonical format + (see :mod:`pyaml.common.units`). + """ + return self.unit() diff --git a/pyaml/common/units.py b/pyaml/common/units.py index 5577931e..db85936c 100644 --- a/pyaml/common/units.py +++ b/pyaml/common/units.py @@ -9,14 +9,36 @@ is not the SI unit expected by PyAML (see :class:`~pyaml.control.si_deviceaccess.SIDeviceAccess`); - to let users pass a :class:`pint.Quantity` to ``set()`` instead of a float - (see :func:`to_magnitude`). + (see :func:`to_magnitude`); +- optionally, to return a :class:`pint.Quantity` from ``get(quantity=True)`` + (see :func:`to_quantity`). ``get()`` returns plain floats by default. Conversions are purely multiplicative: offset units such as ``degC`` are rejected. + +Unit strings +------------ +Units accepted in configurations (magnet models, devices) and reported by the +control-system backends: + +- any unit expression understood by pint: unit symbols or names, with SI + prefixes, combined with ``*``, ``/`` and ``**`` or ``^`` for powers, e.g. + ``mm``, ``MHz``, ``kV``, ``mrad``, ``deg``, ``1/m**2``, ``T*m``; +- the accelerator notations ``m-1``, ``m-2`` (negative exponent) and ``T.m`` + (product), see :func:`normalize_unit`; +- ``""``, ``"none"`` or ``"No unit"``: no unit given, the value is assumed to + already be in the unit expected by PyAML (no conversion); +- ``"1"`` or ``"dimensionless"``: dimensionless value. + +Units reported by ``unit()`` and ``control_system_unit()`` are in a canonical +form, pint's compact abbreviated format (see :func:`format_unit`), so that two +spellings of the same unit compare equal: ``m-1``, ``1/m`` and ``m^-1`` are all +reported as ``1/m``, ``m-2`` as ``1/m**2``, ``T.m`` as ``m*T``, ``um`` as +``μm``; dimensionless values as ``"1"`` and a device without unit as ``""``. """ import re -from functools import lru_cache, wraps +from functools import cache, wraps from typing import Any import numpy as np @@ -24,7 +46,7 @@ from .exception import PyAMLConfigException, PyAMLException -# SI units in which PyAML exposes values, shared by the simulator and the control systems +# Units used by PyAML (interally and used by get/set methods). SI_POSITION = "m" SI_ANGLE = "rad" SI_VOLTAGE = "V" @@ -33,8 +55,10 @@ _UREG: pint.UnitRegistry | None = None -# Strings meaning "no unit": the value is passed through unchanged. -_NO_UNIT = ("", "1", "none", "no unit", "dimensionless") +# Strings meaning "no unit given" and "dimensionless": the value is passed through unchanged. +_NOT_GIVEN = ("", "none", "no unit") +_DIMENSIONLESS = ("1", "dimensionless") +_NO_UNIT = _NOT_GIVEN + _DIMENSIONLESS def get_registry() -> pint.UnitRegistry: @@ -75,7 +99,8 @@ def normalize_unit(unit: str) -> str: Rewrite accelerator-style unit strings in a syntax understood by pint. ``m-1`` becomes ``m^-1`` and ``T.m`` becomes ``T*m``. Other strings are - returned stripped and otherwise unchanged. + returned stripped and otherwise unchanged. See the "Unit strings" section + of :mod:`pyaml.common.units` for the accepted formats. Parameters ---------- @@ -100,7 +125,42 @@ def _parse_unit(unit: str): raise PyAMLConfigException(f"Unknown unit '{unit}': {e}") from e -@lru_cache(maxsize=None) +@cache +def format_unit(unit: str | None) -> str | None: + """ + Return the canonical form of a unit string. + + The canonical form is pint's compact abbreviated format (``~C``): ``m-1``, + ``1/m`` and ``m^-1`` all give ``1/m``, ``T.m`` gives ``m*T``. + + Parameters + ---------- + unit : str or None + Unit string, in any of the formats accepted by PyAML (see the "Unit + strings" section of :mod:`pyaml.common.units`). + + Returns + ------- + str or None + ``"1"`` for a dimensionless unit, ``""`` when no unit is given, + ``None`` for ``None``. A string that pint cannot parse is returned + stripped, unchanged. + """ + if unit is None: + return None + u = str(unit).strip() + if u.lower() in _NOT_GIVEN: + return "" + if u.lower() in _DIMENSIONLESS: + return "1" + try: + parsed = _parse_unit(u) + except PyAMLConfigException: + return u + return format(parsed, "~C") or "1" + + +@cache def conversion_factor(src: str | None, dst: str | None) -> float: """ Return the factor ``k`` such that ``value_dst = k * value_src``. @@ -115,9 +175,10 @@ def conversion_factor(src: str | None, dst: str | None) -> float: Returns ------- float - Multiplicative conversion factor. ``1.0`` when ``src`` or ``dst`` is - empty, ``None`` or dimensionless (passthrough: the value is assumed to - already be in the expected unit). + Multiplicative conversion factor. ``1.0`` when ``src`` is empty, + ``None`` or dimensionless (passthrough: the value is assumed to + already be in the expected unit). An empty ``dst`` means + dimensionless: ``src`` must then be dimensionless too (``%``...). Raises ------ @@ -125,11 +186,11 @@ def conversion_factor(src: str | None, dst: str | None) -> float: If a unit is unknown to pint, if the two units have different dimensions, or if the conversion is not purely multiplicative. """ - if _is_no_unit(src) or _is_no_unit(dst) or str(src).strip() == str(dst).strip(): + if _is_no_unit(src) or str(src).strip() == str(dst).strip(): return 1.0 ureg = get_registry() qsrc = ureg.Quantity(1.0, _parse_unit(src)) - udst = _parse_unit(dst) + udst = ureg.dimensionless if _is_no_unit(dst) else _parse_unit(dst) # Compare root units rather than dimensions: pint treats rad as dimensionless, # so a dimension check alone would accept '%' or 'count' for an angle. if qsrc.to_root_units().units != ureg.Quantity(1.0, udst).to_root_units().units: @@ -155,6 +216,68 @@ def has_quantity(value: Any) -> bool: return is_quantity(value) or (isinstance(value, (list, tuple)) and any(is_quantity(v) for v in value)) +def common_unit(units: list) -> str | list | None: + """ + Return the unit shared by all values, or the per-value units if they differ. + + Accessors report a single unit when all their values share it, and one + unit per value only when the units genuinely differ (e.g. strengths of + different multipoles). + + Parameters + ---------- + units : list + One unit per value, possibly nested to follow the shape of ``get()``. + ``None`` entries (no device behind a value) are ignored. + + Returns + ------- + str or list or None + The shared unit, ``units`` unchanged if they differ, ``None`` if + there is no unit at all. + """ + + def _flatten(items): + for u in items: + if isinstance(u, (list, tuple)): + yield from _flatten(u) + elif u is not None: + yield u + + flat = list(_flatten(units)) + if not flat: + return None + return flat[0] if len(set(flat)) == 1 else units + + +def per_value_units(unit: str | list[str] | None, n: int) -> list: + """ + Expand the ``unit()`` of an accessor of ``n`` values to one unit per value. + + Parameters + ---------- + unit : str or list of str or None + Unit as returned by ``unit()`` or ``control_system_unit()``. + n : int + Number of values of the accessor. + + Returns + ------- + list + ``n`` units. + + Raises + ------ + PyAMLException + If ``unit`` is a list whose length is not ``n``. + """ + if not isinstance(unit, (list, tuple)): + return [unit] * n + if len(unit) != n: + raise PyAMLException(f"Expected {n} units but got {len(unit)}") + return list(unit) + + def to_magnitude(value: Any, unit: str | list[str] | None) -> Any: """ Strip the unit of a user input, converting it to ``unit`` first. @@ -209,6 +332,77 @@ def to_magnitude(value: Any, unit: str | list[str] | None) -> Any: raise PyAMLException(f"Cannot convert {value} to '{unit}': {e}") from e +def to_quantity(value: Any, unit: str | list[str] | None) -> Any: + """ + Attach ``unit`` to a value returned by ``get()``. + + Parameters + ---------- + value : object + Float, array-like or ``None``, expressed in ``unit``. + unit : str or list of str or None + Unit of ``value`` (as returned by the accessor's ``unit()`` method), + either one for all values or one per element of ``value``. + + Returns + ------- + pint.Quantity or list of pint.Quantity or None + A single quantity when all values share the same unit. A list of + quantities, one per element, when the units differ (a pint array + cannot hold several units). ``None`` when ``value`` is ``None``. + + Raises + ------ + PyAMLException + If ``unit`` is unknown or if the number of units does not match ``value``. + """ + if value is None: + return None + if isinstance(unit, (list, tuple)): + if len(set(unit)) > 1: + if len(unit) != len(value): + raise PyAMLException(f"Expected {len(unit)} values but got {len(value)}") + return [to_quantity(v, u) for v, u in zip(value, unit, strict=True)] + unit = unit[0] if unit else None + ureg = get_registry() + try: + u = ureg.dimensionless if _is_no_unit(unit) else _parse_unit(unit) + except PyAMLConfigException as e: + raise PyAMLException(str(e)) from e + magnitude = float(value) if np.ndim(value) == 0 else np.asarray(value, dtype=float) + return ureg.Quantity(magnitude, u) + + +def returns_quantity(method): + """ + Decorate a ``get(self, ...)``-like method with an optional ``quantity`` keyword. + + ``method(..., quantity=True)`` returns the value as a :class:`pint.Quantity` + in ``self.unit()`` (see :func:`to_quantity`). By default (``quantity=False``) + the value is returned untouched, without calling ``unit()``. + + Parameters + ---------- + method : callable + Method returning values expressed in ``self.unit()``. + + Returns + ------- + callable + The wrapped method. + """ + if getattr(method, "__pyaml_returns_quantity__", False): + return method + + @wraps(method) + def wrapper(self, *args, quantity: bool = False, **kwargs): + value = method(self, *args, **kwargs) + return to_quantity(value, self.unit()) if quantity else value + + wrapper.__pyaml_returns_quantity__ = True + return wrapper + + def accepts_quantity(method): """ Decorate a ``set(self, value, ...)``-like method so that ``value`` may be a quantity. @@ -240,21 +434,68 @@ def wrapper(self, value, *args, **kwargs): return wrapper +def formats_unit(method): + """ + Decorate a ``unit(self)``-like method so that it returns canonical unit strings. + + The result (a unit, ``None`` or a possibly nested list of them) is passed + through :func:`format_unit`. + + Parameters + ---------- + method : callable + Method returning unit string(s). + + Returns + ------- + callable + The wrapped method. + """ + if getattr(method, "__pyaml_formats_unit__", False): + return method + + def _format(unit): + return [_format(u) for u in unit] if isinstance(unit, (list, tuple)) else format_unit(unit) + + @wraps(method) + def wrapper(self, *args, **kwargs): + return _format(method(self, *args, **kwargs)) + + wrapper.__pyaml_formats_unit__ = True + return wrapper + + class AcceptsQuantity: """ - Mixin making ``set``/``set_and_wait`` of every subclass accept :class:`pint.Quantity` values. + Mixin adding :class:`pint.Quantity` support to every subclass. + + - ``set``/``set_and_wait`` accept quantities, converted to ``unit()`` + (see :func:`accepts_quantity`); + - ``get`` accepts an optional ``quantity=True`` keyword returning a + quantity in ``unit()`` (see :func:`returns_quantity`). The default + still returns plain floats; + - ``unit``/``control_system_unit`` return canonical unit strings (see + :func:`formats_unit`), so that two spellings of the same unit compare + equal. Inherited by the PyAML read/write interfaces, so that every implementation (including the ones of external packages) supports quantities without any - change: the setters defined by a subclass are wrapped with - :func:`accepts_quantity` when the subclass is created. + change: the methods defined by a subclass are wrapped when the subclass is + created. """ _QUANTITY_SETTERS = ("set", "set_and_wait") + _QUANTITY_GETTERS = ("get",) + _UNIT_METHODS = ("unit", "control_system_unit") def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) - for name in cls._QUANTITY_SETTERS: - method = cls.__dict__.get(name) - if callable(method) and not getattr(method, "__isabstractmethod__", False): - setattr(cls, name, accepts_quantity(method)) + for names, decorator in ( + (cls._QUANTITY_SETTERS, accepts_quantity), + (cls._QUANTITY_GETTERS, returns_quantity), + (cls._UNIT_METHODS, formats_unit), + ): + for name in names: + method = cls.__dict__.get(name) + if callable(method) and not getattr(method, "__isabstractmethod__", False): + setattr(cls, name, decorator(method)) diff --git a/pyaml/control/abstract_impl.py b/pyaml/control/abstract_impl.py index 33d9fa81..e96767ac 100644 --- a/pyaml/control/abstract_impl.py +++ b/pyaml/control/abstract_impl.py @@ -15,9 +15,10 @@ from .. import PyAMLException from ..common import abstract from ..common.abstract_aggregator import ScalarAggregator -from ..common.units import SI_ANGLE, SI_FREQUENCY, SI_POSITION, SI_TUNE, SI_VOLTAGE +from ..common.units import SI_ANGLE, SI_FREQUENCY, SI_POSITION, SI_TUNE, SI_VOLTAGE, common_unit from ..control.deviceaccess import DeviceAccess from ..control.deviceaccesslist import DeviceAccessList +from ..control.si_deviceaccess import control_system_unit_of from ..magnet.magnet import Magnet from ..magnet.model import MagnetModel from ..rf.rf_plant import RFPlant @@ -222,7 +223,9 @@ class CSScalarAggregator(ScalarAggregator): readback() Read the last available values from all managed devices. unit() - Return the unit reported by the managed devices. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit for this quantity. nb_device() Return the number of managed devices. """ @@ -283,9 +286,13 @@ def readback(self) -> np.array: """Read the last available values from all managed devices.""" return self._devs.readback() - def unit(self) -> str: - """Return the unit reported by the managed devices.""" - return self._devs.unit() + def unit(self) -> str | list[str] | None: + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return common_unit(self._devs.unit()) + + def control_system_unit(self) -> str | list[str | None] | None: + """Return the control-system unit for this quantity.""" + return common_unit(self._devs.control_system_unit()) def nb_device(self) -> int: """Return the number of managed devices.""" @@ -322,6 +329,8 @@ class CSSparseScalarAggregator(CSScalarAggregator): Read all slot readbacks, NaN for slots without device. nb_device() Return the number of slots. + control_system_unit() + Return the control-system unit for this quantity. """ def __init__(self, devs: DeviceAccessList): @@ -374,6 +383,13 @@ def nb_device(self) -> int: """Return the number of slots.""" return self._nb_slots + def control_system_unit(self) -> str | list[str | None] | None: + """Return the control-system unit for this quantity.""" + out: list[str | None] = [None] * self._nb_slots + for slot, u in zip(self._slots, self._devs.control_system_unit(), strict=True): + out[slot] = u + return common_unit(out) + # ------------------------------------------------------------------------------ @@ -404,7 +420,9 @@ class CSStrengthScalarAggregator(CSScalarAggregator): readback() Read back magnet strengths from measured hardware values. unit() - Return the strength unit of each registered magnet. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit for this quantity. """ def __init__(self, peer: CSScalarAggregator): @@ -522,9 +540,17 @@ def readback(self) -> np.array: hardwareIndex += nbDev return allStrength - def unit(self) -> list[str]: - """Return the strength unit of each registered magnet.""" - return list(self.__units) + def unit(self) -> str | list[str] | None: + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return common_unit(self.__units) + + def control_system_unit(self) -> str | list[str] | None: + """ + Return the control-system unit for this quantity. + + Same as unit(): no control-system device holds these values. + """ + return self.unit() # ------------------------------------------------------------------------------ @@ -553,7 +579,9 @@ class RWHardwareScalar(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the hardware value and wait for readback confirmation. unit() - Return the hardware unit defined by the magnet model. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit for this quantity. set_magnet_rigidity(brho) Set the beam rigidity used by the magnet model. """ @@ -605,9 +633,13 @@ def set_and_wait(self, value: double): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the hardware unit defined by the magnet model.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return self.__model.get_hardware_units()[0] + def control_system_unit(self) -> str | None: + """Return the control-system unit for this quantity.""" + return control_system_unit_of(self.__dev) + def set_magnet_rigidity(self, brho: np.double): """ Set the beam rigidity used by the magnet model. @@ -643,7 +675,7 @@ class RWStrengthScalar(abstract.ReadWriteFloatScalar): set_and_wait(value) Set a magnet strength and wait for readback confirmation. unit() - Return the strength unit defined by the magnet model. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). set_magnet_rigidity(brho) Set the beam rigidity used by the magnet model. """ @@ -702,7 +734,7 @@ def set_and_wait(self, value: float): # Gets the unit of the value def unit(self) -> str: - """Return the strength unit defined by the magnet model.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return self.__model.get_strength_units()[0] def set_magnet_rigidity(self, brho: np.double): @@ -776,7 +808,9 @@ class RWHardwareArray(abstract.ReadWriteFloatArray): set_and_wait(value) Set hardware values and wait for readback confirmation. unit() - Return the hardware units defined by the magnet model. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit for this quantity. """ def __init__(self, model: MagnetModel, devs: list[DeviceAccess]): @@ -830,9 +864,13 @@ def set_and_wait(self, value: np.array): raise NotImplementedError("Not implemented yet.") # Gets the unit of the value - def unit(self) -> list[str]: - """Return the hardware units defined by the magnet model.""" - return self.__model.get_hardware_units() + def unit(self) -> str | list[str]: + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return common_unit(self.__model.get_hardware_units()) + + def control_system_unit(self) -> str | list[str | None] | None: + """Return the control-system unit for this quantity.""" + return common_unit([control_system_unit_of(d) for d in self.__devs]) # ------------------------------------------------------------------------------ @@ -858,7 +896,7 @@ class RWStrengthArray(abstract.ReadWriteFloatArray): set_and_wait(value) Set magnet strengths and wait for readback confirmation. unit() - Return the strength units defined by the magnet model. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). """ def __init__(self, model: MagnetModel, devs: list[DeviceAccess]): @@ -912,9 +950,9 @@ def set_and_wait(self, value: np.array): raise NotImplementedError("Not implemented yet.") # Gets the unit of the value - def unit(self) -> list[str]: - """Return the strength units defined by the magnet model.""" - return self.__model.get_strength_units() + def unit(self) -> str | list[str]: + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return common_unit(self.__model.get_strength_units()) # ------------------------------------------------------------------------------ @@ -938,7 +976,9 @@ class RBpmArray(abstract.ReadFloatArray): get() Return horizontal and vertical BPM positions (NaN for a missing plane). unit() - Return the SI unit of BPM positions. + Return the pyAML unit for this quantity, i.e. returned by get(). + control_system_unit() + Return the control-system unit for this quantity. """ def __init__(self, hDev: DeviceAccess | None, vDev: DeviceAccess | None): @@ -953,9 +993,13 @@ def get(self) -> np.array: return np.array([d.get() if d is not None else np.nan for d in (self._hDev, self._vDev)], dtype=float) def unit(self) -> str: - """Return the SI unit of BPM positions.""" + """Return the pyAML unit for this quantity, i.e. returned by get().""" return SI_POSITION + def control_system_unit(self) -> str | list[str | None] | None: + """Return the control-system unit for this quantity.""" + return common_unit([control_system_unit_of(d) for d in (self._hDev, self._vDev)]) + # ------------------------------------------------------------------------------ @@ -978,7 +1022,9 @@ class RWBpmTiltScalar(abstract.ReadFloatScalar): set_and_wait(value) Set the BPM tilt and wait for readback confirmation. unit() - Return the SI unit of the BPM tilt. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit for this quantity. """ def __init__(self, dev: DeviceAccess): @@ -1020,9 +1066,13 @@ def set_and_wait(self, value: NDArray[np.float64]): # Gets the unit of the value def unit(self) -> str: - """Return the SI unit of the BPM tilt.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return SI_ANGLE + def control_system_unit(self) -> str | None: + """Return the control-system unit for this quantity.""" + return control_system_unit_of(self._dev) + # ------------------------------------------------------------------------------ @@ -1047,7 +1097,9 @@ class RWBpmOffsetArray(abstract.ReadWriteFloatArray): set_and_wait(value) Set BPM offsets and wait for readback confirmation. unit() - Return the SI unit of BPM offsets. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit for this quantity. """ def __init__(self, hDev: DeviceAccess, vDev: DeviceAccess): @@ -1090,9 +1142,13 @@ def set_and_wait(self, value: NDArray[np.float64]): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the SI unit of BPM offsets.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return SI_POSITION + def control_system_unit(self) -> str | list[str | None] | None: + """Return the control-system unit for this quantity.""" + return common_unit([control_system_unit_of(d) for d in (self._hDev, self._vDev)]) + # ------------------------------------------------------------------------------ @@ -1118,7 +1174,9 @@ class RWRFVoltageScalar(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the cavity voltage and wait for readback confirmation. unit() - Return the SI unit of the cavity voltage. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit for this quantity. """ def __init__(self, transmitter: RFTransmitter, dev: DeviceAccess): @@ -1160,9 +1218,13 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the SI unit of the cavity voltage.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return SI_VOLTAGE + def control_system_unit(self) -> str | None: + """Return the control-system unit for this quantity.""" + return control_system_unit_of(self.__dev) + # ------------------------------------------------------------------------------ @@ -1188,7 +1250,9 @@ class RWRFPhaseScalar(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the cavity phase and wait for readback confirmation. unit() - Return the SI unit of the cavity phase. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit for this quantity. """ def __init__(self, transmitter: RFTransmitter, dev: DeviceAccess): @@ -1230,9 +1294,13 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the SI unit of the cavity phase.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return SI_ANGLE + def control_system_unit(self) -> str | None: + """Return the control-system unit for this quantity.""" + return control_system_unit_of(self.__dev) + # ------------------------------------------------------------------------------ @@ -1257,7 +1325,9 @@ class RWRFFrequencyScalar(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the RF frequency and wait for readback confirmation. unit() - Return the SI unit of the RF frequency. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit for this quantity. """ def __init__(self, rf: RFPlant, dev: DeviceAccess): @@ -1300,9 +1370,13 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the SI unit of the RF frequency.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return SI_FREQUENCY + def control_system_unit(self) -> str | None: + """Return the control-system unit for this quantity.""" + return control_system_unit_of(self.__dev) + # ------------------------------------------------------------------------------ @@ -1323,7 +1397,9 @@ class RBetatronTuneArray(abstract.ReadFloatArray): get() Return horizontal and vertical betatron tunes. unit() - Return the betatron-tune unit (dimensionless). + Return the pyAML unit for this quantity, i.e. returned by get(). + control_system_unit() + Return the control-system unit for this quantity. """ def __init__(self, tune_monitor, devs: list[DeviceAccess]): @@ -1344,8 +1420,12 @@ def get(self) -> NDArray: ) def unit(self) -> str: - """Return the betatron-tune unit (dimensionless).""" + """Return the pyAML unit for this quantity, i.e. returned by get().""" return SI_TUNE + def control_system_unit(self) -> str | list[str | None] | None: + """Return the control-system unit for this quantity.""" + return common_unit([control_system_unit_of(d) for d in self.__devs]) + # ------------------------------------------------------------------------------ diff --git a/pyaml/control/controlsystem.py b/pyaml/control/controlsystem.py index 02dd553c..225fe2e0 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -140,9 +140,10 @@ def get_si_device_access(self, ref: str | BaseModel | None, si_unit: str | None) Returns ------- DeviceAccess or None - The backend device, wrapped in a - :class:`~pyaml.control.si_deviceaccess.SIDeviceAccess` when a - conversion is needed. + The backend device wrapped in a + :class:`~pyaml.control.si_deviceaccess.SIDeviceAccess` (factor 1 + when no conversion is needed), or the raw backend device when + ``si_unit`` is empty. Raises ------ diff --git a/pyaml/control/deviceaccess.py b/pyaml/control/deviceaccess.py index 5ac63897..9cd9d3a2 100644 --- a/pyaml/control/deviceaccess.py +++ b/pyaml/control/deviceaccess.py @@ -33,7 +33,7 @@ class DeviceAccess(metaclass=ABCMeta): readback() Return the latest measured value reported by the device. unit() - Return the physical unit of the device variable. + Return the control-system unit of the device variable. get_range() Get the valid range for the device variable. check_device_availability() @@ -109,7 +109,7 @@ def readback(self): @abstractmethod def unit(self) -> str: """ - Return the physical unit of the device variable. + Return the control-system unit of the device variable. Returns ------- diff --git a/pyaml/control/deviceaccesslist.py b/pyaml/control/deviceaccesslist.py index 38513fee..649a140f 100644 --- a/pyaml/control/deviceaccesslist.py +++ b/pyaml/control/deviceaccesslist.py @@ -38,7 +38,7 @@ class DeviceAccessList(metaclass=ABCMeta): readback() Return the latest measured values in collection order. unit() - Return the unit or units associated with the devices. + Return the unit of each device. get_range() Get the valid range for the device variables. check_device_availability() @@ -122,8 +122,8 @@ def readback(self) -> np.array: pass @abstractmethod - def unit(self) -> str: - """Return the unit or units associated with the devices.""" + def unit(self) -> list[str]: + """Return the unit of each device.""" pass @abstractmethod diff --git a/pyaml/control/si_deviceaccess.py b/pyaml/control/si_deviceaccess.py index 2113f498..801cfaf5 100644 --- a/pyaml/control/si_deviceaccess.py +++ b/pyaml/control/si_deviceaccess.py @@ -25,9 +25,9 @@ from .readback_value import Value -def _scale(value: Any, k: float | np.ndarray) -> Any: +def _scale(value: Any, k: float | np.ndarray, inverse: bool = False) -> Any: """ - Multiply a raw device value by ``k`` (one factor, or one per element). + Multiply a raw device value by ``k`` (one factor, or one per element), or divide it when ``inverse``. Handles scalars, numeric arrays, :class:`Value` objects (metadata kept) and lists/object arrays of them, as returned by ``readback()``. @@ -35,12 +35,12 @@ def _scale(value: Any, k: float | np.ndarray) -> Any: if value is None: return None if isinstance(value, Value): - return Value(_scale(value.value, k), value.quality, value.timestamp) + return Value(_scale(value.value, k, inverse), value.quality, value.timestamp) if isinstance(value, (list, tuple)) or (isinstance(value, np.ndarray) and value.dtype == object): ks = np.broadcast_to(k, (len(value),)) - scaled = [_scale(v, kk) for v, kk in zip(value, ks, strict=True)] + scaled = [_scale(v, kk, inverse) for v, kk in zip(value, ks, strict=True)] return np.array(scaled, dtype=object) if isinstance(value, np.ndarray) else scaled - return value * k + return value / k if inverse else value * k def _scale_range(rng: list | None, k: float | np.ndarray) -> list | None: @@ -84,14 +84,16 @@ class SIDeviceAccess(DeviceAccess): readback() Return the latest measured value in SI. unit() - Return the SI unit. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit of the wrapped backend device. get_range() Return the device range in SI. check_device_availability() Check if the device is available and accessible. """ - def __init__(self, raw: DeviceAccess, si_unit: str, factor: float): + def __init__(self, raw: DeviceAccess, si_unit: str, factor: float = 1.0): self.raw = raw self.factor = factor self._si_unit = si_unit @@ -106,27 +108,34 @@ def measure_name(self) -> str: def set(self, value): """Convert a SI setpoint to the device unit and write it.""" - self.raw.set(_scale(value, 1.0 / self.factor)) + self.raw.set(value if self.factor == 1.0 else _scale(value, self.factor, inverse=True)) def set_and_wait(self, value): """Convert a SI setpoint to the device unit, write it and wait.""" - self.raw.set_and_wait(_scale(value, 1.0 / self.factor)) + self.raw.set_and_wait(value if self.factor == 1.0 else _scale(value, self.factor, inverse=True)) def get(self): """Return the current setpoint in SI.""" - return _scale(self.raw.get(), self.factor) + v = self.raw.get() + return v if self.factor == 1.0 else _scale(v, self.factor) def readback(self): """Return the latest measured value in SI.""" - return _scale(self.raw.readback(), self.factor) + v = self.raw.readback() + return v if self.factor == 1.0 else _scale(v, self.factor) def unit(self) -> str: - """Return the SI unit.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return self._si_unit + def control_system_unit(self) -> str | None: + """Return the control-system unit of the wrapped backend device.""" + return self.raw.unit() + def get_range(self) -> list[float]: """Return the device range in SI.""" - return _scale_range(self.raw.get_range(), self.factor) + rng = self.raw.get_range() + return rng if self.factor == 1.0 else _scale_range(rng, self.factor) def check_device_availability(self) -> bool: """Check if the device is available and accessible.""" @@ -153,15 +162,15 @@ def wrap_si(dev: DeviceAccess | None, si_unit: str | None) -> DeviceAccess | Non Returns ------- DeviceAccess or None - ``dev`` itself when no conversion is needed (factor 1, empty unit), - otherwise a :class:`SIDeviceAccess`. + A :class:`SIDeviceAccess` (with factor 1 when no conversion is + needed), or ``dev`` itself when ``si_unit`` is empty or ``None``. Raises ------ PyAMLConfigException If the device unit cannot be converted to ``si_unit``. """ - if dev is None or isinstance(dev, SIDeviceAccess): + if dev is None or isinstance(dev, SIDeviceAccess) or si_unit is None or not str(si_unit).strip(): return dev dev_unit = dev.unit() if isinstance(dev_unit, (list, tuple)): # Defensive: some backends may return a list @@ -170,8 +179,6 @@ def wrap_si(dev: DeviceAccess | None, si_unit: str | None) -> DeviceAccess | Non k = conversion_factor(dev_unit, si_unit) except PyAMLConfigException as e: raise PyAMLConfigException(f"Device '{dev.name()}': {e}") from e - if k == 1.0: - return dev return SIDeviceAccess(dev, si_unit, k) @@ -211,7 +218,9 @@ class SIDeviceAccessList(DeviceAccessList): readback() Return all readbacks in SI. unit() - Return the SI unit of each device. + Return the pyAML unit for each device, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit of each wrapped backend device. get_range() Return the ranges in SI. check_device_availability() @@ -261,9 +270,13 @@ def readback(self) -> np.array: return v if self._passthrough or v is None or len(v) == 0 else _scale(v, self.factors) def unit(self) -> list[str]: - """Return the SI unit of each device.""" + """Return the pyAML unit for each device, i.e. returned by get() and expected by set().""" return [d.unit() for d in self._items] + def control_system_unit(self) -> list[str | None]: + """Return the control-system unit of each wrapped backend device.""" + return [control_system_unit_of(d) for d in self._items] + def get_range(self) -> list[float]: """Return the ranges in SI.""" rng = self.raw.get_range() @@ -272,3 +285,22 @@ def get_range(self) -> list[float]: def check_device_availability(self) -> bool: """Check if all devices are available.""" return self.raw.check_device_availability() + + +def control_system_unit_of(dev: DeviceAccess | None) -> str | None: + """ + Return the control-system unit of ``dev``. + + Parameters + ---------- + dev : DeviceAccess or None + Backend device, possibly wrapped in a :class:`SIDeviceAccess`. + + Returns + ------- + str or None + Unit reported by the backend device, ``None`` for a missing device. + """ + if dev is None: + return None + return dev.control_system_unit() if isinstance(dev, SIDeviceAccess) else dev.unit() diff --git a/pyaml/diagnostics/tune_monitor.py b/pyaml/diagnostics/tune_monitor.py index 3a771cb6..5ba0c6eb 100644 --- a/pyaml/diagnostics/tune_monitor.py +++ b/pyaml/diagnostics/tune_monitor.py @@ -154,7 +154,7 @@ class TuneFreq(ReadFloatArray): get() Return tune frequencies in hertz. unit() - Return the frequency unit label. + Return the pyAML unit for this quantity, i.e. returned by get(). """ def __init__(self, parent: BetatronTuneMonitor): @@ -174,7 +174,7 @@ def get(self) -> NDArray: return tune * freq / h def unit(self) -> str: - """Return the frequency unit label.""" + """Return the pyAML unit for this quantity, i.e. returned by get().""" return "Hz" self.check_peer() diff --git a/pyaml/lattice/abstract_impl.py b/pyaml/lattice/abstract_impl.py index 5321036e..4fa73119 100644 --- a/pyaml/lattice/abstract_impl.py +++ b/pyaml/lattice/abstract_impl.py @@ -13,7 +13,7 @@ from ..common import abstract from ..common.abstract_aggregator import ScalarAggregator from ..common.exception import PyAMLException -from ..common.units import SI_ANGLE, SI_FREQUENCY, SI_POSITION, SI_TUNE, SI_VOLTAGE +from ..common.units import SI_ANGLE, SI_FREQUENCY, SI_POSITION, SI_TUNE, SI_VOLTAGE, common_unit from ..magnet.model import MagnetModel from .polynom_info import PolynomInfo @@ -65,7 +65,7 @@ class RWHardwareScalar(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the value and wait for readback convergence. unit() - Return the value unit. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). get_model() Return the associated magnet model. """ @@ -128,7 +128,7 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the value unit.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return self._model.get_hardware_units()[0] def get_model(self) -> MagnetModel: @@ -167,7 +167,7 @@ class RWStrengthScalar(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the value and wait for readback convergence. unit() - Return the value unit. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). get_model() Return the associated magnet model. """ @@ -264,7 +264,7 @@ def set_and_wait(self, value: float): # Gets the unit of the value def unit(self) -> str: - """Return the value unit.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return self._model.get_strength_units()[0] # ------------------------------------------------------------------------------ @@ -300,7 +300,7 @@ class RWSerializedHardware(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the value and wait for readback convergence. unit() - Return the value unit. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). set_magnet_rigidity(brho) Set the magnetic rigidity used for conversion. """ @@ -359,7 +359,7 @@ def set_and_wait(self, value: float): # Gets the unit of the value def unit(self) -> str: - """Return the value unit.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return self.__elements[self.__element_index].unit() def set_magnet_rigidity(self, brho: np.double): @@ -400,7 +400,7 @@ class RWSerializedStrength(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the value and wait for readback convergence. unit() - Return the value unit. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). set_magnet_rigidity(brho) Set the magnetic rigidity used for conversion. """ @@ -486,7 +486,7 @@ def set_and_wait(self, value: float): # Gets the unit of the value def unit(self) -> str: - """Return the value unit.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return self.__element.unit() def set_magnet_rigidity(self, brho: np.double): @@ -525,7 +525,7 @@ class RWHardwareArray(abstract.ReadWriteFloatArray): set_and_wait(value) Set the value and wait for readback convergence. unit() - Return the value unit. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). """ def __init__(self, elements: list[at.Element], poly: list[PolynomInfo], model: MagnetModel): @@ -585,9 +585,9 @@ def set_and_wait(self, value: np.array): raise NotImplementedError("Not implemented yet.") # Gets the unit of the value - def unit(self) -> list[str]: - """Return the value unit.""" - return self.__model.get_hardware_units() + def unit(self) -> str | list[str]: + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return common_unit(self.__model.get_hardware_units()) # ------------------------------------------------------------------------------ @@ -616,7 +616,7 @@ class RWStrengthArray(abstract.ReadWriteFloatArray): set_and_wait(value) Set the value and wait for readback convergence. unit() - Return the value unit. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). """ def __init__(self, elements: list[at.Element], poly: list[PolynomInfo], model: MagnetModel): @@ -676,9 +676,9 @@ def set_and_wait(self, value: np.array): raise NotImplementedError("Not implemented yet.") # Gets the unit of the value - def unit(self) -> list[str]: - """Return the value unit.""" - return self.__model.get_strength_units() + def unit(self) -> str | list[str]: + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return common_unit(self.__model.get_strength_units()) # ------------------------------------------------------------------------------ @@ -706,7 +706,7 @@ class BPMScalarAggregator(ScalarAggregator): readback() Return the current readback value. unit() - Return the value unit. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). """ def __init__(self, ring: at.Lattice, twiss_in: dict): @@ -761,7 +761,7 @@ def readback(self) -> np.array: return self.get() def unit(self) -> str: - """Return the value unit.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return SI_POSITION def _transform(self) -> np.array: @@ -861,7 +861,7 @@ class RBpmArray(abstract.ReadFloatArray): get() Return the current value. unit() - Return the value unit. + Return the pyAML unit for this quantity, i.e. returned by get(). """ def __init__(self, element: at.Element, lattice: at.Lattice, twiss_in: dict): @@ -887,7 +887,7 @@ def get(self) -> np.array: # Gets the unit of the value def unit(self) -> str: - """Return the value unit.""" + """Return the pyAML unit for this quantity, i.e. returned by get().""" return SI_POSITION @@ -913,7 +913,7 @@ class RWBpmOffsetArray(abstract.ReadWriteFloatArray): set_and_wait(value) Set the value and wait for readback convergence. unit() - Return the value unit. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). """ def __init__(self, element: at.Element): @@ -959,7 +959,7 @@ def set_and_wait(self, value: np.array): # Gets the unit of the value def unit(self) -> str: - """Return the value unit.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return SI_POSITION @@ -987,7 +987,7 @@ class RWBpmTiltScalar(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the value and wait for readback convergence. unit() - Return the value unit. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). """ def __init__(self, element: at.Element): @@ -1036,7 +1036,7 @@ def set_and_wait(self, value: float): # Gets the unit of the value def unit(self) -> str: - """Return the value unit.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return SI_ANGLE @@ -1062,7 +1062,7 @@ class RWRFVoltageScalar(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the value and wait for readback convergence. unit() - Return the value unit. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). """ def __init__(self, elements: list[at.Element]): @@ -1108,7 +1108,7 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the value unit.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return SI_VOLTAGE @@ -1137,7 +1137,7 @@ class RWRFPhaseScalar(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the value and wait for readback convergence. unit() - Return the value unit. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). """ def __init__(self, elements: list[at.Element]): @@ -1183,7 +1183,7 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the value unit.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return SI_ANGLE @@ -1210,7 +1210,7 @@ class RWRFFrequencyScalar(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the value and wait for readback convergence. unit() - Return the value unit. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). """ def __init__(self, elements: list[at.Element], harmonics: list[float]): @@ -1254,7 +1254,7 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the value unit.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return SI_FREQUENCY @@ -1282,7 +1282,7 @@ class RWRFATFrequencyScalar(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the value and wait for readback convergence. unit() - Return the value unit. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). """ def __init__(self, ring: at.Lattice): @@ -1323,7 +1323,7 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the value unit.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return SI_FREQUENCY @@ -1351,7 +1351,7 @@ class RWRFATotalVoltageScalar(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the value and wait for readback convergence. unit() - Return the value unit. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). """ def __init__(self, ring: at.Lattice): @@ -1392,7 +1392,7 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the value unit.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return SI_VOLTAGE @@ -1413,7 +1413,7 @@ class RBetatronTuneArray(abstract.ReadFloatArray): get() Return the current value. unit() - Return the value unit. + Return the pyAML unit for this quantity, i.e. returned by get(). """ def __init__(self, ring: at.Lattice): @@ -1427,7 +1427,7 @@ def get(self) -> float: return self.__ring.get_tune()[:2] def unit(self) -> str: - """Return the value unit.""" + """Return the pyAML unit for this quantity, i.e. returned by get().""" return SI_TUNE diff --git a/pyaml/magnet/corrector.py b/pyaml/magnet/corrector.py index 1f828450..282dc4d6 100644 --- a/pyaml/magnet/corrector.py +++ b/pyaml/magnet/corrector.py @@ -35,7 +35,7 @@ class RWCorrectorAngle(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the kick angle and wait for it to reach the setpoint. unit() - Get the unit for the kick angle. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). """ def __init__(self, corr: Magnet): @@ -84,11 +84,11 @@ def set_and_wait(self, value: float): def unit(self) -> str: """ - Get the unit for the kick angle. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). Returns ------- str - Unit string, always 'rad' for radians + Unit label. """ return "rad" diff --git a/pyaml/magnet/serialized_magnet.py b/pyaml/magnet/serialized_magnet.py index c5aab6fa..52e55b73 100644 --- a/pyaml/magnet/serialized_magnet.py +++ b/pyaml/magnet/serialized_magnet.py @@ -45,7 +45,7 @@ class ReadWriteSerializedStrengths(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the shared strength and wait for convergence. unit() - Return the physical strength unit. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). get_model() Return the magnet conversion model. get_elements() @@ -97,7 +97,7 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the physical strength unit.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return self.model.get_strength_units()[0] def get_model(self) -> MagnetModel: @@ -134,7 +134,9 @@ class ReadWriteSerializedHardwares(ReadWriteSerializedStrengths): Methods ------- unit() - Return the hardware-value unit. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). + control_system_unit() + Return the control-system unit for this quantity. set_magnet_rigidity(brho) Set the magnetic rigidity used for conversion. """ @@ -150,9 +152,13 @@ def __init__( super().__init__(elements, model) def unit(self) -> str: - """Return the hardware-value unit.""" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" return self.model.get_hardware_units()[0] + def control_system_unit(self) -> str | None: + """Return the control-system unit for this quantity.""" + return self.elements[0].control_system_unit() + def set_magnet_rigidity(self, brho: np.double): """ Set the magnetic rigidity used for conversion. diff --git a/pyaml/rf/rf_plant.py b/pyaml/rf/rf_plant.py index 62e5954b..95e89246 100644 --- a/pyaml/rf/rf_plant.py +++ b/pyaml/rf/rf_plant.py @@ -12,6 +12,7 @@ from .. import PyAMLException from ..common import abstract from ..common.element import Element, __pyaml_repr__ +from ..common.units import SI_VOLTAGE from ..validation import DynamicValidation, register_schema from .rf_transmitter import RFTransmitter @@ -153,7 +154,7 @@ class RWTotalVoltage(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the total voltage and wait for readback convergence. unit() - Return the voltage unit reported by the first transmitter. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). """ def __init__(self, transmitters: list[RFTransmitter]): @@ -204,8 +205,8 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the voltage unit reported by the first transmitter.""" - return self.__trans[0].phase_device_access.unit() + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return SI_VOLTAGE def __repr__(self): """ diff --git a/pyaml/tuning_tools/chromaticity_monitor.py b/pyaml/tuning_tools/chromaticity_monitor.py index 2186a275..fd48195e 100644 --- a/pyaml/tuning_tools/chromaticity_monitor.py +++ b/pyaml/tuning_tools/chromaticity_monitor.py @@ -50,7 +50,7 @@ class RChromaDispArray(ReadFloatArray): get() Return the latest chromaticity or dispersion values. unit() - Return the unit of the reported values. + Return the pyAML unit for this quantity, i.e. returned by get(). """ def __init__(self, parent: "ChromaticityMonitor", name: str, unit: str): @@ -70,7 +70,7 @@ def get(self) -> np.array: return None def unit(self) -> str: - """Return the unit of the reported values.""" + """Return the pyAML unit for this quantity, i.e. returned by get().""" return self._unit diff --git a/tests/arrays/test_arrays.py b/tests/arrays/test_arrays.py index 5bd02a3d..1960d7ed 100644 --- a/tests/arrays/test_arrays.py +++ b/tests/arrays/test_arrays.py @@ -190,10 +190,10 @@ def test_arrays(install_test_package): strHVSQu = cfm.strengths.unit() assert strHVSQu[0] == "rad" assert strHVSQu[1] == "rad" - assert strHVSQu[2] == "m-1" + assert strHVSQu[2] == "1/m" assert strHVSQu[3] == "rad" assert strHVSQu[4] == "rad" - assert strHVSQu[5] == "m-1" + assert strHVSQu[5] == "1/m" cfm.strengths.set([0.000010, 0.000015, 1e-6, -0.000008, -0.000017, 1e-6]) strHVSQ = cfm.strengths.get() diff --git a/tests/config/EBSTuneOATango.yaml b/tests/config/EBSTuneOATango.yaml index dae87e8d..7fca7dc2 100644 --- a/tests/config/EBSTuneOATango.yaml +++ b/tests/config/EBSTuneOATango.yaml @@ -2005,11 +2005,11 @@ devices: tune_h: type: pyaml_cs_oa.tangoR attribute: srdiag/beam-tune/main/Qh - unit: mm + unit: '1' tune_v: type: pyaml_cs_oa.tangoR attribute: srdiag/beam-tune/main/Qv - unit: mm + unit: '1' - type: pyaml.tuning_tools.tune name: DEFAULT_TUNE_CORRECTION quad_array: QForTune diff --git a/tests/test_units.py b/tests/test_units.py index 20692f7e..066a500a 100644 --- a/tests/test_units.py +++ b/tests/test_units.py @@ -6,7 +6,15 @@ from pyaml.accelerator import Accelerator from pyaml.common.exception import PyAMLConfigException, PyAMLException -from pyaml.common.units import conversion_factor, get_registry, normalize_unit, to_magnitude +from pyaml.common.units import ( + common_unit, + conversion_factor, + format_unit, + get_registry, + normalize_unit, + to_magnitude, + to_quantity, +) TANGO = pytest.mark.parametrize( "install_test_package", @@ -38,12 +46,14 @@ def test_conversion_factor(src, dst, k): assert conversion_factor(src, dst) == pytest.approx(k) -@pytest.mark.parametrize("src,dst", [("", "m"), (None, "m"), ("mm", ""), ("A", "A"), ("whatever", "whatever")]) +@pytest.mark.parametrize("src,dst", [("", "m"), (None, "m"), ("", "1"), ("A", "A"), ("whatever", "whatever")]) def test_conversion_factor_passthrough(src, dst): assert conversion_factor(src, dst) == 1.0 -@pytest.mark.parametrize("src,dst", [("A", "m"), ("foo", "m"), ("degC", "K"), ("%", "rad"), ("count", "rad")]) +@pytest.mark.parametrize( + "src,dst", [("A", "m"), ("foo", "m"), ("degC", "K"), ("%", "rad"), ("count", "rad"), ("mm", ""), ("Hz", "1")] +) def test_conversion_factor_errors(src, dst): with pytest.raises(PyAMLConfigException): conversion_factor(src, dst) @@ -53,6 +63,12 @@ def test_normalize_unit(): assert normalize_unit(" m-2 ") == "m^-2" assert normalize_unit("T.m") == "T*m" assert normalize_unit("mm") == "mm" + # Canonical form reported by unit(): equivalent spellings compare equal + assert format_unit("m-1") == format_unit("1/m") == format_unit("m^-1") == "1/m" + assert format_unit("T.m") == "m*T" + assert format_unit("") == format_unit("No unit") == "" + assert format_unit("dimensionless") == "1" + assert format_unit("whatever") == "whatever" def test_to_magnitude(): @@ -94,6 +110,50 @@ def unit(self): assert t.value == pytest.approx(1e-3) +def test_to_quantity(): + assert to_quantity(None, "m") is None + q = to_quantity(1.5, "mm") + assert q.units == ureg.mm and q.magnitude == 1.5 + assert np.allclose(to_quantity(np.array([1.0, 2.0]), "m").to("mm").magnitude, [1e3, 2e3]) + assert to_quantity(0.2, "").dimensionless + assert to_quantity(0.2, "1").dimensionless + assert to_quantity([1.0, 2.0], "m-1").units == 1 / ureg.m # Accelerator notation + # Same unit for all values: one array quantity + q = to_quantity([1.0, 2.0], ["A", "A"]) + assert q.units == ureg.A and np.allclose(q.magnitude, [1.0, 2.0]) + # Mixed units: one quantity per value + q = to_quantity([0.5, 0.1], ["1/m", "1/m**2"]) + assert isinstance(q, list) and q[0].units == 1 / ureg.m and q[1].units == 1 / ureg.m**2 + with pytest.raises(PyAMLException): + to_quantity([0.5, 0.1, 0.2], ["1/m", "1/m**2"]) + with pytest.raises(PyAMLException): + to_quantity(1.0, "foo") + + +def test_common_unit(): + assert common_unit(["A", "A"]) == "A" + assert common_unit([["mm", "mm"], ["mm", None]]) == "mm" # Nested (shaped like get()), missing device ignored + assert common_unit(["1/m", "1/m**2"]) == ["1/m", "1/m**2"] # Units that really differ are kept + assert common_unit([None, None]) is None + + +def test_get_returns_quantity_on_any_implementation(): + from pyaml.common.abstract import ReadFloatArray + + class Positions(ReadFloatArray): # Minimal implementation, like an external package + def get(self): + return np.array([1e-3, -2e-3]) + + def unit(self): + return "m" + + p = Positions() + assert isinstance(p.get(), np.ndarray) # Default unchanged + q = p.get(quantity=True) + assert np.allclose(q.to("mm").magnitude, [1.0, -2.0]) + assert p.get(quantity=False) is not None and not isinstance(p.get(quantity=False), pint.Quantity) + + def test_hardware_unit_of_model(): from pyaml.control.controlsystem import _hardware_unit @@ -125,14 +185,14 @@ def _entry(key: str, unit: str, range=None, read_only=False) -> dict: return {"type": "tango.pyaml.static_catalog_entry", "key": key, "device": device} -def _quad(name: str, ps: str) -> dict: +def _quad(name: str, ps: str, unit: str = "1/m") -> dict: return { "type": "pyaml.magnet.quadrupole", "name": name, "model": { "type": "pyaml.magnet.linear_model", "calibration_factor": 0.01, - "unit": "1/m", + "unit": unit, "hardware_unit": "A", "powerconverter": ps, }, @@ -187,7 +247,7 @@ def _config(bpm_unit="mm", freq_unit="MHz", volt_unit="kV", phase_unit="deg", ps ], }, _quad("Q1", "ps/q1"), - _quad("Q2", "ps/q2"), + _quad("Q2", "ps/q2", unit="m-1"), # Same unit as Q1, spelled differently ], } @@ -222,9 +282,9 @@ def test_rf_is_converted_to_si(install_test_package): rf = sr.live.rf.get("RF") tra = sr.live.rf.transmitter.get("RFTRA") - rf.frequency.set(352.2e6) - assert get_attribute("sr/test/rf/freq") == pytest.approx(352.2) - assert rf.frequency.get() == pytest.approx(352.2e6) + rf.frequency.set(352.372e6) + assert get_attribute("sr/test/rf/freq") == 352.372 # Divided by the factor: exact, no rounding error + assert rf.frequency.get() == pytest.approx(352.372e6) assert rf.frequency.unit() == "Hz" tra.voltage.set(1.5e6) @@ -310,7 +370,7 @@ def test_strength_aggregator_unit_and_quantity(install_test_package): sr = Accelerator.from_dict(_config()) agg = sr.live.create_magnet_strength_aggregator(list(sr.live.magnets.get("QUADS"))) - assert agg.unit() == ["1/m", "1/m"] + assert agg.unit() == "1/m" agg.set(np.array([0.01, 0.02]) / ureg.m) q1, q2 = sr.live.magnet.get("Q1"), sr.live.magnet.get("Q2") assert [q1.strength.get(), q2.strength.get()] == pytest.approx([0.01, 0.02]) @@ -347,6 +407,127 @@ def test_device_without_unit_is_passthrough(install_test_package): assert get_attribute("sr/test/rf/freq") == pytest.approx(352.5) +@TANGO +@pytest.mark.parametrize("no_unit", ["", "No unit"]) +def test_device_without_unit_reports_si_unit(install_test_package, no_unit): + from pyaml.control.si_deviceaccess import SIDeviceAccess + + sr = Accelerator.from_dict(_config(bpm_unit=no_unit, freq_unit=no_unit, ps_unit=no_unit)) + + dev = sr.live.get_si_device_access("rf/freq", "Hz") + assert isinstance(dev, SIDeviceAccess) and dev.factor == 1.0 + assert dev.unit() == "Hz" + assert dev.control_system_unit() == no_unit + + # Grouped accessors report the SI unit, not the raw device unit + quads = list(sr.live.magnets.get("QUADS")) + assert sr.live.create_magnet_hardware_aggregator(quads).unit() == "A" + _, aggh, _ = sr.live.create_bpm_aggregators(list(sr.live.diagnostic.bpms.get("BPM"))) + assert aggh.unit() == "m" + + +@TANGO +def test_si_device_access_reports_control_system_unit(install_test_package): + from pyaml.control.si_deviceaccess import control_system_unit_of + + sr = Accelerator.from_dict(_config()) + dev = sr.live.get_si_device_access("rf/freq", "Hz") + assert dev.unit() == "Hz" + assert dev.control_system_unit() == "MHz" + assert control_system_unit_of(dev) == "MHz" + assert control_system_unit_of(sr.live.get_device_access("rf/freq")) == "MHz" + assert control_system_unit_of(None) is None + + quads = list(sr.live.magnets.get("QUADS")) + agg = sr.live.create_magnet_hardware_aggregator(quads) + assert agg.unit() == "A" + assert agg.control_system_unit() == "mA" + assert agg._devs.control_system_unit() == ["mA", "mA"] # Device level: one per device + + +@TANGO +def test_total_voltage_unit_is_si(install_test_package): + from tango.pyaml.attribute_store import get_attribute + + sr = Accelerator.from_dict(_config()) + rf = sr.live.rf.get("RF") + assert rf.voltage.unit() == "V" + rf.voltage.set(2 * ureg.MV) + assert get_attribute("sr/test/rf/volt") == pytest.approx(2000.0) + assert rf.voltage.get() == pytest.approx(2e6) + + +@TANGO +def test_accessors_report_control_system_unit(install_test_package): + sr = Accelerator.from_dict(_config()) + + bpm = sr.live.diagnostic.bpm.get("BPM1") + assert bpm.positions.unit() == "m" + assert bpm.positions.control_system_unit() == "mm" + + rf = sr.live.rf.get("RF") + tra = sr.live.rf.transmitter.get("RFTRA") + assert rf.frequency.control_system_unit() == "MHz" + assert tra.voltage.control_system_unit() == "kV" + assert tra.phase.control_system_unit() == "deg" + assert rf.voltage.control_system_unit() == "V" # Aggregate of transmitters, no device + + q1 = sr.live.magnet.get("Q1") + assert q1.hardware.unit() == "A" + assert q1.hardware.control_system_unit() == "mA" + assert q1.strength.control_system_unit() == q1.strength.unit() # No device holds a strength + + quads = sr.live.magnets.get("QUADS") + assert quads.hardwares.control_system_unit() == "mA" + assert quads.strengths.control_system_unit() == quads.strengths.unit() + + bpms = sr.live.diagnostic.bpms.get("BPM") + assert bpms.positions.control_system_unit() == "mm" + assert bpms.h.control_system_unit() == "mm" + + +def test_control_system_unit_defaults_to_unit_on_simulator(): + sr = Accelerator.load("tests/config/EBS_rf.yaml", ignore_external=True) + assert sr.design.rf.frequency.control_system_unit() == sr.design.rf.frequency.unit() == "Hz" + + +@TANGO +def test_get_quantity_on_control_system(install_test_package): + from tango.pyaml.attribute_store import set_attribute + + for key, value in [("bpm1/H", 0.1), ("bpm1/V", -0.2), ("bpm2/H", 0.3), ("bpm2/V", -0.4)]: + set_attribute(f"sr/test/{key}", value, unit="mm") + sr = Accelerator.from_dict(_config()) + + rf = sr.live.rf.get("RF") + rf.frequency.set(352.2 * ureg.MHz) + f = rf.frequency.get(quantity=True) + assert isinstance(f, pint.Quantity) and f.to("MHz").magnitude == pytest.approx(352.2) + assert isinstance(rf.frequency.get(), float) # Default unchanged + + bpm = sr.live.diagnostic.bpm.get("BPM1") + assert np.allclose(bpm.positions.get(quantity=True).to("mm").magnitude, [0.1, -0.2]) + bpms = sr.live.diagnostic.bpms.get("BPM") + q = bpms.positions.get(quantity=True) + assert q.shape == (2, 2) and np.allclose(q.to("mm").magnitude, [[0.1, -0.2], [0.3, -0.4]]) + assert np.allclose(bpms.h.get(quantity=True).to("um").magnitude, [100.0, 300.0]) + + quads = sr.live.magnets.get("QUADS") + quads.hardwares.set(np.array([1.0, 3.0]) * ureg.A) + assert np.allclose(quads.hardwares.get(quantity=True).to("mA").magnitude, [1000.0, 3000.0]) + assert quads.strengths.get(quantity=True).units == 1 / ureg.m + + agg = sr.live.create_magnet_strength_aggregator(list(quads)) + assert agg.get(quantity=True).units == 1 / ureg.m + assert sr.live.magnet.get("Q1").hardware.get(quantity=True).to("mA").magnitude == pytest.approx(1000.0) + + +def test_get_quantity_on_simulator(): + sr = Accelerator.load("tests/config/EBS_rf.yaml", ignore_external=True) + sr.design.rf.frequency.set(352.3 * ureg.MHz) + assert sr.design.rf.frequency.get(quantity=True).to("MHz").magnitude == pytest.approx(352.3) + + # --------------------------------------------------------------------------- simulator @@ -362,3 +543,39 @@ def test_set_energy_accepts_quantity(): sr = Accelerator.load("tests/config/EBS_rf.yaml", ignore_external=True) sr.set_energy(6 * ureg.GeV) assert sr._energy == pytest.approx(6e9) + + +def _check_units(acc): + """A single unit when all values share it, one per value (shaped like get()) only when they differ.""" + values = acc.get() + for unit in (acc.unit(), acc.control_system_unit()): + if not isinstance(unit, str): + assert np.shape(unit) == np.shape(values) and len(set(np.ravel(unit))) > 1, unit + acc.get(quantity=True) + + +def test_units_of_simulator_accessors(): + sr = Accelerator.load("tests/config/sr_serialized_magnets.yaml", ignore_external=True) + series = sr.design.serialized_magnets.get("QForTune") + _check_units(series.strengths) + _check_units(series.hardwares) + assert series.strengths.unit() == "1/m" # Declared as m-1, reported in canonical form + + sr = Accelerator.load("tests/config/EBSOrbit.yaml", ignore_external=True) + bpms = sr.design.diagnostic.bpms.get("BPM") + bpm = sr.design.diagnostic.bpm.get(bpms.names()[0]) + for acc in (bpms.positions, bpms.h, bpms.v, bpm.positions, bpm.offset): + _check_units(acc) + + +@TANGO +def test_units_of_control_system_accessors(install_test_package): + sr = Accelerator.from_dict(_config()) + bpms = sr.live.diagnostic.bpms.get("BPM") + quads = sr.live.magnets.get("QUADS") + assert quads.strengths.unit() == "1/m" # Q1 in 1/m and Q2 in m-1 share one unit + accessors = [bpms.positions, bpms.h, bpms.v, quads.hardwares, quads.strengths] + accessors += [sr.live.create_magnet_strength_aggregator(list(quads))] + accessors += sr.live.create_bpm_aggregators(list(bpms)) + for acc in accessors: + _check_units(acc) diff --git a/tests/tuning_tools/test_tune_hardware.py b/tests/tuning_tools/test_tune_hardware.py index e48ce265..05e18058 100644 --- a/tests/tuning_tools/test_tune_hardware.py +++ b/tests/tuning_tools/test_tune_hardware.py @@ -40,4 +40,4 @@ def test_tune(): assert np.abs(diffTune[1] - 0.05) < 1.1e-3 assert np.abs(currents[0] - 88.04522942) < 1e-8 assert np.abs(currents[1] - 88.26677735) < 1e-8 - assert units[0] == "A" and units[1] == "A" + assert units == "A" From 0ab973c2b59cfbd322a4db293e96646da61fadd1 Mon Sep 17 00:00:00 2001 From: Alexis Gamelin Date: Fri, 20 Nov 2026 21:01:32 +0100 Subject: [PATCH 6/8] Convert tune devices reporting a frequency to tunes (#350) A tune monitor device declared in a frequency unit (Hz, kHz...) is read in Hz and converted to the fractional tune with the revolution frequency f_rev = f_RF / h, read on every call from the monitor's RF plant and the accelerator harmonic number. A frequency only gives the tune modulo 1 and up to q / 1 - q (betatron sidebands (n +/- q) f_rev): frac(f / f_rev) is folded into [0, 0.5], and the new tune_above_half option returns 1 - q for a plane whose fractional tune is above the half-integer. Tune devices in a frequency unit without rf_plant_name raise at load. Co-Authored-By: Claude Opus 5.5 --- pyaml/common/units.py | 23 ++++++++++ pyaml/control/abstract_impl.py | 48 +++++++++++++++----- pyaml/control/controlsystem.py | 20 +++++++-- pyaml/diagnostics/tune_monitor.py | 74 +++++++++++++++++++++++++++---- tests/test_units.py | 40 +++++++++++++++++ 5 files changed, 181 insertions(+), 24 deletions(-) diff --git a/pyaml/common/units.py b/pyaml/common/units.py index db85936c..2450d525 100644 --- a/pyaml/common/units.py +++ b/pyaml/common/units.py @@ -206,6 +206,29 @@ def conversion_factor(src: str | None, dst: str | None) -> float: return float(k) +def is_frequency_unit(unit: str | None) -> bool: + """ + Return ``True`` if ``unit`` is a frequency unit (``Hz``, ``kHz``, ``1/s``...). + + Parameters + ---------- + unit : str or None + Unit string, in any of the formats accepted by PyAML. + + Returns + ------- + bool + ``False`` for an empty, dimensionless, unknown or non-frequency unit. + """ + if _is_no_unit(unit): + return False + try: + conversion_factor(unit, SI_FREQUENCY) + except PyAMLConfigException: + return False + return True + + def is_quantity(value: Any) -> bool: """Return ``True`` if ``value`` is a :class:`pint.Quantity`.""" return isinstance(value, pint.Quantity) diff --git a/pyaml/control/abstract_impl.py b/pyaml/control/abstract_impl.py index e96767ac..8b585434 100644 --- a/pyaml/control/abstract_impl.py +++ b/pyaml/control/abstract_impl.py @@ -1385,12 +1385,19 @@ class RBetatronTuneArray(abstract.ReadFloatArray): """ Expose horizontal and vertical betatron tunes as a read-only array. + A plane whose device reports a frequency ``f`` is converted to the + fractional tune. + Parameters ---------- - tune_monitor : object - Tune monitor configuration supplying the tune unit. devs : list[DeviceAccess] - Devices providing horizontal and vertical tune measurements. + Devices providing horizontal and vertical tune measurements, in tune + units or in Hz. + is_frequency : list[bool] or None, optional + ``[horizontal, vertical]`` flags, ``True`` for a device read in Hz. + above_half : list[bool] or None, optional + ``[horizontal, vertical]`` flags, ``True`` when the fractional tune of + a plane read in Hz is above the half-integer. Methods ------- @@ -1400,24 +1407,41 @@ class RBetatronTuneArray(abstract.ReadFloatArray): Return the pyAML unit for this quantity, i.e. returned by get(). control_system_unit() Return the control-system unit for this quantity. + set_revolution_frequency_source(source) + Set the callable returning the revolution frequency in Hz. """ - def __init__(self, tune_monitor, devs: list[DeviceAccess]): + def __init__(self, devs: list[DeviceAccess], is_frequency: list[bool] | None = None, above_half: list[bool] | None = None): """ Initialize the RBetatronTuneArray. """ - self.__tune_monitor = tune_monitor self.__devs = devs + self.__is_frequency = np.array(is_frequency if is_frequency is not None else [False, False], dtype=bool) + self.__above_half = np.array(above_half if above_half is not None else [False, False], dtype=bool) + self.__frev_source = None + + def set_revolution_frequency_source(self, source): + """ + Set the callable returning the revolution frequency in Hz. + + Parameters + ---------- + source : callable + Called on every ``get()`` when a plane is read in Hz. + """ + self.__frev_source = source def get(self) -> NDArray: - # Return horizontal and vertical betatron tunes as a NumPy array """Return horizontal and vertical betatron tunes.""" - return np.array( - [ - self.__devs[0].get(), - self.__devs[1].get(), - ] - ) + values = np.array([d.get() for d in self.__devs], dtype=float) + if self.__is_frequency.any(): + if self.__frev_source is None: + raise PyAMLException("Tune devices read in Hz need a revolution frequency source") + q = np.mod(values / self.__frev_source(), 1.0) # Sidebands (n ± q) f_rev + q = np.minimum(q, 1.0 - q) # Fold into [0, 0.5] + q = np.where(self.__above_half, 1.0 - q, q) + values = np.where(self.__is_frequency, q, values) + return values def unit(self) -> str: """Return the pyAML unit for this quantity, i.e. returned by get().""" diff --git a/pyaml/control/controlsystem.py b/pyaml/control/controlsystem.py index 225fe2e0..7747440a 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -16,7 +16,7 @@ from ..common.abstract_aggregator import ScalarAggregator from ..common.exception import PyAMLConfigException, PyAMLException from ..common.holders.element_holder import ElementHolder -from ..common.units import SI_ANGLE, SI_FREQUENCY, SI_POSITION, SI_TUNE, SI_VOLTAGE +from ..common.units import SI_ANGLE, SI_FREQUENCY, SI_POSITION, SI_TUNE, SI_VOLTAGE, is_frequency_unit from ..configuration.unbound_element import UnboundElement from ..control.abstract_impl import ( CSScalarAggregator, @@ -332,8 +332,22 @@ def _fill_rf_plant(self, rf_plant: RFPlant) -> None: self.rf.add(rf_plant.attach(self, frequency, voltage)) def _fill_betatron_tune_monitor(self, monitor: BetatronTuneMonitor) -> None: - devices = self.get_si_devices_access([monitor.tune_h, monitor.tune_v], SI_TUNE) - self.add_betatron_tune_monitor(monitor.attach(self, RBetatronTuneArray(monitor, devices))) + # A tune device may report the betatron frequency: it is then read in Hz + # and converted to a tune with the revolution frequency on every read. + devices, is_frequency = [], [] + for ref in (monitor.tune_h, monitor.tune_v): + dev = self.get_device_access(ref) + in_hz = dev is not None and is_frequency_unit(dev.unit()) + devices.append(wrap_si(dev, SI_FREQUENCY if in_hz else SI_TUNE)) + is_frequency.append(in_hz) + if any(is_frequency) and monitor.rf_plant_name is None: + raise PyAMLConfigException( + f"{monitor.get_name()}: tune devices in a frequency unit need rf_plant_name to be converted to tunes" + ) + tune = RBetatronTuneArray(devices, is_frequency, monitor.tune_above_half) + attached = monitor.attach(self, tune) + tune.set_revolution_frequency_source(attached.revolution_frequency) + self.add_betatron_tune_monitor(attached) def _fill_tool(self, tool: TuningTool | MeasurementTool) -> None: self.add_tool(tool.attach(self)) diff --git a/pyaml/diagnostics/tune_monitor.py b/pyaml/diagnostics/tune_monitor.py index 5ba0c6eb..01b71f53 100644 --- a/pyaml/diagnostics/tune_monitor.py +++ b/pyaml/diagnostics/tune_monitor.py @@ -12,6 +12,7 @@ from ..common.abstract import ReadFloatArray from ..common.element import Element, __pyaml_repr__ +from ..common.exception import PyAMLConfigException, PyAMLException from ..validation import DynamicValidation, register_schema from .atune_monitor import ABetatronTuneMonitor @@ -28,8 +29,14 @@ class BetatronTuneMonitor(Element, DynamicValidation, ABetatronTuneMonitor): Represents a betatron tune monitor in the accelerator lattice and provides access to the measured horizontal and vertical betatron - tunes. Optionally, the monitor can be associated with an RF plant - used to convert tune measurements to frequency values. + tunes. + + The tune devices may report the fractional tune (unit ``"1"`` or no + unit) or the betatron frequency, in any frequency unit (``Hz``, + ``kHz``...). The fractional tune ``q`` is then computed from the + frequency ``f`` and the revolution frequency ``f_rev = f_RF / h``, read + on every call from the RF plant ``rf_plant_name`` and the accelerator + ``harmonic_number``, which are then both required. Parameters ---------- @@ -43,6 +50,10 @@ class BetatronTuneMonitor(Element, DynamicValidation, ABetatronTuneMonitor): Device catalog key for the vertical betatron tune measurement. rf_plant_name : str | None, optional Name of the associated RF plant element used by the monitor. + tune_above_half : list[bool] | None, optional + ``[horizontal, vertical]`` flags, only used for a tune device + reporting a frequency: ``True`` when the fractional tune of the plane + is above the half-integer. Defaults to ``[False, False]``. Attributes ---------- @@ -50,6 +61,10 @@ class BetatronTuneMonitor(Element, DynamicValidation, ABetatronTuneMonitor): Return the horizontal tune device catalog key. tune_v Return the vertical tune device catalog key. + rf_plant_name + Return the name of the RF plant used for tune-frequency conversion. + tune_above_half + Return the ``[horizontal, vertical]`` above-half-integer flags. tune Get the betatron tune values. frequency @@ -59,6 +74,8 @@ class BetatronTuneMonitor(Element, DynamicValidation, ABetatronTuneMonitor): ------- set_harmonic(h) Set the harmonic number used for tune-frequency conversion. + revolution_frequency() + Return the revolution frequency from the RF frequency and harmonic number. attach(peer, betatron_tune) Attach the tune monitor to a peer with betatron tune data. @@ -71,6 +88,7 @@ class BetatronTuneMonitor(Element, DynamicValidation, ABetatronTuneMonitor): tune_h: DEVICE/HORIZONTAL_TUNE tune_v: DEVICE/VERTICAL_TUNE rf_plant_name: RF + tune_above_half: [false, false] """ def __init__( @@ -80,6 +98,7 @@ def __init__( tune_h: str | None = None, tune_v: str | None = None, rf_plant_name: str | None = None, + tune_above_half: list[bool] | None = None, ): """ Initialize a betatron tune monitor. @@ -88,6 +107,13 @@ def __init__( self._tune_h = tune_h self._tune_v = tune_v self._rf_plant_name = rf_plant_name + if tune_above_half is None: + tune_above_half = [False, False] + if len(tune_above_half) != 2: + raise PyAMLConfigException( + f"{name}: tune_above_half expects 2 values [horizontal, vertical], got {tune_above_half}" + ) + self._tune_above_half = [bool(a) for a in tune_above_half] self.__tune = None self._h = None @@ -103,6 +129,32 @@ def set_harmonic(self, h: int): """ self._h = float(h) + def revolution_frequency(self) -> float: + """ + Return the revolution frequency from the RF frequency and harmonic number. + + The RF frequency is read from the RF plant ``rf_plant_name`` of the + mode the monitor is attached to. + + Returns + ------- + float + Revolution frequency ``f_RF / h`` in Hz. + + Raises + ------ + PyAMLException + If no RF plant or no harmonic number is defined. + """ + if self._rf_plant_name is None: + raise PyAMLException(f"{self.get_name()}: rf_plant_name is required to compute the revolution frequency") + if self._h is None: + raise PyAMLException( + f"{self.get_name()}: the accelerator harmonic_number is required to compute the revolution frequency" + ) + self.check_peer() + return self.peer.rf.get(self._rf_plant_name).frequency.get() / self._h + def _fill_device(self, holder: "ElementHolder") -> None: holder._fill_betatron_tune_monitor(self) @@ -116,6 +168,16 @@ def tune_v(self) -> str | None: """Return the vertical tune device catalog key.""" return self._tune_v + @property + def rf_plant_name(self) -> str | None: + """Return the name of the RF plant used for tune-frequency conversion.""" + return self._rf_plant_name + + @property + def tune_above_half(self) -> list[bool]: + """Return the ``[horizontal, vertical]`` above-half-integer flags.""" + return list(self._tune_above_half) + @property def tune(self) -> ReadFloatArray: """ @@ -165,13 +227,7 @@ def __init__(self, parent: BetatronTuneMonitor): def get(self) -> NDArray: """Return tune frequencies in hertz.""" - h = self.parent._h - rf_name = self.parent._rf_plant_name - if h is not None and rf_name is not None: - tune = self.parent.tune.get() - rf = self.parent.peer.rf.get(rf_name) - freq = rf.frequency.get() - return tune * freq / h + return self.parent.tune.get() * self.parent.revolution_frequency() def unit(self) -> str: """Return the pyAML unit for this quantity, i.e. returned by get().""" diff --git a/tests/test_units.py b/tests/test_units.py index 066a500a..d392709e 100644 --- a/tests/test_units.py +++ b/tests/test_units.py @@ -392,6 +392,46 @@ def broken_unit(): wrap_si(dev, "m") +def _tune_config(rf_plant_name="RF") -> dict: + """``_config()`` plus a tune monitor whose devices report the betatron frequency in kHz.""" + cfg = _config() + cfg["harmonic_number"] = 416 + entries = cfg["controls"][0]["catalog"]["entries"] + entries += [_entry("tune/h", "kHz", read_only=True), _entry("tune/v", "kHz", read_only=True)] + monitor = {"type": "pyaml.diagnostics.tune_monitor", "name": "TUNE", "tune_h": "tune/h", "tune_v": "tune/v"} + if rf_plant_name is not None: + monitor.update(rf_plant_name=rf_plant_name, tune_above_half=[False, True]) + cfg["devices"].append(monitor) + return cfg + + +@TANGO +def test_tune_device_in_frequency_unit(install_test_package): + from tango.pyaml.attribute_store import set_attribute + + set_attribute("sr/test/tune/h", 180.0, unit="kHz") + set_attribute("sr/test/tune/v", 300.0, unit="kHz") + sr = Accelerator.from_dict(_tune_config()) + rf = sr.live.rf.get("RF") + tune = sr.live.diagnostic.get("TUNE") + + for f_rf in (352.2e6, 352.3e6): # The revolution frequency follows the RF frequency + rf.frequency.set(f_rf) + f_rev = f_rf / 416 + assert np.allclose(tune.tune.get(), [180e3 / f_rev, 1 - 300e3 / f_rev]) # Vertical tune above half + # Any betatron sideband (n ± q) f_rev gives the same tune + for f in (f_rev + 180e3, 2 * f_rev - 180e3): + set_attribute("sr/test/tune/h", f / 1e3) + assert tune.tune.get()[0] == pytest.approx(180e3 / f_rev) + set_attribute("sr/test/tune/h", 180.0) + assert tune.tune.unit() == "1" + assert tune.tune.control_system_unit() == "kHz" + assert tune.frequency.get()[0] == pytest.approx(180e3) + + with pytest.raises(PyAMLConfigException, match="rf_plant_name"): + Accelerator.from_dict(_tune_config(rf_plant_name=None)) + + @TANGO def test_incompatible_device_unit_raises_at_load(install_test_package): with pytest.raises(PyAMLConfigException, match="cannot be converted"): From 2bd91770c4d906fd8005251b37956a0743764853 Mon Sep 17 00:00:00 2001 From: Alexis Gamelin Date: Fri, 20 Nov 2026 21:18:52 +0100 Subject: [PATCH 7/8] Move revolution_frequency() to the RF plant (#350) The revolution frequency f_RF / h belongs to the RF plant: RFPlant gains set_harmonic() and revolution_frequency(), which reads the RF frequency on every call. BetatronTuneMonitor no longer stores the harmonic number; its frequency property and the control-system tune conversion use the revolution frequency of the RF plant rf_plant_name. Co-Authored-By: Claude Opus 5.5 --- pyaml/control/controlsystem.py | 2 +- pyaml/diagnostics/tune_monitor.py | 48 ++++--------------------------- pyaml/rf/rf_plant.py | 38 ++++++++++++++++++++++++ tests/test_accelerator_add.py | 2 -- tests/test_units.py | 1 + 5 files changed, 45 insertions(+), 46 deletions(-) diff --git a/pyaml/control/controlsystem.py b/pyaml/control/controlsystem.py index 7747440a..0f265780 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -346,7 +346,7 @@ def _fill_betatron_tune_monitor(self, monitor: BetatronTuneMonitor) -> None: ) tune = RBetatronTuneArray(devices, is_frequency, monitor.tune_above_half) attached = monitor.attach(self, tune) - tune.set_revolution_frequency_source(attached.revolution_frequency) + tune.set_revolution_frequency_source(lambda: self.rf.get(monitor.rf_plant_name).revolution_frequency()) self.add_betatron_tune_monitor(attached) def _fill_tool(self, tool: TuningTool | MeasurementTool) -> None: diff --git a/pyaml/diagnostics/tune_monitor.py b/pyaml/diagnostics/tune_monitor.py index 01b71f53..e4bd05d6 100644 --- a/pyaml/diagnostics/tune_monitor.py +++ b/pyaml/diagnostics/tune_monitor.py @@ -34,9 +34,7 @@ class BetatronTuneMonitor(Element, DynamicValidation, ABetatronTuneMonitor): The tune devices may report the fractional tune (unit ``"1"`` or no unit) or the betatron frequency, in any frequency unit (``Hz``, ``kHz``...). The fractional tune ``q`` is then computed from the - frequency ``f`` and the revolution frequency ``f_rev = f_RF / h``, read - on every call from the RF plant ``rf_plant_name`` and the accelerator - ``harmonic_number``, which are then both required. + frequency ``f`` and the revolution frequency of the RF plant. Parameters ---------- @@ -72,10 +70,6 @@ class BetatronTuneMonitor(Element, DynamicValidation, ABetatronTuneMonitor): Methods ------- - set_harmonic(h) - Set the harmonic number used for tune-frequency conversion. - revolution_frequency() - Return the revolution frequency from the RF frequency and harmonic number. attach(peer, betatron_tune) Attach the tune monitor to a peer with betatron tune data. @@ -115,45 +109,13 @@ def __init__( ) self._tune_above_half = [bool(a) for a in tune_above_half] self.__tune = None - self._h = None - def set_harmonic(self, h: int): - """ - Set the harmonic number used for tune-frequency conversion. - - Parameters - ---------- - h : int - Harmonic number relating the RF frequency to the measured - betatron tune frequency. - """ - self._h = float(h) - - def revolution_frequency(self) -> float: - """ - Return the revolution frequency from the RF frequency and harmonic number. - - The RF frequency is read from the RF plant ``rf_plant_name`` of the - mode the monitor is attached to. - - Returns - ------- - float - Revolution frequency ``f_RF / h`` in Hz. - - Raises - ------ - PyAMLException - If no RF plant or no harmonic number is defined. - """ + def _rf_plant(self): + """Return the RF plant of the mode the monitor is attached to.""" if self._rf_plant_name is None: raise PyAMLException(f"{self.get_name()}: rf_plant_name is required to compute the revolution frequency") - if self._h is None: - raise PyAMLException( - f"{self.get_name()}: the accelerator harmonic_number is required to compute the revolution frequency" - ) self.check_peer() - return self.peer.rf.get(self._rf_plant_name).frequency.get() / self._h + return self.peer.rf.get(self._rf_plant_name) def _fill_device(self, holder: "ElementHolder") -> None: holder._fill_betatron_tune_monitor(self) @@ -227,7 +189,7 @@ def __init__(self, parent: BetatronTuneMonitor): def get(self) -> NDArray: """Return tune frequencies in hertz.""" - return self.parent.tune.get() * self.parent.revolution_frequency() + return self.parent.tune.get() * self.parent._rf_plant().revolution_frequency() def unit(self) -> str: """Return the pyAML unit for this quantity, i.e. returned by get().""" diff --git a/pyaml/rf/rf_plant.py b/pyaml/rf/rf_plant.py index 95e89246..3d9dd98f 100644 --- a/pyaml/rf/rf_plant.py +++ b/pyaml/rf/rf_plant.py @@ -53,6 +53,10 @@ class RFPlant(Element, DynamicValidation): Methods ------- + set_harmonic(h) + Set the harmonic number used to compute the revolution frequency. + revolution_frequency() + Return the revolution frequency ``f_RF / h``. attach(peer, frequency, voltage) Return a copy attached to RF read/write handles. @@ -87,6 +91,40 @@ def __init__( self.transmitters = transmitters self.__frequency = None self.__voltage = None + self._h = None + + def set_harmonic(self, h: int): + """ + Set the harmonic number used to compute the revolution frequency. + + Parameters + ---------- + h : int + Number of RF buckets per revolution. + """ + self._h = float(h) + + def revolution_frequency(self) -> float: + """ + Return the revolution frequency ``f_RF / h``. + + The RF frequency is read on every call. + + Returns + ------- + float + Revolution frequency in Hz. + + Raises + ------ + PyAMLException + If no harmonic number is defined or the plant has no master clock. + """ + if self._h is None: + raise PyAMLException( + f"{self.get_name()}: the accelerator harmonic_number is required to compute the revolution frequency" + ) + return self.frequency.get() / self._h @property def frequency(self) -> abstract.ReadWriteFloatScalar: diff --git a/tests/test_accelerator_add.py b/tests/test_accelerator_add.py index 8e75ec26..ca6da7f7 100644 --- a/tests/test_accelerator_add.py +++ b/tests/test_accelerator_add.py @@ -168,7 +168,6 @@ def test_add_registers_diagnostics_in_every_mode(accelerator_factory): assert attached is holder[monitor.name] assert attached.peer is holder assert attached is not monitor - assert attached._h == 992 assert monitor.peer is None assert accelerator.yellow_pages.availability(monitor.name) == set(accelerator.modes()) @@ -294,5 +293,4 @@ def test_add_device_uses_the_same_binding_and_initialization(accelerator_factory for holder in accelerator.modes().values(): monitor = holder.diagnostic.get("NEW_TUNE") assert monitor.peer is holder - assert monitor._h == 992 assert accelerator._devices[0].name == "NEW_TUNE" diff --git a/tests/test_units.py b/tests/test_units.py index d392709e..f984be97 100644 --- a/tests/test_units.py +++ b/tests/test_units.py @@ -418,6 +418,7 @@ def test_tune_device_in_frequency_unit(install_test_package): for f_rf in (352.2e6, 352.3e6): # The revolution frequency follows the RF frequency rf.frequency.set(f_rf) f_rev = f_rf / 416 + assert rf.revolution_frequency() == pytest.approx(f_rev) assert np.allclose(tune.tune.get(), [180e3 / f_rev, 1 - 300e3 / f_rev]) # Vertical tune above half # Any betatron sideband (n ± q) f_rev gives the same tune for f in (f_rev + 180e3, 2 * f_rev - 180e3): From cf46e64eeb571f29c2ca43e01c6df198d5c94fb0 Mon Sep 17 00:00:00 2001 From: Alexis Gamelin Date: Fri, 20 Nov 2026 21:39:03 +0100 Subject: [PATCH 8/8] Simplify SI unit code and consolidate unit tests (#350) - Pass the revolution frequency to RBetatronTuneArray at construction instead of through a setter. - Factor the resolution of magnet devices in their hardware unit into ControlSystem._get_magnet_devices(). - Remove a misleading comment in _hardware_unit and an unneeded list branch in wrap_si; fix a comment typo in units.py. - Shorten the get(quantity=True) docstring note. - Merge overlapping tests in tests/test_units.py (32 -> 23 tests) without losing coverage. Co-Authored-By: Claude Opus 5.5 --- pyaml/common/abstract.py | 12 +- pyaml/common/units.py | 2 +- pyaml/control/abstract_impl.py | 32 +++-- pyaml/control/controlsystem.py | 24 ++-- pyaml/control/si_deviceaccess.py | 5 +- tests/test_units.py | 196 +++++++++---------------------- 6 files changed, 88 insertions(+), 183 deletions(-) diff --git a/pyaml/common/abstract.py b/pyaml/common/abstract.py index acd4b453..1e4c881c 100644 --- a/pyaml/common/abstract.py +++ b/pyaml/common/abstract.py @@ -34,10 +34,8 @@ def get(self) -> double: """ Return the current scalar value. - Implementations take no argument: every subclass also accepts - ``get(quantity=True)``, which returns the value as a - :class:`pint.Quantity` in ``unit()`` (see - :class:`~pyaml.common.units.AcceptsQuantity`). + ``get(quantity=True)`` returns a :class:`pint.Quantity` in ``unit()`` + (see :class:`~pyaml.common.units.AcceptsQuantity`). Returns ------- @@ -134,10 +132,8 @@ def get(self) -> array: """ Return the current values as an array. - Implementations take no argument: every subclass also accepts - ``get(quantity=True)``, which returns the values as a - :class:`pint.Quantity` in ``unit()`` (see - :class:`~pyaml.common.units.AcceptsQuantity`). + ``get(quantity=True)`` returns a :class:`pint.Quantity` in ``unit()`` + (see :class:`~pyaml.common.units.AcceptsQuantity`). """ pass diff --git a/pyaml/common/units.py b/pyaml/common/units.py index 2450d525..c81b4efa 100644 --- a/pyaml/common/units.py +++ b/pyaml/common/units.py @@ -46,7 +46,7 @@ from .exception import PyAMLConfigException, PyAMLException -# Units used by PyAML (interally and used by get/set methods). +# pyAML units, used internally and by get()/set(). SI_POSITION = "m" SI_ANGLE = "rad" SI_VOLTAGE = "V" diff --git a/pyaml/control/abstract_impl.py b/pyaml/control/abstract_impl.py index 8b585434..191c1d43 100644 --- a/pyaml/control/abstract_impl.py +++ b/pyaml/control/abstract_impl.py @@ -1398,6 +1398,9 @@ class RBetatronTuneArray(abstract.ReadFloatArray): above_half : list[bool] or None, optional ``[horizontal, vertical]`` flags, ``True`` when the fractional tune of a plane read in Hz is above the half-integer. + revolution_frequency : callable or None, optional + Returns the revolution frequency in Hz, called on every ``get()`` + when a plane is read in Hz. Methods ------- @@ -1407,37 +1410,30 @@ class RBetatronTuneArray(abstract.ReadFloatArray): Return the pyAML unit for this quantity, i.e. returned by get(). control_system_unit() Return the control-system unit for this quantity. - set_revolution_frequency_source(source) - Set the callable returning the revolution frequency in Hz. """ - def __init__(self, devs: list[DeviceAccess], is_frequency: list[bool] | None = None, above_half: list[bool] | None = None): + def __init__( + self, + devs: list[DeviceAccess], + is_frequency: list[bool] | None = None, + above_half: list[bool] | None = None, + revolution_frequency=None, + ): """ Initialize the RBetatronTuneArray. """ self.__devs = devs self.__is_frequency = np.array(is_frequency if is_frequency is not None else [False, False], dtype=bool) self.__above_half = np.array(above_half if above_half is not None else [False, False], dtype=bool) - self.__frev_source = None - - def set_revolution_frequency_source(self, source): - """ - Set the callable returning the revolution frequency in Hz. - - Parameters - ---------- - source : callable - Called on every ``get()`` when a plane is read in Hz. - """ - self.__frev_source = source + self.__revolution_frequency = revolution_frequency def get(self) -> NDArray: """Return horizontal and vertical betatron tunes.""" values = np.array([d.get() for d in self.__devs], dtype=float) if self.__is_frequency.any(): - if self.__frev_source is None: - raise PyAMLException("Tune devices read in Hz need a revolution frequency source") - q = np.mod(values / self.__frev_source(), 1.0) # Sidebands (n ± q) f_rev + if self.__revolution_frequency is None: + raise PyAMLException("Tune devices read in Hz need a revolution frequency") + q = np.mod(values / self.__revolution_frequency(), 1.0) # Sidebands (n ± q) f_rev q = np.minimum(q, 1.0 - q) # Fold into [0, 0.5] q = np.where(self.__above_half, 1.0 - q, q) values = np.where(self.__is_frequency, q, values) diff --git a/pyaml/control/controlsystem.py b/pyaml/control/controlsystem.py index 0f265780..9ac4ce48 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -51,7 +51,6 @@ def _hardware_unit(model, index: int = 0) -> str: """Return the hardware unit of device ``index`` of a magnet model ('' if unknown).""" - # Identity models without power supply still report the unit of the device they read units = model.get_hardware_units() if not units: return "" @@ -182,6 +181,11 @@ def get_si_devices_access( units = si_units if isinstance(si_units, list) else [si_units] * len(refs) return [self.get_si_device_access(ref, unit) for ref, unit in zip(refs, units, strict=True)] + def _get_magnet_devices(self, model) -> list[DeviceAccess | None]: + """Resolve all devices of a magnet model, each read and written in its model hardware unit.""" + names = model.get_device_names() + return self.get_si_devices_access(names, [_hardware_unit(model, i) for i in range(len(names))]) + def _get_si_aggregator(self) -> SIDeviceAccessList | None: """Return an empty backend aggregator wrapped for SI conversion, or ``None``.""" agg = self.get_aggregator() @@ -214,9 +218,7 @@ def create_magnet_strength_aggregator(self, magnets: list[Magnet]) -> ScalarAggr return None magg = CSStrengthScalarAggregator(agg) for m in magnets: - names = m.model.get_device_names() - devs = self.get_si_devices_access(names, [_hardware_unit(m.model, i) for i in range(len(names))]) - magg.add_magnet(m, devs) + magg.add_magnet(m, self._get_magnet_devices(m.model)) return magg def create_magnet_hardware_aggregator(self, magnets: list[Magnet]) -> ScalarAggregator | None: @@ -283,8 +285,7 @@ def _fill_magnet(self, magnet: Magnet) -> None: self.magnet.add(magnet.attach(self, strength, current)) def _fill_combined_function_magnet(self, magnet: CombinedFunctionMagnet) -> None: - names = magnet.model.get_device_names() - devices = self.get_si_devices_access(names, [_hardware_unit(magnet.model, i) for i in range(len(names))]) + devices = self._get_magnet_devices(magnet.model) currents = RWHardwareArray(magnet.model, devices) strengths = RWStrengthArray(magnet.model, devices) attached_magnets = magnet.attach(self, strengths, currents) @@ -344,10 +345,13 @@ def _fill_betatron_tune_monitor(self, monitor: BetatronTuneMonitor) -> None: raise PyAMLConfigException( f"{monitor.get_name()}: tune devices in a frequency unit need rf_plant_name to be converted to tunes" ) - tune = RBetatronTuneArray(devices, is_frequency, monitor.tune_above_half) - attached = monitor.attach(self, tune) - tune.set_revolution_frequency_source(lambda: self.rf.get(monitor.rf_plant_name).revolution_frequency()) - self.add_betatron_tune_monitor(attached) + tune = RBetatronTuneArray( + devices, + is_frequency, + monitor.tune_above_half, + revolution_frequency=lambda: self.rf.get(monitor.rf_plant_name).revolution_frequency(), + ) + self.add_betatron_tune_monitor(monitor.attach(self, tune)) def _fill_tool(self, tool: TuningTool | MeasurementTool) -> None: self.add_tool(tool.attach(self)) diff --git a/pyaml/control/si_deviceaccess.py b/pyaml/control/si_deviceaccess.py index 801cfaf5..015396b0 100644 --- a/pyaml/control/si_deviceaccess.py +++ b/pyaml/control/si_deviceaccess.py @@ -172,11 +172,8 @@ def wrap_si(dev: DeviceAccess | None, si_unit: str | None) -> DeviceAccess | Non """ if dev is None or isinstance(dev, SIDeviceAccess) or si_unit is None or not str(si_unit).strip(): return dev - dev_unit = dev.unit() - if isinstance(dev_unit, (list, tuple)): # Defensive: some backends may return a list - dev_unit = dev_unit[0] if dev_unit else None try: - k = conversion_factor(dev_unit, si_unit) + k = conversion_factor(dev.unit(), si_unit) except PyAMLConfigException as e: raise PyAMLConfigException(f"Device '{dev.name()}': {e}") from e return SIDeviceAccess(dev, si_unit, k) diff --git a/tests/test_units.py b/tests/test_units.py index f984be97..c0d51f52 100644 --- a/tests/test_units.py +++ b/tests/test_units.py @@ -89,27 +89,6 @@ def test_to_magnitude_scalar_quantity_broadcast_to_unit_list(): to_magnitude(0.5 / ureg.m, ["1/m", "1/m**2"]) -def test_read_write_interfaces_accept_quantity(): - from pyaml.common.abstract import ReadFloatScalar - - class Tilt(ReadFloatScalar): # Read-only interface with a setter, like the BPM tilt - def __init__(self): - self.value = 0.0 - - def get(self): - return self.value - - def set(self, value): - self.value = value - - def unit(self): - return "rad" - - t = Tilt() - t.set(1 * ureg.mrad) - assert t.value == pytest.approx(1e-3) - - def test_to_quantity(): assert to_quantity(None, "m") is None q = to_quantity(1.5, "mm") @@ -137,21 +116,27 @@ def test_common_unit(): assert common_unit([None, None]) is None -def test_get_returns_quantity_on_any_implementation(): +def test_any_implementation_accepts_and_returns_quantity(): from pyaml.common.abstract import ReadFloatArray - class Positions(ReadFloatArray): # Minimal implementation, like an external package + class Positions(ReadFloatArray): # Minimal read-only interface with a setter, like an external package + def __init__(self): + self.value = np.array([1e-3, -2e-3]) + def get(self): - return np.array([1e-3, -2e-3]) + return self.value + + def set(self, value): + self.value = value def unit(self): return "m" p = Positions() - assert isinstance(p.get(), np.ndarray) # Default unchanged - q = p.get(quantity=True) - assert np.allclose(q.to("mm").magnitude, [1.0, -2.0]) - assert p.get(quantity=False) is not None and not isinstance(p.get(quantity=False), pint.Quantity) + assert not isinstance(p.get(), pint.Quantity) # Default unchanged + assert np.allclose(p.get(quantity=True).to("mm").magnitude, [1.0, -2.0]) + p.set(np.array([3.0, 4.0]) * ureg.mm) + assert np.allclose(p.value, [3e-3, 4e-3]) def test_hardware_unit_of_model(): @@ -299,32 +284,40 @@ def test_rf_is_converted_to_si(install_test_package): @TANGO -def test_set_accepts_quantity_on_control_system(install_test_package): - from tango.pyaml.attribute_store import get_attribute +def test_quantities_on_control_system(install_test_package): + from tango.pyaml.attribute_store import get_attribute, set_attribute + for key, value in [("bpm1/H", 0.1), ("bpm1/V", -0.2), ("bpm2/H", 0.3), ("bpm2/V", -0.4)]: + set_attribute(f"sr/test/{key}", value, unit="mm") sr = Accelerator.from_dict(_config()) rf = sr.live.rf.get("RF") tra = sr.live.rf.transmitter.get("RFTRA") + # set() converts a quantity to the pyAML unit, then to the device unit rf.frequency.set(352.3 * ureg.MHz) assert get_attribute("sr/test/rf/freq") == pytest.approx(352.3) - tra.voltage.set(0.8 * ureg.MV) - assert get_attribute("sr/test/rf/volt") == pytest.approx(800.0) tra.phase.set(45 * ureg.deg) assert get_attribute("sr/test/rf/phase") == pytest.approx(45.0) + rf.voltage.set(2 * ureg.MV) # Total voltage, aggregate of transmitters + assert get_attribute("sr/test/rf/volt") == pytest.approx(2000.0) + with pytest.raises(PyAMLException): + rf.frequency.set(1 * ureg.A) - q1 = sr.live.magnet.get("Q1") - q1.hardware.set(2 * ureg.A) - assert get_attribute("sr/test/ps/q1") == pytest.approx(2000.0) + # get(quantity=True) returns a quantity in unit(), get() still a float + assert rf.frequency.get(quantity=True).to("MHz").magnitude == pytest.approx(352.3) + assert isinstance(rf.frequency.get(), float) + q = sr.live.diagnostic.bpms.get("BPM").positions.get(quantity=True) + assert q.shape == (2, 2) and np.allclose(q.to("mm").magnitude, [[0.1, -0.2], [0.3, -0.4]]) - # Arrays and aggregators accept quantities too + # Arrays and aggregators quads = sr.live.magnets.get("QUADS") quads.hardwares.set(np.array([1.0, 3.0]) * ureg.A) - assert get_attribute("sr/test/ps/q1") == pytest.approx(1000.0) - assert get_attribute("sr/test/ps/q2") == pytest.approx(3000.0) - - with pytest.raises(PyAMLException): - rf.frequency.set(1 * ureg.A) + assert [get_attribute("sr/test/ps/q1"), get_attribute("sr/test/ps/q2")] == pytest.approx([1000.0, 3000.0]) + assert np.allclose(quads.hardwares.get(quantity=True).to("mA").magnitude, [1000.0, 3000.0]) + agg = sr.live.create_magnet_strength_aggregator(list(quads)) + agg.set(np.array([0.01, 0.02]) / ureg.m) + assert [m.strength.get() for m in quads] == pytest.approx([0.01, 0.02]) + assert agg.get(quantity=True).units == 1 / ureg.m @TANGO @@ -364,19 +357,6 @@ def test_magnet_device_unit_is_converted_to_model_hardware_unit(install_test_pac assert np.allclose(quads.hardwares.get(), [10.0, 14.0]) -@TANGO -def test_strength_aggregator_unit_and_quantity(install_test_package): - from tango.pyaml.attribute_store import get_attribute - - sr = Accelerator.from_dict(_config()) - agg = sr.live.create_magnet_strength_aggregator(list(sr.live.magnets.get("QUADS"))) - assert agg.unit() == "1/m" - agg.set(np.array([0.01, 0.02]) / ureg.m) - q1, q2 = sr.live.magnet.get("Q1"), sr.live.magnet.get("Q2") - assert [q1.strength.get(), q2.strength.get()] == pytest.approx([0.01, 0.02]) - assert get_attribute("sr/test/ps/q1") == pytest.approx(1000 * q1.hardware.get()) - - @TANGO def test_device_unit_error_is_not_swallowed(install_test_package): from pyaml.control.si_deviceaccess import wrap_si @@ -440,20 +420,15 @@ def test_incompatible_device_unit_raises_at_load(install_test_package): @TANGO -def test_device_without_unit_is_passthrough(install_test_package): +@pytest.mark.parametrize("no_unit", ["", "No unit"]) +def test_device_without_unit_is_passthrough(install_test_package, no_unit): from tango.pyaml.attribute_store import get_attribute - sr = Accelerator.from_dict(_config(freq_unit="")) - sr.live.rf.get("RF").frequency.set(352.5) - assert get_attribute("sr/test/rf/freq") == pytest.approx(352.5) - - -@TANGO -@pytest.mark.parametrize("no_unit", ["", "No unit"]) -def test_device_without_unit_reports_si_unit(install_test_package, no_unit): from pyaml.control.si_deviceaccess import SIDeviceAccess sr = Accelerator.from_dict(_config(bpm_unit=no_unit, freq_unit=no_unit, ps_unit=no_unit)) + sr.live.rf.get("RF").frequency.set(352.5) # Assumed to already be in Hz + assert get_attribute("sr/test/rf/freq") == pytest.approx(352.5) dev = sr.live.get_si_device_access("rf/freq", "Hz") assert isinstance(dev, SIDeviceAccess) and dev.factor == 1.0 @@ -468,38 +443,9 @@ def test_device_without_unit_reports_si_unit(install_test_package, no_unit): @TANGO -def test_si_device_access_reports_control_system_unit(install_test_package): +def test_accessors_report_control_system_unit(install_test_package): from pyaml.control.si_deviceaccess import control_system_unit_of - sr = Accelerator.from_dict(_config()) - dev = sr.live.get_si_device_access("rf/freq", "Hz") - assert dev.unit() == "Hz" - assert dev.control_system_unit() == "MHz" - assert control_system_unit_of(dev) == "MHz" - assert control_system_unit_of(sr.live.get_device_access("rf/freq")) == "MHz" - assert control_system_unit_of(None) is None - - quads = list(sr.live.magnets.get("QUADS")) - agg = sr.live.create_magnet_hardware_aggregator(quads) - assert agg.unit() == "A" - assert agg.control_system_unit() == "mA" - assert agg._devs.control_system_unit() == ["mA", "mA"] # Device level: one per device - - -@TANGO -def test_total_voltage_unit_is_si(install_test_package): - from tango.pyaml.attribute_store import get_attribute - - sr = Accelerator.from_dict(_config()) - rf = sr.live.rf.get("RF") - assert rf.voltage.unit() == "V" - rf.voltage.set(2 * ureg.MV) - assert get_attribute("sr/test/rf/volt") == pytest.approx(2000.0) - assert rf.voltage.get() == pytest.approx(2e6) - - -@TANGO -def test_accessors_report_control_system_unit(install_test_package): sr = Accelerator.from_dict(_config()) bpm = sr.live.diagnostic.bpm.get("BPM1") @@ -526,62 +472,28 @@ def test_accessors_report_control_system_unit(install_test_package): assert bpms.positions.control_system_unit() == "mm" assert bpms.h.control_system_unit() == "mm" - -def test_control_system_unit_defaults_to_unit_on_simulator(): - sr = Accelerator.load("tests/config/EBS_rf.yaml", ignore_external=True) - assert sr.design.rf.frequency.control_system_unit() == sr.design.rf.frequency.unit() == "Hz" - - -@TANGO -def test_get_quantity_on_control_system(install_test_package): - from tango.pyaml.attribute_store import set_attribute - - for key, value in [("bpm1/H", 0.1), ("bpm1/V", -0.2), ("bpm2/H", 0.3), ("bpm2/V", -0.4)]: - set_attribute(f"sr/test/{key}", value, unit="mm") - sr = Accelerator.from_dict(_config()) - - rf = sr.live.rf.get("RF") - rf.frequency.set(352.2 * ureg.MHz) - f = rf.frequency.get(quantity=True) - assert isinstance(f, pint.Quantity) and f.to("MHz").magnitude == pytest.approx(352.2) - assert isinstance(rf.frequency.get(), float) # Default unchanged - - bpm = sr.live.diagnostic.bpm.get("BPM1") - assert np.allclose(bpm.positions.get(quantity=True).to("mm").magnitude, [0.1, -0.2]) - bpms = sr.live.diagnostic.bpms.get("BPM") - q = bpms.positions.get(quantity=True) - assert q.shape == (2, 2) and np.allclose(q.to("mm").magnitude, [[0.1, -0.2], [0.3, -0.4]]) - assert np.allclose(bpms.h.get(quantity=True).to("um").magnitude, [100.0, 300.0]) - - quads = sr.live.magnets.get("QUADS") - quads.hardwares.set(np.array([1.0, 3.0]) * ureg.A) - assert np.allclose(quads.hardwares.get(quantity=True).to("mA").magnitude, [1000.0, 3000.0]) - assert quads.strengths.get(quantity=True).units == 1 / ureg.m - - agg = sr.live.create_magnet_strength_aggregator(list(quads)) - assert agg.get(quantity=True).units == 1 / ureg.m - assert sr.live.magnet.get("Q1").hardware.get(quantity=True).to("mA").magnitude == pytest.approx(1000.0) - - -def test_get_quantity_on_simulator(): - sr = Accelerator.load("tests/config/EBS_rf.yaml", ignore_external=True) - sr.design.rf.frequency.set(352.3 * ureg.MHz) - assert sr.design.rf.frequency.get(quantity=True).to("MHz").magnitude == pytest.approx(352.3) + # Device level: SIDeviceAccess reports both units, lists one unit per device + dev = sr.live.get_si_device_access("rf/freq", "Hz") + assert (dev.unit(), dev.control_system_unit()) == ("Hz", "MHz") + assert control_system_unit_of(sr.live.get_device_access("rf/freq")) == "MHz" + assert control_system_unit_of(None) is None + agg = sr.live.create_magnet_hardware_aggregator(list(quads)) + assert (agg.unit(), agg.control_system_unit()) == ("A", "mA") + assert agg._devs.control_system_unit() == ["mA", "mA"] # --------------------------------------------------------------------------- simulator -def test_set_accepts_quantity_on_simulator(): +def test_quantities_on_simulator(): sr = Accelerator.load("tests/config/EBS_rf.yaml", ignore_external=True) - sr.design.rf.frequency.set(352.3 * ureg.MHz) - assert sr.design.rf.frequency.get() == pytest.approx(352.3e6) + freq = sr.design.rf.frequency + freq.set(352.3 * ureg.MHz) + assert freq.get() == pytest.approx(352.3e6) + assert freq.get(quantity=True).to("MHz").magnitude == pytest.approx(352.3) + assert freq.control_system_unit() == freq.unit() == "Hz" # No device: same as unit() with pytest.raises(PyAMLException): - sr.design.rf.frequency.set(1 * ureg.m) - - -def test_set_energy_accepts_quantity(): - sr = Accelerator.load("tests/config/EBS_rf.yaml", ignore_external=True) + freq.set(1 * ureg.m) sr.set_energy(6 * ureg.GeV) assert sr._energy == pytest.approx(6e9)