Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 10 additions & 16 deletions pyaml/arrays/element_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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
--------
Expand Down Expand Up @@ -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
--------
Expand Down Expand Up @@ -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")
Expand Down
20 changes: 20 additions & 0 deletions pyaml/arrays/magnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
--------

Expand Down
88 changes: 83 additions & 5 deletions pyaml/arrays/magnet_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)
Expand All @@ -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:
"""
Expand Down
44 changes: 16 additions & 28 deletions pyaml/arrays/serialized_magnet.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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)
Loading
Loading