diff --git a/pyaml/accelerator.py b/pyaml/accelerator.py index 90d83961..957ed175 100644 --- a/pyaml/accelerator.py +++ b/pyaml/accelerator.py @@ -321,6 +321,7 @@ def add(self, element: Element) -> None: holder._BPMS, holder._RFPLANT, holder._RFTRANSMITTER, + holder._INSERTION_DEVICES, holder._DIAG, holder._TOOLS, ) diff --git a/pyaml/apidoc/gen_api.py b/pyaml/apidoc/gen_api.py index 8c3ad368..624b0f0f 100644 --- a/pyaml/apidoc/gen_api.py +++ b/pyaml/apidoc/gen_api.py @@ -9,6 +9,9 @@ modules = [ "pyaml.accelerator", + "pyaml.insertion_device", + "pyaml.insertion_device.control_variable", + "pyaml.configuration.named_value", "pyaml.arrays.array", "pyaml.arrays.bpm", "pyaml.arrays.bpm_array", diff --git a/pyaml/common/abstract.py b/pyaml/common/abstract.py index 498a72ff..d0ab77c6 100644 --- a/pyaml/common/abstract.py +++ b/pyaml/common/abstract.py @@ -27,6 +27,20 @@ def set(self, value: bool) -> None: pass +class RWInsertionDeviceMode(metaclass=ABCMeta): + """Define the optional mode interface shared by live and design accessors.""" + + @abstractmethod + def get(self) -> str: + """Return the mode.""" + pass + + @abstractmethod + def set(self, value: str) -> None: + """Request a mode.""" + pass + + # Float ---------------------------------------------------------------- diff --git a/pyaml/common/abstract_impl.py b/pyaml/common/abstract_impl.py new file mode 100644 index 00000000..38b5356a --- /dev/null +++ b/pyaml/common/abstract_impl.py @@ -0,0 +1,30 @@ +"""Backend-independent implementations of PyAML read/write interfaces.""" + +from collections.abc import Iterator, Mapping +from types import MappingProxyType + + +class RInsertionDeviceModelPoint(Mapping[str, float | str]): + """Read-only reference settings and units, independent of live hardware.""" + + def __init__(self, settings: Mapping[str, float | str], units: Mapping[str, str]): + self._settings = MappingProxyType(dict(settings)) + self._units = MappingProxyType(dict(units)) + + def __getitem__(self, name: str) -> float | str: + return self._settings[name] + + def __iter__(self) -> Iterator[str]: + return iter(self._settings) + + def __len__(self) -> int: + return len(self._settings) + + @property + def units(self) -> Mapping[str, str]: + return self._units + + @property + def mode(self) -> str | None: + value = self._settings.get("mode") + return value if isinstance(value, str) else None diff --git a/pyaml/common/holders/element_holder.py b/pyaml/common/holders/element_holder.py index 4f121f4e..0637b2b9 100644 --- a/pyaml/common/holders/element_holder.py +++ b/pyaml/common/holders/element_holder.py @@ -8,6 +8,7 @@ from ...arrays.element_array import ElementArray from ...diagnostics.tune_monitor import BetatronTuneMonitor +from ...insertion_device import InsertionDevice from ...magnet.cfm_magnet import CombinedFunctionMagnet from ...magnet.magnet import Magnet from ...magnet.serialized_magnet import SerializedMagnets @@ -22,6 +23,7 @@ from .sub_holders import ( CombinedFunctionMagnetHolder, CombinedFunctionMagnetsHolder, + InsertionDeviceHolder, MagnetHolder, MagnetsHolder, SerializedMagnetHolder, @@ -57,6 +59,8 @@ class ElementHolder(metaclass=ABCMeta): ``magnets`` arrays. ``serialized_magnets`` is a deprecated alias of ``magnets`` arrays. rf RF plant and transmitters of this mode. + insertion_device + Individual insertion devices and their control variables. diagnostic Diagnostics of this mode, with typed default-name access. tool @@ -97,6 +101,7 @@ def __init__(self): self._BPMS: dict[str, BPM] = {} self._RFPLANT: dict[str, RFPlant] = {} self._RFTRANSMITTER: dict[str, RFTransmitter] = {} + self._INSERTION_DEVICES: dict[str, InsertionDevice] = {} self._DIAG: dict[str, Element] = {} self._TOOLS: dict[str, Element] = {} self._ALL: dict[str, Element] = {} @@ -108,6 +113,7 @@ def __init__(self): BPM: self._BPMS, RFPlant: self._RFPLANT, RFTransmitter: self._RFTRANSMITTER, + InsertionDevice: self._INSERTION_DEVICES, } # Array handle @@ -124,6 +130,7 @@ def __init__(self): self._combined_function_magnet_holder = CombinedFunctionMagnetHolder(self) self._combined_function_magnets_holder = CombinedFunctionMagnetsHolder(self) self._rf_holder = RFHolder(self) + self._insertion_device_holder = InsertionDeviceHolder(self) self._diagnostic_holder = DiagnosticHolder(self) self._tool_holder = ToolHolder(self) @@ -134,6 +141,11 @@ def peer(self) -> "Accelerator": # Sub holders ---------------------------------------------------------------- + @property + def insertion_device(self) -> InsertionDeviceHolder: + """Return this mode's insertion devices.""" + return self._insertion_device_holder + @property def magnet(self) -> MagnetHolder: """Return the magnet.""" @@ -198,6 +210,9 @@ def fill_device(self, elements: list[Element]): for element in elements: element._fill_device(self) + def _fill_insertion_device(self, device: InsertionDevice) -> None: + raise PyAMLException(f"{device.name}: insertion devices are unsupported by {self.__class__.__name__}") + def _fill_switch_element(self, element: "SwitchElement") -> None: """Reject switches unless the backend supports their binding.""" raise PyAMLException(f"{self.__class__.__name__} does not support switch element {element.name}") diff --git a/pyaml/common/holders/sub_holders.py b/pyaml/common/holders/sub_holders.py index 29c28714..4d873c8c 100644 --- a/pyaml/common/holders/sub_holders.py +++ b/pyaml/common/holders/sub_holders.py @@ -7,6 +7,8 @@ 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 ...insertion_device import InsertionDevice from ...magnet.cfm_magnet import CombinedFunctionMagnet from ...magnet.magnet import Magnet from ...magnet.serialized_magnet import SerializedMagnets @@ -17,6 +19,13 @@ from .element_holder import ElementHolder +class InsertionDeviceHolder(GenericElementHolder[InsertionDevice]): + """Provide typed access to individual insertion devices.""" + + def __init__(self, peer: "ElementHolder"): + super().__init__(peer, peer._INSERTION_DEVICES, "Insertion device") + + class MagnetHolder(GenericElementHolder[Magnet]): """ Provide access to individual magnet elements. diff --git a/pyaml/configuration/__init__.py b/pyaml/configuration/__init__.py index 12346acf..0433f7e4 100644 --- a/pyaml/configuration/__init__.py +++ b/pyaml/configuration/__init__.py @@ -5,10 +5,12 @@ from .factory import Factory from .fileloader import ROOT from .manager import ConfigurationManager, UnsupportedConfigurationRootError +from .named_value import NamedValue __all__ = [ "ConfigurationManager", "UnsupportedConfigurationRootError", "Factory", "ROOT", + "NamedValue", ] diff --git a/pyaml/configuration/named_value.py b/pyaml/configuration/named_value.py new file mode 100644 index 00000000..b4e25a7b --- /dev/null +++ b/pyaml/configuration/named_value.py @@ -0,0 +1,37 @@ +"""Reusable named values for object-based configuration.""" + +from typing import Any + +from ..common.exception import PyAMLConfigException +from ..validation import DynamicValidation, register_schema + +PYAMLCLASS = "NamedValue" + + +@register_schema +class NamedValue(DynamicValidation): + """Associate a nonempty name with a value without registering an element. + + The consuming class validates value types, allowed names and uniqueness. + Values are not coerced to a common scalar type. + A scalar, a one-item list and a multi-item list are all accepted; consumers + decide how list entries correspond to their configuration. + + Configuration + ------------- + .. code-block:: yaml + + - type: pyaml.configuration.named_value + name: gap + value: 4.0 + + - type: pyaml.configuration.named_value + name: gap + value: [4.0, 8.0] + """ + + def __init__(self, name: str, value: Any): + if not name.strip(): + raise PyAMLConfigException("NamedValue requires a nonempty name") + self.name = name + self.value = value diff --git a/pyaml/control/abstract_impl.py b/pyaml/control/abstract_impl.py index 4d1d3671..886fa37d 100644 --- a/pyaml/control/abstract_impl.py +++ b/pyaml/control/abstract_impl.py @@ -6,6 +6,8 @@ strengths, BPM readings, and RF quantities. """ +import time +from collections.abc import Mapping from typing import Any import numpy as np @@ -15,6 +17,8 @@ from .. import PyAMLException from ..common import abstract from ..common.abstract_aggregator import ScalarAggregator +from ..common.abstract_impl import RInsertionDeviceModelPoint +from ..common.exception import PyAMLConfigException from ..common.units import SI_ANGLE, SI_FREQUENCY, SI_POSITION, SI_TUNE, SI_VOLTAGE, common_unit from ..control.deviceaccess import DeviceAccess from ..control.deviceaccesslist import DeviceAccessList @@ -61,6 +65,137 @@ def _require_device(self) -> DeviceAccess: return self._device +class RWInsertionDeviceMode(abstract.RWInsertionDeviceMode): + """Expose an optional mode; the control system owns allowed transitions.""" + + def __init__(self, device: DeviceAccess): + self._device = device + + def get(self) -> str: + value = self._device.readback() + if isinstance(value, Value): + value = value.value + if not isinstance(value, str) or not value.strip(): + raise PyAMLException(f"{self._device.name()}: expected a nonempty string mode, got {value!r}") + return value + + def set(self, value: str) -> None: + if not isinstance(value, str) or not value.strip(): + raise PyAMLException(f"{self._device.name()}: expected a nonempty string mode, got {value!r}") + self._device.set(value) + + +class RWInsertionDeviceControlVariable(abstract.ReadWriteFloatScalar): + """Write gap/phase variables with movement flags or currents without them.""" + + def __init__(self, device: DeviceAccess, unit: str, moving: abstract.RWBooleanScalar | None = None): + if device.unit() != unit: + raise PyAMLConfigException( + f"{device.name()}: backend unit {device.unit()!r} does not match configured unit {unit!r}" + ) + self._device = device + self._unit = unit + self.moving = moving + + def get(self) -> float: + """Return the requested setpoint.""" + return float(self._device.get()) + + def readback(self) -> float: + """Return the measured control-variable value.""" + return float(self._device.readback()) + + def unit(self) -> str: + return self._unit + + def get_range(self) -> list[float | None]: + return self._device.get_range() + + def set(self, value: float) -> None: + if not check_range(value, self.get_range()): + raise PyAMLException(format_out_of_range_message(value, self._device)) + self._device.set(value) + + def set_and_wait(self, value: float) -> None: + """Set a gap or phase/shift variable and wait while its movement flag is true.""" + if self.moving is None: + raise PyAMLException( + f"{self._device.name()}: set_and_wait requires a movement_flag; use set() for current variables" + ) + self.set(value) + while self.moving.get(): + time.sleep(0.1) + + +class RWInsertionDeviceEnabled(abstract.RWBooleanScalar): + """Apply live operating points and retain pyAML's logical enabled state.""" + + def __init__( + self, + name: str, + control_variables: Mapping[str, RWInsertionDeviceControlVariable | None], + point: RInsertionDeviceModelPoint | None, + disabled_point: Mapping[str, float] | None, + mode: RWInsertionDeviceMode | None, + ): + self._name = name + self._control_variables = dict(control_variables) + self._point = point + self._disabled_point = dict(disabled_point) if disabled_point is not None else None + self._mode = mode + self._enabled = True + if self._disabled_point: + variables = self._variables(self._disabled_point) + self._enabled = not all(variable.get() == target for _, variable, target in variables) + + def get(self) -> bool: + """Return logical state, not measured completion or external changes.""" + return self._enabled + + def _variables(self, targets: Mapping[str, float]) -> list[tuple[str, RWInsertionDeviceControlVariable, float]]: + variables = [] + for name, target in targets.items(): + variable = self._control_variables.get(name) + if variable is None: + raise PyAMLException(f"{self._name}.{name}: control variable is unavailable") + variables.append((name, variable, target)) + return variables + + def set(self, value: bool) -> None: + if not isinstance(value, bool): + raise PyAMLException(f"{self._name}: expected a boolean enabled state, got {value!r}") + mode = None + if value: + if self._point is None or not set(self._control_variables).issubset(self._point): + raise PyAMLException( + f"{self._name}: model_operating_point must include every configured control variable to enable" + ) + targets = {} + for name in self._control_variables: + target = self._point[name] + if not isinstance(target, (int, float)): + raise PyAMLException(f"{self._name}.{name}: numeric model reference is required") + targets[name] = float(target) + if self._mode is not None: + mode = self._point.mode + if mode is None: + raise PyAMLException(f"{self._name}: model_operating_point must include mode to enable") + else: + if not self._disabled_point: + raise PyAMLException(f"{self._name}: disabled_operating_point is required to disable") + targets = self._disabled_point + variables = self._variables(targets) + for name, variable, target in variables: + limits = variable.get_range() + if not check_range(target, limits): + raise PyAMLException(f"{self._name}.{name}: value {target!r} is out of range {limits}") + for _, variable, target in variables: + variable.set(target) + if mode is not None and self._mode is not None: + self._mode.set(mode) + self._enabled = value + + def check_range(values: Any, dev_range: Any) -> bool: """ Check whether values are within given ranges. diff --git a/pyaml/control/controlsystem.py b/pyaml/control/controlsystem.py index 91f7bc39..374cbc4d 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -12,7 +12,7 @@ from pyaml.diagnostics.bpm import BPM -from ..common.abstract import RWMapper +from ..common.abstract import ReadWriteFloatScalar, RWMapper from ..common.abstract_aggregator import ScalarAggregator from ..common.exception import PyAMLConfigException, PyAMLException from ..common.holders.element_holder import ElementHolder @@ -31,6 +31,9 @@ RWBpmTiltScalar, RWHardwareArray, RWHardwareScalar, + RWInsertionDeviceControlVariable, + RWInsertionDeviceEnabled, + RWInsertionDeviceMode, RWRFFrequencyScalar, RWRFPhaseScalar, RWRFVoltageScalar, @@ -40,6 +43,7 @@ ) from ..diagnostics.atune_monitor import ABetatronTuneMonitor from ..diagnostics.tune_monitor import BetatronTuneMonitor +from ..insertion_device import InsertionDevice from ..magnet.cfm_magnet import CombinedFunctionMagnet from ..magnet.magnet import Magnet from ..magnet.serialized_magnet import SerializedMagnets @@ -282,6 +286,25 @@ def create_bpm_aggregators(self, bpms: list[BPM]) -> list[ScalarAggregator | Non aggv.add_devices(devs[1]) return [agg, aggh, aggv] + def _fill_insertion_device(self, device: InsertionDevice) -> None: + """Bind named control variables and optional controls through backend references.""" + control_variables: dict[str, RWInsertionDeviceControlVariable | None] = {} + for name, definition in device._control_variable_definitions.items(): + if "backend" not in definition: + control_variables[name] = None + continue + backend = self.get_device_access(definition["backend"]) + moving = ( + RWBooleanScalar(self.get_device_access(definition["movement_flag"])) if "movement_flag" in definition else None + ) + control_variables[name] = RWInsertionDeviceControlVariable(backend, definition["unit"], moving) + flags = {name: RWBooleanScalar(self.get_device_access(ref)) for name, ref in device.flag_references.items()} + mode = RWInsertionDeviceMode(self.get_device_access(device.control_mode)) if device.control_mode is not None else None + enabled = RWInsertionDeviceEnabled( + device.name, control_variables, device.model_operating_point, device.disabled_operating_point, mode + ) + self.insertion_device.add(device.attach(self, control_variables, enabled=enabled, flags=flags, mode=mode)) + def _fill_magnet(self, magnet: Magnet) -> None: device = self.get_si_device_access(magnet.model.get_device_names()[0], _hardware_unit(magnet.model)) current = RWHardwareScalar(magnet.model, device) if magnet.model.has_hardware() else None diff --git a/pyaml/insertion_device/__init__.py b/pyaml/insertion_device/__init__.py new file mode 100644 index 00000000..4cfd62d3 --- /dev/null +++ b/pyaml/insertion_device/__init__.py @@ -0,0 +1,10 @@ +"""Insertion-device elements.""" + +from ..validation import SchemaRegistry +from ..validation.schema_builder import generate_configuration_schema +from .control_variable import ControlVariable +from .insertion_device import PYAMLCLASS, InsertionDevice + +__all__ = ["InsertionDevice", "ControlVariable"] + +SchemaRegistry().register(f"{__name__}.InsertionDevice", generate_configuration_schema(InsertionDevice)) diff --git a/pyaml/insertion_device/control_variable.py b/pyaml/insertion_device/control_variable.py new file mode 100644 index 00000000..8ba32956 --- /dev/null +++ b/pyaml/insertion_device/control_variable.py @@ -0,0 +1,26 @@ +"""Named insertion-device control-variable configuration.""" + +from ..common.exception import PyAMLConfigException +from ..validation import DynamicValidation, register_schema + +PYAMLCLASS = "ControlVariable" + + +@register_schema +class ControlVariable(DynamicValidation): + """Configure one scalar coordinate without registering an accelerator element. + + ``backend`` and optional boolean ``movement_flag`` are opaque references + resolved by the control-system backend. ``unit`` is the coordinate unit. + """ + + def __init__(self, name: str, unit: str, backend: str | None = None, movement_flag: str | None = None): + if not name.strip() or not unit.strip(): + raise PyAMLConfigException("Each control variable requires a name and unit") + for field, value in (("backend", backend), ("movement_flag", movement_flag)): + if value is not None and not value.strip(): + raise PyAMLConfigException(f"{name}: {field} must not be empty") + self.name = name + self.unit = unit + self.backend = backend + self.movement_flag = movement_flag diff --git a/pyaml/insertion_device/insertion_device.py b/pyaml/insertion_device/insertion_device.py new file mode 100644 index 00000000..a2f975c6 --- /dev/null +++ b/pyaml/insertion_device/insertion_device.py @@ -0,0 +1,410 @@ +"""Insertion-device holding class, independent of facility control systems. + +Object-based configuration (the lattice already contains the kickmap):: + + - type: pyaml.insertion_device + name: APPLE01 + device_id: APPLE01_SERIAL + lattice_names: ID02 + description: Kickmap measured at 4 mm gap and zero phase. + control_variables: + - type: pyaml.insertion_device.control_variable + name: gap + unit: mm + backend: APPLE01_GAP + movement_flag: APPLE01_GAP_MOVING + - type: pyaml.insertion_device.control_variable + name: phase + unit: mm + backend: APPLE01_PHASE + movement_flag: APPLE01_MOVING + control_mode: APPLE01_MODE + model_operating_point: + - type: pyaml.configuration.named_value + name: gap + value: 4.0 + - type: pyaml.configuration.named_value + name: phase + value: 0.0 + - type: pyaml.configuration.named_value + name: mode + value: parallel + disabled_operating_point: + - type: pyaml.configuration.named_value + name: gap + value: 30.0 + - type: pyaml.configuration.named_value + name: phase + value: 0.0 + orbit_feedforward: ID01_ORBIT_FF + +Runtime ``control_variables`` use existing pyAML scalar accessors. An absent key +means no configured variable; None means configured but unavailable. +Both backends expose ReadWriteFloatScalar accessors; the fixed model rejects +control-variable writes. + +Live control variables bind through opaque backend references. ``get()`` reads +the requested setpoint; ``readback()`` reads the measured value. Without a backend +reference a variable remains unavailable. Gap and phase/shift variables use +``set_and_wait()`` with a configured boolean movement flag. PS1 and other current +controls have no movement flags and use plain ``set()``. Sequencing and interlocks +remain control-system concerns. +FFWD objects own their correctors, controls and measurements. + +The same class supports phase-only devices (including a fixed gap in the model +reference) and electromagnetic devices with arbitrarily named current variables. +The equivalent object-based configuration is:: + + - type: pyaml.insertion_device + name: EM01 + device_id: EM01_SERIAL + lattice_names: ID03 + control_variables: + - type: pyaml.insertion_device.control_variable + name: ps1 + unit: A + backend: EM01_PS1 + - type: pyaml.insertion_device.control_variable + name: ps2 + unit: A + backend: EM01_PS2 + - type: pyaml.insertion_device.control_variable + name: ps3 + unit: A + backend: EM01_PS3 + model_operating_point: + - type: pyaml.configuration.named_value + name: ps1 + value: 100.0 + - type: pyaml.configuration.named_value + name: ps2 + value: 0.0 + - type: pyaml.configuration.named_value + name: ps3 + value: 0.0 + +After retrieving a device through ``sr.live.insertion_device.get(name)``, use +``device.control_variables["gap"].set_and_wait(12.0)`` for gap or phase/shift +motion, or ``device.control_variables["ps1"].set(100.0)`` for a current control +without a movement flag. For gap and phase/shift motion, waiting only polls the +boolean flag until false: no readback tolerance, moving edge detection, or +timeout policy is added. Without a movement flag, ``set_and_wait()`` raises +before writing. Backend errors propagate unchanged. +Optional controls use ``device.mode.get()/set(value)`` and +``device.flags[name].get()/set(value)``; the latter reuse ``RWBooleanScalar``. + +Both holders expose ``device.enable()``, ``device.disable()`` and the boolean +``device.enabled.get()/set(value)`` accessor. Live enable applies the configured +model point; disable applies ``disabled_operating_point``, a nonempty subset of +the configured control variables. Targets and bindings are checked before writes. +Writes follow configuration order, with mode last on enable; they do not wait +for motion or provide atomicity. Sequencing and interlocks remain backend concerns. +The logical state initially reflects an exact match of requested setpoints to +the disabled point (otherwise enabled). It changes only after successful +enable/disable commands, not after external changes or direct variable writes. + +In a simulator, variable reads report the configured reference point and all +control-variable writes raise an error. Disable delegates to pyAT's same-length +drift/identity approximation; enable restores the kickmap. Neither changes the +reference point or any hardware. ``model_reference`` exposes reference metadata, +including kickmap filenames when attached to a simulator. +Without named working points, ``model_operating_point`` exposes the same +read-only ``RInsertionDeviceModelPoint`` in live and simulator holders. + +For multiple stored kickmaps, configure aligned columns using NamedValue:: + + model_working_points: + - type: pyaml.configuration.named_value + name: name + value: [LH_gap4, LV_gap8] + - type: pyaml.configuration.named_value + name: gap + value: [4.0, 8.0] + - type: pyaml.configuration.named_value + name: phase + value: [0.0, 10.0] + - type: pyaml.configuration.named_value + name: mode + value: [parallel, antiparallel] + +Each name must match a stored pyAT kickmap key on every linked segment. Users +are responsible for the correspondence between coordinates and kickmap physics. +The lattice's active key must initially match a configured point. Every list +must match the number of names; scalars apply to all points. Selection is +explicit via ``device.use_working_point("LV_gap8")``, with names available from +``list_working_points()`` and the current key from ``active_working_point``. +Simulator reads, fixed ranges and reference metadata follow the selected point. +Selection preserves ON/OFF state and segment lengths, does not interpolate, and +never changes another holder or the single live ``model_operating_point``. +""" + +import copy +import math +from collections.abc import Mapping +from types import MappingProxyType +from typing import TYPE_CHECKING, Self + +from ..common import abstract +from ..common.abstract_impl import RInsertionDeviceModelPoint +from ..common.element import Element +from ..common.exception import PyAMLConfigException, PyAMLException +from ..configuration.named_value import NamedValue +from ..validation import DynamicValidation, register_schema +from .control_variable import ControlVariable + +if TYPE_CHECKING: + from ..common.holders.element_holder import ElementHolder + from ..lattice.abstract_impl import InsertionDeviceWorkingPoints + +PYAMLCLASS = "InsertionDevice" + + +@register_schema +class InsertionDevice(Element, DynamicValidation): + """Hold control variables and references to other pyAML elements. + + ``control_variables`` is a list of named :class:`ControlVariable` objects + configuring units and opaque backend references. + Live control variables are always read/write. Gap and phase/shift variables may + configure a ``movement_flag`` for ``set_and_wait()``. Current controls have + no movement flags and use ``set()``. + After attachment, the same attribute exposes the bound scalar accessors. + At least one named variable is required, but no particular gap, phase or + current channel is mandatory. + ``model_operating_point`` is a list of :class:`~pyaml.configuration.named_value.NamedValue` objects: + numeric coordinates and optional string ``mode``. Names must be unique in + each list. Missing coordinates never imply zero. Additional provenance may + be recorded in the free-form ``description``. + + ``control_mode`` and boolean ``flags`` are opaque backend references. + ``orbit_feedforward`` and ``tune_feedforward`` reference existing elements + in the same holder, resolved after attachment. Runtime ``mode`` and ``flags`` + expose the optional backend controls. + ``disabled_operating_point`` lists named numeric live resting setpoints. Enable uses + ``model_operating_point``; neither command modifies that fixed reference. + + ``model_working_points`` uses NamedValue columns: ``name`` contains kickmap + keys, and coordinate/mode lists align with those keys by index. Every list + must have the same length; scalar coordinates apply to every point. + Select explicitly with ``use_working_point(name)``. Simulator reads follow + selection; live enable still uses the single ``model_operating_point``. + """ + + def __init__( + self, + name: str, + device_id: str, + control_variables: list[ControlVariable] | None = None, + control_mode: str | None = None, + flags: dict[str, str] | None = None, + orbit_feedforward: str | None = None, + tune_feedforward: str | None = None, + model_operating_point: list[NamedValue] | None = None, + lattice_names: str | None = None, + description: str | None = None, + disabled_operating_point: list[NamedValue] | None = None, + model_working_points: list[NamedValue] | None = None, + ): + super().__init__(name, lattice_names, description) + if not device_id.strip(): + raise PyAMLConfigException(f"{name}: device_id must not be empty") + if not control_variables: + raise PyAMLConfigException(f"{name}: at least one control variable is required") + for field, entries in ( + ("control_variables", control_variables), + ("model_operating_point", model_operating_point), + ("disabled_operating_point", disabled_operating_point), + ("model_working_points", model_working_points), + ): + if entries is not None and len({entry.name for entry in entries}) != len(entries): + raise PyAMLConfigException(f"{name}: duplicate names in {field}") + definitions = { + entry.name: { + "unit": entry.unit, + **({"backend": entry.backend} if entry.backend is not None else {}), + **({"movement_flag": entry.movement_flag} if entry.movement_flag is not None else {}), + } + for entry in control_variables + } + model_values = ( + {entry.name: entry.value for entry in model_operating_point} if model_operating_point is not None else None + ) + disabled_values = ( + {entry.name: entry.value for entry in disabled_operating_point} if disabled_operating_point is not None else None + ) + if any(not key.strip() or not value.strip() for key, value in (flags or {}).items()): + raise PyAMLConfigException(f"{name}: flag names and references must not be empty") + if control_mode is not None and not control_mode.strip(): + raise PyAMLConfigException(f"{name}: control_mode must not be empty") + self._validate_model_values(name, model_values or {}) + units = {key: definition["unit"] for key, definition in definitions.items()} + working_points = {} + if model_working_points is not None: + columns = {entry.name: entry.value for entry in model_working_points} + names = columns.pop("name", None) + if isinstance(names, str): + names = [names] + if not isinstance(names, list) or not names or not all(isinstance(key, str) and key.strip() for key in names): + raise PyAMLConfigException(f"{name}: model_working_points requires nonempty string names") + if len(set(names)) != len(names): + raise PyAMLConfigException(f"{name}: duplicate working-point names") + if not set(definitions).issubset(columns): + raise PyAMLConfigException(f"{name}: working points must include every configured control variable") + if control_mode is not None and "mode" not in columns: + raise PyAMLConfigException(f"{name}: working points must include mode") + for key, values in columns.items(): + if isinstance(values, list) and len(values) != len(names): + raise PyAMLConfigException(f"{name}.{key}: working-point lists must match the number of names") + for index, key in enumerate(names): + values = { + coordinate: column[index] if isinstance(column, list) else column for coordinate, column in columns.items() + } + self._validate_model_values(f"{name}.{key}", values) + working_points[key] = RInsertionDeviceModelPoint(values, units) + if disabled_values is not None: + if not disabled_values: + raise PyAMLConfigException(f"{name}: disabled_operating_point must not be empty") + for key, value in disabled_values.items(): + if key not in definitions: + raise PyAMLConfigException( + f"{name}.{key}: disabled_operating_point requires a configured control variable" + ) + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise PyAMLConfigException(f"{name}.{key}: disabled_operating_point requires a finite setpoint") + self.device_id = device_id + self.control_mode = control_mode + self.orbit_feedforward_name = orbit_feedforward + self.tune_feedforward_name = tune_feedforward + self._control_variable_definitions = definitions + self._flag_refs = dict(flags or {}) + self._disabled_point = disabled_values + self._point = RInsertionDeviceModelPoint(model_values, units) if model_values is not None else None + self._working_points = MappingProxyType(working_points) + self._working_point_selection: InsertionDeviceWorkingPoints | None = None + self._control_variables: dict[str, abstract.ReadWriteFloatScalar | None] = dict.fromkeys( + self._control_variable_definitions + ) + self._flags: dict[str, abstract.RWBooleanScalar | None] = dict.fromkeys(self._flag_refs) + self.mode: abstract.RWInsertionDeviceMode | None = None + self.orbit_feedforward: Element | None = None + self.tune_feedforward: Element | None = None + self._enabled: abstract.RWBooleanScalar | None = None + self._model_maps: tuple[str | None, ...] = () + + @staticmethod + def _validate_model_values(name: str, values: Mapping[str, object]) -> None: + for key, value in values.items(): + valid = ( + isinstance(value, str) and bool(value.strip()) + if key == "mode" + else isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) + ) + if not valid: + raise PyAMLConfigException(f"{name}.{key}: expected a finite coordinate or string mode") + + def list_working_points(self) -> list[str]: + """Return configured simulator working-point names.""" + return list(self._working_points) + + @property + def active_working_point(self) -> str | None: + """Return the selected simulator point, or None for live/legacy access.""" + return self._working_point_selection.active if self._working_point_selection is not None else None + + def use_working_point(self, name: str) -> None: + """Select a stored simulator point without changing enabled state. + + Every segment must contain the key and retain its length. Live and + unattached selection is unsupported and never writes hardware. + """ + if self._working_point_selection is None: + raise PyAMLException(f"{self.name}: named working-point selection requires simulator attachment") + self._working_point_selection.use(name) + + @property + def control_variables(self) -> Mapping[str, abstract.ReadWriteFloatScalar | None]: + """Bound scalar accessors, or None for configured but unavailable variables.""" + return MappingProxyType(self._control_variables) + + @property + def flags(self) -> Mapping[str, abstract.RWBooleanScalar | None]: + """Boolean backend controls, or None when unavailable in this holder.""" + return MappingProxyType(self._flags) + + @property + def flag_references(self) -> Mapping[str, str]: + return MappingProxyType(self._flag_refs) + + @property + def model_operating_point(self) -> RInsertionDeviceModelPoint | None: + """Active simulator point, or the configured legacy/live reference.""" + if self._working_point_selection is not None: + return self._working_point_selection.point + return self._point + + @property + def disabled_operating_point(self) -> Mapping[str, float] | None: + """Configured live resting setpoints.""" + return MappingProxyType(self._disabled_point) if self._disabled_point is not None else None + + @property + def model_reference(self) -> dict: + """Return a snapshot of model settings and provenance, never live values.""" + point = self.model_operating_point + reference = { + "device_id": self.device_id, + "description": self.description, + "operating_point": dict(point) if point is not None else None, + "units": dict(point.units) if point is not None else {}, + "maps": self._working_point_selection.maps if self._working_point_selection is not None else self._model_maps, + } + if self._working_point_selection is not None: + reference["working_point"] = self.active_working_point + return reference + + @property + def enabled(self) -> abstract.RWBooleanScalar: + """Logical enabled-state accessor for this holder.""" + if self._enabled is None: + raise PyAMLException(f"{self.name}: enabled state is unavailable before attachment") + return self._enabled + + def enable(self) -> None: + """Apply the live model point or restore design kickmap tracking.""" + self.enabled.set(True) + + def disable(self) -> None: + """Apply live resting setpoints or disable design kickmap tracking.""" + self.enabled.set(False) + + def attach( + self, + peer: "ElementHolder", + control_variables: Mapping[str, abstract.ReadWriteFloatScalar | None] | None = None, + enabled: abstract.RWBooleanScalar | None = None, + flags: Mapping[str, abstract.RWBooleanScalar | None] | None = None, + mode: abstract.RWInsertionDeviceMode | None = None, + model_maps: tuple[str | None, ...] = (), + working_point_selection: "InsertionDeviceWorkingPoints | None" = None, + ) -> Self: + """Return a per-peer copy; defaults give metadata-only access.""" + obj = copy.copy(self) + obj._peer = peer + obj._control_variables = ( + dict(control_variables) if control_variables is not None else dict.fromkeys(self._control_variable_definitions) + ) + obj._flags = dict(flags) if flags is not None else dict.fromkeys(self._flag_refs) + obj.mode = mode + obj.orbit_feedforward = obj.tune_feedforward = None + obj._enabled = enabled + obj._model_maps = model_maps + obj._working_point_selection = working_point_selection + return obj + + def _fill_device(self, holder: "ElementHolder") -> None: + holder._fill_insertion_device(self) + + def post_init(self) -> None: + self.check_peer() + self.orbit_feedforward = self.peer[self.orbit_feedforward_name] if self.orbit_feedforward_name is not None else None + self.tune_feedforward = self.peer[self.tune_feedforward_name] if self.tune_feedforward_name is not None else None diff --git a/pyaml/lattice/abstract_impl.py b/pyaml/lattice/abstract_impl.py index d8c7cdc8..12016698 100644 --- a/pyaml/lattice/abstract_impl.py +++ b/pyaml/lattice/abstract_impl.py @@ -11,6 +11,8 @@ they never change the lattice elements' bending angles. """ +from collections.abc import Callable, Mapping + import at import numpy as np from numpy.typing import NDArray @@ -18,6 +20,7 @@ from ..common import abstract from ..common.abstract_aggregator import ScalarAggregator +from ..common.abstract_impl import RInsertionDeviceModelPoint from ..common.exception import PyAMLException from ..common.units import SI_ANGLE, SI_FREQUENCY, SI_POSITION, SI_TUNE, SI_VOLTAGE, common_unit from ..magnet.model import MagnetModel @@ -28,6 +31,160 @@ # ------------------------------------------------------------------------------ +class InsertionDeviceWorkingPoints: + """Select named kickmaps and coordinate references for one simulator holder.""" + + _tracking_fields = ( + "ActiveKickmap", + "Filename_in", + "Normalization_energy", + "Nslice", + "Length", + "xtable", + "ytable", + "xkick", + "ykick", + "xkick1", + "ykick1", + "PassMethod", + "_enable_passmethod", + ) + + def __init__( + self, + name: str, + kickmaps: list[at.InsertionDeviceKickMap], + points: Mapping[str, RInsertionDeviceModelPoint], + ): + self._name = name + self._kickmaps = tuple(kickmaps) + self._points = dict(points) + for element in self._kickmaps: + if not callable(getattr(element, "use_kickmap", None)) or not callable(getattr(element, "list_kickmaps", None)): + raise PyAMLException(f"{name}: named working points require pyAT's multi-kickmap API") + active = {element.active_kickmap for element in self._kickmaps} + if len(active) != 1: + raise PyAMLException(f"{name}: inconsistent active kickmap keys") + key = active.pop() + if key is None or key not in self._points: + raise PyAMLException(f"{name}: active kickmap must match a configured working point") + for point in self._points: + self._validate(point) + self.active = key + + @property + def point(self) -> RInsertionDeviceModelPoint: + return self._points[self.active] + + @property + def maps(self) -> tuple[str | None, ...]: + return tuple(getattr(element, "Filename_in", None) for element in self._kickmaps) + + def _validate(self, name: str) -> None: + if not isinstance(name, str) or name not in self._points: + raise PyAMLException(f"{self._name}: unknown working point {name!r}") + for element in self._kickmaps: + if name not in element.list_kickmaps(): + raise PyAMLException(f"{self._name}: kickmap {name!r} is missing from a linked segment") + candidate = element.deepcopy() + candidate.use_kickmap(name) + if candidate.Length != element.Length: + raise PyAMLException(f"{self._name}: working point {name!r} changes a segment length") + + def use(self, name: str) -> None: + self._validate(name) + snapshots = [ + {field: vars(element)[field] for field in self._tracking_fields if field in vars(element)} + for element in self._kickmaps + ] + try: + for element in self._kickmaps: + element.use_kickmap(name) + except Exception as error: + failures = [] + for element, snapshot in zip(self._kickmaps, snapshots, strict=True): + try: + # Restore tracking data directly: the failing native method cannot be relied on for rollback. + for field in self._tracking_fields: + vars(element).pop(field, None) + vars(element).update(snapshot) + except Exception as restoration_error: + failures.append(restoration_error) + if failures: + raise ExceptionGroup(f"{self._name}: working-point restoration failed", [error, *failures]) from error + raise + self.active = name + + +class RWInsertionDeviceControlVariable(abstract.ReadWriteFloatScalar): + """Expose the shared control-variable interface while rejecting model writes.""" + + def __init__(self, name: str, value: float | Callable[[], float], unit: str): + self._name = name + self._value = value + self._unit = unit + + def get(self) -> float: + return self._value() if callable(self._value) else self._value + + def readback(self) -> float: + """Return the model reference, not a hardware readback.""" + return self.get() + + def unit(self) -> str: + return self._unit + + def get_range(self) -> list[float]: + value = self.get() + return [value, value] + + def set(self, value: float) -> None: + raise PyAMLException(f"{self._name}: fixed model operating point does not support writes ({value!r})") + + def set_and_wait(self, value: float) -> None: + self.set(value) + + +class RWInsertionDeviceMode(abstract.RWInsertionDeviceMode): + """Expose the fixed reference mode through the shared mode interface.""" + + def __init__(self, name: str, mode: str | Callable[[], str]): + self._name = name + self._mode = mode + + def get(self) -> str: + return self._mode() if callable(self._mode) else self._mode + + def set(self, value: str) -> None: + if value != self.get(): + raise PyAMLException(f"{self._name}: fixed model operating point does not support mode {value!r}") + + +class RWInsertionDeviceEnabled(abstract.RWBooleanScalar): + """Toggle kickmap tracking and retain pyAML's logical enabled state.""" + + def __init__(self, name: str, kickmaps: list[at.InsertionDeviceKickMap]): + self._name = name + self._kickmaps = tuple(kickmaps) + states = {element.PassMethod not in ("DriftPass", "IdentityPass") for element in self._kickmaps} + if len(states) != 1: + raise PyAMLException(f"{self._name}: inconsistent kickmap enabled states") + self._enabled = states.pop() + + def get(self) -> bool: + return self._enabled + + def set(self, value: bool) -> None: + if not isinstance(value, bool): + raise PyAMLException(f"{self._name}: expected a boolean enabled state, got {value!r}") + for element in self._kickmaps: + if value: + element.enable() + else: + element.disable() + self._enabled = value + + class RWBooleanScalar(abstract.RWBooleanScalar): """Maintain an initially disabled boolean state independent of the lattice.""" diff --git a/pyaml/lattice/simulator.py b/pyaml/lattice/simulator.py index ac9b0806..41f605c0 100644 --- a/pyaml/lattice/simulator.py +++ b/pyaml/lattice/simulator.py @@ -19,10 +19,12 @@ from ..common.switch_element import SwitchElement from ..configuration import ROOT from ..diagnostics.tune_monitor import BetatronTuneMonitor +from ..insertion_device import InsertionDevice from ..lattice.abstract_impl import ( BPMHScalarAggregator, BPMScalarAggregator, BPMVScalarAggregator, + InsertionDeviceWorkingPoints, RBetatronTuneArray, RBpmArray, RWBooleanScalar, @@ -30,6 +32,9 @@ RWBpmTiltScalar, RWHardwareArray, RWHardwareScalar, + RWInsertionDeviceControlVariable, + RWInsertionDeviceEnabled, + RWInsertionDeviceMode, RWRFATFrequencyScalar, RWRFATotalVoltageScalar, RWRFFrequencyScalar, @@ -247,6 +252,45 @@ def create_bpm_aggregators(self, bpms: list[BPM]) -> list[ScalarAggregator]: aggv.add_elem(e) return [agg, aggh, aggv] + def _fill_insertion_device(self, device: InsertionDevice) -> None: + kickmaps = [] + for element in self.get_at_elems(device): + if not isinstance(element, at.InsertionDeviceKickMap): + raise PyAMLException(f"{device.name}: expected InsertionDeviceKickMap lattice elements") + kickmaps.append(element) + if not kickmaps: + raise PyAMLException(f"{device.name}: no insertion-device kickmaps found") + selection = ( + InsertionDeviceWorkingPoints(device.name, kickmaps, device._working_points) if device._working_points else None + ) + point = selection.point if selection is not None else device.model_operating_point + if point is None or not set(device.control_variables).issubset(point): + raise PyAMLException(f"{device.name}: model_operating_point must include every configured control variable") + mode = None + if device.control_mode is not None or (selection is not None and point.mode is not None): + if point.mode is None: + raise PyAMLException(f"{device.name}: model_operating_point must include mode") + mode = RWInsertionDeviceMode( + device.name, (lambda: str(selection.point["mode"])) if selection is not None else point.mode + ) + control_variables = {} + for name, definition in device._control_variable_definitions.items(): + value = point[name] + if not isinstance(value, (int, float)): + raise PyAMLException(f"{device.name}.{name}: numeric model reference is required") + control_variables[name] = RWInsertionDeviceControlVariable( + f"{device.name}.{name}", + (lambda name=name: float(selection.point[name])) if selection is not None else float(value), + definition["unit"], + ) + enabled = RWInsertionDeviceEnabled(device.name, kickmaps) + model_maps = tuple(getattr(element, "Filename_in", None) for element in kickmaps) + self.insertion_device.add( + device.attach( + self, control_variables, enabled=enabled, mode=mode, model_maps=model_maps, working_point_selection=selection + ) + ) + def _fill_magnet(self, magnet: Magnet) -> None: current = ( RWHardwareScalar(self.get_at_elems(magnet), magnet.polynom, magnet.model) if magnet.model.has_physics() else None diff --git a/tests/configuration/test_factory.py b/tests/configuration/test_factory.py index 692706bc..7e764ecf 100644 --- a/tests/configuration/test_factory.py +++ b/tests/configuration/test_factory.py @@ -2,9 +2,10 @@ from pyaml import PyAMLConfigException, PyAMLException from pyaml.accelerator import Accelerator -from pyaml.configuration import ROOT -from pyaml.configuration.factory import Factory +from pyaml.configuration import ROOT, NamedValue +from pyaml.configuration.factory import ELEMENT_REGISTRY, Factory from pyaml.configuration.fileloader import load +from pyaml.validation.validator import SchemaValidator from tests.conftest import MockElement @@ -16,6 +17,23 @@ def test_factory_build_default(): assert obj.name == "simple" +@pytest.mark.parametrize("value", [True, {"labels": ["a", "b"]}, 0.0, [1.0], [1.0, 1.5, 2.0]]) +def test_named_value_configuration(value): + obj = Factory.build( + SchemaValidator.validate_to_dict({"type": "pyaml.configuration.named_value", "name": "setting", "value": value}) + ) + assert isinstance(obj, NamedValue) + assert obj.name == "setting" + assert obj.value == value + assert type(obj.value) is type(value) + assert "setting" not in ELEMENT_REGISTRY + + +def test_named_value_requires_nonempty_name(): + with pytest.raises(PyAMLConfigException, match="nonempty name"): + NamedValue(" ", 4.0) + + @pytest.mark.parametrize( "test_file", [ diff --git a/tests/lattice/test_switch_simulator.py b/tests/lattice/test_switch_simulator.py index 75af445c..a3681f84 100644 --- a/tests/lattice/test_switch_simulator.py +++ b/tests/lattice/test_switch_simulator.py @@ -122,7 +122,7 @@ def test_accelerator_configuration_keeps_live_and_simulated_state_separate( "simulators": [{"type": "pyaml.lattice.simulator", "name": "design", "lattice": str(ebs_lattice_file)}], "devices": [ {"class": "pyaml.common.switch_element.SwitchElement", "name": "SOFB", "device": device_name}, - {"type": "pyaml.diagnostics.bpm.bpm", "name": "BPM_C04-01"}, + {"type": "pyaml.diagnostics.bpm", "name": "BPM_C04-01"}, ], } config_path = tmp_path / "switch.yaml" diff --git a/tests/test_insertion_device.py b/tests/test_insertion_device.py new file mode 100644 index 00000000..84e74af6 --- /dev/null +++ b/tests/test_insertion_device.py @@ -0,0 +1,770 @@ +import copy +from unittest.mock import Mock, patch + +import at +import numpy as np +import pytest + +from pyaml import PyAMLConfigException, PyAMLException +from pyaml.accelerator import Accelerator +from pyaml.common import abstract +from pyaml.common.abstract_impl import RInsertionDeviceModelPoint +from pyaml.common.element import Element +from pyaml.configuration import NamedValue +from pyaml.configuration.factory import ELEMENT_REGISTRY, Factory +from pyaml.control.abstract_impl import RWBooleanScalar +from pyaml.control.readback_value import Value +from pyaml.insertion_device import ControlVariable, InsertionDevice +from pyaml.lattice.simulator import Simulator +from pyaml.validation.validator import SchemaValidator + + +class _Feedforward(Element): + def _fill_device(self, holder): + obj = copy.copy(self) + obj._peer = holder + holder.add_element(obj) + + +def _control(): + from tango.pyaml.attribute import Attribute + from tango.pyaml.attribute import ConfigModel as AttributeConfig + from tango.pyaml.attribute_store import set_attribute + from tango.pyaml.catalog import Catalog + from tango.pyaml.controlsystem import ConfigModel, TangoControlSystem + + set_attribute("GAP", 9.0, unit="mm", range=(2.0, 30.0), readback=8.0) + set_attribute("MOVING", False) + set_attribute("MODE", "parallel") + set_attribute("FF", True) + catalog = Mock(spec=Catalog) + catalog.resolve.side_effect = lambda ref: Attribute(AttributeConfig(attribute=ref)) + return TangoControlSystem(ConfigModel(name="live", catalog=catalog)) + + +@pytest.fixture +def id_lattice_file(tmp_path): + grid = np.linspace(-0.02, 0.02, 4) + data = { + "Length": 0.4, + "xtable": grid, + "ytable": grid, + "xkick": np.full((4, 4), 1.0e-4), + "ykick": np.full((4, 4), -2.0e-4), + "xkick1": np.zeros((4, 4)), + "ykick1": np.zeros((4, 4)), + } + kickmap = at.InsertionDeviceKickMap("MAP", 1, data, 3.0) + path = tmp_path / "ids.mat" + at.save_mat(at.Lattice([kickmap, kickmap.deepcopy(), at.Drift("D", 0.2)], energy=3.0e9), path) + return str(path) + + +@pytest.fixture +def working_point_lattice_file(id_lattice_file): + ring = at.load_lattice(id_lattice_file) + for element in ring[:2]: + data = { + field: getattr(element, field) for field in ("Length", "xtable", "ytable", "xkick", "ykick", "xkick1", "ykick1") + } + element.add_kickmap("first", 1, data, 3.0) + element.add_kickmap("second", 2, {**data, "xkick": data["xkick"] * 3.0}, 3.0) + element.use_kickmap("first") + at.save_mat(ring, id_lattice_file) + return id_lattice_file + + +def _working_points(**overrides): + columns = {"name": ["first", "second"], "gap": [4.0, 8.0], "phase": 0.0, "mode": ["parallel", "antiparallel"]} + columns.update(overrides) + return [NamedValue(name=name, value=value) for name, value in columns.items()] + + +def _device(**overrides): + config = { + "name": "ID", + "device_id": "SERIAL", + "control_variables": {"gap": {"unit": "mm", "backend": "GAP", "movement_flag": "MOVING"}}, + "lattice_names": "list(MAP)", + "model_operating_point": {"gap": 4.0}, + } + config.update(overrides) + if isinstance(config["control_variables"], dict): + config["control_variables"] = [ + ControlVariable(name=name, **definition) for name, definition in config["control_variables"].items() + ] + for field in ("model_operating_point", "disabled_operating_point"): + if isinstance(config.get(field), dict): + config[field] = [NamedValue(name=name, value=value) for name, value in config[field].items()] + return InsertionDevice(**config) + + +def _machine(path, devices=None, controls=None): + return Accelerator( + facility="TEST", + machine="sr", + energy=3.0e9, + simulators=[Simulator("design", path), Simulator("comparison", path)], + controls=[_control()] if controls is None else controls, + devices=devices or [], + ) + + +@pytest.mark.parametrize( + ("declaration", "control_variables", "point"), + [ + ({"type": "pyaml.insertion_device"}, {"gap": {"unit": "mm"}}, {"gap": 4.0}), + ( + {"class": "pyaml.insertion_device.InsertionDevice"}, + {"phase": {"unit": "mm"}}, + {"gap": 4.0, "phase": 0.0}, + ), + ( + {"class_path": "pyaml.insertion_device.insertion_device.InsertionDevice"}, + {"gap": {"unit": "mm"}, "parallel": {"unit": "mm"}, "antiparallel": {"unit": "mm"}}, + {"gap": 4.0, "parallel": 1.0, "antiparallel": 0.0, "mode": "parallel"}, + ), + ( + {"type": "pyaml.insertion_device"}, + {"ps1": {"unit": "A"}, "ps2": {"unit": "A"}}, + {"ps1": 100.0, "ps2": 0.0}, + ), + ], +) +def test_configuration_supports_control_variable_families(id_lattice_file, declaration, control_variables, point): + from tango.pyaml.attribute_store import set_attribute + + control = _control() + for name, definition in control_variables.items(): + set_attribute(name, 0.0, unit=definition["unit"], range=(-200.0, 200.0), readback=0.0) + config = { + **declaration, + "name": "ID", + "device_id": "SERIAL", + "lattice_names": "list(MAP)", + "control_variables": [ + {"type": "pyaml.insertion_device.control_variable", "name": name, "backend": name, **definition} + for name, definition in control_variables.items() + ], + "model_operating_point": [ + {"type": "pyaml.configuration.named_value", "name": name, "value": value} for name, value in point.items() + ], + "disabled_operating_point": [ + {"type": "pyaml.configuration.named_value", "name": name, "value": 0.0} for name in control_variables + ], + } + device = Factory.build(SchemaValidator.validate_to_dict(config)) + simulator = Simulator("design", id_lattice_file) + simulator.fill_device([device]) + control.fill_device([device]) + attached = simulator.insertion_device.get("ID") + live = control.insertion_device.get("ID") + assert set(attached.control_variables) == set(control_variables) + assert set(live.control_variables) == set(control_variables) + for name, definition in control_variables.items(): + assert attached.control_variables[name].get() == point[name] + assert attached.control_variables[name].unit() == definition["unit"] + variable = live.control_variables[name] + variable.set(5.0) + assert variable.get() == 5.0 + assert variable.readback() == 0.0 + assert variable.unit() == definition["unit"] + assert live.mode is None + assert live.flags == {} + assert attached.model_reference["operating_point"] == point + assert attached.disabled_operating_point == {name: 0.0 for name in control_variables} + assert device.peer is None + assert "gap" not in ELEMENT_REGISTRY + assert "phase" not in ELEMENT_REGISTRY + + +@pytest.mark.parametrize( + ("overrides", "error"), + [ + ({"control_variables": {}}, "at least one control variable"), + ({"control_variables": {"gap": {"unit": ""}}}, "requires a name and unit"), + ({"control_variables": {"gap": {"unit": "mm", "backend": ""}}}, "backend must not be empty"), + ({"model_operating_point": {"gap": float("inf")}}, "finite coordinate"), + ({"disabled_operating_point": {"missing": 0.0}}, "requires a configured control variable"), + ({"disabled_operating_point": {"gap": float("nan")}}, "finite setpoint"), + ({"disabled_operating_point": {"gap": True}}, "finite setpoint"), + ({"model_operating_point": {"gap": True}}, "finite coordinate"), + ({"model_operating_point": {"gap": "4.0"}}, "finite coordinate"), + ({"model_operating_point": {"gap": 4.0, "mode": 1.0}}, "string mode"), + ( + {"control_variables": [ControlVariable("gap", "mm"), ControlVariable("gap", "mm")]}, + "duplicate names in control_variables", + ), + ( + {"model_operating_point": [NamedValue("gap", 4.0), NamedValue("gap", 5.0)]}, + "duplicate names in model_operating_point", + ), + ], +) +def test_invalid_configuration_is_rejected(overrides, error): + with pytest.raises(PyAMLConfigException, match=error): + _device(**overrides) + + +@pytest.mark.parametrize( + ("overrides", "error"), + [ + ({"model_operating_point": {}}, "include every configured control variable"), + ({"control_mode": "MODE"}, "include mode"), + ({"lattice_names": "list(D)"}, "expected InsertionDeviceKickMap"), + ], +) +def test_invalid_model_binding_does_not_register_device(id_lattice_file, overrides, error): + simulator = Simulator("design", id_lattice_file) + with pytest.raises(PyAMLException, match=error): + simulator.fill_device([_device(**overrides)]) + assert not simulator.insertion_device.all() + assert all(element.PassMethod == "IdTablePass" for element in simulator.ring[:2]) + + +def test_holder_registration_associations_and_add_rollback(id_lattice_file): + machine = _machine(id_lattice_file) + machine.add(_Feedforward("ORBIT_FF")) + machine.add(_Feedforward("TUNE_FF")) + source = _device(orbit_feedforward="ORBIT_FF", tune_feedforward="TUNE_FF", description="Measured fixed kickmap") + machine.add(source) + copies = [] + for holder in machine.modes().values(): + device = holder.insertion_device.get("ID") + assert type(device) is InsertionDevice + assert isinstance(device.enabled, abstract.RWBooleanScalar) + copies.append(device) + assert holder["ID"] is device + assert holder.insertion_device.all() == [device] + assert device.device_id == "SERIAL" + assert device.orbit_feedforward is holder["ORBIT_FF"] + assert device.tune_feedforward is holder["TUNE_FF"] + assert len({id(device) for device in copies}) == len(copies) + assert source.peer is None + assert source.orbit_feedforward is None + with pytest.raises(PyAMLException, match="MISSING"): + machine.add(_device(name="BAD_ID", orbit_feedforward="MISSING")) + for holder in machine.modes().values(): + assert "BAD_ID" not in holder._ALL + assert "BAD_ID" not in holder._INSERTION_DEVICES + machine.add(_device(name="BAD_ID")) + + +def test_live_attachment_binds_hardware_separately_from_model(id_lattice_file): + from tango.pyaml.attribute_store import set_attribute + + control = _control() + source = _device( + control_variables={ + "gap": {"unit": "mm", "backend": "GAP", "movement_flag": "MOVING"}, + "phase": {"unit": "mm"}, + }, + control_mode="MODE", + flags={"moving": "MOVING", "orbit_ff": "FF"}, + model_operating_point={ + "gap": 4.0, + "phase": 0.0, + "mode": "parallel", + }, + ) + with ( + patch.object(control, "get_device_access", wraps=control.get_device_access) as lookup, + patch.object(control, "get_aggregator", side_effect=AssertionError("ID must not create hardware aggregators")), + ): + machine = _machine(id_lattice_file, [source], controls=[control]) + assert {args[0] for args, _ in lookup.call_args_list} == {"GAP", "MOVING", "FF", "MODE"} + live = machine.live.insertion_device.get("ID") + design = machine.design.insertion_device.get("ID") + for device in (source, live, design): + with pytest.raises(PyAMLException, match="requires simulator attachment"): + device.use_working_point("first") + gap = live.control_variables["gap"] + assert isinstance(gap, abstract.ReadWriteFloatScalar) + assert gap.readback() == 8.0 + assert gap.get() == 9.0 + assert gap.get_range() == [2.0, 30.0] + assert live.control_variables["phase"] is None + assert "current" not in live.control_variables + assert isinstance(live.flags["moving"], RWBooleanScalar) + assert live.flags["moving"].get() is False + assert live.flags["orbit_ff"].get() is True + assert live.mode.get() == "parallel" + assert design.flags == {"moving": None, "orbit_ff": None} + point = live.model_operating_point + assert isinstance(point, RInsertionDeviceModelPoint) + assert point is design.model_operating_point is source.model_operating_point + assert dict(point) == {"gap": 4.0, "phase": 0.0, "mode": "parallel"} + assert point.units == {"gap": "mm", "phase": "mm"} + with pytest.raises(TypeError): + point["gap"] = 20.0 + with pytest.raises(TypeError): + point.units["gap"] = "m" + assert design.control_variables["gap"].unit() == live.control_variables["gap"].unit() == "mm" + reference = design.model_reference + gap.set_and_wait(12.0) + set_attribute("GAP", 12.0) + live.mode.set("antiparallel") + live.flags["orbit_ff"].set(False) + assert gap.get() == gap.readback() == 12.0 + assert live.mode.get() == "antiparallel" + assert live.flags["orbit_ff"].get() is False + assert design.control_variables["gap"].get() == 4.0 + assert design.control_variables["phase"].get() == 0.0 + assert design.mode.get() == "parallel" + with patch.object(control, "get_device_access", side_effect=AssertionError("Model must not access hardware")): + design.disable() + design.enable() + assert design.model_reference == reference + assert dict(point) == reference["operating_point"] + + +@pytest.mark.parametrize("moving_values", [[], [Value(True), Value(True)]]) +def test_set_and_wait_uses_only_boolean_movement_flag(monkeypatch, moving_values): + control = _control() + control.fill_device([_device()]) + variable = control.insertion_device.get("ID").control_variables["gap"] + backend = control.get_device_access("GAP") + moving = control.get_device_access("MOVING") + sleep = Mock() + monkeypatch.setattr("pyaml.control.abstract_impl.time.sleep", sleep) + with ( + patch.object(backend, "set", wraps=backend.set) as write, + patch.object(backend, "set_and_wait", side_effect=AssertionError("Must not use backend completion logic")), + patch.object(moving, "readback", side_effect=[*moving_values, Value(False)]), + ): + variable.set_and_wait(12.0) + write.assert_called_once_with(12.0) + assert sleep.call_count == len(moving_values) + assert backend.get() == 12.0 + + +def test_set_and_wait_without_flag_does_not_write(): + from tango.pyaml.attribute_store import set_attribute + + set_attribute("CURRENT", 0.0, unit="A", range=(-100.0, 100.0)) + control = _control() + control.fill_device([_device(control_variables={"current": {"unit": "A", "backend": "CURRENT"}})]) + variable = control.insertion_device.get("ID").control_variables["current"] + with pytest.raises(PyAMLException, match="requires a movement_flag"): + variable.set_and_wait(12.0) + assert variable.get() == 0.0 + + +def test_limits_and_backend_errors_are_propagated(): + control = _control() + control.fill_device([_device(control_mode="MODE", flags={"ff": "FF"})]) + device = control.insertion_device.get("ID") + gap = device.control_variables["gap"] + for method in (gap.set, gap.set_and_wait): + with pytest.raises(PyAMLException, match="out of range"): + method(40.0) + assert gap.get() == 9.0 + for ref, write, value in ( + ("GAP", gap.set_and_wait, 12.0), + ("MODE", device.mode.set, "antiparallel"), + ("FF", device.flags["ff"].set, False), + ): + error = RuntimeError(f"{ref}: interlocked") + with patch.object(control.get_device_access(ref), "set", side_effect=error): + with pytest.raises(RuntimeError) as caught: + write(value) + assert caught.value is error + error = RuntimeError("Cannot read movement flag") + with patch.object(control.get_device_access("MOVING"), "readback", side_effect=error): + with pytest.raises(RuntimeError) as caught: + gap.set_and_wait(12.0) + assert caught.value is error + + +def test_unit_mismatch_does_not_register_device(): + control = _control() + with pytest.raises(PyAMLConfigException, match="does not match"): + control.fill_device([_device(control_variables={"gap": {"unit": "A", "backend": "GAP"}})]) + assert not control.insertion_device.all() + + +def test_boolean_scalar_reads_writes_and_rejects_nonboolean_values(): + control = _control() + backend = control.get_device_access("FF") + flag = RWBooleanScalar(backend) + flag.set(False) + assert flag.get() is False + with patch.object(backend, "readback", return_value=True): + assert flag.get() is True + with pytest.raises(PyAMLException, match="boolean flag"): + flag.set("off") + with patch.object(backend, "readback", return_value="off"): + with pytest.raises(PyAMLException, match="boolean flag"): + flag.get() + + +def test_fixed_reference_rejects_control_variable_writes(id_lattice_file): + machine = _machine(id_lattice_file, [_device(control_mode="MODE", model_operating_point={"gap": 4.0, "mode": "parallel"})]) + device = machine.design.insertion_device.get("ID") + variable = device.control_variables["gap"] + reference = device.model_reference + assert variable.readback() == variable.get() == 4.0 + assert variable.get_range() == [4.0, 4.0] + for disabled in (False, True): + if disabled: + device.disable() + device.mode.set("parallel") + for value in (4.0, 5.0, float("nan")): + for write in (variable.set, variable.set_and_wait): + with pytest.raises(PyAMLException, match="fixed model operating point"): + write(value) + with pytest.raises(PyAMLException, match="fixed model operating point"): + device.mode.set("antiparallel") + assert variable.get() == 4.0 + assert device.model_reference == reference + reference["operating_point"]["gap"] = 20.0 + assert device.model_reference["operating_point"]["gap"] == 4.0 + + +def test_model_on_off_preserves_split_maps_and_tracking(id_lattice_file): + machine = _machine(id_lattice_file, [_device()]) + device = machine.design.insertion_device.get("ID") + maps = machine.design.ring[:2] + original = [(element.PassMethod, element.Length, element.xkick.copy(), element.ykick.copy()) for element in maps] + reference = device.model_reference + assert reference["maps"] == tuple(getattr(element, "Filename_in", None) for element in maps) + particle = np.array([1.0e-3, 0.0, 2.0e-3, 0.0, 0.0, 0.0]) + enabled = at.lattice_track(machine.design.ring, particle.copy(), nturns=1)[0] + with pytest.raises(PyAMLException, match="boolean enabled state"): + device.enabled.set(1) + assert device.enabled.get() + device.disable() + device.enabled.set(False) + assert not device.enabled.get() + disabled = at.lattice_track(machine.design.ring, particle.copy(), nturns=1)[0] + drift = at.Lattice([at.Drift("D", sum(element.Length for element in machine.design.ring))], energy=3.0e9) + np.testing.assert_allclose(disabled, at.lattice_track(drift, particle.copy(), nturns=1)[0]) + assert not np.allclose(disabled, enabled, atol=1e-12, rtol=0) + assert machine.comparison.insertion_device.get("ID").enabled.get() + assert machine.live.insertion_device.get("ID").enabled.get() + device.enable() + device.enabled.set(True) + assert device.enabled.get() + np.testing.assert_allclose(at.lattice_track(machine.design.ring, particle.copy(), nturns=1)[0], enabled) + for element, (method, length, xkick, ykick) in zip(maps, original, strict=True): + assert element.PassMethod == method + assert element.Length == length + np.testing.assert_array_equal(element.xkick, xkick) + np.testing.assert_array_equal(element.ykick, ykick) + assert device.model_reference == reference + + +def test_live_enable_disable_apply_points_and_keep_logical_state(): + control = _control() + control.fill_device( + [ + _device( + control_mode="MODE", + model_operating_point={"gap": 4.0, "mode": "parallel"}, + disabled_operating_point={"gap": 30}, + ) + ] + ) + device = control.insertion_device.get("ID") + reference = device.model_reference + gap = device.control_variables["gap"] + assert device.enabled.get() is True + with pytest.raises(PyAMLException, match="boolean enabled state"): + device.enabled.set(1) + assert device.enabled.get() is True + gap.set(30.0) + assert device.enabled.get() is True + device.mode.set("antiparallel") + with patch.object(control.get_device_access("MOVING"), "readback", side_effect=AssertionError("Must not wait")): + device.enable() + assert gap.get() == 4.0 + assert device.mode.get() == "parallel" + gap.set(12.0) + device.enabled.set(True) + assert gap.get() == 4.0 + device.disable() + assert device.enabled.get() is False + assert gap.get() == 30.0 + gap.set(12.0) + assert device.enabled.get() is False + device.enabled.set(False) + assert gap.get() == 30.0 + assert gap.readback() == 8.0 + assert device.model_reference == reference + + +@pytest.mark.parametrize(("values", "enabled"), [((0.0, 0.0), False), ((1.0e-12, 0.0), True), ((0.0, 1.0), True)]) +def test_initial_live_state_matches_all_disabled_requested_setpoints(values, enabled): + from tango.pyaml.attribute_store import set_attribute + + control = _control() + names = ("ps1", "ps2") + for name, value in zip(names, values, strict=True): + set_attribute(name, value, unit="A", range=(-100.0, 100.0), readback=50.0) + control.fill_device( + [ + _device( + control_variables={name: {"unit": "A", "backend": name} for name in names}, + model_operating_point={"ps1": 10.0, "ps2": 20.0}, + disabled_operating_point={name: 0.0 for name in names}, + ) + ] + ) + device = control.insertion_device.get("ID") + assert device.enabled.get() is enabled + device.enable() + assert [device.control_variables[name].get() for name in names] == [10.0, 20.0] + device.disable() + assert [device.control_variables[name].get() for name in names] == [0.0, 0.0] + + +@pytest.mark.parametrize( + ("overrides", "command", "error"), + [ + ({}, "disable", "disabled_operating_point is required"), + ({"model_operating_point": None}, "enable", "include every configured control variable"), + ({"control_mode": "MODE"}, "enable", "include mode"), + ({"control_variables": {"gap": {"unit": "mm"}}}, "enable", "control variable is unavailable"), + ], +) +def test_live_enable_disable_missing_configuration_fails_before_writes(overrides, command, error): + control = _control() + control.fill_device([_device(**overrides)]) + device = control.insertion_device.get("ID") + backend = control.get_device_access("GAP") + with patch.object(backend, "set", wraps=backend.set) as write: + with pytest.raises(PyAMLException, match=error): + getattr(device, command)() + write.assert_not_called() + assert device.enabled.get() is True + + +def test_live_enable_prevalidates_all_targets_before_writing(): + from tango.pyaml.attribute_store import set_attribute + + control = _control() + set_attribute("PHASE", 0.0, unit="mm", range=(-10.0, 10.0)) + control.fill_device( + [ + _device( + control_variables={"gap": {"unit": "mm", "backend": "GAP"}, "phase": {"unit": "mm", "backend": "PHASE"}}, + model_operating_point={"gap": 4.0, "phase": 20.0}, + disabled_operating_point={"gap": 30.0}, + ) + ] + ) + device = control.insertion_device.get("ID") + backend = control.get_device_access("GAP") + with patch.object(backend, "set", wraps=backend.set) as write: + with pytest.raises(PyAMLException, match="out of range"): + device.enable() + write.assert_not_called() + device.disable() + assert device.control_variables["gap"].get() == 30.0 + assert device.control_variables["phase"].get() == 0.0 + + +@pytest.mark.parametrize(("command", "ref"), [("disable", "GAP"), ("enable", "MODE")]) +def test_live_enable_disable_failures_do_not_update_logical_state(command, ref): + control = _control() + control.fill_device( + [ + _device( + control_mode="MODE", + model_operating_point={"gap": 4.0, "mode": "parallel"}, + disabled_operating_point={"gap": 30.0}, + ) + ] + ) + device = control.insertion_device.get("ID") + if command == "enable": + device.disable() + previous = device.enabled.get() + error = RuntimeError("Interlocked") + with patch.object(control.get_device_access(ref), "set", side_effect=error): + with pytest.raises(RuntimeError) as caught: + getattr(device, command)() + assert caught.value is error + assert device.enabled.get() is previous + if command == "enable": + assert device.control_variables["gap"].get() == 4.0 + + +@pytest.mark.parametrize("disabled_maps", [1, 2]) +def test_design_initial_enabled_state_comes_from_consistent_kickmaps(id_lattice_file, disabled_maps): + simulator = Simulator("design", id_lattice_file) + for element in simulator.ring[:disabled_maps]: + element.disable() + if disabled_maps == 1: + with pytest.raises(PyAMLException, match="inconsistent kickmap enabled states"): + simulator.fill_device([_device()]) + assert not simulator.insertion_device.all() + else: + simulator.fill_device([_device()]) + device = simulator.insertion_device.get("ID") + assert device.enabled.get() is False + device.enable() + assert device.enabled.get() is True + assert all(element.PassMethod == "IdTablePass" for element in simulator.ring[:2]) + + +def test_named_working_points_follow_persisted_maps_and_retained_accessors(working_point_lattice_file): + config = { + "type": "pyaml.insertion_device", + "name": "ID", + "device_id": "SERIAL", + "lattice_names": "list(MAP)", + "control_variables": [ + {"type": "pyaml.insertion_device.control_variable", "name": name, "unit": "mm"} for name in ("gap", "phase") + ], + "model_working_points": [ + {"type": "pyaml.configuration.named_value", "name": entry.name, "value": entry.value} + for entry in _working_points() + ], + } + source = Factory.build(SchemaValidator.validate_to_dict(config)) + simulator = Simulator("design", working_point_lattice_file) + simulator.fill_device([source]) + device = simulator.insertion_device.get("ID") + gap, phase = device.control_variables.values() + mode = device.mode + reference = device.model_operating_point + particle = np.array([1.0e-3, 0.0, 2.0e-3, 0.0, 0.0, 0.0]) + original = at.lattice_track(simulator.ring, particle.copy(), nturns=1)[0] + assert device.list_working_points() == ["first", "second"] + assert device.active_working_point == "first" + assert reference["gap"] == gap.get() == 4.0 + with pytest.raises(PyAMLException, match="unknown working point"): + device.use_working_point("missing") + assert device.active_working_point == "first" + device.use_working_point("second") + assert gap.get() == gap.readback() == 8.0 + assert gap.get_range() == [8.0, 8.0] + assert phase.get() == 0.0 + assert mode.get() == "antiparallel" + mode.set("antiparallel") + with pytest.raises(PyAMLException, match="fixed model operating point"): + gap.set(8.0) + with pytest.raises(PyAMLException, match="fixed model operating point"): + mode.set("parallel") + assert device.model_operating_point["gap"] == 8.0 + assert reference["gap"] == 4.0 + assert source.model_operating_point is None + assert device.model_reference["working_point"] == "second" + assert device.model_reference["maps"] == tuple(element.Filename_in for element in simulator.ring[:2]) + assert all(element.active_kickmap == "second" and element.Nslice == 2 for element in simulator.ring[:2]) + assert not np.allclose(at.lattice_track(simulator.ring, particle.copy(), nturns=1)[0], original, atol=1e-12, rtol=0) + device.use_working_point("first") + assert mode.get() == "parallel" + assert gap.get() == 4.0 + np.testing.assert_allclose(at.lattice_track(simulator.ring, particle.copy(), nturns=1)[0], original) + + +def test_working_point_selection_while_disabled_is_isolated(working_point_lattice_file): + source = _device( + model_working_points=_working_points(), + control_mode="MODE", + model_operating_point={"gap": 4.0, "mode": "parallel"}, + disabled_operating_point={"gap": 30.0}, + ) + machine = _machine(working_point_lattice_file, [source]) + device = machine.design.insertion_device.get("ID") + live = machine.live.insertion_device.get("ID") + maps = machine.design.ring[:2] + length = machine.design.ring.get_s_pos()[-1] + device.disable() + device.use_working_point("second") + assert device.enabled.get() is False + assert all(element.PassMethod == "DriftPass" and element.active_kickmap == "second" for element in maps) + device.enable() + assert all(element.PassMethod == "IdTablePass" and element.active_kickmap == "second" for element in maps) + assert machine.design.ring.get_s_pos()[-1] == length + assert machine.comparison.insertion_device.get("ID").active_working_point == "first" + assert live.active_working_point is None + assert live.model_operating_point is source.model_operating_point + live.disable() + live.enable() + assert live.control_variables["gap"].get() == 4.0 + with patch.object(machine.live, "get_device_access", side_effect=AssertionError("No hardware access")): + with pytest.raises(PyAMLException, match="requires simulator attachment"): + live.use_working_point("second") + + +@pytest.mark.parametrize( + "failure", + [ + "duplicate", + "incomplete", + "mismatched_lists", + "invalid_coordinate", + "missing_map", + "inconsistent", + "unconfigured_active", + "length", + "activation", + ], +) +def test_invalid_working_points_do_not_publish_partial_state(working_point_lattice_file, failure, monkeypatch): + simulator = Simulator("design", working_point_lattice_file) + maps = simulator.ring[:2] + columns = _working_points() + error = "working point" + if failure == "duplicate": + columns = _working_points(name=["first", "first"]) + error = "duplicate working-point names" + elif failure == "incomplete": + columns = [entry for entry in columns if entry.name != "gap"] + error = "include every configured control variable" + elif failure == "mismatched_lists": + columns = _working_points(gap=[4.0]) + error = "lists must match" + elif failure == "invalid_coordinate": + columns = _working_points(gap=[4.0, True]) + error = "finite coordinate" + elif failure == "missing_map": + maps[1].KickmapStore.pop("second") + error = "missing from a linked segment" + elif failure == "inconsistent": + maps[1].use_kickmap("second") + error = "inconsistent active kickmap keys" + elif failure == "unconfigured_active": + for element in maps: + element.use_kickmap("default") + error = "active kickmap must match a configured working point" + elif failure == "length": + maps[1].KickmapStore["second"]["Length"] = 0.8 + error = "changes a segment length" + if failure != "activation": + before = [(element.active_kickmap, element.xkick.copy()) for element in maps] + with pytest.raises((PyAMLConfigException, PyAMLException), match=error): + simulator.fill_device([_device(model_working_points=columns)]) + assert not simulator.insertion_device.all() + for element, (key, kicks) in zip(maps, before, strict=True): + assert element.active_kickmap == key + np.testing.assert_array_equal(element.xkick, kicks) + return + simulator.fill_device([_device(model_working_points=columns)]) + device = simulator.insertion_device.get("ID") + device.disable() + reference = device.model_reference + before = [element.xkick.copy() for element in maps] + native_use = at.InsertionDeviceKickMap.use_kickmap + error = RuntimeError("Cannot activate second segment") + + def fail_after_activation(element, key): + native_use(element, key) + if element is maps[1] and key == "second": + raise error + + monkeypatch.setattr(at.InsertionDeviceKickMap, "use_kickmap", fail_after_activation) + with pytest.raises(RuntimeError) as caught: + device.use_working_point("second") + assert caught.value is error + assert device.model_reference == reference + assert device.control_variables["gap"].get() == 4.0 + assert device.enabled.get() is False + for element, kicks in zip(maps, before, strict=True): + assert element.active_kickmap == "first" + assert element.PassMethod == "DriftPass" + assert element.Nslice == 1 + np.testing.assert_array_equal(element.xkick, kicks)