diff --git a/pyaml/arrays/element_array.py b/pyaml/arrays/element_array.py index d39d7cbb..f9729dfb 100644 --- a/pyaml/arrays/element_array.py +++ b/pyaml/arrays/element_array.py @@ -17,7 +17,6 @@ from ..common.name_matching import resolve_names from ..magnet.cfm_magnet import CombinedFunctionMagnet from ..magnet.magnet import Magnet -from ..magnet.serialized_magnet import SerializedMagnets if TYPE_CHECKING: from ..common.holders.element_holder import ElementHolder @@ -143,12 +142,6 @@ def __create_array(self, array_name: str, element_type: type, elements: list): m = importlib.import_module("pyaml.arrays.cfm_magnet_array") array_class = getattr(m, "CombinedFunctionMagnetArray", None) return array_class(array_name, elements, False) - elif issubclass(element_type, SerializedMagnets): - # SerializedMagnetsArray has no aggregator support, unlike the - # array type this selection was derived from. - m = importlib.import_module("pyaml.arrays.serialized_magnet_array") - array_class = getattr(m, "SerializedMagnetsArray", None) - return array_class(array_name, elements, False) elif issubclass(element_type, Element): return ElementArray(array_name, elements, self.__use_aggregator) else: @@ -306,8 +299,8 @@ def __and__(self, other: object): common base class of the remaining elements which can be: :py:class:`.BPMArray` or :py:class:`.MagnetArray` or :py:class:`.CombinedFunctionMagnetArray` or - :py:class:`.SerializedMagnetsArray` or - :py:class:`.ElementArray`. + :py:class:`.ElementArray`. A serialized family is a magnet, so + families give a :py:class:`.MagnetArray`. """ # --- mask filtering --- if self.__is_bool_mask(other): @@ -378,8 +371,8 @@ def __sub__(self, other: object): common base class of the remaining elements which can be: :py:class:`.BPMArray` or :py:class:`.MagnetArray` or :py:class:`.CombinedFunctionMagnetArray` or - :py:class:`.SerializedMagnetsArray` or - :py:class:`.ElementArray`. + :py:class:`.ElementArray`. A serialized family is a magnet, so + families give a :py:class:`.MagnetArray`. """ # --- mask removal --- if self.__is_bool_mask(other): @@ -418,8 +411,8 @@ def __or__(self, other: object): common base class of the remaining elements which can be: :py:class:`.BPMArray` or :py:class:`.MagnetArray` or :py:class:`.CombinedFunctionMagnetArray` or - :py:class:`.SerializedMagnetsArray` or - :py:class:`.ElementArray`. + :py:class:`.ElementArray`. A serialized family is a magnet, so + families give a :py:class:`.MagnetArray`. Examples -------- @@ -479,8 +472,8 @@ def __add__(self, other: object): common base class of the remaining elements which can be: :py:class:`.BPMArray` or :py:class:`.MagnetArray` or :py:class:`.CombinedFunctionMagnetArray` or - :py:class:`.SerializedMagnetsArray` or - :py:class:`.ElementArray`. + :py:class:`.ElementArray`. A serialized family is a magnet, so + families give a :py:class:`.MagnetArray`. Examples -------- @@ -518,7 +511,8 @@ def mask_by_type(self, element_type: type) -> list[bool]: ------- list[bool] A list of booleans where True indicates the element is an instance - of the given type (including subclasses). + of the given type (including subclasses). A serialized family is an + instance of ``Magnet``. """ if not isinstance(element_type, type): raise TypeError(f"{self.__class__.__name__}: element_type must be a type") diff --git a/pyaml/arrays/magnet.py b/pyaml/arrays/magnet.py index c37d2169..940d9075 100644 --- a/pyaml/arrays/magnet.py +++ b/pyaml/arrays/magnet.py @@ -30,6 +30,26 @@ class Magnet(ArrayConfig, DynamicValidation): fill_array(holder) Fill the magnet array in the element holder. + Notes + ----- + A serialized family (:py:class:`~pyaml.magnet.serialized_magnet.SerializedMagnets`) is a magnet: its name, + or a pattern matching it, adds one element to the array, the family, which reads and writes the average + strength and the power-supply current of its series. The magnets of the family are not added, even when + listed explicitly or matched by the same pattern: they are already driven through the family. + + - ``~FAMILY`` excludes the family and its magnets. + - Excluding one magnet of a family which is in the array raises an error: a series cannot be split. List the + individual magnets of the series instead to drive a part of it. + + .. code-block:: yaml + + - type: pyaml.arrays.magnet + name: QForTune + elements: + - QF1A # serialized family: one element + - QF1A-C05 # magnet of QF1A: already driven by the family, not added + - QD2* # individual quadrupoles and families matching the pattern + Examples -------- diff --git a/pyaml/arrays/magnet_array.py b/pyaml/arrays/magnet_array.py index 55d6854c..49457208 100644 --- a/pyaml/arrays/magnet_array.py +++ b/pyaml/arrays/magnet_array.py @@ -10,10 +10,37 @@ from ..common.abstract import ReadWriteFloatArray from ..common.abstract_aggregator import ScalarAggregator +from ..common.exception import PyAMLException from ..magnet.magnet import Magnet from .element_array import ElementArray +def _values_per_magnet(value, nb: int, kind: str) -> np.ndarray: + """ + Return one value per magnet of the array. + + Parameters + ---------- + value : float | int | array-like + A scalar, broadcast to every magnet, or one value per magnet. + nb : int + Number of magnets of the array. + kind : str + Kind of value (``strength`` or ``hardware``), used in the error message. + + Raises + ------ + PyAMLException + If ``value`` is neither a scalar nor a 1-D sequence holding one value per magnet. + """ + if np.ndim(value) == 0: + return np.full(nb, float(value)) + values = np.asarray(value, dtype=float) + if values.ndim != 1 or len(values) != nb: + raise PyAMLException(f"One {kind} value per magnet is expected ({nb} values), got {np.shape(value)}") + return values + + class RWMagnetStrength(ReadWriteFloatArray): """ Array accessor for the strengths of a magnet family. @@ -69,11 +96,27 @@ def set(self, value: np.array, wait_seconds_after: float = None): wait_seconds_after: float number of seconds to wait after setting the strengths. see also set_and_wait for waiting based on setpoint-readback difference. + + Raises + ------ + PyAMLException + If ``value`` is neither a scalar nor one value per magnet. Nothing is written. """ - nvalue = np.ones(self.__nb) * value if isinstance(value, float) else value + nvalue = _values_per_magnet(value, self.__nb, "strength") if not self.__aggregator: + # Magnets of a series share one power supply: it is written once, from the strengths of the + # magnets of the series present in the array, the others following the resulting hardware value. + # A serialized family has no series index: its own strength accessor writes its power supply. + series: dict[int, tuple[Magnet, dict[int, float]]] = {} for idx, m in enumerate(self.__magnets): - m.strength.set(nvalue[idx]) + series_index = m.series_index + if series_index is not None: + series.setdefault(id(m.model), (m, {}))[1][series_index] = nvalue[idx] + else: + m.strength.set(nvalue[idx]) + for m, requested in series.values(): + current_hardware = np.array([m.hardware.get()]) + m.hardware.set(m.model.compute_hardware_values_partial(current_hardware, requested)[0]) else: self.__aggregator.set(nvalue) @@ -168,13 +211,28 @@ def set(self, value: np.array): ---------- value : np.array Hardware value for each magnet, ordered like the array. A scalar is broadcast to every magnet. + + Raises + ------ + PyAMLException + If ``value`` is neither a scalar nor one value per magnet. Nothing is written. """ - nvalue = np.ones(self.__nb) * value if isinstance(value, float) else value + nvalue = _values_per_magnet(value, self.__nb, "hardware") if not self.__aggregator: + # Magnets of a series share one power supply: it is written once, from the hardware values of the + # magnets of the series present in the array, the others following it. + # A serialized family has no series index: its own hardware accessor writes its power supply. + series: dict[int, tuple[Magnet, dict[int, float]]] = {} for idx, m in enumerate(self.__magnets): - m.hardware.set(value[idx]) + series_index = m.series_index + if series_index is not None: + series.setdefault(id(m.model), (m, {}))[1][series_index] = nvalue[idx] + else: + m.hardware.set(nvalue[idx]) + for m, requested in series.values(): + m.hardware.set(m.model.compute_hardware_from_hardwares(requested)) else: - self.__aggregator.set(value) + self.__aggregator.set(nvalue) # Sets the values and waits that the read values reach their setpoint def set_and_wait(self, value: np.array): @@ -248,6 +306,7 @@ def __init__(self, arrayName: str, magnets: list[Magnet], use_aggregator=True): Initialize the MagnetArray. """ super().__init__(arrayName, magnets, use_aggregator) + self.__check_families(arrayName, magnets) self.__rwstrengths = RWMagnetStrength(arrayName, magnets) self.__rwhardwares = RWMagnetHardware(arrayName, magnets) @@ -258,6 +317,25 @@ def __init__(self, arrayName: str, magnets: list[Magnet], use_aggregator=True): self.__rwstrengths.set_aggregator(aggs) self.__rwhardwares.set_aggregator(aggh) + @staticmethod + def __check_families(arrayName: str, magnets: list[Magnet]): + """ + Raise if a serialized family and one of its magnets are both in the array. + + A family drives every magnet of its series: a magnet of the series cannot also be driven on its own. A family + is a magnet with no series index whose model is shared by a series, its magnets share the same model. + """ + families = { + id(m.model): m for m in magnets if m.model is not None and m.model.shares_power_supply() and m.series_index is None + } + for m in magnets: + family = families.get(id(m.model)) + if family is not None and m is not family: + raise PyAMLException( + f"MagnetArray {arrayName} : {m.get_name()} and {family.get_name()}: a serialized family and its " + "magnets cannot be in the same array, the family already drives all its magnets" + ) + @property def strengths(self) -> RWMagnetStrength: """ diff --git a/pyaml/arrays/serialized_magnet.py b/pyaml/arrays/serialized_magnet.py index 5f3c07a3..383a5cab 100644 --- a/pyaml/arrays/serialized_magnet.py +++ b/pyaml/arrays/serialized_magnet.py @@ -1,22 +1,28 @@ """ Serialized Magnet module. -This module provides serialized magnet functionality. +This module provides the deprecated serialized magnet array configuration. """ -from ..common.holders.element_holder import ElementHolder +import warnings + from ..validation import DynamicValidation, register_schema -from .array import ArrayConfig +from .magnet import Magnet # Define the main class name for this module PYAMLCLASS = "SerializedMagnets" @register_schema -class SerializedMagnets(ArrayConfig, DynamicValidation): +class SerializedMagnets(Magnet, DynamicValidation): """ Serialized magnets array configuration. + .. deprecated:: + A serialized family is a magnet: use :py:class:`pyaml.arrays.magnet.Magnet` + (``type: pyaml.arrays.magnet``). This configuration builds the same + :py:class:`.MagnetArray`, registered with the magnet arrays. + Parameters ---------- name : str @@ -28,34 +34,16 @@ class SerializedMagnets(ArrayConfig, DynamicValidation): Methods ------- fill_array(holder) - Fill the serialized magnet array in the element holder. - - Examples - -------- - - A magnet array configuration can also be created by code using - the following example:: - - from pyaml.arrays.serialized_magnet import SerializedMagnets - from pyaml.arrays.serialized_magnet import ConfigModel as SerializedMagnetConfigModel - magArray = SerializedMagnets( - SerializedMagnetConfigModel(name="mySerializedMagnets", elements=["mag1","mag2"]) - ) + Fill the magnet array in the element holder. """ def __init__(self, name: str, elements: list[str]): """ Initialize the SerializedMagnets. """ + warnings.warn( + f"{name}: pyaml.arrays.serialized_magnet is deprecated, a serialized family is a magnet: use pyaml.arrays.magnet", + DeprecationWarning, + stacklevel=2, + ) super().__init__(name, elements) - - def fill_array(self, holder: ElementHolder): - """ - Fill the serialized magnet array in the element holder. - - Parameters - ---------- - holder : ElementHolder - The element holder to populate with serialized magnet array - """ - holder.serialized_magnets.add(self._name, self._elements) diff --git a/pyaml/arrays/serialized_magnet_array.py b/pyaml/arrays/serialized_magnet_array.py index c891e5c6..be2f7a19 100644 --- a/pyaml/arrays/serialized_magnet_array.py +++ b/pyaml/arrays/serialized_magnet_array.py @@ -1,221 +1,40 @@ """ Serialized Magnet Array module. -This module provides serialized magnet array functionality. +This module provides the deprecated serialized magnet array. """ -import numpy as np +import warnings -from ..common.abstract import ReadWriteFloatArray -from ..common.exception import PyAMLException from ..magnet.serialized_magnet import SerializedMagnets -from .element_array import ElementArray +from .magnet_array import MagnetArray -# TODO handle aggregator for serialized magnets - -class RWMagnetStrengths(ReadWriteFloatArray): - """ - Array accessor for the strengths of serialized magnet groups. - - Parameters - ---------- - name : str - Name of the array, used when the accessor is reported or logged. - magnets : list[SerializedMagnets] - Serialized magnet groups making up the array, in the order their values are read and written. - - Methods - ------- - get() - Return the shared strength of every serialized group. - set(value) - Set the shared strength of every serialized group. - set_and_wait(value) - Set every shared strength and wait for the readbacks to converge. - unit() - Return the strength unit of every serialized group. - """ - - def __init__(self, name: str, magnets: list[SerializedMagnets]): - """ - Initialize the RWMagnetStrengths. - """ - self.__name = name - self.__magnets = magnets - self.__nb = sum(m.get_nb_magnets() for m in magnets) - - # Gets the values - def get(self) -> np.array: - """Return the shared strength of every serialized group.""" - return np.array([m.strength.get() for m in self.__magnets]) - - # Sets the values - def set(self, value: np.array): - """ - Set the shared strength of every serialized group. - - Parameters - ---------- - value : np.array - Shared strength for each serialized group, ordered like the array. - """ - nvalue = np.ones(len(self.__magnets)) * value if isinstance(value, float) else value - for value, m in zip(nvalue, self.__magnets, strict=True): - m.strength.set(value) - - # Sets the values and waits that the read values reach their setpoint - def set_and_wait(self, value: np.array): - """ - Set every shared strength and wait for the readbacks to converge. - - Parameters - ---------- - value : np.array - Shared strength for each serialized group, ordered like the array. - - Raises - ------ - NotImplementedError - Waiting for readback convergence is not implemented for this accessor. - """ - raise NotImplementedError("Not implemented yet.") - - # Gets the unit of the values - def unit(self) -> list[str]: - """Return the strength unit of every serialized group.""" - r = [] - for m in self.__magnets: - r.extend(m.strength.unit()) - return r - - -class RWMagnetHardwares(ReadWriteFloatArray): - """ - Array accessor for the hardware values of serialized magnet groups. - - Parameters - ---------- - name : str - Name of the array, used when the accessor is reported or logged. - magnets : list[SerializedMagnets] - Serialized magnet groups making up the array, in the order their values are read and written. - - Methods - ------- - get() - Return the shared hardware value of every serialized group. - set(value) - Set the shared hardware value of every serialized group. - set_and_wait(value) - Set every shared hardware value and wait for the readbacks to converge. - unit() - Return the hardware unit of every serialized group. +class SerializedMagnetsArray(MagnetArray): """ + Array of serialized magnet groups. - def __init__(self, name: str, magnets: list[SerializedMagnets]): - """ - Initialize the RWMagnetHardwares. - """ - self.__name = name - self.__magnets = magnets - self.__nb = sum(m.get_nb_magnets() for m in magnets) - - # Gets the values - def get(self) -> np.array: - """Return the shared hardware value of every serialized group.""" - return np.array([m.hardware.get() for m in self.__magnets]) - - # Sets the values - def set(self, value: np.array): - """ - Set the shared hardware value of every serialized group. - - Parameters - ---------- - value : np.array - Shared hardware value for each serialized group, ordered like the array. - """ - nvalue = np.ones(len(self.__magnets)) * value if isinstance(value, float) else value - for value, m in zip(nvalue, self.__magnets, strict=True): - m.hardware.set(value) - - # Sets the values and waits that the read values reach their setpoint - def set_and_wait(self, value: np.array): - """ - Set every shared hardware value and wait for the readbacks to converge. - - Parameters - ---------- - value : np.array - Shared hardware value for each serialized group, ordered like the array. - - Raises - ------ - NotImplementedError - Waiting for readback convergence is not implemented for this accessor. - """ - raise NotImplementedError("Not implemented yet.") - - # Gets the unit of the values - def unit(self) -> list[str]: - """Return the hardware unit of every serialized group.""" - r = [] - for m in self.__magnets: - r.extend(m.hardware.unit()) - return r - - -class SerializedMagnetsArray(ElementArray): - """ - Class that implements access to a serialized magnets array + .. deprecated:: + A serialized family is a magnet: use :py:class:`.MagnetArray`, which reads and writes the average strength + and the power-supply current of each family. Parameters ---------- arrayName : str Array name magnets : list[SerializedMagnets] - Magnet list, all elements must be attached to the same instance of - either a Simulator or a ControlSystem. + Serialized families, all attached to the same instance of either a Simulator or a ControlSystem. use_aggregator : bool - Use aggregator to increase performance by using parallel - access to underlying devices. - - Attributes - ---------- - strengths - Give access to strength of each magnet of this array - hardwares - Give access to hardware value of each magnet of this array + Use aggregator to increase performance by using parallel access to underlying devices. """ - def __init__( - self, - arrayName: str, - magnets: list[SerializedMagnets], - use_aggregator=False, - ): + def __init__(self, arrayName: str, magnets: list[SerializedMagnets], use_aggregator=True): """ Initialize the SerializedMagnetsArray. """ + warnings.warn( + "SerializedMagnetsArray is deprecated, a serialized family is a magnet: use MagnetArray", + DeprecationWarning, + stacklevel=2, + ) super().__init__(arrayName, magnets, use_aggregator) - - self.__rwstrengths = RWMagnetStrengths(arrayName, magnets) - self.__rwhardwares = RWMagnetHardwares(arrayName, magnets) - - if use_aggregator: - raise (PyAMLException("Aggregator not implemented for SerializedMagnetsArray")) - - @property - def strengths(self) -> RWMagnetStrengths: - """ - Give access to strength of each magnet of this array - """ - return self.__rwstrengths - - @property - def hardwares(self) -> RWMagnetHardwares: - """ - Give access to hardware value of each magnet of this array - """ - return self.__rwhardwares diff --git a/pyaml/common/holders/element_holder.py b/pyaml/common/holders/element_holder.py index 1cf63dfb..f7378371 100644 --- a/pyaml/common/holders/element_holder.py +++ b/pyaml/common/holders/element_holder.py @@ -1,5 +1,6 @@ """Store, resolve, and group elements shared by runtime backends.""" +import warnings from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING, overload @@ -50,8 +51,9 @@ class ElementHolder(metaclass=ABCMeta): Single magnet by name, or a named magnet array. combined_function_magnet, combined_function_magnets Single combined-function magnet by name, or a named array. - serialized_magnet, serialized_magnets - Single serialized magnet group by name, or a named array. + serialized_magnet + Single serialized magnet group by name. A serialized group is also a magnet and can be used in + ``magnets`` arrays. ``serialized_magnets`` is a deprecated alias of ``magnets`` arrays. rf RF plant and transmitters of this mode. diagnostic @@ -110,7 +112,6 @@ def __init__(self): # Array handle self._MAGNET_ARRAYS: dict = {} self._CFM_MAGNET_ARRAYS: dict = {} - self._SERIALIZED_MAGNETS_ARRAYS: dict = {} self._BPM_ARRAYS: dict = {} self._ELEMENT_ARRAYS: dict = {} @@ -149,7 +150,17 @@ def serialized_magnet(self) -> SerializedMagnetHolder: @property def serialized_magnets(self) -> SerializedMagnetsHolder: - """Return the serialized magnets.""" + """ + Return the serialized magnet arrays. + + .. deprecated:: + A serialized family is a magnet: use :attr:`magnets`, which shares the same arrays. + """ + warnings.warn( + "holder.serialized_magnets is deprecated, a serialized family is a magnet: use holder.magnets", + DeprecationWarning, + stacklevel=2, + ) return self._serialized_magnets_holder @property @@ -309,6 +320,7 @@ def _fill_array( get_func, constructor, ARR: dict, + members_func=None, ): """ Resolve selectors and store a constructed element array. @@ -325,6 +337,16 @@ def _fill_array( Constructor for the resulting array. ARR : dict Destination array store. + members_func : Callable[[str], list[str] | None], optional + Callback returning the member names of a group element (a serialized family), ``None`` for another + element. A group stands for one element of the array and already drives its members: the members of an + included group are left out of the array, and excluding a group also excludes its members. + + Raises + ------ + PyAMLException + If a name cannot be resolved, if an element is listed twice, or if a member of an included group is + excluded explicitly (a group cannot be split). """ all_names: list[str] = [] excluded_names: set[str] = set() @@ -334,6 +356,23 @@ def _fill_array( else: all_names.extend(self.find_elements(name)) + if members_func is not None: + members_of = {n: members_func(n) for n in set(all_names) | excluded_names} + for group in [n for n in excluded_names if members_of[n] is not None]: + excluded_names.update(members_of[group]) + covered: set[str] = set() + for group in all_names: + if members_of[group] is None or group in excluded_names: + continue + split = [m for m in members_of[group] if m in excluded_names] + if split: + raise PyAMLException( + f"{constructor.__name__} {array_name} : {split[0]} cannot be excluded, it is driven by " + f"{group} which is in the array. List the individual magnets to drive a part of {group}" + ) + covered.update(members_of[group]) + excluded_names.update(covered) + all_names = [n for n in all_names if n not in excluded_names] a = [] @@ -591,8 +630,6 @@ def _get_array(self, name: str): return self._MAGNET_ARRAYS[name] if name in self._CFM_MAGNET_ARRAYS: return self._CFM_MAGNET_ARRAYS[name] - if name in self._SERIALIZED_MAGNETS_ARRAYS: - return self._SERIALIZED_MAGNETS_ARRAYS[name] if name in self._ELEMENT_ARRAYS: return self._ELEMENT_ARRAYS[name] @@ -622,7 +659,6 @@ def _list_arrays(self) -> list[str]: arrays.extend(self._BPM_ARRAYS.keys()) arrays.extend(self._MAGNET_ARRAYS.keys()) arrays.extend(self._CFM_MAGNET_ARRAYS.keys()) - arrays.extend(self._SERIALIZED_MAGNETS_ARRAYS.keys()) arrays.extend(self._ELEMENT_ARRAYS.keys()) return arrays diff --git a/pyaml/common/holders/generic_array_holder.py b/pyaml/common/holders/generic_array_holder.py index 50fec2c1..b12c23ee 100644 --- a/pyaml/common/holders/generic_array_holder.py +++ b/pyaml/common/holders/generic_array_holder.py @@ -35,6 +35,10 @@ class GenericArrayHolder(Generic[T, A]): Callback constructing an array from a name and elements. what : str Human-readable array type used for lookup errors. + members_func : Callable[[str], list[str] | None], optional + Callback returning the names of the members of a group element (a + serialized family), ``None`` for an element that is not a group. See + :meth:`ElementHolder._fill_array`. Methods ------- @@ -59,6 +63,7 @@ def __init__( get_func: Callable[[str], T], constructor: Callable[[str, list[T]], A], what: str, + members_func: Callable[[str], list[str] | None] | None = None, ): """ Initialize an array holder with storage and lookup callbacks. @@ -69,6 +74,7 @@ def __init__( self._get_func = get_func self._constructor = constructor self._what = what + self._members_func = members_func def get(self, name: str | None = None) -> A: """ @@ -106,7 +112,9 @@ def add(self, arrayName: str, elementNames: list[str]): :class:`~pyaml.common.holders.element_holder.ElementHolder`, including wildcard and exclusion patterns. """ - self._peer._fill_array(arrayName, elementNames, self._get_func, self._constructor, self._array_store) + self._peer._fill_array( + arrayName, elementNames, self._get_func, self._constructor, self._array_store, self._members_func + ) def __getitem__(self, key): """ diff --git a/pyaml/common/holders/sub_holders.py b/pyaml/common/holders/sub_holders.py index 7d2bdc0a..29c28714 100644 --- a/pyaml/common/holders/sub_holders.py +++ b/pyaml/common/holders/sub_holders.py @@ -7,7 +7,6 @@ from ...arrays.bpm_array import BPMArray from ...arrays.cfm_magnet_array import CombinedFunctionMagnetArray from ...arrays.magnet_array import MagnetArray -from ...arrays.serialized_magnet_array import SerializedMagnetsArray from ...magnet.cfm_magnet import CombinedFunctionMagnet from ...magnet.magnet import Magnet from ...magnet.serialized_magnet import SerializedMagnets @@ -51,6 +50,10 @@ class MagnetsHolder(GenericArrayHolder[Magnet, MagnetArray]): equivalent to ``magnets.get("QuadForTune")``. Family names appear in ``dir(magnets)`` for interactive completion. + A serialized family name in an array stands for one magnet, the family + itself. Its magnets are not added to the array, and excluding one of them + while the family is in the array raises an error. + Examples -------- >>> quad_family = sr.live.magnets.get("QuadForTune") @@ -66,11 +69,23 @@ def __init__(self, peer: "ElementHolder"): peer, peer._MAGNET_ARRAYS, peer.magnet.all, - peer.magnet.get, + self.__get_magnet, MagnetArray, "Magnet array", + self.__family_members, ) + def __get_magnet(self, name: str) -> Magnet: + """Resolve a magnet or a serialized family by name.""" + if name in self._peer._SERIALIZED_MAGNETS: + return self._peer._SERIALIZED_MAGNETS[name] + return self._peer.magnet.get(name) + + def __family_members(self, name: str) -> list[str] | None: + """Return the magnet names of a serialized family, ``None`` for another element.""" + family = self._peer._SERIALIZED_MAGNETS.get(name) + return None if family is None else family.names() + def get_cfm(self) -> CombinedFunctionMagnetArray: """ Return all combined-function magnets. @@ -153,10 +168,15 @@ def __init__(self, peer: "ElementHolder"): super().__init__(peer, peer._SERIALIZED_MAGNETS, "Serialized magnet") -class SerializedMagnetsHolder(GenericArrayHolder[SerializedMagnets, SerializedMagnetsArray]): +class SerializedMagnetsHolder(GenericArrayHolder[SerializedMagnets, MagnetArray]): """ Provide access to arrays of serialized magnet groups. + .. deprecated:: + A serialized family is a magnet: use :class:`MagnetsHolder` + (``holder.magnets``), which handles family names. This holder shares + its arrays with it. + Parameters ---------- peer : 'ElementHolder' @@ -176,11 +196,11 @@ def __init__(self, peer: "ElementHolder"): """ super().__init__( peer, - peer._SERIALIZED_MAGNETS_ARRAYS, + peer._MAGNET_ARRAYS, peer.serialized_magnet.all, peer.serialized_magnet.get, - SerializedMagnetsArray, - "serialized magnet array", + MagnetArray, + "Magnet array", ) diff --git a/pyaml/control/abstract_impl.py b/pyaml/control/abstract_impl.py index 5b110562..98a8c361 100644 --- a/pyaml/control/abstract_impl.py +++ b/pyaml/control/abstract_impl.py @@ -412,7 +412,8 @@ def __init__(self, peer: CSScalarAggregator): """ CSScalarAggregator.__init__(self, peer._devs) self.__models: list[MagnetModel] = [] # List of magnet model - self.__modelToMagnet: list[list[tuple[int, int]]] = [] # strengths indexing + 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 def add_magnet(self, magnet: Magnet, devs: list[DeviceAccess]): @@ -431,9 +432,13 @@ def add_magnet(self, magnet: Magnet, devs: list[DeviceAccess]): Hardware devices associated with the magnet model. """ # Magnets of a serialized group share the serialized model (one power supply for N strengths): - # the power-supply current is computed by the model from the N strengths (mean of the implied currents). - is_indexed = isinstance(magnet.strength, (abstract.RWMapper, RWSerializedStrengthScalar)) - strengthIndex = magnet.strength.index() if is_indexed else 0 + # the power-supply current is computed by the model from the strengths of the magnets present in the array, + # the others following the resulting current. A serialized family has no series index: its value is the + # average strength of the series, converted by the family strength accessor. + if magnet.model.shares_power_supply(): + strengthIndex = magnet.series_index + else: + strengthIndex = magnet.strength.index() if isinstance(magnet.strength, abstract.RWMapper) else 0 if magnet.model not in self.__models: index = len(self.__models) self.__models.append(magnet.model) @@ -442,6 +447,9 @@ def add_magnet(self, magnet: Magnet, devs: list[DeviceAccess]): else: index = self.__models.index(magnet.model) self.__modelToMagnet[index].append((self.__nbMagnet, strengthIndex)) + if strengthIndex is None: + # MagnetArray guarantees that a family is never registered together with one of its magnets + self.__families[index] = magnet.strength self.__nbMagnet += 1 def set(self, value: NDArray[np.float64]): @@ -458,10 +466,17 @@ def set(self, value: NDArray[np.float64]): hardwareIndex = 0 for modelIndex, model in enumerate(self.__models): nbDev = len(model.get_device_names()) - mStrengths = model.compute_strengths(allHardwareValues[hardwareIndex : hardwareIndex + nbDev]) - for valueIdx, strengthIdx in self.__modelToMagnet[modelIndex]: - mStrengths[strengthIdx] = value[valueIdx] - newHardwareValues[hardwareIndex : hardwareIndex + nbDev] = model.compute_hardware_values(mStrengths) + current = allHardwareValues[hardwareIndex : hardwareIndex + nbDev] + if modelIndex in self.__families: + [(valueIdx, _)] = self.__modelToMagnet[modelIndex] + newHardwareValues[hardwareIndex] = self.__families[modelIndex].hardware_from_strength( + value[valueIdx], current[0] + ) + else: + requested = {strengthIdx: value[valueIdx] for valueIdx, strengthIdx in self.__modelToMagnet[modelIndex]} + newHardwareValues[hardwareIndex : hardwareIndex + nbDev] = model.compute_hardware_values_partial( + current, requested + ) hardwareIndex += nbDev dev_range = self._devs.get_range() if not check_range(newHardwareValues, dev_range): @@ -488,14 +503,22 @@ def set_and_wait(self, value: NDArray[np.float64]): def get(self) -> NDArray[np.float64]: """Read the current values from the underlying devices.""" - allHardwareValues = self._devs.get() # Read all hardware setpoints + return self.__strengths_from_hardware(self._devs.get()) # Read all hardware setpoints + + def __strengths_from_hardware(self, allHardwareValues: NDArray[np.float64]) -> NDArray[np.float64]: + """Convert the hardware values of every registered device to the strength of every registered magnet.""" allStrength = np.zeros(self.__nbMagnet) hardwareIndex = 0 for modelIndex, model in enumerate(self.__models): nbDev = len(model.get_device_names()) - mStrengths = model.compute_strengths(allHardwareValues[hardwareIndex : hardwareIndex + nbDev]) - for valueIdx, strengthIdx in self.__modelToMagnet[modelIndex]: - allStrength[valueIdx] = mStrengths[strengthIdx] + hardware = allHardwareValues[hardwareIndex : hardwareIndex + nbDev] + if modelIndex in self.__families: + [(valueIdx, _)] = self.__modelToMagnet[modelIndex] + allStrength[valueIdx] = self.__families[modelIndex].strength_from_hardware(hardware[0]) + else: + mStrengths = model.compute_strengths(hardware) + for valueIdx, strengthIdx in self.__modelToMagnet[modelIndex]: + allStrength[valueIdx] = mStrengths[strengthIdx] hardwareIndex += nbDev return allStrength @@ -508,22 +531,137 @@ def readback(self) -> np.array: numpy.ndarray Magnet strengths corresponding to the latest device readbacks. """ - allHardwareValues = self._devs.readback() # Read all hardware readback - allStrength = np.zeros(self.__nbMagnet) - hardwareIndex = 0 - for modelIndex, model in enumerate(self.__models): - nbDev = len(model.get_device_names()) - mStrengths = model.compute_strengths(allHardwareValues[hardwareIndex : hardwareIndex + nbDev]) - for valueIdx, strengthIdx in self.__modelToMagnet[modelIndex]: - allStrength[valueIdx] = mStrengths[strengthIdx] - hardwareIndex += nbDev - return allStrength + 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() +class CSHardwareScalarAggregator(CSScalarAggregator): + """ + Aggregate magnet hardware values, writing the power supply of a series once. + + Each registered magnet has one value. The magnets of a series share one power-supply device, added once: it gets + the hardware value computed by the model of the series from the values of the magnets of the series present in the + aggregator, and its value is read back for each of them. + + Parameters + ---------- + peer : CSScalarAggregator + Scalar device aggregator receiving the hardware devices. + + Methods + ------- + add_magnet(magnet, dev) + Register a magnet and the device holding its hardware value. + set(value) + Write the hardware value of every registered magnet. + set_and_wait(value) + Set the hardware values and wait for hardware readback. + get() + Return the hardware value of every registered magnet. + readback() + Return the hardware readback of every registered magnet. + nb_device() + Return the number of registered magnets. + """ + + def __init__(self, peer: CSScalarAggregator): + """ + Initialize the CSHardwareScalarAggregator. + """ + CSScalarAggregator.__init__(self, peer._devs) + self.__slotToDevice: list[int] = [] # device index of each registered magnet + self.__deviceOfSeries: dict[int, int] = {} # id of a series model -> device index + self.__series: list[tuple[MagnetModel, list[tuple[int, int]]] | None] = [] # per device: model, (slot, index) + + def add_magnet(self, magnet: Magnet, dev: DeviceAccess): + """ + Register a magnet and the device holding its hardware value. + + Parameters + ---------- + magnet : Magnet + Magnet whose hardware value is aggregated. + dev : DeviceAccess + Device holding the hardware value of the magnet. + """ + slot = len(self.__slotToDevice) + series_index = magnet.series_index + if series_index is None: + device = self.__add_device(dev, None) + else: + device = self.__deviceOfSeries.get(id(magnet.model)) + if device is None: + device = self.__add_device(dev, magnet.model) + self.__deviceOfSeries[id(magnet.model)] = device + self.__series[device][1].append((slot, series_index)) + self.__slotToDevice.append(device) + + def __add_device(self, dev: DeviceAccess, model: MagnetModel | None) -> int: + self._devs.add_devices(dev) + self.__series.append(None if model is None else (model, [])) + return len(self.__series) - 1 + + def __device_values(self, value: NDArray[np.float64]) -> NDArray[np.float64]: + """Return the value to write to each device from the value of each registered magnet.""" + value = np.asarray(value, dtype=float) + if value.ndim == 0: + value = np.full(len(self.__slotToDevice), float(value)) + deviceValues = np.zeros(len(self.__series)) + for slot, device in enumerate(self.__slotToDevice): + if self.__series[device] is None: + deviceValues[device] = value[slot] + for device, series in enumerate(self.__series): + if series is not None: + model, members = series + deviceValues[device] = model.compute_hardware_from_hardwares({idx: value[slot] for slot, idx in members}) + dev_range = self._devs.get_range() + if not check_range(deviceValues, dev_range): + raise PyAMLException(format_out_of_range_message(deviceValues, self._devs)) + return deviceValues + + def set(self, value: NDArray[np.float64]): + """ + Write the hardware value of every registered magnet. + + Parameters + ---------- + value : NDArray[np.float64] + Hardware value of each registered magnet, in registration order. A scalar is applied to every magnet. + + Raises + ------ + PyAMLException + If a value to write is outside the range of its device. Nothing is written. + """ + self._devs.set(self.__device_values(value)) + + def set_and_wait(self, value: NDArray[np.float64]): + """ + Set the hardware values and wait for hardware readback. + + Parameters + ---------- + value : NDArray[np.float64] + Hardware value of each registered magnet, in registration order. + """ + self._devs.set_and_wait(self.__device_values(value)) + + def get(self) -> NDArray[np.float64]: + """Return the hardware value of every registered magnet.""" + return np.asarray(self._devs.get())[self.__slotToDevice] + + def readback(self) -> np.array: + """Return the hardware readback of every registered magnet.""" + return np.asarray(self._devs.readback())[self.__slotToDevice] + + def nb_device(self) -> int: + """Return the number of registered magnets.""" + return len(self.__slotToDevice) + + # ------------------------------------------------------------------------------ @@ -719,36 +857,66 @@ class RWSerializedStrengthScalar(RWStrengthScalar): Expose the strength of one magnet of a serialized group. All magnets of a serialized group share one power supply. This accessor - converts with the magnet's own sub-model and remembers the magnet position - in the group so that aggregators can map it to the right strength of the - serialized model. + reads with the magnet's own sub-model, writes through the model of the + series, and remembers the magnet position in the group so that aggregators + can map it to the right strength of the serialized model. Parameters ---------- model : MagnetModel - Sub-model of the magnet, used for strength conversion and units. + Sub-model of the magnet, used for strength reading and units. dev : DeviceAccess Power-supply device shared by the serialized group. idx : int Zero-based position of the magnet in the serialized group. + series_model : MagnetModel + Model of the series, used to convert the strength of the magnet to the shared hardware value. Methods ------- index() Return the position of the magnet in the serialized group. + set(value) + Set the shared hardware value giving the requested strength of the magnet. """ - def __init__(self, model: MagnetModel, dev: DeviceAccess, idx: int): + def __init__(self, model: MagnetModel, dev: DeviceAccess, idx: int, series_model: MagnetModel): """ Initialize the RWSerializedStrengthScalar. """ super().__init__(model, dev) + self.__dev = dev self.__idx = idx + self.__series_model = series_model def index(self) -> int: """Return the position of the magnet in the serialized group.""" return self.__idx + def set(self, value: float): + """ + Set the shared hardware value giving the requested strength of the magnet. + + The model of the series solves for the hardware value from the present one, so that the power supply does not + move when it already gives the requested strength (for example on a plateau of the excitation curve). + + Parameters + ---------- + value : float + Strength of the magnet. + + Raises + ------ + PyAMLException + If the converted hardware value is outside the device's configured range. + """ + current_hardware = np.array([self.__dev.get()]) + current = self.__series_model.compute_hardware_values_partial(current_hardware, {self.__idx: value})[0] + dev_range = self.__dev.get_range() + if not check_range(current, dev_range): + raise PyAMLException(format_out_of_range_message(current, self.__dev)) + self.__dev.set(current) + # ------------------------------------------------------------------------------ diff --git a/pyaml/control/controlsystem.py b/pyaml/control/controlsystem.py index 4800f796..13a6b4d5 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -18,6 +18,7 @@ from ..common.holders.element_holder import ElementHolder from ..configuration.unbound_element import UnboundElement from ..control.abstract_impl import ( + CSHardwareScalarAggregator, CSScalarAggregator, CSSparseScalarAggregator, CSStrengthScalarAggregator, @@ -180,12 +181,13 @@ def create_magnet_hardware_aggregator(self, magnets: list[Magnet]) -> ScalarAggr agg = self._create_scalar_aggregator() if agg is None: return None + hagg = CSHardwareScalarAggregator(agg) for m in magnets: if not m.model.has_hardware(): return None psIndex = m.hardware.index() if isinstance(m.hardware, RWMapper) else 0 - agg.add_devices(self.get_devices_access([m.model.get_device_names()[psIndex]])[0]) - return agg + hagg.add_magnet(m, self.get_devices_access([m.model.get_device_names()[psIndex]])[0]) + return hagg def create_bpm_aggregators(self, bpms: list[BPM]) -> list[ScalarAggregator | None]: """ @@ -238,7 +240,9 @@ def _fill_serialized_magnets(self, magnets: SerializedMagnets) -> None: for index in range(magnets.get_nb_magnets()): sub_model = magnets.model.get_sub_model(index) currents.append(RWHardwareScalar(sub_model, device) if magnets.model.has_hardware() else None) - strengths.append(RWSerializedStrengthScalar(sub_model, device, index) if magnets.model.has_physics() else None) + strengths.append( + RWSerializedStrengthScalar(sub_model, device, index, magnets.model) if magnets.model.has_physics() else None + ) attached_magnets = magnets.attach(self, strengths, currents) self.serialized_magnet.add(attached_magnets[0]) for magnet in attached_magnets[1:]: diff --git a/pyaml/lattice/abstract_impl.py b/pyaml/lattice/abstract_impl.py index a734a587..c0ecb817 100644 --- a/pyaml/lattice/abstract_impl.py +++ b/pyaml/lattice/abstract_impl.py @@ -277,7 +277,10 @@ def get_model(self) -> MagnetModel: class RWSerializedHardware(abstract.ReadWriteFloatScalar): """ - RWSerializedHardware configuration or runtime object. + Hardware value of one magnet of a serialized group. + + All the magnets of the group share one power supply: writing the hardware + value of one magnet writes it to every magnet of the group. Parameters ---------- @@ -288,18 +291,18 @@ class RWSerializedHardware(abstract.ReadWriteFloatScalar): Methods ------- - get_element_length() - Return the total length of the represented element. - get_total_length() - Return the total length of the represented elements. + index() + Return the position of the magnet in the serialized group. get() Return the current value. set(value) - Set the current value. + Set the current value of the whole serialized group. set_and_wait(value) Set the value and wait for readback convergence. unit() Return the value unit. + get_model() + Return the submodel of the magnet. set_magnet_rigidity(brho) Set the magnetic rigidity used for conversion. """ @@ -310,17 +313,10 @@ def __init__(self, elements: list[RWHardwareScalar], element_index: int): """ self.__elements = elements self.__element_index = element_index - self.__total_length = 0 - for e in elements: - self.__total_length += e.get_length() - def get_element_length(self) -> float: - """Return the total length of the represented element.""" - return self.__elements[self.__element_index].get_length() - - def get_total_length(self) -> float: - """Return the total length of the represented elements.""" - return self.__total_length + def index(self) -> int: + """Return the position of the magnet in the serialized group.""" + return self.__element_index # Gets the value def get(self) -> float: @@ -330,7 +326,7 @@ def get(self) -> float: # Sets the value def set(self, value: float): """ - Set the current value. + Set the current value of the whole serialized group. Parameters ---------- @@ -361,6 +357,10 @@ def unit(self) -> str: """Return the value unit.""" return self.__elements[self.__element_index].unit() + def get_model(self) -> MagnetModel: + """Return the submodel of the magnet.""" + return self.__elements[self.__element_index].get_model() + def set_magnet_rigidity(self, brho: np.double): """ Set the magnetic rigidity used for conversion. @@ -375,7 +375,14 @@ def set_magnet_rigidity(self, brho: np.double): class RWSerializedStrength(abstract.ReadWriteFloatScalar): """ - RWSerializedStrength configuration or runtime object. + Strength of one magnet of a serialized group. + + All the magnets of the group share one power supply. Writing the strength + ``x`` of magnet ``i`` sets the shared hardware value ``I`` solving + ``f_i(I) = x``, and the other magnets follow as ``f_j(I)``. With the model of + the series, the solution starts from the present hardware value, so that the + power supply does not move when it already gives ``x`` (for example on a + plateau of the excitation curve). Parameters ---------- @@ -385,13 +392,14 @@ class RWSerializedStrength(abstract.ReadWriteFloatScalar): Hardware accessors of the same magnets, used to apply the shared setpoint. element_index : int Index of the magnet this accessor represents within the serialized group. + series_model : MagnetModel, optional + Model of the series, used to convert the strength of the magnet to the shared hardware value. If omitted, the + submodel of the magnet is inverted. Methods ------- - get_element_length() - Return the total length of the represented element. - get_total_length() - Return the total length of the represented elements. + index() + Return the position of the magnet in the serialized group. get() Return the current value. set(value) @@ -409,38 +417,24 @@ def __init__( elements_strength: list[RWStrengthScalar], elements_hardware: list[RWHardwareScalar], element_index: int, + series_model: MagnetModel | None = None, ): """ Initialize the RWSerializedStrength. """ self.__element = elements_strength[element_index] - self.__elements_strength = elements_strength self.__elements_hardware = elements_hardware self.__element_index = element_index - # The strength is shared between the serialized magnets in proportion to their (effective) length: thick - # magnets share by length, thin magnets share equally. Mixing both has no meaningful share rule. - thin_flags = [e.is_thin() for e in elements_hardware] - if any(thin_flags) and not all(thin_flags): - raise PyAMLException( - "Serialized magnets must be either all thin (zero length) or all thick; " - f"got {sum(thin_flags)} thin out of {len(thin_flags)} magnets" - ) - self.__total_length = 0 - for e in self.__elements_hardware: - self.__total_length += e.get_length() - - def get_element_length(self) -> float: - """Return the total length of the represented element.""" - return self.__element.get_element_length() + self.__series_model = series_model - def get_total_length(self) -> float: - """Return the total length of the represented elements.""" - return self.__total_length + def index(self) -> int: + """Return the position of the magnet in the serialized group.""" + return self.__element_index # Gets the value def get(self) -> float: """Return the current value.""" - return self.__elements_strength[self.__element_index].get() + return self.__element.get() # Sets the value def set(self, value: float): @@ -452,19 +446,15 @@ def set(self, value: float): value : float Strength to apply to the magnet, converted to the shared hardware setpoint. """ - elements_values = [value * e.get_length() / self.get_total_length() for e in self.__elements_hardware] - self.__element.set(elements_values[self.__element_index]) - - # compute the local hardware value - hardware_value = self.__elements_hardware[self.__element_index].get() - - # compute the total hardware value - total_hardware = hardware_value * self.get_total_length() / self.get_element_length() - - # dispatch this value - for index, element in enumerate(self.__elements_hardware): - if index != self.__element_index: - element.set(total_hardware * element.get_length() / self.get_total_length()) + hardware = self.__elements_hardware[self.__element_index] + if self.__series_model is None: + hardware_value = hardware.get_model().compute_hardware_values([value])[0] + else: + current_hardware = np.array([hardware.get()]) + hardware_value = self.__series_model.compute_hardware_values_partial( + current_hardware, {self.__element_index: value} + )[0] + [element.set(hardware_value) for element in self.__elements_hardware] # Sets the value and wait that the read value reach the setpoint def set_and_wait(self, value: float): diff --git a/pyaml/lattice/simulator.py b/pyaml/lattice/simulator.py index e0922ae3..aea7921e 100644 --- a/pyaml/lattice/simulator.py +++ b/pyaml/lattice/simulator.py @@ -271,12 +271,12 @@ def _fill_serialized_magnets(self, magnets: SerializedMagnets) -> None: strengths = [] for index, magnet in enumerate(magnets.get_magnets()): current = ( - RWHardwareScalar(self.get_at_elems(magnet), magnets.polynom, magnets.model.get_sub_model(index)) + RWHardwareScalar(self.get_at_elems(magnet), magnets.polynoms[index], magnets.model.get_sub_model(index)) if magnets.model.has_hardware() else None ) strength = ( - RWStrengthScalar(self.get_at_elems(magnet), magnets.polynom, magnets.model.get_sub_model(index)) + RWStrengthScalar(self.get_at_elems(magnet), magnets.polynoms[index], magnets.model.get_sub_model(index)) if magnets.model.has_physics() else None ) @@ -286,7 +286,9 @@ def _fill_serialized_magnets(self, magnets: SerializedMagnets) -> None: linked_strengths = [] for index in range(magnets.get_nb_magnets()): linked_currents.append(RWSerializedHardware(currents, index) if magnets.model.has_hardware() else None) - linked_strengths.append(RWSerializedStrength(strengths, currents, index) if magnets.model.has_physics() else None) + linked_strengths.append( + RWSerializedStrength(strengths, currents, index, magnets.model) if magnets.model.has_physics() else None + ) attached_magnets = magnets.attach(self, linked_strengths, linked_currents) self.serialized_magnet.add(attached_magnets[0]) for magnet in attached_magnets[1:]: diff --git a/pyaml/magnet/linear_model.py b/pyaml/magnet/linear_model.py index 6ffa0608..c16227a2 100644 --- a/pyaml/magnet/linear_model.py +++ b/pyaml/magnet/linear_model.py @@ -96,7 +96,7 @@ def __init__( Initialize the LinearMagnetModel. """ if curve: - self.__curve = curve.get_curve() + self.__curve = curve.get_curve().copy() self.__curve[:, 1] = self.__curve[:, 1] * calibration_factor * crosstalk + calibration_offset self.__rcurve = Curve.inverse(self.__curve) else: diff --git a/pyaml/magnet/linear_serialized_model.py b/pyaml/magnet/linear_serialized_model.py index 1e912c11..7e232277 100644 --- a/pyaml/magnet/linear_serialized_model.py +++ b/pyaml/magnet/linear_serialized_model.py @@ -4,6 +4,8 @@ This model applies linear calibration to a configurable sequence of serialized magnet elements and hardware channels. """ +import logging + import numpy as np from ..common.element import __pyaml_repr__ @@ -17,6 +19,87 @@ # Define the main class name for this module PYAMLCLASS = "LinearSerializedMagnetModel" +logger = logging.getLogger(__name__) + +# Relative gap above which strengths requested for a series are considered unreachable with a single hardware value +_SPREAD_RTOL = 1e-6 +# Normalized residual below which a breakpoint is considered to be exactly on the solution (rounding errors) +_ZERO_ATOL = 1e-12 + + +def _first_zero(currents: np.ndarray, residuals: np.ndarray) -> float: + """ + Return the lowest hardware value where an increasing piecewise-linear residual reaches zero. + + Parameters + ---------- + currents : np.ndarray + Breakpoints, in ascending order. + residuals : np.ndarray + Residual at each breakpoint, increasing. + + Returns + ------- + float + Hardware value, interpolated on the segment where the residual becomes non-negative. + """ + above = np.nonzero(residuals >= 0.0)[0] + if len(above) == 0: + return float(currents[-1]) + j = above[0] + if j == 0: + return float(currents[0]) + return float(currents[j - 1] - residuals[j - 1] * (currents[j] - currents[j - 1]) / (residuals[j] - residuals[j - 1])) + + +def _last_zero(currents: np.ndarray, residuals: np.ndarray) -> float: + """ + Return the highest hardware value where an increasing piecewise-linear residual is still zero. + + Parameters + ---------- + currents : np.ndarray + Breakpoints, in ascending order. + residuals : np.ndarray + Residual at each breakpoint, increasing. + + Returns + ------- + float + Hardware value, interpolated on the segment where the residual becomes positive. + """ + below = np.nonzero(residuals <= 0.0)[0] + if len(below) == 0: + return float(currents[0]) + j = below[-1] + if j == len(currents) - 1: + return float(currents[-1]) + return float(currents[j] - residuals[j] * (currents[j + 1] - currents[j]) / (residuals[j + 1] - residuals[j])) + + +def _pick(low: float, high: float, current_hardware: float | None) -> float: + """ + Return the hardware value chosen in the interval of solutions ``[low, high]``. + + Parameters + ---------- + low : float + Lowest hardware value of the solutions. + high : float + Highest hardware value of the solutions. + current_hardware : float or None + Present hardware value of the power supply, if known. + + Returns + ------- + float + ``current_hardware`` clipped to ``[low, high]``, so that the power supply does not move when it already gives + the requested strengths, or the middle of the interval when the present hardware value is not known. + """ + if current_hardware is None: + return float((low + high) / 2.0) + return float(np.clip(current_hardware, low, high)) + def _get_length(elem) -> int: """ @@ -132,6 +215,17 @@ class LinearSerializedMagnetModel(MagnetModel, DynamicValidation): hardware values. Conversely, a hardware current is mapped back to a strength value for each sub-model. + The serialized magnets have a single degree of freedom, the power-supply + current ``I``. Magnet ``i`` has the strength ``k_i = f_i(I)``, where ``f_i`` + is its sub-model. The family strength is the average strength + ``sum(p_i * f_i(I)) / N``, ``p_i`` being the declared polarity of magnet ``i``. + The polarities must make every ``p_i * f_i`` vary in the same direction with + ``I``: a series with magnets wired in reverse declares ``-1`` for them. + + The power supply only drives the series on the current range shared by all + the excitation curves, ``[max_i I_min,i, min_i I_max,i]``. Hardware values + computed from strengths are clamped to this range. + Parameters ---------- curves : Curve or list[Curve] @@ -145,6 +239,9 @@ class LinearSerializedMagnetModel(MagnetModel, DynamicValidation): If omitted, defaults to 0.0 for all magnets. crosstalk : float or list[float], optional Crosstalk factor for each magnet. If omitted, defaults to 1.0. + polarities : int or list[int], optional + Polarity ``p_i`` of each magnet in the family strength, ``+1`` or ``-1``. + If omitted, defaults to ``+1`` for all magnets. powerconverter : str, optional Name of the associated power converter or power converter group. unit : str, optional @@ -162,6 +259,18 @@ class LinearSerializedMagnetModel(MagnetModel, DynamicValidation): Convert magnet strengths to hardware values. compute_strengths(currents) Convert hardware values to magnet strengths. + compute_hardware_values_partial(current_hardware, strengths_by_index) + Convert the strengths of some magnets of the series to the shared hardware value. + compute_hardware_from_hardwares(hardwares_by_index) + Return the shared hardware value for the hardware values requested for some magnets of the series. + compute_mean_strength(current) + Return the average strength of the series for a hardware value. + compute_hardware_from_mean_strength(strength, current_hardware=None) + Return the hardware value giving an average strength of the series. + compute_hardware_from_strengths(strengths, current_hardware=None) + Return the hardware value for a requested strength of each magnet of the series. + shares_power_supply() + Return True, all the magnets of the series share one power supply. get_strength_units() Return the units of magnet strengths. get_hardware_units() @@ -173,6 +282,13 @@ class LinearSerializedMagnetModel(MagnetModel, DynamicValidation): get_magnet_rigidity() Return the configured magnetic rigidity. + Raises + ------ + PyAMLException + When the number of magnets is set, if a polarity is not ``+1`` or ``-1``, + if the excitation curves share no current range, or if the polarities do + not make every ``p_i * f_i`` vary in the same direction. + Notes ----- The number of magnets is inferred from the longest list among the supplied @@ -199,6 +315,7 @@ def __init__( calibration_factors: float | list[float] | None = None, calibration_offsets: float | list[float] | None = None, crosstalk: float | list[float] = 1.0, + polarities: int | list[int] | None = None, powerconverter: str | None = None, unit: str | None = None, hardware_unit: str | None = None, @@ -211,17 +328,20 @@ def __init__( self._calibration_factors = calibration_factors self._calibration_offsets = calibration_offsets self._crosstalk = crosstalk + self._polarities_config = polarities self._powerconverter = powerconverter self._unit = unit self._hardware_unit = hardware_unit # Check config - self.__nbMagnets: int = _get_max_length(curves, calibration_factors, calibration_offsets, crosstalk) + self.__nbMagnets: int = _get_max_length(curves, calibration_factors, calibration_offsets, crosstalk, polarities) self.__calibration_factors = np.ones(self.__nbMagnets) self.__calibration_offsets = np.ones(self.__nbMagnets) self.__crosstalk = np.ones(self.__nbMagnets) + self.__polarities = np.ones(self.__nbMagnets) self.__curves = _to_list_of_length(curves, self.__nbMagnets) self.__sub_models: list[LinearMagnetModel] = [] + self.__current_range = (np.nan, np.nan) def __initialize(self): """ @@ -254,10 +374,20 @@ def __initialize(self): curve = InlineCurve(mat=self._curves.get_curve()) self.__curves.append(curve) + if self._polarities_config is None: + self.__polarities = np.ones(self.__nbMagnets) + else: + self.__polarities = np.array(_to_list_of_length(self._polarities_config, self.__nbMagnets), dtype=float) + _check_len(self.__calibration_factors, "calibration_factors", self.__nbMagnets) _check_len(self.__calibration_offsets, "calibration_offsets", self.__nbMagnets) _check_len(self.__crosstalk, "crosstalk", self.__nbMagnets) + _check_len(self.__polarities, "polarities", self.__nbMagnets) _check_len(self.__curves, "curves", self.__nbMagnets) + if not np.all(np.isin(self.__polarities, (1.0, -1.0))): + raise PyAMLException( + f"polarities of the series on {self._powerconverter} must be +1 or -1, got {self.__polarities.tolist()}" + ) self.__sub_models: list[LinearMagnetModel] = [] for magnet_idx in range(self.__nbMagnets): @@ -272,6 +402,54 @@ def __initialize(self): ) self.__sub_models.append(LinearMagnetModel(**sub_model)) + self.__current_range = self.__shared_current_range() + self.__check_polarities() + + def __shared_current_range(self) -> tuple[float, float]: + """ + Return the current range shared by all the excitation curves of the series. + + Raises + ------ + PyAMLException + If the excitation curves share no current range. + """ + tables = [curve.get_curve()[:, 0] for curve in self.__curves] + low = max(float(table.min()) for table in tables) + high = min(float(table.max()) for table in tables) + if low >= high: + raise PyAMLException( + f"The excitation curves of the series on {self._powerconverter} share no current range ([{low}, {high}])" + ) + return low, high + + def __check_polarities(self): + """ + Check that the polarities make every ``p_i * f_i`` vary in the same direction with the hardware value. + + The direction of each curve is taken from the curve itself, with its calibration, so that the check does not + depend on the magnetic rigidity. A curve with no strength range has no direction and is not checked. + + Raises + ------ + PyAMLException + If two magnets vary in opposite directions once multiplied by their polarity. + """ + low, high = self.__current_range + directions = [] + for idx, curve in enumerate(self.__curves): + table = curve.get_curve() + gain = self.__calibration_factors[idx] * self.__crosstalk[idx] + span = gain * (np.interp(high, table[:, 0], table[:, 1]) - np.interp(low, table[:, 0], table[:, 1])) + directions.append(np.sign(self.__polarities[idx] * span)) + directions = np.array(directions) + if np.any(directions > 0) and np.any(directions < 0): + raise PyAMLException( + f"The magnets {np.nonzero(directions < 0)[0].tolist()} of the series on {self._powerconverter} vary in " + f"the opposite direction to the magnets {np.nonzero(directions > 0)[0].tolist()}: declare polarities " + f"-1 for the magnets wired in reverse" + ) + def set_number_of_magnets(self, nb_magnets: int): """ Set the number of serialized magnets and rebuild submodels. @@ -312,10 +490,9 @@ def compute_hardware_values(self, strengths: np.array) -> np.array: Returns ------- np.array - Hardware value obtained from the submodels. + Hardware value of the power supply, computed by :meth:`compute_hardware_from_strengths`. """ - currents = [model.compute_hardware_values([s])[0] for s, model in zip(strengths, self.__sub_models, strict=True)] - return np.array([np.mean(currents)]) + return np.array([self.compute_hardware_from_strengths(strengths)]) def compute_strengths(self, currents: np.array) -> np.array: """ @@ -334,6 +511,287 @@ def compute_strengths(self, currents: np.array) -> np.array: current = currents[0] return np.array([model.compute_strengths([current])[0] for model in self.__sub_models]) + def compute_hardware_values_partial( + self, current_hardware: np.ndarray, strengths_by_index: dict[int, float] + ) -> np.ndarray: + """ + Convert the strengths of some magnets of the series to the shared hardware value. + + Only the requested magnets define the hardware value, solved as in :meth:`compute_hardware_from_strengths`. The + other magnets of the series follow the resulting hardware value. A warning is logged when the requested + strengths cannot all be reached with one hardware value, or when they are outside the excitation curves. + + Parameters + ---------- + current_hardware : np.array + Present hardware value of the series, one value per power supply. It is kept when it already gives the + requested strengths. + strengths_by_index : dict[int, float] + Requested strengths, indexed by the position of the magnet in the series. + + Returns + ------- + np.array + Hardware value of the power supply, with the shape of ``current_hardware``. + + Raises + ------ + PyAMLException + If ``current_hardware`` does not hold one value per power supply of the series, if an excitation curve has + no strength range, or if an excitation curve is not monotonic. + """ + _check_len(current_hardware, "current_hardware", len(self.get_device_names())) + indices = list(strengths_by_index.keys()) + strengths = np.array(list(strengths_by_index.values()), dtype=float) + return np.array([self._compute_hardware_from_strengths(strengths, indices, float(current_hardware[0]))]) + + def compute_hardware_from_hardwares(self, hardwares_by_index: dict[int, float]) -> float: + """ + Return the shared hardware value for the hardware values requested for some magnets of the series. + + Every magnet of the series reads the same hardware value, so the power supply gets the average of the values + requested for the magnets present in the request. The other magnets of the series follow it. + + Parameters + ---------- + hardwares_by_index : dict[int, float] + Requested hardware values, indexed by the position of the magnet in the series. + + Returns + ------- + float + Average of the requested hardware values. + + Raises + ------ + PyAMLException + If no hardware value is requested. + """ + if not hardwares_by_index: + raise PyAMLException(f"No hardware value requested for the series on {self._powerconverter}") + return float(np.mean(list(hardwares_by_index.values()))) + + def compute_mean_strength(self, current: float) -> float: + """ + Return the average strength of the series for a hardware value. + + Each strength is taken with the declared polarity of its magnet, so that a magnet wired in reverse counts with + its magnitude instead of cancelling the others. + + Parameters + ---------- + current : float + Hardware value shared by the serialized magnets. + + Returns + ------- + float + Average strength ``sum(p_i * f_i(I)) / N``, ``p_i`` being the polarity of magnet ``i``. + """ + return float(np.mean(self._polarities() * self.compute_strengths([current]))) + + def compute_hardware_from_mean_strength(self, strength: float, current_hardware: float | None = None) -> float: + """ + Return the hardware value giving an average strength of the series. + + The average strength is defined as in :meth:`compute_mean_strength`. The polarities make every term vary in the + same direction, so the average is monotonic. The submodels are piecewise linear in the hardware value, so the + average is piecewise linear on the union of the curve breakpoints and is inverted exactly by interpolation. + When every hardware value of an interval gives the requested strength (a plateau), the present hardware value + clipped to this interval is returned. A strength outside the range reachable by the excitation curves is + clamped to the end of the shared current range, and a warning is logged. + + Parameters + ---------- + strength : float + Requested average strength of the series. + current_hardware : float, optional + Present hardware value of the power supply. If omitted, the middle of a plateau is returned. + + Returns + ------- + float + Hardware value ``I`` such that ``sum(p_i * f_i(I)) / N == strength``. + + Raises + ------ + PyAMLException + If the average strength is not monotonic in the hardware value. + """ + polarities = self._polarities() + currents = self._solve_points(range(self.__nbMagnets)) + strengths = np.array([np.mean(polarities * self.compute_strengths([current])) for current in currents]) + steps = np.diff(strengths) + if np.all(steps >= 0): + residuals = strengths - strength + elif np.all(steps <= 0): + residuals = strength - strengths + else: + raise PyAMLException( + f"Average strength of the series on {self._powerconverter} is not monotonic, it cannot be inverted" + ) + scale = max(float(np.max(np.abs(strengths))), 1.0) + if residuals[0] > _SPREAD_RTOL * scale or residuals[-1] < -_SPREAD_RTOL * scale: + logger.warning( + f"Strength {strength:.6g} requested for the series on {self._powerconverter} is outside the range " + f"[{strengths.min():.6g}, {strengths.max():.6g}] reachable by the excitation curves, the hardware value " + f"is clamped to the end of the curves" + ) + residuals[np.abs(residuals) < _ZERO_ATOL * scale] = 0.0 + return _pick(_first_zero(currents, residuals), _last_zero(currents, residuals), current_hardware) + + def compute_hardware_from_strengths(self, strengths: np.ndarray, current_hardware: float | None = None) -> float: + """ + Return the hardware value for a requested strength of each magnet of the series. + + The series has a single hardware value ``I``. It solves ``sum((f_i(I) - k_i) / span_i) == 0``, where ``span_i`` + is the signed strength range ``f_i(I_max) - f_i(I_min)`` of magnet ``i`` on the current range ``[I_min, I_max]`` + shared by all the excitation curves. Each term is dimensionless and increasing, so every magnet weighs the same + whatever its unit, its polarity or how far its curve is tabulated, and the equation always has a solution, + exact for a request reachable with one hardware value. When every hardware value of an interval is a solution + (a plateau), the present hardware value clipped to this interval is returned. When the requested strengths + cannot all be reached with one hardware value, the result is a compromise and a warning is logged. + + Parameters + ---------- + strengths : np.ndarray + Requested strength ``k_i`` of each magnet of the series, in declaration order. + current_hardware : float, optional + Present hardware value of the power supply. If omitted, the middle of a plateau is returned. + + Returns + ------- + float + Hardware value of the power supply. + + Raises + ------ + PyAMLException + If the number of strengths does not match the number of magnets, if an excitation curve has no strength + range, or if an excitation curve is not monotonic. + """ + strengths = np.asarray(strengths, dtype=float) + _check_len(strengths, "strengths", self.__nbMagnets) + return self._compute_hardware_from_strengths(strengths, list(range(self.__nbMagnets)), current_hardware) + + def _compute_hardware_from_strengths( + self, strengths: np.ndarray, indices: list[int], current_hardware: float | None = None + ) -> float: + """ + Return the hardware value for the requested strengths of some magnets of the series. + + Parameters + ---------- + strengths : np.ndarray + Requested strength ``k_i`` of each magnet in ``indices``. + indices : list[int] + Positions of the requested magnets in the series. + current_hardware : float, optional + Present hardware value of the power supply. + + Returns + ------- + float + Hardware value of the power supply. + """ + current, clamped = self._solve_normalized_residual(strengths, indices, current_hardware) + if not clamped: + reached = np.array([self.__sub_models[idx].compute_strengths([current])[0] for idx in indices]) + spans = np.array([self._strength_span(idx) for idx in indices]) + relative_gaps = (reached - strengths) / np.abs(spans) + if np.any(np.abs(relative_gaps) > _SPREAD_RTOL): + worst = int(np.argmax(np.abs(relative_gaps))) + logger.warning( + f"Inconsistent strengths requested for the series on {self._powerconverter}: the hardware value " + f"{current} misses the requested strengths by up to {reached[worst] - strengths[worst]:.3g} " + f"(magnet {indices[worst]}, {100 * relative_gaps[worst]:.3g} % of its curve range)" + ) + return current + + def _solve_normalized_residual( + self, strengths: np.ndarray, indices: list[int], current_hardware: float | None = None + ) -> tuple[float, bool]: + """ + Solve ``g(I) = sum((f_i(I) - k_i) / span_i) == 0`` over some magnets of the series. + + ``g`` is piecewise linear on the union of the curve breakpoints and increasing, so its zero is found exactly by + interpolation. When ``g`` is zero on an interval (for example two saturated magnets), the present hardware value + clipped to the interval is returned, or the middle of the interval when the present hardware value is not + known. When the zero is outside the shared current range, the hardware value is clamped to the end of this + range and a warning is logged. + + Parameters + ---------- + strengths : np.ndarray + Requested strength ``k_i`` of each magnet in ``indices``. + indices : list[int] + Positions of the requested magnets in the series. + current_hardware : float, optional + Present hardware value of the power supply. + + Returns + ------- + tuple[float, bool] + Hardware value, and whether it was clamped to the end of the shared current range. + + Raises + ------ + PyAMLException + If an excitation curve has no strength range, or if an excitation curve is not monotonic. + """ + spans = np.array([self._strength_span(idx) for idx in indices]) + if np.any(spans == 0.0): + flat = [idx for idx, span in zip(indices, spans, strict=True) if span == 0.0] + raise PyAMLException( + f"Magnets {flat} of the series on {self._powerconverter} have an excitation curve with no strength " + f"range, the hardware value cannot be computed from their strength" + ) + currents = self._solve_points(indices) + residuals = np.array( + [ + sum( + (self.__sub_models[idx].compute_strengths([current])[0] - strength) / span + for idx, strength, span in zip(indices, strengths, spans, strict=True) + ) + for current in currents + ] + ) + if np.any(np.diff(residuals) < -_SPREAD_RTOL): + raise PyAMLException( + f"An excitation curve of the series on {self._powerconverter} is not monotonic, " + f"the hardware value cannot be computed" + ) + residuals[np.abs(residuals) < _ZERO_ATOL] = 0.0 + if residuals[0] > _SPREAD_RTOL or residuals[-1] < -_SPREAD_RTOL: + current = currents[0] if residuals[0] > 0.0 else currents[-1] + logger.warning( + f"Strengths {strengths} requested for the series on {self._powerconverter} are outside the range " + f"reachable by the excitation curves, the hardware value is clamped to the end of the curves ({current})" + ) + return float(current), True + return _pick(_first_zero(currents, residuals), _last_zero(currents, residuals), current_hardware), False + + def _solve_points(self, indices) -> np.ndarray: + """Return the curve breakpoints of the magnets ``indices`` inside the shared current range, with its ends.""" + low, high = self.__current_range + breakpoints = np.concatenate([self.__curves[idx].get_curve()[:, 0] for idx in indices]) + inside = breakpoints[(breakpoints > low) & (breakpoints < high)] + return np.unique(np.concatenate([[low, high], inside])) + + def _strength_span(self, idx: int) -> float: + """Return the signed strength range ``f_i(I_max) - f_i(I_min)`` of magnet ``idx`` on the shared current range.""" + low, high = self.__current_range + model = self.__sub_models[idx] + return float(model.compute_strengths([high])[0] - model.compute_strengths([low])[0]) + + def _polarities(self) -> np.ndarray: + """Return the declared polarity ``p_i`` of each magnet.""" + return self.__polarities + + def shares_power_supply(self) -> bool: + """Return True, all the magnets of the series share one power supply.""" + return True + def get_strength_units(self) -> list[str]: """Return the units of magnet strengths.""" return [self._unit] * self.__nbMagnets diff --git a/pyaml/magnet/magnet.py b/pyaml/magnet/magnet.py index fd5a4a09..f2e152b8 100644 --- a/pyaml/magnet/magnet.py +++ b/pyaml/magnet/magnet.py @@ -51,6 +51,9 @@ class Magnet(Element): Read/write accessor for the hardware value, in the model's hardware unit. model Magnet model performing the strength to hardware conversion. + series_index + Position of this magnet in the series driven by its power supply, ``None`` for a magnet with its own power + supply. Methods ------- @@ -104,6 +107,16 @@ def model(self) -> MagnetModel: """ return self.__model + @property + def series_index(self) -> int | None: + """ + Position of this magnet in the series driven by its power supply, ``None`` when the magnet does not share + its power supply with other magnets + """ + if self.__model is None or not self.__model.shares_power_supply(): + return None + return self.strength.index() + def attach( self, peer, diff --git a/pyaml/magnet/model.py b/pyaml/magnet/model.py index 47ffe366..c74c9350 100644 --- a/pyaml/magnet/model.py +++ b/pyaml/magnet/model.py @@ -34,6 +34,12 @@ class MagnetModel(metaclass=ABCMeta): Tells if the model allows to work in hardware unit. has_physics() Tells if the model allows to work in physics unit. + shares_power_supply() + Tells if all the strengths of the model are driven by one power supply. + compute_hardware_values_partial(current_hardware, strengths_by_index) + Compute hardware value(s) when only some strengths are requested. + compute_hardware_from_hardwares(hardwares_by_index) + Compute the shared hardware value from the hardware values requested for some magnets of a series. """ @abstractmethod @@ -130,3 +136,64 @@ def has_physics(self) -> bool: True if the model supports physics unit """ return True + + def shares_power_supply(self) -> bool: + """ + Tells if all the strengths of the model are driven by one power supply. + + Returns + ------- + bool + True if the model has a single degree of freedom shared by all its strengths (serialized magnets) + """ + return False + + def compute_hardware_values_partial( + self, + current_hardware: npt.NDArray[np.float64] | None, + strengths_by_index: dict[int, float], + ) -> npt.NDArray[np.float64]: + """ + Compute hardware value(s) when only some strengths of the model are requested. + + The strengths that are not requested keep the value computed from the current hardware values. + + Parameters + ---------- + current_hardware : npt.NDArray[np.float64] | None + Current hardware values of the model. + strengths_by_index : dict[int, float] + Requested strengths, indexed by their position in the model. + + Returns + ------- + npt.NDArray[np.float64] + Array of hardware values (i.e. currents or voltages). + """ + strengths = self.compute_strengths(current_hardware) + for idx, value in strengths_by_index.items(): + strengths[idx] = value + return self.compute_hardware_values(strengths) + + def compute_hardware_from_hardwares(self, hardwares_by_index: dict[int, float]) -> float: + """ + Compute the shared hardware value from the hardware values requested for some magnets of a series. + + Only defined for a model whose strengths share one power supply (see :meth:`shares_power_supply`). + + Parameters + ---------- + hardwares_by_index : dict[int, float] + Requested hardware values, indexed by the position of the magnet in the series. + + Returns + ------- + float + Hardware value to write to the shared power supply. + + Raises + ------ + NotImplementedError + For a model whose strengths do not share one power supply. + """ + raise NotImplementedError(f"{type(self).__name__} does not drive a series of magnets on one power supply") diff --git a/pyaml/magnet/serialized_magnet.py b/pyaml/magnet/serialized_magnet.py index c5aab6fa..4217304f 100644 --- a/pyaml/magnet/serialized_magnet.py +++ b/pyaml/magnet/serialized_magnet.py @@ -11,7 +11,7 @@ from .. import PyAMLException from ..common import abstract -from ..common.element import Element, __pyaml_repr__ +from ..common.element import __pyaml_repr__ from ..configuration.factory import ELEMENT_REGISTRY from ..validation import DynamicValidation, register_schema from .function_mapping import function_map @@ -25,69 +25,66 @@ PYAMLCLASS = "SerializedMagnets" -class ReadWriteSerializedStrengths(abstract.ReadWriteFloatScalar): +class ReadWriteSerializedHardware(abstract.ReadWriteFloatScalar): """ - Read/write aggregate for serialized-magnet strengths. + Read/write access to the hardware value of a serialized-magnet family. + + The family has a single degree of freedom, the hardware value ``I`` of its + power supply, shared by every magnet of the series. Parameters ---------- - elements : list[abstract.ReadWriteFloatScalar] - Per-magnet accessors sharing the group setpoint. - model : MagnetModel | None - Magnet model used to convert between strength and hardware value. Optional for a hardware-only group. + hardwares : list[abstract.ReadWriteFloatScalar] + Per-magnet hardware accessors. Writing one of them moves the whole series. + model : MagnetModel + Serialized magnet model used for units and rigidity. Methods ------- get() - Return the sum of the serialized element strengths. + Return the shared hardware value ``I``. set(value) - Set the shared serialized-magnet strength. + Set the shared hardware value ``I``. set_and_wait(value) - Set the shared strength and wait for convergence. + Set the shared hardware value and wait for convergence. unit() - Return the physical strength unit. + Return the hardware-value unit. get_model() Return the magnet conversion model. - get_elements() - Return the underlying scalar element accessors. set_magnet_rigidity(brho) Set the magnetic rigidity used for conversion. """ - def __init__( - self, - elements: list[abstract.ReadWriteFloatScalar], - model: MagnetModel | None = None, - ): + def __init__(self, hardwares: list[abstract.ReadWriteFloatScalar], model: MagnetModel): """ - Initialize a shared strength accessor for serialized elements. + Initialize a family hardware accessor for serialized magnets. """ - self.elements = elements - self.model = model + self._hardwares = hardwares + self._model = model def get(self) -> float: - """Return the sum of the serialized element strengths.""" - return sum([elem.get() for elem in self.elements]) + """Return the shared hardware value ``I``.""" + return self._hardwares[0].get() def set(self, value: float): """ - Set the shared serialized-magnet strength. + Set the shared hardware value ``I``. Parameters ---------- value : float - Strength applied to every magnet of the group. + Hardware value applied to the power supply of the series. """ - self.elements[0].set(value) + self._hardwares[0].set(value) def set_and_wait(self, value: float): """ - Set the shared strength and wait for convergence. + Set the shared hardware value and wait for convergence. Parameters ---------- value : float - Strength applied to every magnet of the group. + Hardware value applied to the power supply of the series. Raises ------ @@ -97,16 +94,12 @@ def set_and_wait(self, value: float): raise NotImplementedError("Not implemented yet.") def unit(self) -> str: - """Return the physical strength unit.""" - return self.model.get_strength_units()[0] + """Return the hardware-value unit.""" + return self._model.get_hardware_units()[0] def get_model(self) -> MagnetModel: """Return the magnet conversion model.""" - return self.model - - def get_elements(self): - """Return the underlying scalar element accessors.""" - return self.elements + return self._model def set_magnet_rigidity(self, brho: np.double): """ @@ -117,56 +110,290 @@ def set_magnet_rigidity(self, brho: np.double): brho : np.double Magnetic rigidity in tesla metres, forwarded to the magnet model. """ - [element.set_magnet_rigidity(brho) for element in self.elements] + self._model.set_magnet_rigidity(brho) -class ReadWriteSerializedHardwares(ReadWriteSerializedStrengths): +class ReadWriteSerializedStrength(ReadWriteSerializedHardware): """ - Read/write aggregate for serialized-magnet hardware values. + Read/write access to the average strength of a serialized-magnet family. + + Magnet ``i`` of the series has the strength ``k_i = f_i(I)``. The family + strength is the average strength ``sum(p_i * f_i(I)) / N``, ``p_i`` being the + polarity of magnet ``i`` declared in the model (``-1`` for a magnet wired in + reverse, ``+1`` otherwise). On a plateau, the present hardware value is kept + when it already gives the requested strength. + + A single strength value for the whole family is only defined when every magnet has the same function: for a + series mixing functions (e.g. quadrupoles and sextupoles), use the strength of each magnet instead. Parameters ---------- - elements : list[abstract.ReadWriteFloatScalar] - Per-magnet accessors sharing the group setpoint. - model : MagnetModel | None - Magnet model used to convert between strength and hardware value. Optional for a hardware-only group. + hardwares : list[abstract.ReadWriteFloatScalar] + Per-magnet hardware accessors. Writing one of them moves the whole series. + model : MagnetModel + Serialized magnet model converting between average strength and hardware value. + homogeneous : bool, optional + Whether every magnet of the series has the same function. Default is ``True``. Methods ------- + get() + Return the average strength of the series. + set(value) + Set the hardware value giving the requested average strength. + strength_from_hardware(hardware) + Return the average strength for a hardware value, without device access. + hardware_from_strength(strength, current_hardware) + Return the hardware value giving an average strength, without device access. unit() - Return the hardware-value unit. - set_magnet_rigidity(brho) - Set the magnetic rigidity used for conversion. + Return the physical strength unit. + + Raises + ------ + PyAMLException + On every conversion when the series mixes magnet functions. + """ + + def __init__(self, hardwares: list[abstract.ReadWriteFloatScalar], model: MagnetModel, homogeneous: bool = True): + """ + Initialize a family strength accessor for serialized magnets. + """ + super().__init__(hardwares, model) + self._homogeneous = homogeneous + + def get(self) -> float: + """Return the average strength of the series.""" + return self.strength_from_hardware(self._hardwares[0].get()) + + def set(self, value: float): + """ + Set the hardware value giving the requested average strength. + + Parameters + ---------- + value : float + Average strength of the series. + """ + self._hardwares[0].set(self.hardware_from_strength(value, self._hardwares[0].get())) + + def strength_from_hardware(self, hardware: float) -> float: + """ + Return the average strength of the series for a hardware value, without reading the power supply. + + Parameters + ---------- + hardware : float + Hardware value of the power supply. + + Returns + ------- + float + Average strength of the series. + """ + self._check_homogeneous() + return self._model.compute_mean_strength(hardware) + + def hardware_from_strength(self, strength: float, current_hardware: float) -> float: + """ + Return the hardware value giving an average strength of the series, without writing the power supply. + + Parameters + ---------- + strength : float + Requested average strength of the series. + current_hardware : float + Present hardware value of the power supply, kept on a plateau when it already gives ``strength``. + + Returns + ------- + float + Hardware value to write to the power supply. + """ + self._check_homogeneous() + return self._model.compute_hardware_from_mean_strength(strength, current_hardware) + + def unit(self) -> str: + """Return the physical strength unit.""" + return self._model.get_strength_units()[0] + + def _check_homogeneous(self): + if not self._homogeneous: + raise PyAMLException( + "A single strength is not defined for a serialized family mixing magnet functions, " + "use the strength of each magnet (family.strengths or magnet.strength)" + ) + + +class ReadWriteSerializedHardwareArray(abstract.ReadWriteFloatArray): + """ + Read/write access to the hardware value of each magnet of a serialized-magnet family. + + Every magnet of the series reads the hardware value ``I`` of the shared power supply. + + Parameters + ---------- + hardwares : list[abstract.ReadWriteFloatScalar] + Per-magnet hardware accessors. Writing one of them moves the whole series. + model : MagnetModel + Serialized magnet model used for units. + + Methods + ------- + get() + Return the hardware value of each magnet. + set(value) + Set the shared hardware value to the average of the requested values. + set_and_wait(value) + Set the hardware values and wait for convergence. + unit() + Return the hardware-value units. + """ + + def __init__(self, hardwares: list[abstract.ReadWriteFloatScalar], model: MagnetModel): + """ + Initialize a per-magnet hardware accessor for serialized magnets. + """ + self._hardwares = hardwares + self._model = model + + def get(self) -> np.ndarray: + """Return the hardware value of each magnet.""" + return np.array([hardware.get() for hardware in self._hardwares]) + + def set(self, value: np.ndarray): + """ + Set the shared hardware value to the average of the requested values. + + Parameters + ---------- + value : np.ndarray + Requested hardware value of each magnet, in declaration order. + + Raises + ------ + PyAMLException + If ``value`` is not a 1-D sequence holding one value per magnet. A single value for the whole series is + written with ``family.hardware``. + """ + if np.ndim(value) != 1 or len(value) != len(self._hardwares): + raise PyAMLException( + f"One hardware value per magnet is expected ({len(self._hardwares)} values), got {np.shape(value)}" + ) + self._hardwares[0].set(self._model.compute_hardware_from_hardwares(dict(enumerate(value)))) + + def set_and_wait(self, value: np.ndarray): + """ + Set the hardware values and wait for convergence. + + Parameters + ---------- + value : np.ndarray + Requested hardware value of each magnet, in declaration order. + + Raises + ------ + NotImplementedError + Waiting for readback convergence is not implemented for this accessor. + """ + raise NotImplementedError("Not implemented yet.") + + def unit(self) -> list[str]: + """Return the hardware-value units.""" + return self._model.get_hardware_units() + + +class ReadWriteSerializedStrengthArray(abstract.ReadWriteFloatArray): + """ + Read/write access to the strength of each magnet of a serialized-magnet family. + + Magnet ``i`` of the series has the strength ``k_i = f_i(I)``. Writing the strengths ``k_i`` sets the hardware + value ``I`` solving ``sum((f_i(I) - k_i) / span_i) == 0``, ``span_i`` being the signed strength range of magnet + ``i`` on the current range shared by all the excitation curves. It is exact when the requested strengths are + reachable with one hardware value, and every magnet weighs the same whatever its unit or polarity, so this works for + a series mixing magnet functions or polarities. On a plateau, the present hardware value is kept when it already + gives the requested strengths. + + Parameters + ---------- + strengths : list[abstract.ReadWriteFloatScalar] + Per-magnet strength accessors. + hardwares : list[abstract.ReadWriteFloatScalar] + Per-magnet hardware accessors. Writing one of them moves the whole series. + model : MagnetModel + Serialized magnet model converting between strengths and hardware value. + + Methods + ------- + get() + Return the strength of each magnet. + set(value) + Set the hardware value giving the requested strengths. + set_and_wait(value) + Set the strengths and wait for convergence. + unit() + Return the physical strength units. """ def __init__( self, - elements: list[abstract.ReadWriteFloatScalar], - model: MagnetModel | None = None, + strengths: list[abstract.ReadWriteFloatScalar], + hardwares: list[abstract.ReadWriteFloatScalar], + model: MagnetModel, ): """ - Initialize a shared hardware accessor for serialized elements. + Initialize a per-magnet strength accessor for serialized magnets. """ - super().__init__(elements, model) + self._strengths = strengths + self._hardwares = hardwares + self._model = model - def unit(self) -> str: - """Return the hardware-value unit.""" - return self.model.get_hardware_units()[0] + def get(self) -> np.ndarray: + """Return the strength of each magnet.""" + return np.array([strength.get() for strength in self._strengths]) - def set_magnet_rigidity(self, brho: np.double): + def set(self, value: np.ndarray): """ - Set the magnetic rigidity used for conversion. + Set the hardware value giving the requested strengths. Parameters ---------- - brho : np.double - Magnetic rigidity in tesla metres, forwarded to the magnet model. + value : np.ndarray + Requested strength of each magnet, in declaration order. + + Raises + ------ + PyAMLException + If ``value`` is not a 1-D sequence holding one value per magnet. + """ + if np.ndim(value) != 1 or len(value) != len(self._strengths): + raise PyAMLException( + f"One strength value per magnet is expected ({len(self._strengths)} values), got {np.shape(value)}" + ) + self._hardwares[0].set(self._model.compute_hardware_from_strengths(value, self._hardwares[0].get())) + + def set_and_wait(self, value: np.ndarray): + """ + Set the strengths and wait for convergence. + + Parameters + ---------- + value : np.ndarray + Requested strength of each magnet, in declaration order. + + Raises + ------ + NotImplementedError + Waiting for readback convergence is not implemented for this accessor. """ - [element.set_magnet_rigidity(brho) for element in self.elements] + raise NotImplementedError("Not implemented yet.") + + def unit(self) -> list[str]: + """Return the physical strength units.""" + return self._model.get_strength_units() @register_schema -class SerializedMagnets(Element, DynamicValidation): +class SerializedMagnets(Magnet, DynamicValidation): """ Serialized group of magnets that share the same set point. @@ -175,12 +402,18 @@ class SerializedMagnets(Element, DynamicValidation): supply or by several power supplies, but they share a common physics or hardware set point through a combined read/write interface. + The family is a :class:`~pyaml.magnet.magnet.Magnet`: ``strength`` is the average strength of the series and + ``hardware`` the current of its power supply, so it can be used wherever a single magnet is expected. It is + also a container of its magnets: ``len(family)``, ``for magnet in family``, ``family[i]``, ``family["name"]``, + ``family.names()`` and ``family.magnets``. + Parameters ---------- name : str Name of the serialized magnet group. - function : str - Magnet function identifier used to select the concrete virtual magnet type. + function : list[str] | str + Magnet function identifier selecting the concrete virtual magnet type. A single value applies to every + element, a list gives one function per element for a series mixing magnet functions. elements : list[str] | str Names of the individual magnets in the group. model : MagnetModel | None, optional @@ -193,9 +426,18 @@ class SerializedMagnets(Element, DynamicValidation): Attributes ---------- strength - Gives access to the strengths of those magnets in physics unit + Average strength of the magnets of the series, in physics unit. Only defined when every magnet has the same + function. hardware - Gives access to the strengths of this those magnets in hardware unit when possible + Hardware value of the power supply shared by the series + strengths + Strength of each magnet of the series, in physics unit + hardwares + Hardware value of each magnet of the series + magnets + :class:`~pyaml.arrays.magnet_array.MagnetArray` of the magnets of the series, named after the family + series_index + Always ``None``: the family drives its whole series, not one of its magnets Methods ------- @@ -203,6 +445,10 @@ class SerializedMagnets(Element, DynamicValidation): Return the number of magnets in the serialized group. get_magnets() Return the group's virtual single-function magnets. + names() + Return the names of the magnets of the series, in declaration order. + is_homogeneous() + Return True when every magnet of the series has the same function. attach(peer, strengths, hardwares) Attach the group and its virtual magnets to a runtime peer. set_energy(energy) @@ -220,7 +466,38 @@ class SerializedMagnets(Element, DynamicValidation): ----- The serialized group stores a virtual magnet for each underlying element. When attached, each virtual magnet is bound to the same peer and the group exposes - aggregate strength and hardware accessors. + family strength and hardware accessors. + + The series has a single degree of freedom, the power-supply hardware value ``I``. + Magnet ``i`` has the strength ``k_i = f_i(I)``: + + ====================== =============================== ================================================== + Accessor ``get()`` ``set(x)`` + ====================== =============================== ================================================== + ``family.hardware`` ``I`` write ``I = x`` + ``family.strength`` ``sum(p_i * f_i(I)) / N`` solve ``sum(p_i * f_i(I)) / N = x`` for ``I``, write it + ``family.hardwares`` ``[I, ..., I]`` write ``I = mean(x)`` + ``family.strengths`` ``[f_1(I), ..., f_N(I)]`` solve ``sum((f_i(I) - x_i) / span_i) = 0``, write it + ``magnet[i].hardware`` ``I`` write ``I = x``, all the magnets follow + ``magnet[i].strength`` ``k_i = f_i(I)`` solve ``f_i(I) = x``, write it, the others follow + ====================== =============================== ================================================== + + ``p_i`` is the polarity of magnet ``i`` declared in the model, ``-1`` for a magnet wired in reverse and ``+1`` + otherwise. ``span_i`` is the signed strength range of magnet ``i`` on the current range shared by all the excitation + curves, so every magnet weighs the same whatever its unit or polarity (see + :meth:`LinearSerializedMagnetModel.compute_hardware_from_strengths`). Every strength accessor solves with the model + of the series: on a plateau, where several hardware values give the requested strengths, the present hardware value + is kept when it is one of them, so writing back the strengths that were read does not move the power supply. + + ``family.strength`` raises a ``PyAMLException`` for a series mixing magnet functions: a single strength value + cannot be both, say, a quadrupole and a sextupole strength. + + In a :class:`~pyaml.arrays.magnet.Magnet` array, the family name stands for one element, the family itself. + Its magnets are not added to the array, even when listed explicitly or matched by a wildcard: they are already + driven through the family. + + ``attach()`` takes one accessor per magnet of the series and returns the attached family followed by its + attached magnets, unlike :meth:`Magnet.attach`. Configuration ------------- @@ -238,10 +515,12 @@ class SerializedMagnets(Element, DynamicValidation): model: path/to/serialized_magnet_model.yaml """ + __pyaml_repr_exclude__ = ("magnets",) + def __init__( self, name: str, - function: str, + function: list[str] | str, elements: list[str] | str, model: MagnetModel | None = None, description: str | None = None, @@ -250,26 +529,33 @@ def __init__( """ Initialize a group of magnets sharing one setpoint. """ - super().__init__(name, None, description) - - self.function = function - self.model = model + super().__init__(name, model, None, description) - self.polynom = None + self.polynoms = None + self.__magnet_array = None self.__strengths = None self.__hardwares = None + self.__strengths_array = None + self.__hardwares_array = None self.__virtuals: list[Magnet] = [] self.__elements = elements if isinstance(elements, list) else [elements] - self.model.set_number_of_magnets(len(self.__elements)) + self.functions: list[str] = function if isinstance(function, list) else [function] * len(self.__elements) + if len(self.functions) != len(self.__elements): + raise PyAMLException( + f"{name}: function must be a single value or one value per element " + f"({len(self.__elements)} elements, {len(self.functions)} functions)" + ) if peer is None: # Configuration part - self.polynom = function_map[self.function].polynom - if self.function not in function_map: - raise PyAMLException(self.function + " not implemented for serialized magnet") - for element in self.__elements: - # Check mapping validity + for func in self.functions: + if func not in function_map: + raise PyAMLException(func + " not implemented for serialized magnet") + # The submodels are built once here: the attached copies share them with the per-magnet accessors + self.model.set_number_of_magnets(len(self.__elements)) + self.polynoms = [function_map[func].polynom for func in self.functions] + for element, func in zip(self.__elements, self.functions, strict=True): # Create the virtual magnet for the corresponding magnet - vm = self.__create_virtual_magnet(element) + vm = self.__create_virtual_magnet(element, func) self.__virtuals.append(vm) # Register the virtual element in the factory to have a coherent factory and improve error reporting ELEMENT_REGISTRY.register(vm) @@ -280,17 +566,19 @@ def __init__( def _fill_device(self, holder: "ElementHolder") -> None: holder._fill_serialized_magnets(self) - def __create_virtual_magnet(self, name: str) -> Magnet: + def __create_virtual_magnet(self, name: str, function: str) -> Magnet: """ Create a virtual magnet for one serialized element. - The configured function mapping selects the concrete magnet class, and + The function of the element selects the concrete magnet class, and the serialized group's model is shared with the new virtual magnet. Parameters ---------- name : str Name assigned to the virtual magnet. + function : str + Function of the element, selecting the virtual magnet class. Returns ------- @@ -298,10 +586,14 @@ def __create_virtual_magnet(self, name: str) -> Magnet: Newly created virtual magnet linked to the serialized group. """ args = {"name": name, "model": self.model} - virtual: Magnet = function_map[self.function](**args) + virtual: Magnet = function_map[function](**args) virtual.set_model_name(self.get_name()) return virtual + def is_homogeneous(self) -> bool: + """Return True when every magnet of the series has the same function.""" + return len(set(self.functions)) == 1 + def get_nb_magnets(self) -> int: """Return the number of magnets in the serialized group.""" return len(self.__elements) @@ -310,6 +602,65 @@ def get_magnets(self) -> list[Magnet]: """Return the group's virtual single-function magnets.""" return self.__virtuals + def names(self) -> list[str]: + """Return the names of the magnets of the series, in declaration order.""" + return list(self.__elements) + + def __len__(self) -> int: + """Return the number of magnets of the series.""" + return self.get_nb_magnets() + + def __iter__(self): + """Iterate over the magnets of the series, attached to the same peer as the family.""" + return iter(self.get_magnets()) + + def __getitem__(self, key: int | slice | str): + """ + Return one or several magnets of the series. + + Parameters + ---------- + key : int | slice | str + Position of the magnet in the series, a slice of positions, or the name of the magnet. + + Returns + ------- + Magnet | MagnetArray | list[Magnet] + The magnet for an index or a name. For a slice, a ``MagnetArray`` when the family is attached, a list + of the virtual magnets otherwise. + + Raises + ------ + PyAMLException + If ``key`` is a name that is not a magnet of the series. + """ + if isinstance(key, str): + if key not in self.__elements: + raise PyAMLException(f"{key} is not a magnet of the serialized family {self.get_name()}") + return self.get_magnets()[self.__elements.index(key)] + if isinstance(key, slice) and self._peer is not None: + return self.magnets[key] + return self.get_magnets()[key] + + @property + def magnets(self): + """ + :class:`~pyaml.arrays.magnet_array.MagnetArray` of the magnets of the series, named after the family + """ + self.check_peer() + if self.__magnet_array is None: + from ..arrays.magnet_array import MagnetArray + + self.__magnet_array = MagnetArray(self.get_name(), self.get_magnets()) + return self.__magnet_array + + @property + def series_index(self) -> int | None: + """ + Always ``None``: the family drives its whole series, not one of its magnets + """ + return None + def attach( self, peer, @@ -334,9 +685,13 @@ def attach( Virtual magnets of the group, each bound to ``peer``. """ l = [] - n_ser_mag = SerializedMagnets(self._name, self.function, self.__elements, self.model, self.description, peer) - n_ser_mag.__strengths = ReadWriteSerializedStrengths(strengths, self.model) - n_ser_mag.__hardwares = ReadWriteSerializedHardwares(hardwares, self.model) + n_ser_mag = SerializedMagnets(self._name, self.functions, self.__elements, self.model, self.description, peer) + if self.model.has_hardware(): + n_ser_mag.__hardwares = ReadWriteSerializedHardware(hardwares, self.model) + n_ser_mag.__hardwares_array = ReadWriteSerializedHardwareArray(hardwares, self.model) + if self.model.has_physics(): + n_ser_mag.__strengths = ReadWriteSerializedStrength(hardwares, self.model, self.is_homogeneous()) + n_ser_mag.__strengths_array = ReadWriteSerializedStrengthArray(strengths, hardwares, self.model) l.append(n_ser_mag) # Construct a single magnet for each magnet. sub_magnets: list[Magnet] = [] @@ -351,7 +706,7 @@ def attach( @property def strength(self) -> abstract.ReadWriteFloatScalar: """ - Gives access to the strengths of those magnets in physics unit + Average strength of the magnets of the series, in physics unit """ self.check_peer() if self.__strengths is None: @@ -361,13 +716,33 @@ def strength(self) -> abstract.ReadWriteFloatScalar: @property def hardware(self) -> abstract.ReadWriteFloatScalar: """ - Gives access to the strengths of this those magnets in hardware unit when possible + Hardware value of the power supply shared by the series """ self.check_peer() if self.__hardwares is None: raise PyAMLException(f"{self.name} has no model that supports hardware units") return self.__hardwares + @property + def strengths(self) -> abstract.ReadWriteFloatArray: + """ + Strength of each magnet of the series, in physics unit + """ + self.check_peer() + if self.__strengths_array is None: + raise PyAMLException(f"{str(self)} has no model that supports physics units") + return self.__strengths_array + + @property + def hardwares(self) -> abstract.ReadWriteFloatArray: + """ + Hardware value of each magnet of the series, all equal to the shared power-supply value + """ + self.check_peer() + if self.__hardwares_array is None: + raise PyAMLException(f"{str(self)} has no model that supports hardware units") + return self.__hardwares_array + def set_energy(self, energy: float): """ Set beam energy for serialized-magnet strength conversion. diff --git a/pyaml/yellow_pages.py b/pyaml/yellow_pages.py index 34477445..14628fc9 100644 --- a/pyaml/yellow_pages.py +++ b/pyaml/yellow_pages.py @@ -548,7 +548,6 @@ def _discover_overview(self) -> list[tuple[str, YellowPagesCategory, dict[str, d ("diagnostic.bpms", "_BPM_ARRAYS", YellowPagesCategory.ARRAYS), ("magnets", "_MAGNET_ARRAYS", YellowPagesCategory.ARRAYS), ("combined_function_magnets", "_CFM_MAGNET_ARRAYS", YellowPagesCategory.ARRAYS), - ("serialized_magnets", "_SERIALIZED_MAGNETS_ARRAYS", YellowPagesCategory.ARRAYS), ("", "_ELEMENT_ARRAYS", YellowPagesCategory.ARRAYS), ("tool", "_TOOLS", YellowPagesCategory.TOOLS), ("diagnostic", "_DIAG", YellowPagesCategory.DIAGNOSTICS), diff --git a/tests/arrays/test_arrays.py b/tests/arrays/test_arrays.py index 5bd02a3d..62bc46b7 100644 --- a/tests/arrays/test_arrays.py +++ b/tests/arrays/test_arrays.py @@ -247,9 +247,12 @@ def test_arrays(install_test_package): "tests/config/sr_serialized_magnets.yaml", ], ) -def test_serialized_magnets_arrays(sr_file): - sr: Accelerator = Accelerator.load(sr_file, include_locations=False, ignore_external=True) - the_serie = sr.design.serialized_magnets.get("series") +def test_deprecated_serialized_magnet_array_config_builds_a_magnet_array(sr_file): + # "series" is declared with the deprecated type pyaml.arrays.serialized_magnet + with pytest.warns(DeprecationWarning, match="pyaml.arrays.serialized_magnet is deprecated"): + sr: Accelerator = Accelerator.load(sr_file, include_locations=False, ignore_external=True) + the_serie = sr.design.magnets.get("series") + assert isinstance(the_serie, MagnetArray) strength = the_serie.strengths.get() assert len(strength) == 1 print(strength) diff --git a/tests/common/test_array_holder_navigation.py b/tests/common/test_array_holder_navigation.py index 8bd0d2a9..c94c9f1d 100644 --- a/tests/common/test_array_holder_navigation.py +++ b/tests/common/test_array_holder_navigation.py @@ -34,9 +34,14 @@ def test_dynamic_attribute_returns_named_bpm_array(holder): assert holder.diagnostic.bpms.BPMS is holder.diagnostic.bpms.get("BPMS") -def test_dynamic_attribute_returns_named_serialized_magnet_array(serialized_holder): - assert serialized_holder.serialized_magnets.QForTune is serialized_holder.serialized_magnets.get("QForTune") - assert serialized_holder.serialized_magnets.series is serialized_holder.serialized_magnets.get("series") +def test_dynamic_attribute_returns_named_array_of_serialized_families(serialized_holder): + assert serialized_holder.magnets.QForTune is serialized_holder.magnets.get("QForTune") + assert serialized_holder.magnets.series is serialized_holder.magnets.get("series") + + +def test_deprecated_serialized_magnets_holder_shares_the_magnet_arrays(serialized_holder): + with pytest.warns(DeprecationWarning, match="holder.serialized_magnets is deprecated"): + assert serialized_holder.serialized_magnets.series is serialized_holder.magnets.get("series") def test_dynamic_attribute_unknown_name_raises_attribute_error(holder): diff --git a/tests/config/sr_serialized_magnets.yaml b/tests/config/sr_serialized_magnets.yaml index a8a3c486..dd1b0dd8 100644 --- a/tests/config/sr_serialized_magnets.yaml +++ b/tests/config/sr_serialized_magnets.yaml @@ -12,7 +12,7 @@ arrays: name: series elements: - mySeriesOfMagnets - - type: pyaml.arrays.serialized_magnet + - type: pyaml.arrays.magnet name: QForTune elements: - QD2? @@ -37,6 +37,22 @@ devices: type: pyaml.magnet.csvcurve file: sr/magnet_models/serialized_strength.csv powerconverter: srmag/ps-corr-sh1/c01-a-ch1/current + - type: pyaml.magnet.serialized_magnet + name: mixedFunctionSeries + function: [B1, B2] + elements: + - QF6D-C01 + - SD1A-C01 + model: + type: pyaml.magnet.linear_serialized_model + calibration_factors: 1.0 + calibration_offsets: 0.0 + unit: m-1 + hardware_unit: A + curves: + type: pyaml.magnet.csvcurve + file: sr/magnet_models/serialized_strength.csv + powerconverter: srmag/ps-mixed-series/current - type: pyaml.magnet.serialized_magnet name: QF1A function: B1 diff --git a/tests/config/sr_serialized_magnets_cs.yaml b/tests/config/sr_serialized_magnets_cs.yaml index 2db7546f..302605cb 100644 --- a/tests/config/sr_serialized_magnets_cs.yaml +++ b/tests/config/sr_serialized_magnets_cs.yaml @@ -55,3 +55,15 @@ devices: type: pyaml.magnet.csvcurve file: sr/magnet_models/QD2_strength.csv powerconverter: srmag/ps-qd2a/series/current + - type: pyaml.magnet.quadrupole + name: QF1E-C04 + model: + type: pyaml.magnet.linear_model + calibration_factor: 1.0 + crosstalk: 1.0 + curve: + type: pyaml.magnet.csvcurve + file: sr/magnet_models/QF1_strength.csv + unit: 1/m + hardware_unit: A + powerconverter: srmag/vps-qf1/c04-e/current diff --git a/tests/config/sr_serialized_magnets_range.yaml b/tests/config/sr_serialized_magnets_range.yaml new file mode 100644 index 00000000..0e18339f --- /dev/null +++ b/tests/config/sr_serialized_magnets_range.yaml @@ -0,0 +1,48 @@ +type: pyaml.accelerator +facility: ESRF +machine: sr +energy: 6e9 +simulators: + - type: pyaml.lattice.simulator + lattice: sr/lattices/ebs.mat + name: design +controls: + - type: tango.pyaml.controlsystem + tango_host: ebs-simu-3:10000 + name: live + catalog: + type: tango.pyaml.static_catalog + entries: + - type: tango.pyaml.static_catalog_entry + key: srmag/ps-qf1a/series/current + device: + type: tango.pyaml.attribute + attribute: srmag/ps-qf1a/series/current + unit: A + range: [0, 90] +data_folder: /data/store +arrays: + - type: pyaml.arrays.magnet + name: QF1A_PART + elements: + - QF1A-C06 + - QF1A-C07 +devices: + - type: pyaml.magnet.serialized_magnet + name: QF1A + function: B1 + elements: + - QF1A-C05 + - QF1A-C06 + - QF1A-C07 + - QF1A-C08 + model: + type: pyaml.magnet.linear_serialized_model + calibration_factors: [1.0, 1.01, 0.99, 1.02] + calibration_offsets: 0.0 + unit: m-1 + hardware_unit: A + curves: + type: pyaml.magnet.csvcurve + file: sr/magnet_models/QF1_strength.csv + powerconverter: srmag/ps-qf1a/series/current diff --git a/tests/lattice/test_magnet_accessors.py b/tests/lattice/test_magnet_accessors.py index e585b37e..28c7a924 100644 --- a/tests/lattice/test_magnet_accessors.py +++ b/tests/lattice/test_magnet_accessors.py @@ -2,7 +2,6 @@ import numpy as np import pytest -from pyaml import PyAMLException from pyaml.lattice.abstract_impl import ( RWHardwareArray, RWHardwareScalar, @@ -75,8 +74,10 @@ def test_zero_length_combined_function_magnet_stores_integrated_strengths(access np.testing.assert_allclose(accessor.get(), [1.0e-6, -2.0e-6]) -def test_zero_length_serialized_magnets_share_strength_equally(): - elements = [_thin_corrector("COR_A"), _thin_corrector("COR_B")] +def test_serialized_magnets_follow_the_strength_of_one_magnet(): + # Serialized magnets share one power supply: setting the strength of one magnet sets the shared hardware value, + # so every magnet with the same submodel gets the same strength (no length weighting). + elements = [_thin_corrector("COR_A"), at.Corrector("COR_B", 0.2, [0.0, 0.0], PolynomA=[0.0], PolynomB=[0.0])] model = IdentityMagnetModel(physics="COR", unit="rad") strengths = [RWStrengthScalar([e], HCorrector.polynom, model) for e in elements] currents = [RWHardwareScalar([e], HCorrector.polynom, model) for e in elements] @@ -84,17 +85,8 @@ def test_zero_length_serialized_magnets_share_strength_equally(): serialized[0].set(1.0e-6) - assert serialized[0].get() == pytest.approx(0.5e-6) - assert serialized[1].get() == pytest.approx(0.5e-6) - assert elements[0].PolynomB[0] == pytest.approx(-0.5e-6) - assert elements[1].PolynomB[0] == pytest.approx(-0.5e-6) - - -def test_serialized_magnets_mixing_thin_and_thick_is_rejected(): - elements = [_thin_corrector("COR_A"), at.Corrector("COR_B", 0.2, [0.0, 0.0], PolynomA=[0.0], PolynomB=[0.0])] - model = IdentityMagnetModel(physics="COR", unit="rad") - strengths = [RWStrengthScalar([e], HCorrector.polynom, model) for e in elements] - currents = [RWHardwareScalar([e], HCorrector.polynom, model) for e in elements] - - with pytest.raises(PyAMLException, match="all thin .* or all thick"): - RWSerializedStrength(strengths, currents, 0) + assert serialized[0].get() == pytest.approx(1.0e-6) + assert serialized[1].get() == pytest.approx(1.0e-6) + assert elements[0].PolynomB[0] == pytest.approx(-1.0e-6) + assert elements[1].PolynomB[0] * elements[1].Length == pytest.approx(-1.0e-6) + assert serialized[1].index() == 1 diff --git a/tests/magnet/test_serialized_family_as_magnet.py b/tests/magnet/test_serialized_family_as_magnet.py new file mode 100644 index 00000000..9bd6513f --- /dev/null +++ b/tests/magnet/test_serialized_family_as_magnet.py @@ -0,0 +1,341 @@ +""" +A serialized family used like one simple magnet. + +What is a serialized family? + N magnets wired on ONE power supply (see test_serialized_magnets_expected_behaviour.py). + The family itself is a Magnet: family.strength is the average strength of the series, + family.hardware is the current of the power supply. + +What happens in a magnet array? + The family name adds ONE element to the array: the family. Its magnets are not added, they + are already driven through the family. Excluding the family also excludes its magnets, and + excluding one magnet of a family which is in the array raises an error (a series cannot be + split). + +The family is also a container of its magnets: len(family), for magnet in family, family[i], +family["name"], family.names() and family.magnets (a MagnetArray of its magnets). +""" + +import numpy as np +import pytest + +from pyaml import PyAMLException +from pyaml.accelerator import Accelerator +from pyaml.arrays.magnet_array import MagnetArray +from pyaml.magnet.inline_curve import InlineCurve +from pyaml.magnet.linear_serialized_model import LinearSerializedMagnetModel +from pyaml.magnet.magnet import Magnet +from pyaml.magnet.serialized_magnet import SerializedMagnets + +# QF1A (4 magnets) and QD2A (3 magnets) are serialized families, QF1E-C04 has its own power supply +CONFIG = "tests/config/sr_serialized_magnets_cs.yaml" +TANGO_DUMMY = [{"name": "tango-pyaml", "path": "tests/dummy_cs/tango-pyaml"}] +MODES = ["design", "live"] + + +def load(mode: str): + """Load the configuration and return the holder of the requested mode (simulator or control system).""" + sr = Accelerator.load(CONFIG) + return getattr(sr, mode) + + +# --------------------------------------------------------------------------- +# The family is a magnet and a container of its magnets +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_family_is_a_magnet_driving_its_whole_series(install_test_package, mode): + holder = load(mode) + family = holder.serialized_magnet.get("QF1A") + + # The family can be used wherever a magnet is expected + assert isinstance(family, Magnet) + + # It drives the whole series: it is not one magnet of the series + assert family.series_index is None + assert holder.magnet.get("QF1A-C06").series_index == 1 + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_family_gives_access_to_its_magnets(install_test_package, mode): + holder = load(mode) + family = holder.serialized_magnet.get("QF1A") + magnets = family.get_magnets() + + # Number and names of the magnets, in the order of the configuration + assert len(family) == 4 + assert family.names() == ["QF1A-C05", "QF1A-C06", "QF1A-C07", "QF1A-C08"] + + # Iterating gives the magnets attached to the same simulator or control system as the family + assert list(family) == magnets + assert all(m.peer is holder for m in family) + + # One magnet by position or by name: the same object as holder.magnet.get(name) + assert family[1] is magnets[1] + assert family["QF1A-C07"] is holder.magnet.get("QF1A-C07") + + # A slice gives a magnet array + assert family[1:3].names() == ["QF1A-C06", "QF1A-C07"] + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_family_rejects_a_name_outside_the_series(install_test_package, mode): + family = load(mode).serialized_magnet.get("QF1A") + + with pytest.raises(PyAMLException, match="QD2A-C05 is not a magnet of the serialized family QF1A"): + family["QD2A-C05"] + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_family_magnets_is_a_magnet_array_of_the_series(install_test_package, mode): + family = load(mode).serialized_magnet.get("QF1A") + family.hardware.set(80.0) + + # family.magnets is a regular magnet array, named after the family + assert isinstance(family.magnets, MagnetArray) + assert family.magnets.get_name() == "QF1A" + assert family.magnets.names() == family.names() + + # It reads the strength of each magnet, like family.strengths + assert np.allclose(family.magnets.strengths.get(), family.strengths.get()) + + +def test_configured_family_iterates_on_its_virtual_magnets(): + # A family built from the configuration, not attached to a simulator or a control system + model = LinearSerializedMagnetModel( + curves=InlineCurve(mat=np.array([[0.0, 0.0], [100.0, 1.0]])), + calibration_factors=1.0, + calibration_offsets=0.0, + unit="m-1", + hardware_unit="A", + powerconverter="the/power/supply", + ) + family = SerializedMagnets(name="FAMILY", function="B1", elements=["M1", "M2"], model=model) + + # Its magnets are the virtual magnets of the configuration + assert [m.get_name() for m in family] == ["M1", "M2"] + + # They are not attached: reading them raises, as for any magnet not attached + with pytest.raises(PyAMLException, match="not attached"): + family[0].strength.get() + + +# --------------------------------------------------------------------------- +# Family names in a magnet array +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_family_name_adds_the_family_as_one_magnet(install_test_package, mode): + holder = load(mode) + + holder.magnets.add("ARRAY", ["QF1A"]) + array = holder.magnets.get("ARRAY") + + # One element: the family itself + assert array.names() == ["QF1A"] + assert array[0] is holder.serialized_magnet.get("QF1A") + + +@pytest.mark.parametrize( + "elements, expected", + [ + # The family and one of its magnets: the magnet is already driven by the family + (["QF1A", "QF1A-C06"], ["QF1A"]), + # Same thing when the magnet comes first + (["QF1A-C06", "QF1A"], ["QF1A"]), + # A wildcard matching the family and its magnets: only the family is kept, + # QF1E-C04 has its own power supply and is kept too + (["QF1*"], ["QF1A", "QF1E-C04"]), + # The family, then a wildcard matching only its magnets + (["QF1A", "QF1A-C*"], ["QF1A"]), + # A wildcard matching only the magnets of the family, then the family + (["QF1A-C*", "QF1A"], ["QF1A"]), + # The magnets of a family which is not in the array are added as usual + (["QD2A-C05", "QF1A"], ["QD2A-C05", "QF1A"]), + ], +) +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_magnets_of_a_family_in_the_array_are_not_added(install_test_package, mode, elements, expected): + holder = load(mode) + + holder.magnets.add("ARRAY", elements) + + assert holder.magnets.get("ARRAY").names() == expected + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_excluding_a_family_excludes_its_magnets(install_test_package, mode): + holder = load(mode) + + # Every magnet of QF1A and QD2A, then QF1A is excluded: only the magnets of QD2A remain + holder.magnets.add("ARRAY", ["QF1A-C*", "QD2A-C*", "~QF1A"]) + + assert holder.magnets.get("ARRAY").names() == ["QD2A-C05", "QD2A-C06", "QD2A-C07"] + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_excluding_a_magnet_of_a_family_in_the_array_raises(install_test_package, mode): + holder = load(mode) + + # QF1A drives QF1A-C05: the series cannot be split + with pytest.raises(PyAMLException, match="QF1A-C05 cannot be excluded, it is driven by QF1A"): + holder.magnets.add("ARRAY", ["QF1A", "~QF1A-C05"]) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_lone_exclusion_gives_an_empty_array(install_test_package, mode): + holder = load(mode) + + # Nothing is included, so nothing is left + holder.magnets.add("ARRAY", ["~QF1A"]) + + assert len(holder.magnets.get("ARRAY")) == 0 + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_array_with_a_family_and_one_of_its_magnets_raises(install_test_package, mode): + holder = load(mode) + family = holder.serialized_magnet.get("QF1A") + + # Built by hand: a configured array never holds both, the magnet is already driven by the family + with pytest.raises(PyAMLException, match="a serialized family and its magnets cannot be in the same array"): + MagnetArray("MIXED", [family, family[1]]) + + # Same thing when the array comes from a union of arrays + holder.magnets.add("FAMILY", ["QF1A"]) + with pytest.raises(PyAMLException, match="a serialized family and its magnets cannot be in the same array"): + holder.magnets.get("FAMILY") + family.magnets + + +@pytest.mark.parametrize("elements", [["QF1A-C05", "QF1A-C05"], ["QF1A", "QF1A"]]) +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_name_listed_twice_still_raises(install_test_package, mode, elements): + holder = load(mode) + + with pytest.raises(PyAMLException, match="duplicate name"): + holder.magnets.add("ARRAY", elements) + + +# --------------------------------------------------------------------------- +# Reading and writing an array holding families +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_array_reads_the_average_strength_of_each_family(install_test_package, mode): + holder = load(mode) + qf1a, qd2a = holder.serialized_magnet.get("QF1A"), holder.serialized_magnet.get("QD2A") + quad = holder.magnet.get("QF1E-C04") + qf1a.hardware.set(80.0) + qd2a.hardware.set(20.0) + quad.hardware.set(50.0) + + holder.magnets.add("ARRAY", ["QF1A", "QD2A", "QF1E-C04"]) + array = holder.magnets.get("ARRAY") + + # One value per element: the average strength of each family, the strength of the quadrupole + assert np.allclose(array.strengths.get(), [qf1a.strength.get(), qd2a.strength.get(), quad.strength.get()]) + # One current per element: the current of each power supply + assert np.allclose(array.hardwares.get(), [80.0, 20.0, 50.0]) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_array_writes_each_family_like_its_own_strength(install_test_package, mode): + holder = load(mode) + qf1a, qd2a = holder.serialized_magnet.get("QF1A"), holder.serialized_magnet.get("QD2A") + quad = holder.magnet.get("QF1E-C04") + qf1a.hardware.set(80.0) + qd2a.hardware.set(20.0) + holder.magnets.add("ARRAY", ["QF1A", "QD2A", "QF1E-C04"]) + array = holder.magnets.get("ARRAY") + + # Ask for new strengths: each family gets the current giving this average strength, + # exactly as family.strength.set() would do + requested = array.strengths.get() * 1.01 + expected_qf1a = qf1a.strength.hardware_from_strength(requested[0], qf1a.hardware.get()) + expected_qd2a = qd2a.strength.hardware_from_strength(requested[1], qd2a.hardware.get()) + array.strengths.set(requested) + + assert qf1a.hardware.get() == pytest.approx(expected_qf1a) + assert qd2a.hardware.get() == pytest.approx(expected_qd2a) + assert quad.strength.get() == pytest.approx(requested[2]) + assert np.allclose(array.strengths.get(), requested) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_array_set_of_get_does_not_change_the_machine(install_test_package, mode): + holder = load(mode) + qf1a, qd2a = holder.serialized_magnet.get("QF1A"), holder.serialized_magnet.get("QD2A") + quad = holder.magnet.get("QF1E-C04") + qf1a.hardware.set(80.0) + qd2a.hardware.set(20.0) + quad.hardware.set(50.0) + holder.magnets.add("ARRAY", ["QF1A", "QD2A", "QF1E-C04"]) + array = holder.magnets.get("ARRAY") + + # Writing back what was read keeps every power supply where it was + array.strengths.set(array.strengths.get()) + + assert qf1a.hardware.get() == pytest.approx(80.0) + assert qd2a.hardware.get() == pytest.approx(20.0) + assert quad.hardware.get() == pytest.approx(50.0) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_selections_holding_families_are_magnet_arrays(install_test_package, mode): + holder = load(mode) + holder.magnets.add("ARRAY", ["QF1A", "QD2A", "QF1E-C04"]) + array = holder.magnets.get("ARRAY") + + # Families and a magnet, or families only: both are magnet arrays + assert isinstance(array[0:3], MagnetArray) + families_only = array.of_type(SerializedMagnets) + assert isinstance(families_only, MagnetArray) + assert families_only.names() == ["QF1A", "QD2A"] + + +def test_family_mixing_functions_has_no_average_strength_in_an_array(): + sr = Accelerator.load("tests/config/sr_serialized_magnets.yaml", include_locations=False, ignore_external=True) + + # mixedFunctionSeries holds a quadrupole and a sextupole + sr.design.magnets.add("ARRAY", ["mixedFunctionSeries"]) + array = sr.design.magnets.get("ARRAY") + + # Its current is defined, its average strength is not + assert len(array.hardwares.get()) == 1 + with pytest.raises(PyAMLException, match="mixing magnet functions"): + array.strengths.get() + + +# --------------------------------------------------------------------------- +# Families in configured magnet arrays +# --------------------------------------------------------------------------- + + +def test_configured_magnet_array_matching_families_is_used_by_the_tune_tool(): + sr = Accelerator.load("tests/config/sr_serialized_magnets.yaml", include_locations=False, ignore_external=True) + + # QForTune is a pyaml.arrays.magnet with the patterns QD2? and QF1?, which match 4 families + quads = sr.design.magnets.get("QForTune") + assert quads.names() == ["QD2A", "QD2E", "QF1A", "QF1E"] + + # The tune tool finds it as a regular magnet array: one knob per power supply + tool = sr.design.tool.get("DEFAULT_TUNE_RESPONSE_MATRIX") + assert tool.quadrupoles is quads diff --git a/tests/magnet/test_serialized_magnets.py b/tests/magnet/test_serialized_magnets.py index b362f7b7..6ecd7549 100644 --- a/tests/magnet/test_serialized_magnets.py +++ b/tests/magnet/test_serialized_magnets.py @@ -1,8 +1,11 @@ import numpy as np import pytest +from pyaml import PyAMLException from pyaml.accelerator import Accelerator +from pyaml.magnet.quadrupole import Quadrupole from pyaml.magnet.serialized_magnet import SerializedMagnets +from pyaml.magnet.sextupole import Sextupole def check_no_diff(array: list[np.float64]) -> bool: @@ -74,8 +77,8 @@ def test_magnet_modification(sr_file): print() print("Reading strengths from serialized magnets") - for ii in range(len(sm.strength.elements)): - print(element_names[ii], sm.strength.elements[ii].get()) + for ii, magnet in enumerate(sm.get_magnets()): + print(element_names[ii], magnet.strength.get()) print() strength0 = sm.strength.get() @@ -96,8 +99,8 @@ def test_magnet_modification(sr_file): print() print("Reading strengths from serialized magnets") - for ii in range(len(sm.strength.elements)): - print(element_names[ii], sm.strength.elements[ii].get()) + for ii, magnet in enumerate(sm.get_magnets()): + print(element_names[ii], magnet.strength.get()) @pytest.mark.parametrize( @@ -114,7 +117,7 @@ def test_tune(sr_file): print(f"m.strength.get()={m.strength.get()}") assert len(m.get_magnets()) == m.get_nb_magnets() - quadForTuneDesign = sr.design.serialized_magnets.get("QForTune") + quadForTuneDesign = sr.design.magnets.get("QForTune") tune_monitor = sr.design.diagnostic.get("BETATRON_TUNE") # Build tune response matrix tunemat = np.zeros((len(quadForTuneDesign), 2)) @@ -194,10 +197,108 @@ def test_strength_computation(sr_file): sr: Accelerator = Accelerator.load(sr_file, include_locations=False, ignore_external=True) sm: SerializedMagnets = sr.design.serialized_magnet.get("QF1A") assert sm.get_nb_magnets() == 31 - sm.strength.set(24.0) - assert abs(sm.strength.get() - 24.0) < 1e-3 + sm.strength.set(0.8) + assert abs(sm.strength.get() - 0.8) < 1e-6 magnets_strengths = [m.strength.get() for m in sm.get_magnets()] magnets_from_lattice_strengths = get_strengths_from_lattice(sr, sm) - assert abs(sum(magnets_from_lattice_strengths) - 24.0) < 1e-3 + # The family strength is the average strength of the magnets + assert abs(np.mean(magnets_from_lattice_strengths) - 0.8) < 1e-6 assert magnets_strengths == magnets_from_lattice_strengths + + +SR_FILE = "tests/config/sr_serialized_magnets.yaml" +# A quadrupole (B1) and a sextupole (B2) on the same power supply +MIXED = "mixedFunctionSeries" + + +def _effective_length(element) -> float: + return element.Length if element.Length else 1.0 + + +def test_partial_strength_request_keeps_one_hardware_value_per_power_supply(): + sr: Accelerator = Accelerator.load(SR_FILE, include_locations=False, ignore_external=True) + family: SerializedMagnets = sr.design.serialized_magnet.get("QF1A") + model = family.model + current = np.array([family.hardware.get()]) + + assert model.compute_hardware_values_partial(current, {1: 0.8}).shape == current.shape + with pytest.raises(PyAMLException, match="current_hardware"): + model.compute_hardware_values_partial(np.array([80.0, 80.0]), {1: 0.8}) + + +def test_series_with_one_function_is_homogeneous(): + sr: Accelerator = Accelerator.load(SR_FILE, include_locations=False, ignore_external=True) + assert sr.design.serialized_magnet.get("QF1A").is_homogeneous() + assert not sr.design.serialized_magnet.get(MIXED).is_homogeneous() + + +def test_mixed_function_series_has_no_single_family_strength(): + sr: Accelerator = Accelerator.load(SR_FILE, include_locations=False, ignore_external=True) + family: SerializedMagnets = sr.design.serialized_magnet.get(MIXED) + with pytest.raises(PyAMLException, match="mixing magnet functions"): + family.strength.get() + with pytest.raises(PyAMLException, match="mixing magnet functions"): + family.strength.set(0.5) + + +def test_mixed_function_series_keeps_hardware_and_per_magnet_access(): + sr: Accelerator = Accelerator.load(SR_FILE, include_locations=False, ignore_external=True) + family: SerializedMagnets = sr.design.serialized_magnet.get(MIXED) + quad, sextu = family.get_magnets() + assert isinstance(quad, Quadrupole) + assert isinstance(sextu, Sextupole) + + family.hardware.set(50.0) + + assert family.hardware.get() == pytest.approx(50.0) + assert np.allclose(family.hardwares.get(), 50.0) + assert np.allclose(family.strengths.get(), [quad.strength.get(), sextu.strength.get()]) + + +def test_mixed_function_series_writes_each_magnet_in_its_own_polynom(): + sr: Accelerator = Accelerator.load(SR_FILE, include_locations=False, ignore_external=True) + family: SerializedMagnets = sr.design.serialized_magnet.get(MIXED) + ring = sr.design.get_lattice() + quad_element = ring.get_elements("QF6D-C01")[0] + sextu_element = ring.get_elements("SD1A-C01")[0] + sextu_b1_before = sextu_element.PolynomB[1] + + family.hardware.set(50.0) + + quad_strength = family.model.get_sub_model(0).compute_strengths([50.0])[0] + sextu_strength = family.model.get_sub_model(1).compute_strengths([50.0])[0] + assert quad_element.PolynomB[1] * _effective_length(quad_element) == pytest.approx(quad_strength) + assert sextu_element.PolynomB[2] * _effective_length(sextu_element) == pytest.approx(sextu_strength) + assert sextu_element.PolynomB[1] == sextu_b1_before + + +def test_mixed_function_series_strengths_converge_for_a_consistent_request(caplog): + sr: Accelerator = Accelerator.load(SR_FILE, include_locations=False, ignore_external=True) + family: SerializedMagnets = sr.design.serialized_magnet.get(MIXED) + family.hardware.set(50.0) + requested = family.strengths.get() + family.hardware.set(30.0) + + with caplog.at_level("WARNING"): + family.strengths.set(requested) + + assert family.hardware.get() == pytest.approx(50.0) + assert np.allclose(family.strengths.get(), requested) + assert "Inconsistent strengths" not in caplog.text + + +def test_mixed_function_series_strengths_warn_for_an_inconsistent_request(caplog): + sr: Accelerator = Accelerator.load(SR_FILE, include_locations=False, ignore_external=True) + family: SerializedMagnets = sr.design.serialized_magnet.get(MIXED) + family.hardware.set(50.0) + requested = family.strengths.get() * np.array([1.0, 1.1]) + + with caplog.at_level("WARNING"): + family.strengths.set(requested) + + # One power supply: the series gets the hardware value solving sum((f_i(I) - k_i) / span_i) == 0. Both magnets + # of this family share the same curve and calibration, so their spans are equal and the obtained strengths + # average to the requested ones + assert np.mean(family.strengths.get()) == pytest.approx(np.mean(requested)) + assert "Inconsistent strengths" in caplog.text diff --git a/tests/magnet/test_serialized_magnets_cs.py b/tests/magnet/test_serialized_magnets_cs.py index cd4f2998..9a4d6849 100644 --- a/tests/magnet/test_serialized_magnets_cs.py +++ b/tests/magnet/test_serialized_magnets_cs.py @@ -1,6 +1,7 @@ import numpy as np import pytest +from pyaml import PyAMLException from pyaml.accelerator import Accelerator from pyaml.magnet.serialized_magnet import SerializedMagnets @@ -12,6 +13,20 @@ def _sub_strengths(family: SerializedMagnets, current: float) -> np.ndarray: return np.array([family.model.get_sub_model(i).compute_strengths([current])[0] for i in range(family.get_nb_magnets())]) +# Current range of the excitation curve sr/magnet_models/QF1_strength.csv +QF1_CURRENT_RANGE = (0.0, 110.0) + + +def _normalized_residual(family: SerializedMagnets, current: float, requested, indices) -> float: + """Return sum((f_i(I) - k_i) / span_i) over the requested magnets, span_i being the strength range of their curve.""" + total = 0.0 + for idx, strength in zip(indices, requested, strict=True): + model = family.model.get_sub_model(idx) + span = model.compute_strengths([QF1_CURRENT_RANGE[1]])[0] - model.compute_strengths([QF1_CURRENT_RANGE[0]])[0] + total += (model.compute_strengths([current])[0] - strength) / span + return total + + @pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) def test_serialized_magnets_attach_to_control_system(install_test_package): sr: Accelerator = Accelerator.load(CONFIG) @@ -65,3 +80,398 @@ def test_serialized_magnets_aggregator(install_test_package): array.hardwares.set(array.hardwares.get()) assert np.allclose(array.strengths.get(), 2 * expected) + + +MODES = ["design", "live"] + + +def _family(sr: Accelerator, mode: str, name: str = "QF1A") -> SerializedMagnets: + return getattr(sr, mode).serialized_magnet.get(name) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_family_hardware_is_the_power_supply_current(install_test_package, mode): + sr: Accelerator = Accelerator.load(CONFIG) + family = _family(sr, mode) + family.hardware.set(80.0) + assert family.hardware.get() == pytest.approx(80.0) + assert np.allclose([m.hardware.get() for m in family.get_magnets()], 80.0) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_set_of_get_does_not_change_the_machine(install_test_package, mode): + sr: Accelerator = Accelerator.load(CONFIG) + family = _family(sr, mode) + magnet = family.get_magnets()[2] + family.hardware.set(80.0) + for accessor in [family.hardware, family.strength, magnet.hardware, magnet.strength]: + accessor.set(accessor.get()) + assert family.hardware.get() == pytest.approx(80.0) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_family_strength_is_the_average_strength(install_test_package, mode): + sr: Accelerator = Accelerator.load(CONFIG) + family = _family(sr, mode) + family.hardware.set(80.0) + assert family.strength.get() == pytest.approx(np.mean(_sub_strengths(family, 80.0))) + + # QF1A has a different calibration factor per magnet: the requested value is the average strength + family.strength.set(0.79) + assert family.strength.get() == pytest.approx(0.79) + assert np.mean([m.strength.get() for m in family.get_magnets()]) == pytest.approx(0.79) + assert family.hardware.get() == pytest.approx(family.model.compute_hardware_from_mean_strength(0.79)) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_magnet_strength_drives_the_series_with_its_own_submodel(install_test_package, mode): + sr: Accelerator = Accelerator.load(CONFIG) + family = _family(sr, mode) + magnets = family.get_magnets() + magnets[1].strength.set(0.5) + current = family.model.get_sub_model(1).compute_hardware_values([0.5])[0] + assert family.hardware.get() == pytest.approx(current) + assert magnets[1].strength.get() == pytest.approx(0.5) + assert np.allclose([m.strength.get() for m in magnets], _sub_strengths(family, current)) + + +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_design_and_live_agree(install_test_package): + sr: Accelerator = Accelerator.load(CONFIG) + design, live = _family(sr, "design"), _family(sr, "live") + design.hardware.set(80.0) + live.hardware.set(80.0) + assert design.strength.get() == pytest.approx(live.strength.get()) + assert np.allclose( + [m.strength.get() for m in design.get_magnets()], + [m.strength.get() for m in live.get_magnets()], + ) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_array_with_one_magnet_of_a_series_drives_the_series_with_its_own_submodel(install_test_package, mode, caplog): + from pyaml.arrays.magnet_array import MagnetArray + + sr: Accelerator = Accelerator.load(CONFIG) + family = _family(sr, mode) + family.hardware.set(80.0) + array = MagnetArray("ONE", [family.get_magnets()[1]]) + + with caplog.at_level("WARNING"): + array.strengths.set(np.array([0.5])) + + # Same as magnets[1].strength.set(0.5): I = f_1^-1(0.5), the other magnets follow as f_j(I) + current = family.model.get_sub_model(1).compute_hardware_values([0.5])[0] + assert family.hardware.get() == pytest.approx(current) + assert np.allclose(family.strengths.get(), _sub_strengths(family, current)) + assert "Inconsistent strengths" not in caplog.text + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_array_with_consistent_magnets_of_a_series(install_test_package, mode): + sr: Accelerator = Accelerator.load(CONFIG) + qf1a, qd2a = _family(sr, mode, "QF1A"), _family(sr, mode, "QD2A") + qf1a.hardware.set(80.0) + qd2a.hardware.set(20.0) + array = getattr(sr, mode).magnets.get("ALL_SERIALIZED") + array.strengths.set(array.strengths.get()) + assert qf1a.hardware.get() == pytest.approx(80.0) + assert qd2a.hardware.get() == pytest.approx(20.0) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_array_with_inconsistent_magnets_of_a_series(install_test_package, mode, caplog): + sr: Accelerator = Accelerator.load(CONFIG) + qf1a, qd2a = _family(sr, mode, "QF1A"), _family(sr, mode, "QD2A") + qf1a.hardware.set(80.0) + qd2a.hardware.set(20.0) + array = getattr(sr, mode).magnets.get("ALL_SERIALIZED") + strengths = array.strengths.get() + requested = np.array([0.78, 0.79, 0.80, 0.81]) + strengths[:4] = requested + with caplog.at_level("WARNING"): + array.strengths.set(strengths) + # Every magnet of QF1A is in the array: the power supply gets the I solving sum((f_i(I) - k_i) / span_i) == 0 + assert _normalized_residual(qf1a, qf1a.hardware.get(), requested, range(4)) == pytest.approx(0.0, abs=1e-9) + assert qd2a.hardware.get() == pytest.approx(20.0) + assert "Inconsistent strengths" in caplog.text + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_array_with_part_of_a_series_drives_the_series_from_the_requested_magnets_only(install_test_package, mode): + from pyaml.arrays.magnet_array import MagnetArray + + sr: Accelerator = Accelerator.load(CONFIG) + family = _family(sr, mode) + family.hardware.set(80.0) + magnets = family.get_magnets() + array = MagnetArray("PART", [magnets[1], magnets[2]]) + requested = np.array([0.78, 0.82]) + + array.strengths.set(requested) + + # Only magnets 1 and 2 define I: sum((f_i(I) - k_i) / span_i) == 0 over them. Magnets 0 and 3 follow as f_j(I) + current = family.hardware.get() + assert _normalized_residual(family, current, requested, [1, 2]) == pytest.approx(0.0, abs=1e-9) + assert np.allclose(family.strengths.get(), _sub_strengths(family, current)) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_array_hardwares_with_two_magnets_of_a_series_apply_their_average_current(install_test_package, mode): + from pyaml.arrays.magnet_array import MagnetArray + + sr: Accelerator = Accelerator.load(CONFIG) + family = _family(sr, mode) + family.hardware.set(80.0) + magnets = family.get_magnets() + array = MagnetArray("PART", [magnets[1], magnets[2]]) + + array.hardwares.set(np.array([10.0, 20.0])) + + # Same rule as family.hardwares, over the magnets of the series present in the array: I = mean(10, 20) + assert family.hardware.get() == pytest.approx(15.0) + assert np.allclose(array.hardwares.get(), [15.0, 15.0]) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_array_hardwares_write_each_series_with_the_average_of_its_magnets(install_test_package, mode): + sr: Accelerator = Accelerator.load(CONFIG) + qf1a, qd2a = _family(sr, mode, "QF1A"), _family(sr, mode, "QD2A") + array = getattr(sr, mode).magnets.get("ALL_SERIALIZED") + + array.hardwares.set(np.array([10.0, 20.0, 30.0, 40.0, 5.0, 6.0, 7.0])) + + assert qf1a.hardware.get() == pytest.approx(25.0) + assert qd2a.hardware.get() == pytest.approx(6.0) + assert np.allclose(array.hardwares.get(), [25.0] * 4 + [6.0] * 3) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_array_hardwares_of_a_whole_series_match_the_family_hardwares(install_test_package, mode): + from pyaml.arrays.magnet_array import MagnetArray + + sr: Accelerator = Accelerator.load(CONFIG) + family = _family(sr, mode) + requested = np.array([79.0, 80.0, 81.0, 84.0]) + + family.hardwares.set(requested) + from_family = family.hardware.get() + family.hardware.set(0.0) + MagnetArray("WHOLE", family.get_magnets()).hardwares.set(requested) + + assert family.hardware.get() == pytest.approx(from_family) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_writing_back_the_hardwares_of_part_of_a_series_keeps_the_power_supply(install_test_package, mode): + from pyaml.arrays.magnet_array import MagnetArray + + sr: Accelerator = Accelerator.load(CONFIG) + family = _family(sr, mode) + family.hardware.set(80.0) + magnets = family.get_magnets() + array = MagnetArray("PART", [magnets[1], magnets[2]]) + + array.hardwares.set(array.hardwares.get()) + + assert family.hardware.get() == pytest.approx(80.0) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_array_strengths_of_part_of_a_series_match_the_family_strengths(install_test_package, mode): + from pyaml.arrays.magnet_array import MagnetArray + + sr: Accelerator = Accelerator.load(CONFIG) + family = _family(sr, mode) + magnets = family.get_magnets() + array = MagnetArray("PART", [magnets[0], magnets[1]]) + # Each magnet asks for its own strength at 10 A or 20 A: [k_0(10 A), k_1(20 A), k_2(10 A), k_3(20 A)] + requested = np.array([family.model.get_sub_model(i).compute_strengths([[10.0, 20.0][i % 2]])[0] for i in range(4)]) + + family.strengths.set(requested) + from_family = family.hardware.get() + family.hardware.set(80.0) + array.strengths.set(requested[:2]) + + # Both solve in strength space, sum((f_i(I) - k_i) / span_i) == 0: the same current, not the mean of 10 A and 20 A + assert family.hardware.get() == pytest.approx(from_family) + + +@pytest.mark.parametrize("value", [12.0, 12, np.float64(12.0)]) +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_array_hardwares_broadcast_a_single_value(install_test_package, mode, value): + sr: Accelerator = Accelerator.load(CONFIG) + qf1a, qd2a = _family(sr, mode, "QF1A"), _family(sr, mode, "QD2A") + array = getattr(sr, mode).magnets.get("ALL_SERIALIZED") + + array.hardwares.set(value) + + assert qf1a.hardware.get() == pytest.approx(12.0) + assert qd2a.hardware.get() == pytest.approx(12.0) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_array_strengths_broadcast_an_integer_like_a_float(install_test_package, mode): + from pyaml.arrays.magnet_array import MagnetArray + + sr: Accelerator = Accelerator.load(CONFIG) + family = _family(sr, mode) + array = MagnetArray("WHOLE", family.get_magnets()) + + family.hardware.set(80.0) + array.strengths.set(0.0) + from_float = family.hardware.get() + family.hardware.set(80.0) + array.strengths.set(0) + + assert family.hardware.get() == pytest.approx(from_float) + + +@pytest.mark.parametrize("value", [[10.0], [10.0, 20.0, 30.0, 40.0, 5.0, 6.0, 7.0, 8.0], [[10.0] * 7]]) +@pytest.mark.parametrize("accessor", ["strengths", "hardwares"]) +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_array_writes_need_one_value_per_magnet(install_test_package, mode, accessor, value): + sr: Accelerator = Accelerator.load(CONFIG) + qf1a, qd2a = _family(sr, mode, "QF1A"), _family(sr, mode, "QD2A") + qf1a.hardware.set(80.0) + qd2a.hardware.set(20.0) + # 7 magnets: 4 of QF1A and 3 of QD2A + array = getattr(sr, mode).magnets.get("ALL_SERIALIZED") + + with pytest.raises(PyAMLException, match="One .* value per magnet"): + getattr(array, accessor).set(np.array(value)) + + # Nothing is written + assert qf1a.hardware.get() == pytest.approx(80.0) + assert qd2a.hardware.get() == pytest.approx(20.0) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_strength_outside_the_excitation_curve_is_clamped_with_a_warning(install_test_package, mode, caplog): + sr: Accelerator = Accelerator.load(CONFIG) + family = _family(sr, mode) + family.hardware.set(80.0) + # Highest current of the QF1 excitation curve + curve_end = family.model.get_sub_model(0).compute_hardware_values([1e3])[0] + + with caplog.at_level("WARNING"): + family.strengths.set(np.full(family.get_nb_magnets(), 1e3)) + + assert family.hardware.get() == pytest.approx(curve_end) + assert "outside the range" in caplog.text + assert "Inconsistent strengths" not in caplog.text + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_family_strengths_and_hardwares_read_every_magnet(install_test_package, mode): + sr: Accelerator = Accelerator.load(CONFIG) + family = _family(sr, mode) + family.hardware.set(80.0) + + # One call reads every magnet of the series: k_i = f_i(I), and the shared current I + assert np.allclose(family.strengths.get(), [m.strength.get() for m in family.get_magnets()]) + assert np.allclose(family.strengths.get(), _sub_strengths(family, 80.0)) + assert np.allclose(family.hardwares.get(), 80.0) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_family_strengths_set_balances_the_normalized_errors(install_test_package, mode, caplog): + sr: Accelerator = Accelerator.load(CONFIG) + family = _family(sr, mode) + family.hardware.set(80.0) + requested = np.array([0.78, 0.79, 0.80, 0.81]) + + with caplog.at_level("WARNING"): + family.strengths.set(requested) + + # One power supply: the series gets the I solving sum((f_i(I) - k_i) / span_i) == 0 + current = family.hardware.get() + assert _normalized_residual(family, current, requested, range(4)) == pytest.approx(0.0, abs=1e-9) + # QF1A has a different calibration factor per magnet: these strengths cannot all be reached with one current + assert "Inconsistent strengths" in caplog.text + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_family_hardwares_set_applies_the_average_current(install_test_package, mode): + sr: Accelerator = Accelerator.load(CONFIG) + family = _family(sr, mode) + + family.hardwares.set(np.array([79.0, 80.0, 81.0, 84.0])) + + assert family.hardware.get() == pytest.approx(81.0) + assert np.allclose(family.hardwares.get(), 81.0) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_family_array_set_of_get_does_not_change_the_machine(install_test_package, mode, caplog): + sr: Accelerator = Accelerator.load(CONFIG) + family = _family(sr, mode) + family.hardware.set(80.0) + with caplog.at_level("WARNING"): + for accessor in [family.strengths, family.hardwares]: + accessor.set(accessor.get()) + assert family.hardware.get() == pytest.approx(80.0) + assert "Inconsistent strengths" not in caplog.text + + +# QF1A on a power supply limited to [0, 90] A, with an array holding magnets C06 and C07 only +RANGE_CONFIG = "tests/config/sr_serialized_magnets_range.yaml" + + +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_power_supply_range_protects_every_write_to_a_series(install_test_package): + sr: Accelerator = Accelerator.load(RANGE_CONFIG) + family: SerializedMagnets = sr.live.serialized_magnet.get("QF1A") + magnets = family.get_magnets() + family.hardware.set(80.0) + # Strengths that need 100 A, outside the range of the power supply + too_strong = _sub_strengths(family, 100.0) + + writes = [ + lambda: sr.live.magnets.get("QF1A_PART").strengths.set(too_strong[[1, 2]]), + lambda: sr.live.magnets.get("QF1A_PART").hardwares.set(np.array([95.0, 105.0])), + lambda: family.strengths.set(too_strong), + lambda: family.strength.set(np.mean(too_strong)), + lambda: magnets[1].strength.set(too_strong[1]), + lambda: family.hardware.set(100.0), + ] + for write in writes: + with pytest.raises(PyAMLException): + write() + # Nothing is written: the series stays at 80 A + assert family.hardware.get() == pytest.approx(80.0) + + +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_array_with_part_of_a_series_within_the_power_supply_range(install_test_package): + sr: Accelerator = Accelerator.load(RANGE_CONFIG) + family: SerializedMagnets = sr.live.serialized_magnet.get("QF1A") + family.hardware.set(80.0) + within = _sub_strengths(family, 70.0) + + sr.live.magnets.get("QF1A_PART").strengths.set(within[[1, 2]]) + + # Magnets C06 and C07 ask for 70 A, magnets C05 and C08 follow + assert family.hardware.get() == pytest.approx(70.0) + assert np.allclose(family.strengths.get(), within) diff --git a/tests/magnet/test_serialized_magnets_expected_behaviour.py b/tests/magnet/test_serialized_magnets_expected_behaviour.py new file mode 100644 index 00000000..956be0d7 --- /dev/null +++ b/tests/magnet/test_serialized_magnets_expected_behaviour.py @@ -0,0 +1,424 @@ +""" +Expected behaviour of a series of magnets, written as a basis for discussion. + +What is a series? + N magnets wired on ONE power supply. There is a single current I for all of them. + Magnet i has its own excitation curve f_i: its strength is k_i = f_i(I). + +What happens when we ask for strengths? + We ask for one strength k_i per magnet. The power supply can only take one current, so the + code looks for the current I that best matches all the requested strengths: + + sum over i of (f_i(I) - k_i) / span_i == 0 + + [I_min, I_max] is the current range shared by all the curves of the series: the power supply + drives every magnet, so this is the only range that matters. span_i is the strength range of + magnet i on it, f_i(I_max) - f_i(I_min), with its sign. Dividing by span_i makes every term + dimensionless and increasing with I, so: + - every magnet weighs the same, whatever its unit (a sextupole does not outweigh a quadrupole), + - a magnet wired in reverse (negative calibration) is handled like the others, + - extending the table of a curve does not change the result, + - the equation always has a solution. + + A request is "consistent" when one single current gives all the requested strengths: the code + must then find this current exactly. Otherwise the request is "inconsistent": the code returns a + compromise and logs a warning. When several currents give the requested strengths (a plateau), + the present current is kept if it is one of them. + +What is the family strength? + The average of the strengths, each one taken with the polarity p_i (+1 or -1) declared for its + magnet: sum over i of p_i * f_i(I) / N. A magnet wired in reverse must be declared with -1, so + that it counts with its magnitude instead of cancelling the others. + +How to read and modify these tests? + Each test builds a small series with simple curves (current in A, strength = curve value x + calibration), asks for strengths, and checks the current. To discuss another expected behaviour, + change the curves, the calibrations, the request or the expected current in the test. +""" + +import numpy as np +import pytest + +from pyaml import PyAMLException +from pyaml.accelerator import Accelerator +from pyaml.magnet.inline_curve import InlineCurve +from pyaml.magnet.linear_serialized_model import LinearSerializedMagnetModel + +# Excitation curves: each row is [current (A), strength]. +# Straight line, 1.0 at 100 A. +LINEAR = np.array([[0.0, 0.0], [100.0, 1.0]]) +# Steep up to 50 A, then flatter: the magnet starts to saturate. +SATURATING = np.array([[0.0, 0.0], [50.0, 0.6], [100.0, 0.8]]) +# Straight line up to 110 A, used for the quadrupole and the sextupole example. +QUAD_SEXTU = np.array([[0.0, 0.0], [110.0, 1.1]]) +# Fully saturated above 80 A: the strength stays at 0.8 from 80 A to 110 A. +PLATEAU = np.array([[0.0, 0.0], [80.0, 0.8], [110.0, 0.8]]) +# Two slopes: steep up to 50 A, flatter after. +TWO_SLOPES = np.array([[0.0, 0.0], [50.0, 1.0], [100.0, 1.5]]) + + +def make_series( + curves: list[np.ndarray], calibrations: list[float], polarities: list[int] | None = None +) -> LinearSerializedMagnetModel: + """Build the model of a series: one curve, one calibration factor and one polarity (default +1) per magnet.""" + series = LinearSerializedMagnetModel( + curves=[InlineCurve(mat=curve) for curve in curves], + calibration_factors=calibrations, + polarities=polarities, + calibration_offsets=0.0, + unit="m-1", + hardware_unit="A", + powerconverter="the/power/supply", + ) + series.set_number_of_magnets(len(curves)) + # Magnetic rigidity of 1: the strength is directly curve value x calibration + series.set_magnet_rigidity(1.0) + return series + + +def relative_errors(series: LinearSerializedMagnetModel, current: float, requested: list[float]) -> list[str]: + """Return, for each magnet, how far the strength obtained at `current` is from the requested one.""" + obtained = series.compute_strengths([current]) + return [f"{100 * (got - wanted) / wanted:+.1f} %" for got, wanted in zip(obtained, requested, strict=True)] + + +# --------------------------------------------------------------------------------------------------------------------- +# Magnets wired in reverse (opposite polarities) +# --------------------------------------------------------------------------------------------------------------------- + + +def test_opposite_polarities_with_different_saturations_reach_a_consistent_request(): + # Step 1: a series of two magnets on ONE power supply. + # - magnet 0 follows the LINEAR curve, calibration +1 + # - magnet 1 follows the SATURATING curve, calibration -1: it is wired in reverse, + # its strength goes down when the current goes up, so it is declared with polarity -1 + series = make_series([LINEAR, SATURATING], calibrations=[1.0, -1.0], polarities=[1, -1]) + + # Step 2: ask for the strengths the two magnets really have at 40 A. + # This request is "consistent": one single current (40 A) gives both strengths. + requested = series.compute_strengths([40.0]) + + # Step 3: the power-supply current computed from these strengths. + current = series.compute_hardware_from_strengths(requested) + + # Expected: we find 40 A back, even though the two magnets have opposite polarities. + assert current == pytest.approx(40.0) + + +def test_opposite_polarities_with_identical_curves_reach_a_consistent_request(): + # Step 1: two magnets on ONE power supply, same LINEAR curve, the second one wired in reverse. + # At any current, their strengths are exactly opposite: k_1 = -k_0. + series = make_series([LINEAR, LINEAR], calibrations=[1.0, -1.0], polarities=[1, -1]) + + # Step 2: ask for the strengths they have at 40 A: +0.4 and -0.4. + requested = series.compute_strengths([40.0]) + + # Step 3: the power-supply current computed from these strengths. + current = series.compute_hardware_from_strengths(requested) + + # Expected: 40 A. The two strengths add up to 0, but this must not give 0 A. + assert current == pytest.approx(40.0) + + +def test_family_strength_of_opposite_polarities_uses_the_declared_polarities(): + # Step 1: the same two magnets, the second one wired in reverse and declared with polarity -1. + series = make_series([LINEAR, LINEAR], calibrations=[1.0, -1.0], polarities=[1, -1]) + + # Step 2: read the family strength at 40 A. + # The raw strengths are +0.4 and -0.4. The family strength takes each strength with the + # declared polarity of its magnet, so the reversed magnet counts as +0.4, not -0.4. + family_strength = series.compute_mean_strength(40.0) + + # Expected: 0.4 (and not 0.0, the plain average of +0.4 and -0.4). + assert family_strength == pytest.approx(0.4) + + # Step 3: set this family strength back. + # Expected: 40 A. + assert series.compute_hardware_from_mean_strength(0.4) == pytest.approx(40.0) + + +def test_family_strength_of_opposite_polarities_with_different_saturations(): + # Step 1: LINEAR magnet, plus a SATURATING magnet wired in reverse (polarity -1). + series = make_series([LINEAR, SATURATING], calibrations=[1.0, -1.0], polarities=[1, -1]) + + # Step 2: at 40 A, the strengths are +0.40 and -0.48. + # With the declared polarities, the family strength is (0.40 + 0.48) / 2 = 0.44. + assert series.compute_mean_strength(40.0) == pytest.approx(0.44) + + # Step 3: set this family strength back. + # Expected: 40 A. + assert series.compute_hardware_from_mean_strength(0.44) == pytest.approx(40.0) + + +# --------------------------------------------------------------------------------------------------------------------- +# Magnets of different natures on one power supply (strengths with very different magnitudes) +# --------------------------------------------------------------------------------------------------------------------- + + +def test_quadrupole_and_sextupole_share_the_error_when_the_sextupole_asks_for_more(): + # Step 1: a "quadrupole" (calibration 1) and a "sextupole" (calibration 60) on the same curve. + # The sextupole strengths are 60 times bigger numbers than the quadrupole strengths. + series = make_series([QUAD_SEXTU, QUAD_SEXTU], calibrations=[1.0, 60.0]) + + # Step 2: an inconsistent request. + # - the quadrupole alone would need 50 A (0.5) + # - the sextupole alone would need 60 A (36 = 60 x 0.6) + # No single current gives both: the result is a compromise. + requested = [0.5, 36.0] + + # Step 3: the power-supply current computed from these strengths. + current = series.compute_hardware_from_strengths(np.array(requested)) + + # Expected: 55 A, halfway. Both magnets miss their target by about the same amount, the bigger + # numbers of the sextupole do not make it win. + assert current == pytest.approx(55.0), f"relative errors: {relative_errors(series, current, requested)}" + + +def test_quadrupole_and_sextupole_share_the_error_when_the_quadrupole_asks_for_more(): + # Step 1: the same quadrupole (calibration 1) and sextupole (calibration 60). + series = make_series([QUAD_SEXTU, QUAD_SEXTU], calibrations=[1.0, 60.0]) + + # Step 2: an inconsistent request, the other way round. + # - the quadrupole alone would need 60 A (0.6) + # - the sextupole alone would need 50 A (30 = 60 x 0.5) + requested = [0.6, 30.0] + + # Step 3: the power-supply current computed from these strengths. + current = series.compute_hardware_from_strengths(np.array(requested)) + + # Expected: 55 A, halfway again. + assert current == pytest.approx(55.0), f"relative errors: {relative_errors(series, current, requested)}" + + +# --------------------------------------------------------------------------------------------------------------------- +# Particular situations +# --------------------------------------------------------------------------------------------------------------------- + + +def test_two_saturated_magnets_give_the_middle_of_the_plateau(): + # Step 1: two magnets with the PLATEAU curve: from 80 A to 110 A the strength stays at 0.8. + series = make_series([PLATEAU, PLATEAU], calibrations=[1.0, 1.0]) + + # Step 2: ask for 0.8 on both magnets. Every current between 80 A and 110 A gives it. + current = series.compute_hardware_from_strengths(np.array([0.8, 0.8])) + + # Expected: the middle of the interval, 95 A, rather than one of its ends. + assert current == pytest.approx(95.0) + + +def test_strengths_outside_the_curves_are_clamped_with_a_warning(caplog): + # Step 1: two magnets with the LINEAR curve: the strongest they can be is 1.0, at 100 A. + series = make_series([LINEAR, LINEAR], calibrations=[1.0, 1.0]) + + # Step 2: ask for 5.0, far more than the curves can give. + with caplog.at_level("WARNING"): + current = series.compute_hardware_from_strengths(np.array([5.0, 5.0])) + + # Expected: the current stops at the end of the curves (100 A), and a warning says so. + assert current == pytest.approx(100.0) + assert "outside the range reachable by the excitation curves" in caplog.text + + +def test_a_curve_with_no_strength_range_cannot_give_a_current(): + # Step 1: magnet 1 has a flat curve: its strength is 0.3 whatever the current. + flat = np.array([[0.0, 0.3], [100.0, 0.3]]) + series = make_series([LINEAR, flat], calibrations=[1.0, 1.0]) + + # Step 2: ask for strengths. The flat magnet says nothing about the current. + # Expected: an error, rather than a current computed from a meaningless strength. + with pytest.raises(PyAMLException, match="no strength range"): + series.compute_hardware_from_strengths(np.array([0.4, 0.3])) + + +def test_the_model_has_a_single_rule_to_turn_strengths_into_a_current(): + # Step 1: two magnets with the TWO_SLOPES curve, calibrations 1.0 and 1.2. + series = make_series([TWO_SLOPES, TWO_SLOPES], calibrations=[1.0, 1.2]) + + # Step 2: the same request through the two methods of the model that turn strengths into a current. + requested = [0.8, 1.6] + from_hardware_values = series.compute_hardware_values(requested)[0] + from_strengths = series.compute_hardware_from_strengths(requested) + + # Expected: the same current. + assert from_hardware_values == pytest.approx(from_strengths) + + +# --------------------------------------------------------------------------------------------------------------------- +# One hardware value per magnet, on a real series +# --------------------------------------------------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "wrong_value", + [ + pytest.param([10.0, 20.0], id="2 values for 31 magnets"), + pytest.param(7.0, id="a single number"), + pytest.param([80.0] * 34, id="34 values for 31 magnets"), + ], +) +def test_family_hardwares_need_one_value_per_magnet(wrong_value): + # Step 1: the QF1A series of the test lattice: 31 magnets on one power supply. + sr = Accelerator.load("tests/config/sr_serialized_magnets.yaml", include_locations=False, ignore_external=True) + family = sr.design.serialized_magnet.get("QF1A") + family.hardware.set(80.0) + + # Step 2: write a list of hardware values that does not have one value per magnet. + # Expected: an error, and the power supply is not moved. + with pytest.raises(PyAMLException, match="One hardware value per magnet"): + family.hardwares.set(wrong_value) + assert family.hardware.get() == pytest.approx(80.0) + + # Step 3: with one value per magnet it works (a single value is written with family.hardware). + family.hardwares.set([75.0] * family.get_nb_magnets()) + assert family.hardware.get() == pytest.approx(75.0) + + +# --------------------------------------------------------------------------------------------------------------------- +# Edge cases of the normalized residual: curve tables of different lengths, plateaus, polarities +# --------------------------------------------------------------------------------------------------------------------- + +# The LINEAR curve tabulated up to 200 A instead of 100 A: same magnet, same slope, longer table. +LINEAR_UP_TO_200 = np.array([[0.0, 0.0], [200.0, 2.0]]) +# The LINEAR curve with one more point at 300 A, on the same straight line: nothing changes below 100 A. +LINEAR_EXTENDED = np.array([[0.0, 0.0], [100.0, 1.0], [300.0, 3.0]]) + +TANGO_DUMMY = [{"name": "tango-pyaml", "path": "tests/dummy_cs/tango-pyaml"}] + + +def plateau_series_fragment(calibrations: list[float]) -> dict: + """Return a configuration fragment adding a series of two PLATEAU magnets, and an array holding them.""" + return { + "arrays": [{"type": "pyaml.arrays.magnet", "name": "PLATEAU_MAGNETS", "elements": ["QF4A-C10", "QF4B-C10"]}], + "devices": [ + { + "type": "pyaml.magnet.serialized_magnet", + "name": "plateauSeries", + "function": "B1", + "elements": ["QF4A-C10", "QF4B-C10"], + "model": { + "type": "pyaml.magnet.linear_serialized_model", + "calibration_factors": calibrations, + "calibration_offsets": 0.0, + "unit": "m-1", + "hardware_unit": "A", + "powerconverter": "srmag/ps-plateau/series/current", + "curves": {"type": "pyaml.magnet.inline_curve", "mat": PLATEAU.tolist()}, + }, + } + ], + } + + +def load_with_plateau_series(accelerator_from_fragments, calibrations: list[float]) -> Accelerator: + """Load the live test configuration plus a series of two PLATEAU magnets on one power supply.""" + return accelerator_from_fragments("tests/config/sr_serialized_magnets_cs.yaml", plateau_series_fragment(calibrations)) + + +# Point 1: the weight of a magnet must not depend on how far its curve is tabulated + + +@pytest.mark.parametrize( + "other_curve", + [ + pytest.param(LINEAR_UP_TO_200, id="same line tabulated up to 200 A"), + pytest.param(LINEAR_EXTENDED, id="same line with one more point at 300 A"), + ], +) +def test_the_compromise_does_not_depend_on_how_far_a_curve_is_tabulated(other_curve): + # Step 1: two magnets with the same slope (1.0 at 100 A). + # In the reference series, both curves stop at 100 A. + # In the other series, the second curve is the same straight line, only tabulated further. + reference = make_series([LINEAR, LINEAR], calibrations=[1.0, 1.0]) + other = make_series([LINEAR, other_curve], calibrations=[1.0, 1.0]) + + # Step 2: an inconsistent request: magnet 0 alone would need 40 A, magnet 1 alone 60 A. + requested = np.array([0.4, 0.6]) + + # Step 3: the power-supply current computed from these strengths, for both series. + reference_current = reference.compute_hardware_from_strengths(requested) + other_current = other.compute_hardware_from_strengths(requested) + + # Expected: the same current (50 A). The two magnets are physically identical, so the end of a table, which + # anybody can extend when a curve is measured again, must not change the compromise. + assert reference_current == pytest.approx(50.0) + assert other_current == pytest.approx(reference_current) + + +# Point 2: on a plateau, writing back the strengths that were read must not move the power supply + + +@pytest.mark.parametrize("current", [85.0, 100.0]) +def test_writing_back_the_strengths_read_on_a_plateau_keeps_the_current(current): + # Step 1: two PLATEAU magnets: from 80 A to 110 A the strength stays at 0.8. + series = make_series([PLATEAU, PLATEAU], calibrations=[1.0, 1.0]) + + # Step 2: the power supply is at `current`, on the plateau. Read the strengths and write them back, as an array + # holding both magnets does. + requested = series.compute_strengths([current]) + new_current = series.compute_hardware_values_partial(np.array([current]), {0: requested[0], 1: requested[1]})[0] + + # Expected: the current does not move. Every current of the plateau gives the requested strengths, and the + # present one is among them: there is no reason to move the power supply. + assert new_current == pytest.approx(current) + + +def test_writing_back_the_strength_of_one_magnet_read_on_a_plateau_keeps_the_current(): + # Step 1: the same two PLATEAU magnets, the power supply at 85 A. + series = make_series([PLATEAU, PLATEAU], calibrations=[1.0, 1.0]) + current = 85.0 + + # Step 2: an array holding only magnet 0 writes back the strength it read. + requested = series.compute_strengths([current])[0] + new_current = series.compute_hardware_values_partial(np.array([current]), {0: requested})[0] + + # Expected: the current does not move, the present current is one of those giving the requested strength. + assert new_current == pytest.approx(current) + + +@pytest.mark.parametrize("accessor", ["family.strengths", "family.strength", "magnet.strength", "array.strengths"]) +@pytest.mark.parametrize("install_test_package", TANGO_DUMMY, indirect=True) +def test_every_accessor_keeps_the_current_when_writing_back_on_a_plateau( + install_test_package, accelerator_from_fragments, accessor +): + # Step 1: in live, a series of two PLATEAU magnets on one power supply, set at 85 A (on the plateau). + sr = load_with_plateau_series(accelerator_from_fragments, calibrations=[1.0, 1.0]) + family = sr.live.serialized_magnet.get("plateauSeries") + family.hardware.set(85.0) + + # Step 2: read a strength and write it back, through one accessor. + if accessor == "family.strengths": + family.strengths.set(family.strengths.get()) + elif accessor == "family.strength": + family.strength.set(family.strength.get()) + elif accessor == "magnet.strength": + magnet = sr.live.magnet.get("QF4A-C10") + magnet.strength.set(magnet.strength.get()) + else: + array = sr.live.magnets.get("PLATEAU_MAGNETS") + array.strengths.set(array.strengths.get()) + + # Expected: the power supply stays at 85 A whatever the accessor: every accessor follows the same rule. + assert family.hardware.get() == pytest.approx(85.0) + + +# Point 3: the family strength of a series mixing polarities + + +def test_family_strength_does_not_depend_on_the_order_of_the_magnets(): + # Step 1: the same two LINEAR magnets, one of them wired in reverse, declared in both orders. + # Swapping the two magnets in the configuration swaps their calibrations and their polarities. + declared_one_way = make_series([LINEAR, LINEAR], calibrations=[1.0, -1.0], polarities=[1, -1]) + declared_the_other_way = make_series([LINEAR, LINEAR], calibrations=[-1.0, 1.0], polarities=[-1, 1]) + + # Step 2: read the family strength at 40 A. + # Expected: the same value. Swapping two lines of the configuration changes nothing in the machine, so it must + # not change the sign of the family strength. + assert declared_one_way.compute_mean_strength(40.0) == pytest.approx(declared_the_other_way.compute_mean_strength(40.0)) + + +def test_a_series_mixing_polarities_must_declare_them(): + # Step 1: two LINEAR magnets, the second one wired in reverse (calibration -1), without declaring its polarity. + # By default every polarity is +1: the family strength would add +0.4 and -0.4 and give 0 at any current. + # Expected: an error when the series is built, asking to declare the polarity of the magnet wired in reverse. + with pytest.raises(PyAMLException, match="declare polarities"): + make_series([LINEAR, LINEAR], calibrations=[1.0, -1.0]) diff --git a/tests/test_yellow_pages.py b/tests/test_yellow_pages.py index f2fa6924..0f40c6da 100644 --- a/tests/test_yellow_pages.py +++ b/tests/test_yellow_pages.py @@ -56,7 +56,6 @@ def __init__(self, arrays=None, tools=None, diagnostics=None): self._BPM_ARRAYS = {} self._MAGNET_ARRAYS = {} self._CFM_MAGNET_ARRAYS = {} - self._SERIALIZED_MAGNETS_ARRAYS = {} self._ELEMENT_ARRAYS = self._arrays self._TOOLS = self._tools self._DIAG = self._diagnostics