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 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/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 49457208..4bfa465a 100644 --- a/pyaml/arrays/magnet_array.py +++ b/pyaml/arrays/magnet_array.py @@ -11,6 +11,7 @@ from ..common.abstract import ReadWriteFloatArray from ..common.abstract_aggregator import ScalarAggregator from ..common.exception import PyAMLException +from ..common.units import common_unit from ..magnet.magnet import Magnet from .element_array import ElementArray @@ -61,7 +62,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. """ @@ -142,9 +143,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): @@ -180,7 +181,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. """ @@ -252,9 +255,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/common/abstract.py b/pyaml/common/abstract.py index 39805038..1e4c881c 100644 --- a/pyaml/common/abstract.py +++ b/pyaml/common/abstract.py @@ -10,19 +10,23 @@ 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. 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 @@ -30,6 +34,9 @@ def get(self) -> double: """ Return the current scalar value. + ``get(quantity=True)`` returns a :class:`pint.Quantity` in ``unit()`` + (see :class:`~pyaml.common.units.AcceptsQuantity`). + Returns ------- float @@ -40,7 +47,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 ------- @@ -49,6 +59,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): """ @@ -88,28 +113,63 @@ 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. 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. + + ``get(quantity=True)`` returns 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): """ @@ -169,7 +229,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. """ @@ -227,14 +289,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 7a80d644..20a50db3 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 @@ -20,12 +22,14 @@ class ScalarAggregator(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 @@ -40,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 @@ -49,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 new file mode 100644 index 00000000..c81b4efa --- /dev/null +++ b/pyaml/common/units.py @@ -0,0 +1,524 @@ +""" +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`); +- 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 cache, wraps +from typing import Any + +import numpy as np +import pint + +from .exception import PyAMLConfigException, PyAMLException + +# pyAML units, used internally and by get()/set(). +SI_POSITION = "m" +SI_ANGLE = "rad" +SI_VOLTAGE = "V" +SI_FREQUENCY = "Hz" +SI_TUNE = "1" + +_UREG: pint.UnitRegistry | None = None + +# 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: + """ + 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. See the "Unit strings" section + of :mod:`pyaml.common.units` for the accepted formats. + + 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 + + +@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``. + + 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`` 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 + ------ + 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 str(src).strip() == str(dst).strip(): + return 1.0 + ureg = get_registry() + qsrc = ureg.Quantity(1.0, _parse_unit(src)) + 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: + 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_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) + + +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 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. + + 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 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. + + 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 + + +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 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 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 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 98a8c361..fff6d236 100644 --- a/pyaml/control/abstract_impl.py +++ b/pyaml/control/abstract_impl.py @@ -15,8 +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, 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 @@ -221,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. """ @@ -282,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.""" @@ -321,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): @@ -373,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) + # ------------------------------------------------------------------------------ @@ -403,7 +420,9 @@ class CSStrengthScalarAggregator(CSScalarAggregator): readback() Read back magnet strengths from measured hardware values. unit() - Return the units associated with the underlying 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. """ def __init__(self, peer: CSScalarAggregator): @@ -415,6 +434,7 @@ def __init__(self, peer: CSScalarAggregator): self.__modelToMagnet: list[list[tuple[int, int | None]]] = [] # strengths indexing self.__families: dict[int, Any] = {} # model index -> strength accessor of a serialized family 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 @@ -447,6 +467,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()) if strengthIndex is None: # MagnetArray guarantees that a family is never registered together with one of its magnets self.__families[index] = magnet.strength @@ -533,9 +554,17 @@ def readback(self) -> np.array: """ return self.__strengths_from_hardware(self._devs.readback()) # Read all hardware readback - def unit(self) -> str: - """Return the units associated with the underlying 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.__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() class CSHardwareScalarAggregator(CSScalarAggregator): @@ -563,6 +592,10 @@ class CSHardwareScalarAggregator(CSScalarAggregator): Return the hardware value of every registered magnet. readback() Return the hardware readback of every registered magnet. + 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. nb_device() Return the number of registered magnets. """ @@ -657,6 +690,16 @@ def readback(self) -> np.array: """Return the hardware readback of every registered magnet.""" return np.asarray(self._devs.readback())[self.__slotToDevice] + def unit(self) -> str | list[str] | None: + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + units = self._devs.unit() + return common_unit([units[device] for device in self.__slotToDevice]) + + def control_system_unit(self) -> str | list[str | None] | None: + """Return the control-system unit for this quantity.""" + units = self._devs.control_system_unit() + return common_unit([units[device] for device in self.__slotToDevice]) + def nb_device(self) -> int: """Return the number of registered magnets.""" return len(self.__slotToDevice) @@ -688,7 +731,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. """ @@ -740,9 +785,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. @@ -778,7 +827,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. """ @@ -837,7 +886,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): @@ -941,7 +990,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]): @@ -995,9 +1046,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]) # ------------------------------------------------------------------------------ @@ -1023,7 +1078,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]): @@ -1077,9 +1132,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()) # ------------------------------------------------------------------------------ @@ -1103,7 +1158,9 @@ 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 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): @@ -1117,11 +1174,13 @@ 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 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)]) # ------------------------------------------------------------------------------ @@ -1145,7 +1204,9 @@ 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 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): @@ -1165,7 +1226,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) @@ -1187,8 +1248,12 @@ 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 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) # ------------------------------------------------------------------------------ @@ -1214,7 +1279,9 @@ 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 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): @@ -1256,11 +1323,13 @@ 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 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)]) # ------------------------------------------------------------------------------ @@ -1287,7 +1356,9 @@ 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 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): @@ -1308,7 +1379,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) @@ -1329,8 +1400,12 @@ 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 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) # ------------------------------------------------------------------------------ @@ -1357,7 +1432,9 @@ 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 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): @@ -1378,7 +1455,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) @@ -1399,8 +1476,12 @@ 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 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) # ------------------------------------------------------------------------------ @@ -1426,7 +1507,9 @@ 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 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): @@ -1448,7 +1531,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) @@ -1469,8 +1552,12 @@ 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 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) # ------------------------------------------------------------------------------ @@ -1480,41 +1567,67 @@ 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. + revolution_frequency : callable or None, optional + Returns the revolution frequency in Hz, called on every ``get()`` + when a plane is read in Hz. Methods ------- get() Return horizontal and vertical betatron tunes. unit() - Return the configured betatron-tune unit. + 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]): + 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.__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.__revolution_frequency = revolution_frequency 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.__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) + return values def unit(self) -> str: - """Return the configured betatron-tune unit.""" - return self.__tune_monitor._cfg.tune_v.unit() + """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 13a6b4d5..b053df94 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, is_frequency_unit from ..configuration.unbound_element import UnboundElement from ..control.abstract_impl import ( CSHardwareScalarAggregator, @@ -46,6 +47,19 @@ 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).""" + 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): @@ -68,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) @@ -106,32 +122,79 @@ 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` (factor 1 + when no conversion is needed), or the raw backend device when + ``si_unit`` is empty. + + 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_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() + 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) @@ -156,8 +219,7 @@ 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()) - 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: @@ -186,7 +248,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 - hagg.add_magnet(m, self.get_devices_access([m.model.get_device_names()[psIndex]])[0]) + ref = m.model.get_device_names()[psIndex] + hagg.add_magnet(m, self.get_si_device_access(ref, _hardware_unit(m.model, psIndex))) return hagg def create_bpm_aggregators(self, bpms: list[BPM]) -> list[ScalarAggregator | None]: @@ -206,25 +269,25 @@ 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()) + devices = self._get_magnet_devices(magnet.model) currents = RWHardwareArray(magnet.model, devices) strengths = RWStrengthArray(magnet.model, devices) attached_magnets = magnet.attach(self, strengths, currents) @@ -234,7 +297,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()): @@ -249,9 +312,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]) @@ -261,21 +324,38 @@ 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]) - 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, + 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/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 new file mode 100644 index 00000000..015396b0 --- /dev/null +++ b/pyaml/control/si_deviceaccess.py @@ -0,0 +1,303 @@ +""" +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, inverse: bool = False) -> Any: + """ + 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()``. + """ + if value is None: + return None + if isinstance(value, Value): + 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, 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 if inverse else 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 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 = 1.0): + 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(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(value if self.factor == 1.0 else _scale(value, self.factor, inverse=True)) + + def get(self): + """Return the current setpoint in SI.""" + 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.""" + v = self.raw.readback() + return v if self.factor == 1.0 else _scale(v, self.factor) + + def unit(self) -> str: + """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.""" + 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.""" + 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 + 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) or si_unit is None or not str(si_unit).strip(): + return dev + try: + 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) + + +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 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() + 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 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() + 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() + + +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..e4bd05d6 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,12 @@ 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 of the RF plant. Parameters ---------- @@ -43,6 +48,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 +59,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 @@ -57,8 +70,6 @@ class BetatronTuneMonitor(Element, DynamicValidation, ABetatronTuneMonitor): Methods ------- - set_harmonic(h) - Set the harmonic number used for tune-frequency conversion. attach(peer, betatron_tune) Attach the tune monitor to a peer with betatron tune data. @@ -71,6 +82,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 +92,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,20 +101,21 @@ 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 - - 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 _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") + self.check_peer() + return self.peer.rf.get(self._rf_plant_name) def _fill_device(self, holder: "ElementHolder") -> None: holder._fill_betatron_tune_monitor(self) @@ -116,6 +130,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: """ @@ -154,7 +178,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): @@ -165,16 +189,10 @@ 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._rf_plant().revolution_frequency() 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 c0ecb817..a8e18e0e 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, common_unit from ..magnet.model import MagnetModel from .polynom_info import PolynomInfo @@ -64,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. """ @@ -127,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: @@ -166,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. """ @@ -263,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 +301,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(). get_model() Return the submodel of the magnet. set_magnet_rigidity(brho) @@ -354,7 +355,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 get_model(self) -> MagnetModel: @@ -407,7 +408,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. """ @@ -475,7 +476,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): @@ -514,7 +515,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): @@ -574,9 +575,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()) # ------------------------------------------------------------------------------ @@ -605,7 +606,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): @@ -665,9 +666,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()) # ------------------------------------------------------------------------------ @@ -695,7 +696,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): @@ -750,8 +751,8 @@ def readback(self) -> np.array: return self.get() def unit(self) -> str: - """Return the value unit.""" - return "m" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return SI_POSITION def _transform(self) -> np.array: """Transform the configured value for the lattice interface.""" @@ -850,7 +851,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): @@ -876,8 +877,8 @@ def get(self) -> np.array: # Gets the unit of the value def unit(self) -> str: - """Return the value unit.""" - return "m" + """Return the pyAML unit for this quantity, i.e. returned by get().""" + return SI_POSITION # ------------------------------------------------------------------------------ @@ -902,7 +903,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): @@ -948,8 +949,8 @@ 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 the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return SI_POSITION # ------------------------------------------------------------------------------ @@ -976,7 +977,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): @@ -1025,8 +1026,8 @@ 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 the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return SI_ANGLE # ------------------------------------------------------------------------------ @@ -1051,7 +1052,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]): @@ -1097,8 +1098,8 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the value unit.""" - return "V" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return SI_VOLTAGE # ------------------------------------------------------------------------------ @@ -1126,7 +1127,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]): @@ -1172,8 +1173,8 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the value unit.""" - return "rad" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return SI_ANGLE # ------------------------------------------------------------------------------ @@ -1199,7 +1200,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]): @@ -1243,8 +1244,8 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the value unit.""" - return "Hz" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return SI_FREQUENCY # ------------------------------------------------------------------------------ @@ -1271,7 +1272,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): @@ -1312,8 +1313,8 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the value unit.""" - return "Hz" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return SI_FREQUENCY # ------------------------------------------------------------------------------ @@ -1340,7 +1341,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): @@ -1381,8 +1382,8 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the value unit.""" - return "V" + """Return the pyAML unit for this quantity, i.e. returned by get() and expected by set().""" + return SI_VOLTAGE # ------------------------------------------------------------------------------ @@ -1402,7 +1403,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): @@ -1416,8 +1417,8 @@ def get(self) -> float: return self.__ring.get_tune()[:2] def unit(self) -> str: - """Return the value unit.""" - return "1" + """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 4217304f..85a91f4e 100644 --- a/pyaml/magnet/serialized_magnet.py +++ b/pyaml/magnet/serialized_magnet.py @@ -12,6 +12,7 @@ from .. import PyAMLException from ..common import abstract from ..common.element import __pyaml_repr__ +from ..common.units import common_unit from ..configuration.factory import ELEMENT_REGISTRY from ..validation import DynamicValidation, register_schema from .function_mapping import function_map @@ -48,7 +49,9 @@ class ReadWriteSerializedHardware(abstract.ReadWriteFloatScalar): set_and_wait(value) Set the shared hardware value and wait for convergence. 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. get_model() Return the magnet conversion model. set_magnet_rigidity(brho) @@ -94,9 +97,13 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") 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._hardwares[0].control_system_unit() + def get_model(self) -> MagnetModel: """Return the magnet conversion model.""" return self._model @@ -146,7 +153,9 @@ class ReadWriteSerializedStrength(ReadWriteSerializedHardware): hardware_from_strength(strength, current_hardware) Return the hardware value giving an average strength, without device access. unit() - Return the physical strength 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. Raises ------ @@ -213,9 +222,17 @@ def hardware_from_strength(self, strength: float, current_hardware: float) -> fl return self._model.compute_hardware_from_mean_strength(strength, current_hardware) 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 control_system_unit(self) -> str: + """ + Return the control-system unit for this quantity. + + Same as unit(): no control-system device holds the average strength. + """ + return self.unit() + def _check_homogeneous(self): if not self._homogeneous: raise PyAMLException( @@ -246,7 +263,9 @@ class ReadWriteSerializedHardwareArray(abstract.ReadWriteFloatArray): set_and_wait(value) Set the hardware values and wait for convergence. unit() - Return the hardware-value units. + 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, hardwares: list[abstract.ReadWriteFloatScalar], model: MagnetModel): @@ -297,9 +316,13 @@ def set_and_wait(self, value: np.ndarray): """ raise NotImplementedError("Not implemented yet.") - def unit(self) -> list[str]: - """Return the hardware-value units.""" - 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([hardware.control_system_unit() for hardware in self._hardwares]) class ReadWriteSerializedStrengthArray(abstract.ReadWriteFloatArray): @@ -331,7 +354,7 @@ class ReadWriteSerializedStrengthArray(abstract.ReadWriteFloatArray): set_and_wait(value) Set the strengths and wait for convergence. unit() - Return the physical strength units. + Return the pyAML unit for this quantity, i.e. returned by get() and expected by set(). """ def __init__( @@ -387,9 +410,9 @@ def set_and_wait(self, value: np.ndarray): """ raise NotImplementedError("Not implemented yet.") - def unit(self) -> list[str]: - """Return the physical strength units.""" - 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()) @register_schema diff --git a/pyaml/rf/rf_plant.py b/pyaml/rf/rf_plant.py index 62e5954b..3d9dd98f 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 @@ -52,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. @@ -86,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: @@ -153,7 +192,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 +243,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/pyproject.toml b/pyproject.toml index 022dc820..76a44ebc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -42,7 +42,8 @@ dependencies = [ "pydantic>=2.11.7", "accelerator-commissioning==1.5.3", #pySC "h5py", - "matplotlib" + "matplotlib", + "pint>=0.24" ] [project.optional-dependencies] diff --git a/tests/arrays/test_arrays.py b/tests/arrays/test_arrays.py index 62bc46b7..f4044863 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/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_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_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) diff --git a/tests/test_units.py b/tests/test_units.py new file mode 100644 index 00000000..c0d51f52 --- /dev/null +++ b/tests/test_units.py @@ -0,0 +1,534 @@ +"""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 ( + common_unit, + conversion_factor, + format_unit, + get_registry, + normalize_unit, + to_magnitude, + to_quantity, +) + +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"), ("", "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"), ("mm", ""), ("Hz", "1")] +) +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" + # 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(): + 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_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_any_implementation_accepts_and_returns_quantity(): + from pyaml.common.abstract import ReadFloatArray + + 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 self.value + + def set(self, value): + self.value = value + + def unit(self): + return "m" + + p = Positions() + 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(): + 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, unit: str = "1/m") -> dict: + return { + "type": "pyaml.magnet.quadrupole", + "name": name, + "model": { + "type": "pyaml.magnet.linear_model", + "calibration_factor": 0.01, + "unit": unit, + "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", unit="m-1"), # Same unit as Q1, spelled differently + ], + } + + +@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.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) + 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_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.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) + + # 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 + quads = sr.live.magnets.get("QUADS") + quads.hardwares.set(np.array([1.0, 3.0]) * 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 +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_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") + + +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 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): + 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"): + Accelerator.from_dict(_config(bpm_unit="A")) + + +@TANGO +@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 + + 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 + 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_accessors_report_control_system_unit(install_test_package): + from pyaml.control.si_deviceaccess import control_system_unit_of + + 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" + + # 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_quantities_on_simulator(): + sr = Accelerator.load("tests/config/EBS_rf.yaml", ignore_external=True) + 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): + freq.set(1 * ureg.m) + 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"