From 0a76b8f649f2ef7ccc67678b1a330e2efb5c6c89 Mon Sep 17 00:00:00 2001 From: gubaidulinvadim Date: Wed, 25 Nov 2026 17:25:16 +0100 Subject: [PATCH 01/10] Initial implementation for general insertion device (no hardware link yet) --- pyaml/accelerator.py | 1 + pyaml/apidoc/gen_api.py | 1 + pyaml/common/holders/element_holder.py | 15 ++ pyaml/common/holders/sub_holders.py | 8 + pyaml/control/controlsystem.py | 5 + pyaml/insertion_device.py | 150 +++++++++++++++ pyaml/lattice/insertion_device.py | 100 ++++++++++ pyaml/lattice/simulator.py | 13 ++ tests/test_insertion_device.py | 241 +++++++++++++++++++++++++ 9 files changed, 534 insertions(+) create mode 100644 pyaml/insertion_device.py create mode 100644 pyaml/lattice/insertion_device.py create mode 100644 tests/test_insertion_device.py diff --git a/pyaml/accelerator.py b/pyaml/accelerator.py index 0b82df7a..9362fc84 100644 --- a/pyaml/accelerator.py +++ b/pyaml/accelerator.py @@ -319,6 +319,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 4439e85e..556664c3 100644 --- a/pyaml/apidoc/gen_api.py +++ b/pyaml/apidoc/gen_api.py @@ -9,6 +9,7 @@ modules = [ "pyaml.accelerator", + "pyaml.insertion_device", "pyaml.arrays.array", "pyaml.arrays.bpm", "pyaml.arrays.bpm_array", diff --git a/pyaml/common/holders/element_holder.py b/pyaml/common/holders/element_holder.py index 1cf63dfb..54324667 100644 --- a/pyaml/common/holders/element_holder.py +++ b/pyaml/common/holders/element_holder.py @@ -7,6 +7,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 @@ -21,6 +22,7 @@ from .sub_holders import ( CombinedFunctionMagnetHolder, CombinedFunctionMagnetsHolder, + InsertionDeviceHolder, MagnetHolder, MagnetsHolder, SerializedMagnetHolder, @@ -54,6 +56,8 @@ class ElementHolder(metaclass=ABCMeta): Single serialized magnet group by name, or a named array. rf RF plant and transmitters of this mode. + insertion_device + Individual insertion devices and their component capabilities. diagnostic Diagnostics of this mode, with typed default-name access. tool @@ -94,6 +98,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] = {} @@ -105,6 +110,7 @@ def __init__(self): BPM: self._BPMS, RFPlant: self._RFPLANT, RFTransmitter: self._RFTRANSMITTER, + InsertionDevice: self._INSERTION_DEVICES, } # Array handle @@ -122,6 +128,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) @@ -132,6 +139,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.""" @@ -186,6 +198,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__}") + @abstractmethod def _fill_magnet(self, magnet: Magnet) -> None: pass diff --git a/pyaml/common/holders/sub_holders.py b/pyaml/common/holders/sub_holders.py index 7d2bdc0a..d0ad6449 100644 --- a/pyaml/common/holders/sub_holders.py +++ b/pyaml/common/holders/sub_holders.py @@ -8,6 +8,7 @@ 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 @@ -18,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/control/controlsystem.py b/pyaml/control/controlsystem.py index 4800f796..e5398a1d 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -36,6 +36,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 @@ -215,6 +216,10 @@ 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: + """Register metadata only; concrete ID hardware binding is adapter-owned.""" + self.insertion_device.add(device.attach(self)) + def _fill_magnet(self, magnet: Magnet) -> None: device = self.get_device_access(magnet.model.get_device_names()[0]) current = RWHardwareScalar(magnet.model, device) if magnet.model.has_hardware() else None diff --git a/pyaml/insertion_device.py b/pyaml/insertion_device.py new file mode 100644 index 00000000..4f6f4612 --- /dev/null +++ b/pyaml/insertion_device.py @@ -0,0 +1,150 @@ +"""Insertion-device holding class, independent of facility control systems. + +Example (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. + drives: + gap: {unit: mm, backend: APPLE01_GAP} + phase: {unit: mm, backend: APPLE01_PHASE, movement_flag: APPLE01_MOVING} + control_mode: APPLE01_MODE + model_operating_point: {gap: 4.0, phase: 0.0, mode: parallel} + orbit_feedforward: ID01_ORBIT_FF + +Runtime ``components`` use existing pyAML scalar accessors. An absent key means +no configured drive; None means configured but unavailable. ReadFloatScalar +and ReadWriteFloatScalar distinguish read-only and writable drives. + +Live attachment initially exposes metadata only, never simulated hardware +readings. Facility adapters own motion and errors: gap/phase adapters use the +boolean movement flag; electromagnetic adapters initially use plain set(). +FFWD objects own their correctors, controls and measurements. + +In a simulator, drive reads report the configured reference point; writes accept +only that exact value as a no-op. ``device.model.disable()`` delegates to pyAT's +same-length drift/identity approximation; ``enable()`` restores the kickmap. +Neither operation changes the reference point or any hardware. +""" + +import copy +import math +from collections.abc import Mapping +from types import MappingProxyType +from typing import TYPE_CHECKING, Self + +from .common.abstract import ReadFloatScalar +from .common.element import Element +from .common.exception import PyAMLConfigException +from .validation import DynamicValidation, register_schema + +if TYPE_CHECKING: + from .common.holders.element_holder import ElementHolder + from .lattice.insertion_device import FixedInsertionDeviceModel + +PYAMLCLASS = "InsertionDevice" + + +@register_schema +class InsertionDevice(Element, DynamicValidation): + """Hold optional drives and references to other pyAML elements. + + ``drives`` accepts unit, opaque backend reference and optional movement_flag. + No gap, phase or current channel is mandatory in this shared class. + ``model_operating_point`` is flat: numeric coordinates and optional string + ``mode``. 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. + """ + + def __init__( + self, + name: str, + device_id: str, + drives: dict[str, dict[str, str]] | 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: dict[str, float | str] | None = None, + lattice_names: str | None = None, + description: str | None = None, + ): + super().__init__(name, lattice_names, description) + if not device_id.strip(): + raise PyAMLConfigException(f"{name}: device_id must not be empty") + for key, definition in (drives or {}).items(): + if not key.strip() or not definition.get("unit", "").strip(): + raise PyAMLConfigException(f"{name}: each drive requires a name and unit") + if set(definition) - {"unit", "backend", "movement_flag"}: + raise PyAMLConfigException(f"{name}.{key}: expected only unit, backend and movement_flag") + for key, value in (model_operating_point or {}).items(): + valid = ( + isinstance(value, str) and bool(value.strip()) + if key == "mode" + else (isinstance(value, (int, float)) and math.isfinite(value)) + ) + if not key.strip() or not valid: + raise PyAMLConfigException(f"{name}.{key}: expected a finite coordinate or string mode") + self.device_id = device_id + self.control_mode = control_mode + self.orbit_feedforward_name = orbit_feedforward + self.tune_feedforward_name = tune_feedforward + self._drives = copy.deepcopy(drives or {}) + self._flag_refs = dict(flags or {}) + self._point = dict(model_operating_point) if model_operating_point is not None else None + self._components: dict[str, ReadFloatScalar | None] = dict.fromkeys(self._drives) + self._flags: dict[str, None] = dict.fromkeys(self._flag_refs) + self.orbit_feedforward: Element | None = None + self.tune_feedforward: Element | None = None + self.model: FixedInsertionDeviceModel | None = None + + @property + def drives(self) -> dict[str, dict[str, str]]: + """Return drive configuration, not runtime values.""" + return copy.deepcopy(self._drives) + + @property + def components(self) -> Mapping[str, ReadFloatScalar | None]: + return MappingProxyType(self._components) + + @property + def flags(self) -> Mapping[str, None]: + """Configured boolean flags; runtime binding is deferred to adapters.""" + return MappingProxyType(self._flags) + + @property + def flag_references(self) -> Mapping[str, str]: + return MappingProxyType(self._flag_refs) + + @property + def model_operating_point(self) -> Mapping[str, float | str] | None: + return MappingProxyType(self._point) if self._point is not None else None + + def attach( + self, + peer: "ElementHolder", + components: Mapping[str, ReadFloatScalar | None] | None = None, + model: "FixedInsertionDeviceModel | None" = None, + ) -> Self: + """Return a per-peer copy; defaults give metadata-only access.""" + obj = copy.copy(self) + obj._peer = peer + obj._components = dict(components) if components is not None else dict.fromkeys(self._drives) + obj._flags = dict.fromkeys(self._flag_refs) + obj.orbit_feedforward = obj.tune_feedforward = None + obj.model = model + 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/insertion_device.py b/pyaml/lattice/insertion_device.py new file mode 100644 index 00000000..efc99734 --- /dev/null +++ b/pyaml/lattice/insertion_device.py @@ -0,0 +1,100 @@ +"""Fixed-operating-point insertion-device accessors for pyAT.""" + +import copy +import math +from typing import TYPE_CHECKING + +import at + +from ..common.abstract import ReadFloatScalar +from ..common.exception import PyAMLException +from ..insertion_device import InsertionDevice + +if TYPE_CHECKING: + from ..common.holders.element_holder import ElementHolder + + +class _FixedDrive(ReadFloatScalar): + def __init__(self, name: str, value: float, unit: str): + self._name = name + self._value = value + self._unit = unit + + def get(self) -> float: + return self._value + + def get_setpoint(self) -> float: + """Return the model reference, not a hardware setpoint.""" + return self._value + + def unit(self) -> str: + return self._unit + + def set(self, value: float) -> None: + if not isinstance(value, (int, float)) or not math.isfinite(value) or value != self._value: + raise PyAMLException(f"{self._name}: fixed model operating point does not support {value!r}") + + def set_and_wait(self, value: float) -> None: + self.set(value) + + +class FixedInsertionDeviceModel: + """Linked kickmap segment(s) and their fixed reference, independent of hardware.""" + + def __init__(self, device: InsertionDevice, kickmaps: list[at.InsertionDeviceKickMap]): + point = device.model_operating_point + if point is None or not set(device.drives).issubset(point): + raise PyAMLException(f"{device.name}: model_operating_point must include every configured drive") + if device.control_mode is not None and "mode" not in point: + raise PyAMLException(f"{device.name}: model_operating_point must include mode") + self._name = device.name + self._point = dict(point) + self._kickmaps = tuple(kickmaps) + self._reference = { + "device_id": device.device_id, + "description": device.description, + "operating_point": dict(point), + "units": {name: definition["unit"] for name, definition in device.drives.items()}, + "maps": tuple(getattr(element, "Filename_in", None) for element in kickmaps), + } + + @property + def reference(self) -> dict: + """Return reference coordinates/provenance, never live hardware values.""" + return copy.deepcopy(self._reference) + + @property + def mode(self) -> str | None: + value = self._point.get("mode") + return value if isinstance(value, str) else None + + @mode.setter + def mode(self, value: str) -> None: + if self.mode is None or value != self.mode: + raise PyAMLException(f"{self._name}: fixed model operating point does not support mode {value!r}") + + @property + def enabled(self) -> bool: + 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") + return states.pop() + + def enable(self) -> None: + """Restore kickmap tracking through pyAT, without changing its reference.""" + for element in self._kickmaps: + element.enable() + + def disable(self) -> None: + """Use pyAT's same-length drift/identity approximation, not hardware motion.""" + for element in self._kickmaps: + element.disable() + + def attach(self, device: InsertionDevice, peer: "ElementHolder") -> InsertionDevice: + components = {} + for name, definition in device.drives.items(): + value = self._point[name] + if not isinstance(value, (int, float)): + raise PyAMLException(f"{device.name}.{name}: numeric model reference is required") + components[name] = _FixedDrive(f"{device.name}.{name}", float(value), definition["unit"]) + return device.attach(peer, components, self) diff --git a/pyaml/lattice/simulator.py b/pyaml/lattice/simulator.py index e0922ae3..64867d25 100644 --- a/pyaml/lattice/simulator.py +++ b/pyaml/lattice/simulator.py @@ -18,6 +18,7 @@ from ..common.holders.element_holder import ElementHolder from ..configuration import ROOT from ..diagnostics.tune_monitor import BetatronTuneMonitor +from ..insertion_device import InsertionDevice from ..lattice.abstract_impl import ( BPMHScalarAggregator, BPMScalarAggregator, @@ -47,6 +48,7 @@ from ..tuning_tools.measurement_tool import MeasurementTool from ..tuning_tools.tuning_tool import TuningTool from ..validation import DynamicValidation, register_schema +from .insertion_device import FixedInsertionDeviceModel from .lattice_elements_linker import LatticeElementsLinker from .twiss_in import TwissIn @@ -245,6 +247,17 @@ 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") + model = FixedInsertionDeviceModel(device, kickmaps) + self.insertion_device.add(model.attach(device, self)) + 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/test_insertion_device.py b/tests/test_insertion_device.py new file mode 100644 index 00000000..939571e1 --- /dev/null +++ b/tests/test_insertion_device.py @@ -0,0 +1,241 @@ +import copy + +import at +import numpy as np +import pytest + +from pyaml import PyAMLConfigException, PyAMLException +from pyaml.accelerator import Accelerator +from pyaml.common.abstract import ReadFloatScalar, ReadWriteFloatScalar +from pyaml.common.element import Element +from pyaml.configuration.factory import Factory +from pyaml.control.controlsystem import ControlSystem +from pyaml.insertion_device import InsertionDevice +from pyaml.lattice.simulator import Simulator +from pyaml.validation.validator import SchemaValidator + + +class _NoHardware(ControlSystem): + def name(self): + return "live" + + def get_aggregator(self): + raise AssertionError("ID metadata attachment must not access hardware") + + def get_device_access(self, ref): + raise AssertionError("ID metadata attachment must not resolve hardware") + + +class _Feedforward(Element): + def _fill_device(self, holder): + obj = copy.copy(self) + obj._peer = holder + holder.add_element(obj) + + +@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) + + +def _device(**overrides): + config = { + "name": "ID", + "device_id": "SERIAL", + "drives": {"gap": {"unit": "mm", "backend": "GAP", "movement_flag": "MOVING"}}, + "lattice_names": "list(MAP)", + "model_operating_point": {"gap": 4.0}, + } + config.update(overrides) + return InsertionDevice(**config) + + +def _machine(path, devices=None): + return Accelerator( + facility="TEST", + machine="sr", + energy=3.0e9, + simulators=[Simulator("design", path), Simulator("comparison", path)], + controls=[_NoHardware()], + devices=devices or [], + ) + + +@pytest.mark.parametrize( + ("declaration", "drives", "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.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_optional_drive_families(id_lattice_file, declaration, drives, point): + config = { + **declaration, + "name": "ID", + "device_id": "SERIAL", + "lattice_names": "list(MAP)", + "drives": drives, + "model_operating_point": point, + } + device = Factory.build(SchemaValidator.validate_to_dict(config)) + simulator = Simulator("design", id_lattice_file) + simulator.fill_device([device]) + attached = simulator.insertion_device.get("ID") + assert set(attached.components) == set(drives) + for name, definition in drives.items(): + assert attached.components[name].get() == point[name] + assert attached.components[name].unit() == definition["unit"] + assert attached.model.reference["operating_point"] == point + assert device.peer is None + + +@pytest.mark.parametrize( + ("overrides", "error"), + [ + ({"drives": {"gap": {}}}, "requires a name and unit"), + ({"model_operating_point": {"gap": float("inf")}}, "finite coordinate"), + ({"model_operating_point": {}}, "include every configured drive"), + ({"control_mode": "MODE"}, "include mode"), + ({"lattice_names": "list(D)"}, "expected InsertionDeviceKickMap"), + ({"lattice_names": "list(MISSING)"}, "not found in lattice"), + ], +) +def test_invalid_configuration_or_mapping_is_rejected(id_lattice_file, overrides, error): + simulator = Simulator("design", id_lattice_file) + with pytest.raises((PyAMLException, PyAMLConfigException), 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") + 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="Duplicate element"): + machine.add(source) + 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_has_no_simulated_hardware_values(id_lattice_file): + source = _device( + control_mode="MODE", + flags={"moving": "MOVING", "orbit_ff": "FF"}, + model_operating_point={ + "gap": 4.0, + "mode": "parallel", + }, + ) + machine = _machine(id_lattice_file, [source]) + live = machine.live.insertion_device.get("ID") + design = machine.design.insertion_device.get("ID") + assert live.components["gap"] is None + assert "phase" not in live.components + assert live.flags == {"moving": None, "orbit_ff": None} + assert live.flag_references["moving"] == "MOVING" + assert live.control_mode == "MODE" + assert live.model is None + assert isinstance(design.components["gap"], ReadFloatScalar) + assert not isinstance(design.components["gap"], ReadWriteFloatScalar) + assert source.components["gap"] is None + metadata = live.drives + metadata["gap"]["unit"] = "m" + assert design.components["gap"].unit() == live.drives["gap"]["unit"] == "mm" + assert "InsertionDevice" in repr(live) + + +def test_fixed_reference_noops_and_rejected_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") + drive = device.components["gap"] + reference = device.model.reference + assert drive.get_setpoint() == drive.get() == 4.0 + for disabled in (False, True): + if disabled: + device.model.disable() + drive.set(4.0) + drive.set_and_wait(4.0) + device.model.mode = "parallel" + for value in (5.0, float("nan")): + with pytest.raises(PyAMLException, match="fixed model operating point"): + drive.set_and_wait(value) + with pytest.raises(PyAMLException, match="fixed model operating point"): + drive.set(5.0) + with pytest.raises(PyAMLException, match="fixed model operating point"): + device.model.mode = "antiparallel" + assert drive.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()]) + model = machine.design.insertion_device.get("ID").model + maps = machine.design.ring[:2] + original = [(element.PassMethod, element.Length, element.xkick.copy(), element.ykick.copy()) for element in maps] + reference = model.reference + 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] + assert model.enabled + model.disable() + model.disable() + assert not model.enabled + 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").model.enabled + assert machine.live.insertion_device.get("ID").model is None + model.enable() + model.enable() + assert model.enabled + 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 model.reference == reference From 17d926c520f5293d2a5a5054aec354c33470687b Mon Sep 17 00:00:00 2001 From: gubaidulinvadim Date: Wed, 25 Nov 2026 20:41:10 +0100 Subject: [PATCH 02/10] Updated to include control system abstraction --- pyaml/common/holders/element_holder.py | 2 +- pyaml/control/abstract_impl.py | 21 ++ pyaml/control/controlsystem.py | 23 ++- pyaml/control/insertion_device.py | 72 +++++++ pyaml/insertion_device.py | 111 +++++++---- pyaml/lattice/insertion_device.py | 23 ++- tests/test_insertion_device.py | 262 ++++++++++++++++++++++--- 7 files changed, 439 insertions(+), 75 deletions(-) create mode 100644 pyaml/control/insertion_device.py diff --git a/pyaml/common/holders/element_holder.py b/pyaml/common/holders/element_holder.py index 54324667..74101599 100644 --- a/pyaml/common/holders/element_holder.py +++ b/pyaml/common/holders/element_holder.py @@ -57,7 +57,7 @@ class ElementHolder(metaclass=ABCMeta): rf RF plant and transmitters of this mode. insertion_device - Individual insertion devices and their component capabilities. + Individual insertion devices and their control variables. diagnostic Diagnostics of this mode, with typed default-name access. tool diff --git a/pyaml/control/abstract_impl.py b/pyaml/control/abstract_impl.py index 5b110562..9724040e 100644 --- a/pyaml/control/abstract_impl.py +++ b/pyaml/control/abstract_impl.py @@ -21,10 +21,31 @@ from ..magnet.model import MagnetModel from ..rf.rf_plant import RFPlant from ..rf.rf_transmitter import RFTransmitter +from .readback_value import Value # ------------------------------------------------------------------------------ +class RWScalarBoolean: + """Expose a backend boolean through reusable get/set accessors.""" + + def __init__(self, device: DeviceAccess): + self._device = device + + def get(self) -> bool: + value = self._device.readback() + if isinstance(value, Value): + value = value.value + if value not in (False, True): + raise PyAMLException(f"{self._device.name()}: expected a boolean flag, got {value!r}") + return bool(value) + + def set(self, value: bool) -> None: + if not isinstance(value, bool): + raise PyAMLException(f"{self._device.name()}: expected a boolean flag, got {value!r}") + self._device.set(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 e5398a1d..60bcf6e8 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 ReadFloatScalar, RWMapper from ..common.abstract_aggregator import ScalarAggregator from ..common.exception import PyAMLException from ..common.holders.element_holder import ElementHolder @@ -30,6 +30,7 @@ RWRFFrequencyScalar, RWRFPhaseScalar, RWRFVoltageScalar, + RWScalarBoolean, RWSerializedStrengthScalar, RWStrengthArray, RWStrengthScalar, @@ -46,6 +47,7 @@ from ..tuning_tools.tuning_tool import TuningTool from .deviceaccess import DeviceAccess from .deviceaccesslist import DeviceAccessList +from .insertion_device import InsertionDeviceMode, RInsertionDeviceControlVariable, RWInsertionDeviceControlVariable class ControlSystem(ElementHolder, metaclass=ABCMeta): @@ -217,8 +219,23 @@ def create_bpm_aggregators(self, bpms: list[BPM]) -> list[ScalarAggregator | Non return [agg, aggh, aggv] def _fill_insertion_device(self, device: InsertionDevice) -> None: - """Register metadata only; concrete ID hardware binding is adapter-owned.""" - self.insertion_device.add(device.attach(self)) + """Bind named control variables and optional controls through backend references.""" + control_variables: dict[str, ReadFloatScalar | 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 = ( + RWScalarBoolean(self.get_device_access(definition["movement_flag"])) if "movement_flag" in definition else None + ) + accessor = ( + RInsertionDeviceControlVariable if definition.get("access") == "read" else RWInsertionDeviceControlVariable + ) + control_variables[name] = accessor(backend, definition["unit"], moving) + flags = {name: RWScalarBoolean(self.get_device_access(ref)) for name, ref in device.flag_references.items()} + mode = InsertionDeviceMode(self.get_device_access(device.control_mode)) if device.control_mode is not None else None + self.insertion_device.add(device.attach(self, control_variables, flags=flags, mode=mode)) def _fill_magnet(self, magnet: Magnet) -> None: device = self.get_device_access(magnet.model.get_device_names()[0]) diff --git a/pyaml/control/insertion_device.py b/pyaml/control/insertion_device.py new file mode 100644 index 00000000..1fca7af8 --- /dev/null +++ b/pyaml/control/insertion_device.py @@ -0,0 +1,72 @@ +"""Backend-neutral live insertion-device accessors.""" + +import time + +from ..common.abstract import ReadFloatScalar, ReadWriteFloatScalar +from ..common.exception import PyAMLConfigException, PyAMLException +from .abstract_impl import RWScalarBoolean, check_range, format_out_of_range_message +from .deviceaccess import DeviceAccess +from .readback_value import Value + + +class InsertionDeviceMode: + """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 RInsertionDeviceControlVariable(ReadFloatScalar): + """Read an ID control variable, its setpoint, units and backend limits.""" + + def __init__(self, device: DeviceAccess, unit: str, moving: RWScalarBoolean | 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 float(self._device.readback()) + + def get_setpoint(self) -> float: + return float(self._device.get()) + + def unit(self) -> str: + return self._unit + + def get_range(self) -> list[float | None]: + return self._device.get_range() + + +class RWInsertionDeviceControlVariable(RInsertionDeviceControlVariable, ReadWriteFloatScalar): + """Write a control variable, optionally waiting on its boolean movement flag.""" + + 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: + 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) diff --git a/pyaml/insertion_device.py b/pyaml/insertion_device.py index 4f6f4612..8d5f5b72 100644 --- a/pyaml/insertion_device.py +++ b/pyaml/insertion_device.py @@ -7,23 +7,49 @@ device_id: APPLE01_SERIAL lattice_names: ID02 description: Kickmap measured at 4 mm gap and zero phase. - drives: - gap: {unit: mm, backend: APPLE01_GAP} + control_variables: + gap: {unit: mm, backend: APPLE01_GAP, movement_flag: APPLE01_GAP_MOVING} phase: {unit: mm, backend: APPLE01_PHASE, movement_flag: APPLE01_MOVING} control_mode: APPLE01_MODE model_operating_point: {gap: 4.0, phase: 0.0, mode: parallel} orbit_feedforward: ID01_ORBIT_FF -Runtime ``components`` use existing pyAML scalar accessors. An absent key means -no configured drive; None means configured but unavailable. ReadFloatScalar -and ReadWriteFloatScalar distinguish read-only and writable drives. +Runtime ``control_variables`` use existing pyAML scalar accessors. An absent key +means no configured variable; None means configured but unavailable. +ReadFloatScalar and ReadWriteFloatScalar distinguish read-only and writable +control variables. -Live attachment initially exposes metadata only, never simulated hardware -readings. Facility adapters own motion and errors: gap/phase adapters use the -boolean movement flag; electromagnetic adapters initially use plain set(). +Live control variables bind through opaque backend references. ``get()`` reads the measured +coordinate; ``get_setpoint()`` reads the requested value. ``access: read`` exposes +a read-only variable. Without a backend reference a variable remains unavailable. +``set_and_wait()`` uses the configured boolean movement flag; current variables can +use plain ``set()``. Sequencing and interlocks remain control-system concerns. FFWD objects own their correctors, controls and measurements. -In a simulator, drive reads report the configured reference point; writes accept +The same class supports phase-only devices (including a fixed gap in the model +reference) and electromagnetic devices with arbitrarily named current variables:: + + - type: pyaml.insertion_device + name: EM01 + device_id: EM01_SERIAL + lattice_names: ID03 + control_variables: + ps1: {unit: A, backend: EM01_PS1} + ps2: {unit: A, backend: EM01_PS2} + ps3: {unit: A, backend: EM01_PS3, access: read} + model_operating_point: {ps1: 100.0, ps2: 0.0, ps3: 0.0} + +After retrieving a device through ``sr.live.insertion_device.get(name)``, use +``device.control_variables["gap"].set_and_wait(12.0)`` for a mechanical variable +with a movement flag, or ``device.control_variables["ps1"].set(100.0)`` for a +current variable. +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 ``RWScalarBoolean``. + +In a simulator, variable reads report the configured reference point; writes accept only that exact value as a no-op. ``device.model.disable()`` delegates to pyAT's same-length drift/identity approximation; ``enable()`` restores the kickmap. Neither operation changes the reference point or any hardware. @@ -42,6 +68,8 @@ if TYPE_CHECKING: from .common.holders.element_holder import ElementHolder + from .control.abstract_impl import RWScalarBoolean + from .control.insertion_device import InsertionDeviceMode from .lattice.insertion_device import FixedInsertionDeviceModel PYAMLCLASS = "InsertionDevice" @@ -49,24 +77,28 @@ @register_schema class InsertionDevice(Element, DynamicValidation): - """Hold optional drives and references to other pyAML elements. + """Hold control variables and references to other pyAML elements. - ``drives`` accepts unit, opaque backend reference and optional movement_flag. - No gap, phase or current channel is mandatory in this shared class. + ``control_variables`` configures units, opaque backend references, optional + movement_flag and access (``read`` or ``readwrite``, the default). + 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 flat: numeric coordinates and optional string ``mode``. 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. + in the same holder, resolved after attachment. Runtime ``mode`` and ``flags`` + expose the optional backend controls. """ def __init__( self, name: str, device_id: str, - drives: dict[str, dict[str, str]] | None = None, + control_variables: dict[str, dict[str, str]] | None = None, control_mode: str | None = None, flags: dict[str, str] | None = None, orbit_feedforward: str | None = None, @@ -78,11 +110,22 @@ def __init__( super().__init__(name, lattice_names, description) if not device_id.strip(): raise PyAMLConfigException(f"{name}: device_id must not be empty") - for key, definition in (drives or {}).items(): + if not control_variables: + raise PyAMLConfigException(f"{name}: at least one control variable is required") + for key, definition in control_variables.items(): if not key.strip() or not definition.get("unit", "").strip(): - raise PyAMLConfigException(f"{name}: each drive requires a name and unit") - if set(definition) - {"unit", "backend", "movement_flag"}: - raise PyAMLConfigException(f"{name}.{key}: expected only unit, backend and movement_flag") + raise PyAMLConfigException(f"{name}: each control variable requires a name and unit") + if set(definition) - {"unit", "backend", "movement_flag", "access"}: + raise PyAMLConfigException(f"{name}.{key}: expected only unit, backend, movement_flag and access") + if definition.get("access", "readwrite") not in {"read", "readwrite"}: + raise PyAMLConfigException(f"{name}.{key}: access must be read or readwrite") + for field in ("backend", "movement_flag"): + if field in definition and not definition[field].strip(): + raise PyAMLConfigException(f"{name}.{key}: {field} must not be empty") + 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") for key, value in (model_operating_point or {}).items(): valid = ( isinstance(value, str) and bool(value.strip()) @@ -95,27 +138,24 @@ def __init__( self.control_mode = control_mode self.orbit_feedforward_name = orbit_feedforward self.tune_feedforward_name = tune_feedforward - self._drives = copy.deepcopy(drives or {}) + self._control_variable_definitions = copy.deepcopy(control_variables) self._flag_refs = dict(flags or {}) self._point = dict(model_operating_point) if model_operating_point is not None else None - self._components: dict[str, ReadFloatScalar | None] = dict.fromkeys(self._drives) - self._flags: dict[str, None] = dict.fromkeys(self._flag_refs) + self._control_variables: dict[str, ReadFloatScalar | None] = dict.fromkeys(self._control_variable_definitions) + self._flags: dict[str, RWScalarBoolean | None] = dict.fromkeys(self._flag_refs) + self.mode: InsertionDeviceMode | None = None self.orbit_feedforward: Element | None = None self.tune_feedforward: Element | None = None self.model: FixedInsertionDeviceModel | None = None @property - def drives(self) -> dict[str, dict[str, str]]: - """Return drive configuration, not runtime values.""" - return copy.deepcopy(self._drives) - - @property - def components(self) -> Mapping[str, ReadFloatScalar | None]: - return MappingProxyType(self._components) + def control_variables(self) -> Mapping[str, ReadFloatScalar | None]: + """Bound scalar accessors, or None for configured but unavailable variables.""" + return MappingProxyType(self._control_variables) @property - def flags(self) -> Mapping[str, None]: - """Configured boolean flags; runtime binding is deferred to adapters.""" + def flags(self) -> Mapping[str, "RWScalarBoolean | None"]: + """Boolean backend controls, or None when unavailable in this holder.""" return MappingProxyType(self._flags) @property @@ -129,14 +169,19 @@ def model_operating_point(self) -> Mapping[str, float | str] | None: def attach( self, peer: "ElementHolder", - components: Mapping[str, ReadFloatScalar | None] | None = None, + control_variables: Mapping[str, ReadFloatScalar | None] | None = None, model: "FixedInsertionDeviceModel | None" = None, + flags: Mapping[str, "RWScalarBoolean | None"] | None = None, + mode: "InsertionDeviceMode | None" = None, ) -> Self: """Return a per-peer copy; defaults give metadata-only access.""" obj = copy.copy(self) obj._peer = peer - obj._components = dict(components) if components is not None else dict.fromkeys(self._drives) - obj._flags = dict.fromkeys(self._flag_refs) + 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.model = model return obj diff --git a/pyaml/lattice/insertion_device.py b/pyaml/lattice/insertion_device.py index efc99734..c43004b1 100644 --- a/pyaml/lattice/insertion_device.py +++ b/pyaml/lattice/insertion_device.py @@ -14,7 +14,9 @@ from ..common.holders.element_holder import ElementHolder -class _FixedDrive(ReadFloatScalar): +class RInsertionDeviceControlVariable(ReadFloatScalar): + """Expose a control variable at the kickmap's fixed operating point.""" + def __init__(self, name: str, value: float, unit: str): self._name = name self._value = value @@ -30,6 +32,9 @@ def get_setpoint(self) -> float: def unit(self) -> str: return self._unit + def get_range(self) -> list[float]: + return [self._value, self._value] + def set(self, value: float) -> None: if not isinstance(value, (int, float)) or not math.isfinite(value) or value != self._value: raise PyAMLException(f"{self._name}: fixed model operating point does not support {value!r}") @@ -43,8 +48,8 @@ class FixedInsertionDeviceModel: def __init__(self, device: InsertionDevice, kickmaps: list[at.InsertionDeviceKickMap]): point = device.model_operating_point - if point is None or not set(device.drives).issubset(point): - raise PyAMLException(f"{device.name}: model_operating_point must include every configured drive") + 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") if device.control_mode is not None and "mode" not in point: raise PyAMLException(f"{device.name}: model_operating_point must include mode") self._name = device.name @@ -54,7 +59,7 @@ def __init__(self, device: InsertionDevice, kickmaps: list[at.InsertionDeviceKic "device_id": device.device_id, "description": device.description, "operating_point": dict(point), - "units": {name: definition["unit"] for name, definition in device.drives.items()}, + "units": {name: definition["unit"] for name, definition in device._control_variable_definitions.items()}, "maps": tuple(getattr(element, "Filename_in", None) for element in kickmaps), } @@ -91,10 +96,12 @@ def disable(self) -> None: element.disable() def attach(self, device: InsertionDevice, peer: "ElementHolder") -> InsertionDevice: - components = {} - for name, definition in device.drives.items(): + control_variables = {} + for name, definition in device._control_variable_definitions.items(): value = self._point[name] if not isinstance(value, (int, float)): raise PyAMLException(f"{device.name}.{name}: numeric model reference is required") - components[name] = _FixedDrive(f"{device.name}.{name}", float(value), definition["unit"]) - return device.attach(peer, components, self) + control_variables[name] = RInsertionDeviceControlVariable( + f"{device.name}.{name}", float(value), definition["unit"] + ) + return device.attach(peer, control_variables, self) diff --git a/tests/test_insertion_device.py b/tests/test_insertion_device.py index 939571e1..635a8758 100644 --- a/tests/test_insertion_device.py +++ b/tests/test_insertion_device.py @@ -1,4 +1,5 @@ import copy +from unittest.mock import Mock, patch import at import numpy as np @@ -9,7 +10,9 @@ from pyaml.common.abstract import ReadFloatScalar, ReadWriteFloatScalar from pyaml.common.element import Element from pyaml.configuration.factory import Factory +from pyaml.control.abstract_impl import RWScalarBoolean from pyaml.control.controlsystem import ControlSystem +from pyaml.control.readback_value import Value from pyaml.insertion_device import InsertionDevice from pyaml.lattice.simulator import Simulator from pyaml.validation.validator import SchemaValidator @@ -33,6 +36,22 @@ def _fill_device(self, 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) @@ -55,7 +74,7 @@ def _device(**overrides): config = { "name": "ID", "device_id": "SERIAL", - "drives": {"gap": {"unit": "mm", "backend": "GAP", "movement_flag": "MOVING"}}, + "control_variables": {"gap": {"unit": "mm", "backend": "GAP", "movement_flag": "MOVING"}}, "lattice_names": "list(MAP)", "model_operating_point": {"gap": 4.0}, } @@ -63,22 +82,26 @@ def _device(**overrides): return InsertionDevice(**config) -def _machine(path, devices=None): +def _machine(path, devices=None, controls=None): return Accelerator( facility="TEST", machine="sr", energy=3.0e9, simulators=[Simulator("design", path), Simulator("comparison", path)], - controls=[_NoHardware()], + controls=[_control()] if controls is None else controls, devices=devices or [], ) @pytest.mark.parametrize( - ("declaration", "drives", "point"), + ("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": "pyaml.insertion_device.InsertionDevice"}, + {"phase": {"unit": "mm", "access": "read"}}, + {"gap": 4.0, "phase": 0.0}, + ), ( {"class_path": "pyaml.insertion_device.InsertionDevice"}, {"gap": {"unit": "mm"}, "parallel": {"unit": "mm"}, "antiparallel": {"unit": "mm"}}, @@ -91,23 +114,23 @@ def _machine(path, devices=None): ), ], ) -def test_configuration_supports_optional_drive_families(id_lattice_file, declaration, drives, point): +def test_configuration_supports_control_variable_families(id_lattice_file, declaration, control_variables, point): config = { **declaration, "name": "ID", "device_id": "SERIAL", "lattice_names": "list(MAP)", - "drives": drives, + "control_variables": control_variables, "model_operating_point": point, } device = Factory.build(SchemaValidator.validate_to_dict(config)) simulator = Simulator("design", id_lattice_file) simulator.fill_device([device]) attached = simulator.insertion_device.get("ID") - assert set(attached.components) == set(drives) - for name, definition in drives.items(): - assert attached.components[name].get() == point[name] - assert attached.components[name].unit() == definition["unit"] + assert set(attached.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"] assert attached.model.reference["operating_point"] == point assert device.peer is None @@ -115,9 +138,13 @@ def test_configuration_supports_optional_drive_families(id_lattice_file, declara @pytest.mark.parametrize( ("overrides", "error"), [ - ({"drives": {"gap": {}}}, "requires a name and unit"), + ({"control_variables": {}}, "at least one control variable"), + ({"control_variables": None}, "at least one control variable"), + ({"control_variables": {"gap": {}}}, "requires a name and unit"), + ({"control_variables": {"gap": {"unit": "mm", "access": "invalid"}}}, "access must be"), + ({"control_variables": {"gap": {"unit": "mm", "backend": ""}}}, "backend must not be empty"), ({"model_operating_point": {"gap": float("inf")}}, "finite coordinate"), - ({"model_operating_point": {}}, "include every configured drive"), + ({"model_operating_point": {}}, "include every configured control variable"), ({"control_mode": "MODE"}, "include mode"), ({"lattice_names": "list(D)"}, "expected InsertionDeviceKickMap"), ({"lattice_names": "list(MISSING)"}, "not found in lattice"), @@ -159,7 +186,7 @@ def test_holder_registration_associations_and_add_rollback(id_lattice_file): machine.add(_device(name="BAD_ID")) -def test_live_attachment_has_no_simulated_hardware_values(id_lattice_file): +def test_live_attachment_binds_hardware_separately_from_model(id_lattice_file): source = _device( control_mode="MODE", flags={"moving": "MOVING", "orbit_ff": "FF"}, @@ -171,41 +198,216 @@ def test_live_attachment_has_no_simulated_hardware_values(id_lattice_file): machine = _machine(id_lattice_file, [source]) live = machine.live.insertion_device.get("ID") design = machine.design.insertion_device.get("ID") - assert live.components["gap"] is None - assert "phase" not in live.components - assert live.flags == {"moving": None, "orbit_ff": None} + gap = live.control_variables["gap"] + assert isinstance(gap, ReadWriteFloatScalar) + assert gap.get() == 8.0 + assert gap.get_setpoint() == 9.0 + assert gap.get_range() == [2.0, 30.0] + assert "phase" not in live.control_variables + assert isinstance(live.flags["moving"], RWScalarBoolean) + assert live.flags["moving"].get() is False + assert live.flags["orbit_ff"].get() is True assert live.flag_references["moving"] == "MOVING" assert live.control_mode == "MODE" + assert live.mode.get() == "parallel" assert live.model is None - assert isinstance(design.components["gap"], ReadFloatScalar) - assert not isinstance(design.components["gap"], ReadWriteFloatScalar) - assert source.components["gap"] is None - metadata = live.drives - metadata["gap"]["unit"] = "m" - assert design.components["gap"].unit() == live.drives["gap"]["unit"] == "mm" + assert isinstance(design.control_variables["gap"], ReadFloatScalar) + assert not isinstance(design.control_variables["gap"], ReadWriteFloatScalar) + assert source.control_variables["gap"] is None + assert source.mode is None + assert source.flags == {"moving": None, "orbit_ff": None} + assert design.flags == {"moving": None, "orbit_ff": None} + assert design.control_variables["gap"].unit() == live.control_variables["gap"].unit() == "mm" assert "InsertionDevice" in repr(live) +def test_control_variable_without_backend_remains_unavailable(id_lattice_file): + machine = _machine(id_lattice_file, [_device(control_variables={"gap": {"unit": "mm"}})], controls=[_NoHardware()]) + live = machine.live.insertion_device.get("ID") + assert live.control_variables == {"gap": None} + assert live.flags == {} + assert live.mode is None + assert machine.design.insertion_device.get("ID").control_variables["gap"].get() == 4.0 + + +@pytest.mark.parametrize( + "names", + [("gap",), ("phase",), ("gap", "parallel", "antiparallel"), ("ps1", "ps2", "ps3")], +) +def test_same_class_binds_mechanical_and_current_control_variables(names): + from tango.pyaml.attribute_store import set_attribute + + unit = "A" if names[0] == "ps1" else "mm" + control = _control() + for name in names: + set_attribute(name, 0.0, unit=unit, range=(-100.0, 100.0), readback=0.0) + source = _device(control_variables={name: {"unit": unit, "backend": name} for name in names}) + control.fill_device([source]) + attached = control.insertion_device.get("ID") + assert type(attached) is InsertionDevice + assert set(attached.control_variables) == set(names) + for variable in attached.control_variables.values(): + assert isinstance(variable, ReadWriteFloatScalar) + variable.set(5.0) + assert variable.get_setpoint() == 5.0 + assert variable.get() == 0.0 + assert variable.unit() == unit + assert attached.model is None + assert source.peer is None + + +def test_read_only_and_unavailable_control_variables_are_distinguishable(): + source = _device( + control_variables={ + "gap": {"unit": "mm", "backend": "GAP", "access": "read"}, + "phase": {"unit": "mm"}, + } + ) + control = _control() + control.fill_device([source]) + device = control.insertion_device.get("ID") + gap = device.control_variables["gap"] + assert isinstance(gap, ReadFloatScalar) + assert not isinstance(gap, ReadWriteFloatScalar) + assert not hasattr(gap, "set") + assert gap.get() == 8.0 + assert gap.get_setpoint() == 9.0 + assert gap.get_range() == [2.0, 30.0] + assert device.control_variables["phase"] is None + assert "current" not in device.control_variables + + +@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.insertion_device.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_setpoint() == 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_setpoint() == 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() + + +@pytest.mark.parametrize("value", [False, True, Value(False), Value(True)]) +def test_boolean_scalar_reads_boolean_value(value): + control = _control() + backend = control.get_device_access("FF") + with patch.object(backend, "readback", return_value=value): + assert RWScalarBoolean(backend).get() is bool(value.value if isinstance(value, Value) else value) + + +def test_boolean_scalar_writes_and_rejects_nonboolean_values(): + control = _control() + backend = control.get_device_access("FF") + flag = RWScalarBoolean(backend) + flag.set(False) + assert flag.get() is False + 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_optional_controls_and_hardware_motion_do_not_change_model(id_lattice_file): + from tango.pyaml.attribute_store import set_attribute + + control = _control() + source = _device(control_mode="MODE", flags={"orbit_ff": "FF"}, model_operating_point={"gap": 4.0, "mode": "parallel"}) + machine = _machine(id_lattice_file, [source], controls=[control]) + live = machine.live.insertion_device.get("ID") + design = machine.design.insertion_device.get("ID") + reference = design.model.reference + live.control_variables["gap"].set_and_wait(12.0) + set_attribute("GAP", 12.0) + live.mode.set("antiparallel") + live.flags["orbit_ff"].set(False) + assert live.control_variables["gap"].get() == 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["gap"].get_range() == [4.0, 4.0] + assert design.model.mode == "parallel" + with patch.object(control, "get_device_access", side_effect=AssertionError("Model must not access hardware")): + design.model.disable() + design.model.enable() + assert design.model.reference == reference + + def test_fixed_reference_noops_and_rejected_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") - drive = device.components["gap"] + variable = device.control_variables["gap"] reference = device.model.reference - assert drive.get_setpoint() == drive.get() == 4.0 + assert variable.get_setpoint() == variable.get() == 4.0 for disabled in (False, True): if disabled: device.model.disable() - drive.set(4.0) - drive.set_and_wait(4.0) + variable.set(4.0) + variable.set_and_wait(4.0) device.model.mode = "parallel" for value in (5.0, float("nan")): with pytest.raises(PyAMLException, match="fixed model operating point"): - drive.set_and_wait(value) + variable.set_and_wait(value) with pytest.raises(PyAMLException, match="fixed model operating point"): - drive.set(5.0) + variable.set(5.0) with pytest.raises(PyAMLException, match="fixed model operating point"): device.model.mode = "antiparallel" - assert drive.get() == 4.0 + 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 From d3ac934fa70806b75646ae2f0e2f575a042de212 Mon Sep 17 00:00:00 2001 From: gubaidulinvadim Date: Wed, 25 Nov 2026 21:20:39 +0100 Subject: [PATCH 03/10] Corrected docstring --- pyaml/control/insertion_device.py | 3 ++- pyaml/insertion_device.py | 27 +++++++++++++++------------ 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/pyaml/control/insertion_device.py b/pyaml/control/insertion_device.py index 1fca7af8..d42f2a8d 100644 --- a/pyaml/control/insertion_device.py +++ b/pyaml/control/insertion_device.py @@ -55,7 +55,7 @@ def get_range(self) -> list[float | None]: class RWInsertionDeviceControlVariable(RInsertionDeviceControlVariable, ReadWriteFloatScalar): - """Write a control variable, optionally waiting on its boolean movement flag.""" + """Write gap/phase variables with movement flags or currents without them.""" def set(self, value: float) -> None: if not check_range(value, self.get_range()): @@ -63,6 +63,7 @@ def set(self, value: float) -> None: 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" diff --git a/pyaml/insertion_device.py b/pyaml/insertion_device.py index 8d5f5b72..32cdf1ff 100644 --- a/pyaml/insertion_device.py +++ b/pyaml/insertion_device.py @@ -19,10 +19,11 @@ ReadFloatScalar and ReadWriteFloatScalar distinguish read-only and writable control variables. -Live control variables bind through opaque backend references. ``get()`` reads the measured -coordinate; ``get_setpoint()`` reads the requested value. ``access: read`` exposes -a read-only variable. Without a backend reference a variable remains unavailable. -``set_and_wait()`` uses the configured boolean movement flag; current variables can +Live control variables bind through opaque backend references. ``get()`` reads +the measured value; ``get_setpoint()`` reads the requested value. ``access: read`` +exposes a read-only variable. 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. @@ -40,12 +41,12 @@ model_operating_point: {ps1: 100.0, ps2: 0.0, ps3: 0.0} After retrieving a device through ``sr.live.insertion_device.get(name)``, use -``device.control_variables["gap"].set_and_wait(12.0)`` for a mechanical variable -with a movement flag, or ``device.control_variables["ps1"].set(100.0)`` for a -current variable. -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. +``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 ``RWScalarBoolean``. @@ -79,8 +80,10 @@ class InsertionDevice(Element, DynamicValidation): """Hold control variables and references to other pyAML elements. - ``control_variables`` configures units, opaque backend references, optional - movement_flag and access (``read`` or ``readwrite``, the default). + ``control_variables`` configures units, opaque backend references and access + (``read`` or ``readwrite``, the default). 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. From 7d973a8c34886746864e66e83b8168d11305d7fb Mon Sep 17 00:00:00 2001 From: gubaidulinvadim Date: Wed, 25 Nov 2026 21:57:31 +0100 Subject: [PATCH 04/10] Removed unnecessary ID-specific Rclasses --- pyaml/control/controlsystem.py | 7 ++----- pyaml/control/insertion_device.py | 18 ++++++++---------- pyaml/insertion_device.py | 26 ++++++++++++-------------- pyaml/lattice/insertion_device.py | 4 ++-- tests/test_insertion_device.py | 31 +++++++++++++++---------------- 5 files changed, 39 insertions(+), 47 deletions(-) diff --git a/pyaml/control/controlsystem.py b/pyaml/control/controlsystem.py index 60bcf6e8..ca3f507a 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -47,7 +47,7 @@ from ..tuning_tools.tuning_tool import TuningTool from .deviceaccess import DeviceAccess from .deviceaccesslist import DeviceAccessList -from .insertion_device import InsertionDeviceMode, RInsertionDeviceControlVariable, RWInsertionDeviceControlVariable +from .insertion_device import InsertionDeviceMode, RWInsertionDeviceControlVariable class ControlSystem(ElementHolder, metaclass=ABCMeta): @@ -229,10 +229,7 @@ def _fill_insertion_device(self, device: InsertionDevice) -> None: moving = ( RWScalarBoolean(self.get_device_access(definition["movement_flag"])) if "movement_flag" in definition else None ) - accessor = ( - RInsertionDeviceControlVariable if definition.get("access") == "read" else RWInsertionDeviceControlVariable - ) - control_variables[name] = accessor(backend, definition["unit"], moving) + control_variables[name] = RWInsertionDeviceControlVariable(backend, definition["unit"], moving) flags = {name: RWScalarBoolean(self.get_device_access(ref)) for name, ref in device.flag_references.items()} mode = InsertionDeviceMode(self.get_device_access(device.control_mode)) if device.control_mode is not None else None self.insertion_device.add(device.attach(self, control_variables, flags=flags, mode=mode)) diff --git a/pyaml/control/insertion_device.py b/pyaml/control/insertion_device.py index d42f2a8d..5eb11ec3 100644 --- a/pyaml/control/insertion_device.py +++ b/pyaml/control/insertion_device.py @@ -2,7 +2,7 @@ import time -from ..common.abstract import ReadFloatScalar, ReadWriteFloatScalar +from ..common.abstract import ReadWriteFloatScalar from ..common.exception import PyAMLConfigException, PyAMLException from .abstract_impl import RWScalarBoolean, check_range, format_out_of_range_message from .deviceaccess import DeviceAccess @@ -29,8 +29,8 @@ def set(self, value: str) -> None: self._device.set(value) -class RInsertionDeviceControlVariable(ReadFloatScalar): - """Read an ID control variable, its setpoint, units and backend limits.""" +class RWInsertionDeviceControlVariable(ReadWriteFloatScalar): + """Write gap/phase variables with movement flags or currents without them.""" def __init__(self, device: DeviceAccess, unit: str, moving: RWScalarBoolean | None = None): if device.unit() != unit: @@ -42,21 +42,19 @@ def __init__(self, device: DeviceAccess, unit: str, moving: RWScalarBoolean | No self.moving = moving def get(self) -> float: - return float(self._device.readback()) - - def get_setpoint(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() - -class RWInsertionDeviceControlVariable(RInsertionDeviceControlVariable, ReadWriteFloatScalar): - """Write gap/phase variables with movement flags or currents without them.""" - def set(self, value: float) -> None: if not check_range(value, self.get_range()): raise PyAMLException(format_out_of_range_message(value, self._device)) diff --git a/pyaml/insertion_device.py b/pyaml/insertion_device.py index 32cdf1ff..ef8ddb92 100644 --- a/pyaml/insertion_device.py +++ b/pyaml/insertion_device.py @@ -16,15 +16,15 @@ Runtime ``control_variables`` use existing pyAML scalar accessors. An absent key means no configured variable; None means configured but unavailable. -ReadFloatScalar and ReadWriteFloatScalar distinguish read-only and writable -control variables. +Live variables expose ReadWriteFloatScalar accessors; the fixed model exposes +ReadFloatScalar accessors with restricted writes. Live control variables bind through opaque backend references. ``get()`` reads -the measured value; ``get_setpoint()`` reads the requested value. ``access: read`` -exposes a read-only variable. 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. +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 @@ -37,7 +37,7 @@ control_variables: ps1: {unit: A, backend: EM01_PS1} ps2: {unit: A, backend: EM01_PS2} - ps3: {unit: A, backend: EM01_PS3, access: read} + ps3: {unit: A, backend: EM01_PS3} model_operating_point: {ps1: 100.0, ps2: 0.0, ps3: 0.0} After retrieving a device through ``sr.live.insertion_device.get(name)``, use @@ -80,8 +80,8 @@ class InsertionDevice(Element, DynamicValidation): """Hold control variables and references to other pyAML elements. - ``control_variables`` configures units, opaque backend references and access - (``read`` or ``readwrite``, the default). Gap and phase/shift variables may + ``control_variables`` configures 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. @@ -118,10 +118,8 @@ def __init__( for key, definition in control_variables.items(): if not key.strip() or not definition.get("unit", "").strip(): raise PyAMLConfigException(f"{name}: each control variable requires a name and unit") - if set(definition) - {"unit", "backend", "movement_flag", "access"}: - raise PyAMLConfigException(f"{name}.{key}: expected only unit, backend, movement_flag and access") - if definition.get("access", "readwrite") not in {"read", "readwrite"}: - raise PyAMLConfigException(f"{name}.{key}: access must be read or readwrite") + if set(definition) - {"unit", "backend", "movement_flag"}: + raise PyAMLConfigException(f"{name}.{key}: expected only unit, backend and movement_flag") for field in ("backend", "movement_flag"): if field in definition and not definition[field].strip(): raise PyAMLConfigException(f"{name}.{key}: {field} must not be empty") diff --git a/pyaml/lattice/insertion_device.py b/pyaml/lattice/insertion_device.py index c43004b1..6599e784 100644 --- a/pyaml/lattice/insertion_device.py +++ b/pyaml/lattice/insertion_device.py @@ -25,8 +25,8 @@ def __init__(self, name: str, value: float, unit: str): def get(self) -> float: return self._value - def get_setpoint(self) -> float: - """Return the model reference, not a hardware setpoint.""" + def readback(self) -> float: + """Return the model reference, not a hardware readback.""" return self._value def unit(self) -> str: diff --git a/tests/test_insertion_device.py b/tests/test_insertion_device.py index 635a8758..0a1c72db 100644 --- a/tests/test_insertion_device.py +++ b/tests/test_insertion_device.py @@ -99,7 +99,7 @@ def _machine(path, devices=None, controls=None): ({"type": "pyaml.insertion_device"}, {"gap": {"unit": "mm"}}, {"gap": 4.0}), ( {"class": "pyaml.insertion_device.InsertionDevice"}, - {"phase": {"unit": "mm", "access": "read"}}, + {"phase": {"unit": "mm"}}, {"gap": 4.0, "phase": 0.0}, ), ( @@ -141,7 +141,7 @@ def test_configuration_supports_control_variable_families(id_lattice_file, decla ({"control_variables": {}}, "at least one control variable"), ({"control_variables": None}, "at least one control variable"), ({"control_variables": {"gap": {}}}, "requires a name and unit"), - ({"control_variables": {"gap": {"unit": "mm", "access": "invalid"}}}, "access must be"), + ({"control_variables": {"gap": {"unit": "mm", "access": "read"}}}, "expected only unit, backend and movement_flag"), ({"control_variables": {"gap": {"unit": "mm", "backend": ""}}}, "backend must not be empty"), ({"model_operating_point": {"gap": float("inf")}}, "finite coordinate"), ({"model_operating_point": {}}, "include every configured control variable"), @@ -200,8 +200,8 @@ def test_live_attachment_binds_hardware_separately_from_model(id_lattice_file): design = machine.design.insertion_device.get("ID") gap = live.control_variables["gap"] assert isinstance(gap, ReadWriteFloatScalar) - assert gap.get() == 8.0 - assert gap.get_setpoint() == 9.0 + assert gap.readback() == 8.0 + assert gap.get() == 9.0 assert gap.get_range() == [2.0, 30.0] assert "phase" not in live.control_variables assert isinstance(live.flags["moving"], RWScalarBoolean) @@ -249,17 +249,17 @@ def test_same_class_binds_mechanical_and_current_control_variables(names): for variable in attached.control_variables.values(): assert isinstance(variable, ReadWriteFloatScalar) variable.set(5.0) - assert variable.get_setpoint() == 5.0 - assert variable.get() == 0.0 + assert variable.get() == 5.0 + assert variable.readback() == 0.0 assert variable.unit() == unit assert attached.model is None assert source.peer is None -def test_read_only_and_unavailable_control_variables_are_distinguishable(): +def test_writable_and_unavailable_control_variables_are_distinguishable(): source = _device( control_variables={ - "gap": {"unit": "mm", "backend": "GAP", "access": "read"}, + "gap": {"unit": "mm", "backend": "GAP"}, "phase": {"unit": "mm"}, } ) @@ -267,11 +267,9 @@ def test_read_only_and_unavailable_control_variables_are_distinguishable(): control.fill_device([source]) device = control.insertion_device.get("ID") gap = device.control_variables["gap"] - assert isinstance(gap, ReadFloatScalar) - assert not isinstance(gap, ReadWriteFloatScalar) - assert not hasattr(gap, "set") - assert gap.get() == 8.0 - assert gap.get_setpoint() == 9.0 + assert isinstance(gap, ReadWriteFloatScalar) + assert gap.readback() == 8.0 + assert gap.get() == 9.0 assert gap.get_range() == [2.0, 30.0] assert device.control_variables["phase"] is None assert "current" not in device.control_variables @@ -306,7 +304,7 @@ def test_set_and_wait_without_flag_does_not_write(): 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_setpoint() == 0.0 + assert variable.get() == 0.0 def test_limits_and_backend_errors_are_propagated(): @@ -317,7 +315,7 @@ def test_limits_and_backend_errors_are_propagated(): for method in (gap.set, gap.set_and_wait): with pytest.raises(PyAMLException, match="out of range"): method(40.0) - assert gap.get_setpoint() == 9.0 + assert gap.get() == 9.0 for ref, write, value in ( ("GAP", gap.set_and_wait, 12.0), ("MODE", device.mode.set, "antiparallel"), @@ -377,6 +375,7 @@ def test_optional_controls_and_hardware_motion_do_not_change_model(id_lattice_fi live.mode.set("antiparallel") live.flags["orbit_ff"].set(False) assert live.control_variables["gap"].get() == 12.0 + assert live.control_variables["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 @@ -393,7 +392,7 @@ def test_fixed_reference_noops_and_rejected_writes(id_lattice_file): device = machine.design.insertion_device.get("ID") variable = device.control_variables["gap"] reference = device.model.reference - assert variable.get_setpoint() == variable.get() == 4.0 + assert variable.readback() == variable.get() == 4.0 for disabled in (False, True): if disabled: device.model.disable() From d139267fd66fa64c2189f32d27df537cd22f90e9 Mon Sep 17 00:00:00 2001 From: gubaidulinvadim Date: Wed, 25 Nov 2026 22:21:54 +0100 Subject: [PATCH 05/10] Moved InsertionDevice class. Restructure to reduce repeating code. --- pyaml/control/controlsystem.py | 8 ++-- pyaml/control/insertion_device.py | 2 +- pyaml/insertion_device/__init__.py | 9 +++++ .../insertion_device.py | 38 +++++++++---------- pyaml/lattice/insertion_device.py | 20 +++++----- pyaml/lattice/simulator.py | 8 ++-- tests/test_insertion_device.py | 20 ++++------ 7 files changed, 54 insertions(+), 51 deletions(-) create mode 100644 pyaml/insertion_device/__init__.py rename pyaml/{ => insertion_device}/insertion_device.py (87%) diff --git a/pyaml/control/controlsystem.py b/pyaml/control/controlsystem.py index ca3f507a..29822b7c 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 ReadFloatScalar, RWMapper +from ..common.abstract import ReadWriteFloatScalar, RWMapper from ..common.abstract_aggregator import ScalarAggregator from ..common.exception import PyAMLException from ..common.holders.element_holder import ElementHolder @@ -47,7 +47,7 @@ from ..tuning_tools.tuning_tool import TuningTool from .deviceaccess import DeviceAccess from .deviceaccesslist import DeviceAccessList -from .insertion_device import InsertionDeviceMode, RWInsertionDeviceControlVariable +from .insertion_device import RWInsertionDeviceControlVariable, RWInsertionDeviceMode class ControlSystem(ElementHolder, metaclass=ABCMeta): @@ -220,7 +220,7 @@ def create_bpm_aggregators(self, bpms: list[BPM]) -> list[ScalarAggregator | Non def _fill_insertion_device(self, device: InsertionDevice) -> None: """Bind named control variables and optional controls through backend references.""" - control_variables: dict[str, ReadFloatScalar | None] = {} + control_variables: dict[str, ReadWriteFloatScalar | None] = {} for name, definition in device._control_variable_definitions.items(): if "backend" not in definition: control_variables[name] = None @@ -231,7 +231,7 @@ def _fill_insertion_device(self, device: InsertionDevice) -> None: ) control_variables[name] = RWInsertionDeviceControlVariable(backend, definition["unit"], moving) flags = {name: RWScalarBoolean(self.get_device_access(ref)) for name, ref in device.flag_references.items()} - mode = InsertionDeviceMode(self.get_device_access(device.control_mode)) if device.control_mode is not None else None + mode = RWInsertionDeviceMode(self.get_device_access(device.control_mode)) if device.control_mode is not None else None self.insertion_device.add(device.attach(self, control_variables, flags=flags, mode=mode)) def _fill_magnet(self, magnet: Magnet) -> None: diff --git a/pyaml/control/insertion_device.py b/pyaml/control/insertion_device.py index 5eb11ec3..0a6c8462 100644 --- a/pyaml/control/insertion_device.py +++ b/pyaml/control/insertion_device.py @@ -9,7 +9,7 @@ from .readback_value import Value -class InsertionDeviceMode: +class RWInsertionDeviceMode: """Expose an optional mode; the control system owns allowed transitions.""" def __init__(self, device: DeviceAccess): diff --git a/pyaml/insertion_device/__init__.py b/pyaml/insertion_device/__init__.py new file mode 100644 index 00000000..dddbb5fc --- /dev/null +++ b/pyaml/insertion_device/__init__.py @@ -0,0 +1,9 @@ +"""Insertion-device elements.""" + +from ..validation import SchemaRegistry +from ..validation.schema_builder import generate_configuration_schema +from .insertion_device import PYAMLCLASS, InsertionDevice + +__all__ = ["InsertionDevice"] + +SchemaRegistry().register(f"{__name__}.InsertionDevice", generate_configuration_schema(InsertionDevice)) diff --git a/pyaml/insertion_device.py b/pyaml/insertion_device/insertion_device.py similarity index 87% rename from pyaml/insertion_device.py rename to pyaml/insertion_device/insertion_device.py index ef8ddb92..db5d087c 100644 --- a/pyaml/insertion_device.py +++ b/pyaml/insertion_device/insertion_device.py @@ -16,8 +16,8 @@ Runtime ``control_variables`` use existing pyAML scalar accessors. An absent key means no configured variable; None means configured but unavailable. -Live variables expose ReadWriteFloatScalar accessors; the fixed model exposes -ReadFloatScalar accessors with restricted writes. +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 @@ -50,8 +50,8 @@ Optional controls use ``device.mode.get()/set(value)`` and ``device.flags[name].get()/set(value)``; the latter reuse ``RWScalarBoolean``. -In a simulator, variable reads report the configured reference point; writes accept -only that exact value as a no-op. ``device.model.disable()`` delegates to pyAT's +In a simulator, variable reads report the configured reference point and all +control-variable writes raise an error. ``device.model.disable()`` delegates to pyAT's same-length drift/identity approximation; ``enable()`` restores the kickmap. Neither operation changes the reference point or any hardware. """ @@ -62,16 +62,16 @@ from types import MappingProxyType from typing import TYPE_CHECKING, Self -from .common.abstract import ReadFloatScalar -from .common.element import Element -from .common.exception import PyAMLConfigException -from .validation import DynamicValidation, register_schema +from ..common.abstract import ReadWriteFloatScalar +from ..common.element import Element +from ..common.exception import PyAMLConfigException +from ..validation import DynamicValidation, register_schema if TYPE_CHECKING: - from .common.holders.element_holder import ElementHolder - from .control.abstract_impl import RWScalarBoolean - from .control.insertion_device import InsertionDeviceMode - from .lattice.insertion_device import FixedInsertionDeviceModel + from ..common.holders.element_holder import ElementHolder + from ..control.abstract_impl import RWScalarBoolean + from ..control.insertion_device import RWInsertionDeviceMode + from ..lattice import insertion_device PYAMLCLASS = "InsertionDevice" @@ -142,15 +142,15 @@ def __init__( self._control_variable_definitions = copy.deepcopy(control_variables) self._flag_refs = dict(flags or {}) self._point = dict(model_operating_point) if model_operating_point is not None else None - self._control_variables: dict[str, ReadFloatScalar | None] = dict.fromkeys(self._control_variable_definitions) + self._control_variables: dict[str, ReadWriteFloatScalar | None] = dict.fromkeys(self._control_variable_definitions) self._flags: dict[str, RWScalarBoolean | None] = dict.fromkeys(self._flag_refs) - self.mode: InsertionDeviceMode | None = None + self.mode: RWInsertionDeviceMode | None = None self.orbit_feedforward: Element | None = None self.tune_feedforward: Element | None = None - self.model: FixedInsertionDeviceModel | None = None + self.model: insertion_device.InsertionDevice | None = None @property - def control_variables(self) -> Mapping[str, ReadFloatScalar | None]: + def control_variables(self) -> Mapping[str, ReadWriteFloatScalar | None]: """Bound scalar accessors, or None for configured but unavailable variables.""" return MappingProxyType(self._control_variables) @@ -170,10 +170,10 @@ def model_operating_point(self) -> Mapping[str, float | str] | None: def attach( self, peer: "ElementHolder", - control_variables: Mapping[str, ReadFloatScalar | None] | None = None, - model: "FixedInsertionDeviceModel | None" = None, + control_variables: Mapping[str, ReadWriteFloatScalar | None] | None = None, + model: "insertion_device.InsertionDevice | None" = None, flags: Mapping[str, "RWScalarBoolean | None"] | None = None, - mode: "InsertionDeviceMode | None" = None, + mode: "RWInsertionDeviceMode | None" = None, ) -> Self: """Return a per-peer copy; defaults give metadata-only access.""" obj = copy.copy(self) diff --git a/pyaml/lattice/insertion_device.py b/pyaml/lattice/insertion_device.py index 6599e784..2a275465 100644 --- a/pyaml/lattice/insertion_device.py +++ b/pyaml/lattice/insertion_device.py @@ -1,21 +1,20 @@ """Fixed-operating-point insertion-device accessors for pyAT.""" import copy -import math from typing import TYPE_CHECKING import at -from ..common.abstract import ReadFloatScalar +from ..common.abstract import ReadWriteFloatScalar from ..common.exception import PyAMLException -from ..insertion_device import InsertionDevice +from ..insertion_device import insertion_device if TYPE_CHECKING: from ..common.holders.element_holder import ElementHolder -class RInsertionDeviceControlVariable(ReadFloatScalar): - """Expose a control variable at the kickmap's fixed operating point.""" +class RWInsertionDeviceControlVariable(ReadWriteFloatScalar): + """Expose the shared control-variable interface while rejecting model writes.""" def __init__(self, name: str, value: float, unit: str): self._name = name @@ -36,17 +35,16 @@ def get_range(self) -> list[float]: return [self._value, self._value] def set(self, value: float) -> None: - if not isinstance(value, (int, float)) or not math.isfinite(value) or value != self._value: - raise PyAMLException(f"{self._name}: fixed model operating point does not support {value!r}") + 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 FixedInsertionDeviceModel: +class InsertionDevice: """Linked kickmap segment(s) and their fixed reference, independent of hardware.""" - def __init__(self, device: InsertionDevice, kickmaps: list[at.InsertionDeviceKickMap]): + def __init__(self, device: insertion_device.InsertionDevice, kickmaps: list[at.InsertionDeviceKickMap]): point = 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") @@ -95,13 +93,13 @@ def disable(self) -> None: for element in self._kickmaps: element.disable() - def attach(self, device: InsertionDevice, peer: "ElementHolder") -> InsertionDevice: + def attach(self, device: insertion_device.InsertionDevice, peer: "ElementHolder") -> insertion_device.InsertionDevice: control_variables = {} for name, definition in device._control_variable_definitions.items(): value = self._point[name] if not isinstance(value, (int, float)): raise PyAMLException(f"{device.name}.{name}: numeric model reference is required") - control_variables[name] = RInsertionDeviceControlVariable( + control_variables[name] = RWInsertionDeviceControlVariable( f"{device.name}.{name}", float(value), definition["unit"] ) return device.attach(peer, control_variables, self) diff --git a/pyaml/lattice/simulator.py b/pyaml/lattice/simulator.py index 64867d25..d4bc06e9 100644 --- a/pyaml/lattice/simulator.py +++ b/pyaml/lattice/simulator.py @@ -18,7 +18,7 @@ from ..common.holders.element_holder import ElementHolder from ..configuration import ROOT from ..diagnostics.tune_monitor import BetatronTuneMonitor -from ..insertion_device import InsertionDevice +from ..insertion_device import insertion_device from ..lattice.abstract_impl import ( BPMHScalarAggregator, BPMScalarAggregator, @@ -48,7 +48,7 @@ from ..tuning_tools.measurement_tool import MeasurementTool from ..tuning_tools.tuning_tool import TuningTool from ..validation import DynamicValidation, register_schema -from .insertion_device import FixedInsertionDeviceModel +from .insertion_device import InsertionDevice from .lattice_elements_linker import LatticeElementsLinker from .twiss_in import TwissIn @@ -247,7 +247,7 @@ 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: + def _fill_insertion_device(self, device: insertion_device.InsertionDevice) -> None: kickmaps = [] for element in self.get_at_elems(device): if not isinstance(element, at.InsertionDeviceKickMap): @@ -255,7 +255,7 @@ def _fill_insertion_device(self, device: InsertionDevice) -> None: kickmaps.append(element) if not kickmaps: raise PyAMLException(f"{device.name}: no insertion-device kickmaps found") - model = FixedInsertionDeviceModel(device, kickmaps) + model = InsertionDevice(device, kickmaps) self.insertion_device.add(model.attach(device, self)) def _fill_magnet(self, magnet: Magnet) -> None: diff --git a/tests/test_insertion_device.py b/tests/test_insertion_device.py index 0a1c72db..e339117f 100644 --- a/tests/test_insertion_device.py +++ b/tests/test_insertion_device.py @@ -7,7 +7,7 @@ from pyaml import PyAMLConfigException, PyAMLException from pyaml.accelerator import Accelerator -from pyaml.common.abstract import ReadFloatScalar, ReadWriteFloatScalar +from pyaml.common.abstract import ReadWriteFloatScalar from pyaml.common.element import Element from pyaml.configuration.factory import Factory from pyaml.control.abstract_impl import RWScalarBoolean @@ -103,7 +103,7 @@ def _machine(path, devices=None, controls=None): {"gap": 4.0, "phase": 0.0}, ), ( - {"class_path": "pyaml.insertion_device.InsertionDevice"}, + {"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"}, ), @@ -211,8 +211,7 @@ def test_live_attachment_binds_hardware_separately_from_model(id_lattice_file): assert live.control_mode == "MODE" assert live.mode.get() == "parallel" assert live.model is None - assert isinstance(design.control_variables["gap"], ReadFloatScalar) - assert not isinstance(design.control_variables["gap"], ReadWriteFloatScalar) + assert isinstance(design.control_variables["gap"], ReadWriteFloatScalar) assert source.control_variables["gap"] is None assert source.mode is None assert source.flags == {"moving": None, "orbit_ff": None} @@ -387,7 +386,7 @@ def test_optional_controls_and_hardware_motion_do_not_change_model(id_lattice_fi assert design.model.reference == reference -def test_fixed_reference_noops_and_rejected_writes(id_lattice_file): +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"] @@ -396,14 +395,11 @@ def test_fixed_reference_noops_and_rejected_writes(id_lattice_file): for disabled in (False, True): if disabled: device.model.disable() - variable.set(4.0) - variable.set_and_wait(4.0) device.model.mode = "parallel" - for value in (5.0, float("nan")): - with pytest.raises(PyAMLException, match="fixed model operating point"): - variable.set_and_wait(value) - with pytest.raises(PyAMLException, match="fixed model operating point"): - variable.set(5.0) + 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.model.mode = "antiparallel" assert variable.get() == 4.0 From 6b782d3915032dda47d4c3ee84bd842b7194d68e Mon Sep 17 00:00:00 2001 From: gubaidulinvadim Date: Wed, 25 Nov 2026 23:48:53 +0100 Subject: [PATCH 06/10] Merged lattice and control classes --- pyaml/common/abstract.py | 29 +++ pyaml/common/abstract_impl.py | 30 +++ pyaml/control/abstract_impl.py | 137 ++++++++++- pyaml/control/controlsystem.py | 11 +- pyaml/control/insertion_device.py | 71 ------ pyaml/insertion_device/insertion_device.py | 116 ++++++++-- pyaml/lattice/abstract_impl.py | 68 ++++++ pyaml/lattice/insertion_device.py | 105 --------- pyaml/lattice/simulator.py | 29 ++- tests/test_insertion_device.py | 253 ++++++++++++++++++--- 10 files changed, 610 insertions(+), 239 deletions(-) create mode 100644 pyaml/common/abstract_impl.py delete mode 100644 pyaml/control/insertion_device.py delete mode 100644 pyaml/lattice/insertion_device.py diff --git a/pyaml/common/abstract.py b/pyaml/common/abstract.py index 39805038..51a8f071 100644 --- a/pyaml/common/abstract.py +++ b/pyaml/common/abstract.py @@ -10,6 +10,35 @@ from numpy import array, double + +class RWScalarBoolean(metaclass=ABCMeta): + """Define backend-independent boolean get/set access.""" + + @abstractmethod + def get(self) -> bool: + """Return the boolean state.""" + pass + + @abstractmethod + def set(self, value: bool) -> None: + """Write the boolean state.""" + 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/control/abstract_impl.py b/pyaml/control/abstract_impl.py index 9724040e..2d6c2002 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 ..control.deviceaccess import DeviceAccess from ..control.deviceaccesslist import DeviceAccessList from ..magnet.magnet import Magnet @@ -26,7 +30,7 @@ # ------------------------------------------------------------------------------ -class RWScalarBoolean: +class RWScalarBoolean(abstract.RWScalarBoolean): """Expose a backend boolean through reusable get/set accessors.""" def __init__(self, device: DeviceAccess): @@ -46,6 +50,137 @@ def set(self, value: bool) -> None: self._device.set(value) +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.RWScalarBoolean | 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.RWScalarBoolean): + """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 29822b7c..d5eaa181 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -27,6 +27,9 @@ RWBpmTiltScalar, RWHardwareArray, RWHardwareScalar, + RWInsertionDeviceControlVariable, + RWInsertionDeviceEnabled, + RWInsertionDeviceMode, RWRFFrequencyScalar, RWRFPhaseScalar, RWRFVoltageScalar, @@ -47,7 +50,6 @@ from ..tuning_tools.tuning_tool import TuningTool from .deviceaccess import DeviceAccess from .deviceaccesslist import DeviceAccessList -from .insertion_device import RWInsertionDeviceControlVariable, RWInsertionDeviceMode class ControlSystem(ElementHolder, metaclass=ABCMeta): @@ -220,7 +222,7 @@ def create_bpm_aggregators(self, bpms: list[BPM]) -> list[ScalarAggregator | Non def _fill_insertion_device(self, device: InsertionDevice) -> None: """Bind named control variables and optional controls through backend references.""" - control_variables: dict[str, ReadWriteFloatScalar | None] = {} + control_variables: dict[str, RWInsertionDeviceControlVariable | None] = {} for name, definition in device._control_variable_definitions.items(): if "backend" not in definition: control_variables[name] = None @@ -232,7 +234,10 @@ def _fill_insertion_device(self, device: InsertionDevice) -> None: control_variables[name] = RWInsertionDeviceControlVariable(backend, definition["unit"], moving) flags = {name: RWScalarBoolean(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 - self.insertion_device.add(device.attach(self, control_variables, flags=flags, mode=mode)) + 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_device_access(magnet.model.get_device_names()[0]) diff --git a/pyaml/control/insertion_device.py b/pyaml/control/insertion_device.py deleted file mode 100644 index 0a6c8462..00000000 --- a/pyaml/control/insertion_device.py +++ /dev/null @@ -1,71 +0,0 @@ -"""Backend-neutral live insertion-device accessors.""" - -import time - -from ..common.abstract import ReadWriteFloatScalar -from ..common.exception import PyAMLConfigException, PyAMLException -from .abstract_impl import RWScalarBoolean, check_range, format_out_of_range_message -from .deviceaccess import DeviceAccess -from .readback_value import Value - - -class 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(ReadWriteFloatScalar): - """Write gap/phase variables with movement flags or currents without them.""" - - def __init__(self, device: DeviceAccess, unit: str, moving: RWScalarBoolean | 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) diff --git a/pyaml/insertion_device/insertion_device.py b/pyaml/insertion_device/insertion_device.py index db5d087c..46070094 100644 --- a/pyaml/insertion_device/insertion_device.py +++ b/pyaml/insertion_device/insertion_device.py @@ -12,6 +12,7 @@ phase: {unit: mm, backend: APPLE01_PHASE, movement_flag: APPLE01_MOVING} control_mode: APPLE01_MODE model_operating_point: {gap: 4.0, phase: 0.0, mode: parallel} + disabled_operating_point: {gap: 30.0, phase: 0.0} orbit_feedforward: ID01_ORBIT_FF Runtime ``control_variables`` use existing pyAML scalar accessors. An absent key @@ -50,10 +51,23 @@ Optional controls use ``device.mode.get()/set(value)`` and ``device.flags[name].get()/set(value)``; the latter reuse ``RWScalarBoolean``. +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. ``device.model.disable()`` delegates to pyAT's -same-length drift/identity approximation; ``enable()`` restores the kickmap. -Neither operation changes the reference point or any hardware. +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. +``model_operating_point`` exposes the same read-only +``RInsertionDeviceModelPoint`` in live and simulator holders. """ import copy @@ -62,16 +76,16 @@ from types import MappingProxyType from typing import TYPE_CHECKING, Self -from ..common.abstract import ReadWriteFloatScalar +from pydantic import StrictFloat + +from ..common import abstract +from ..common.abstract_impl import RInsertionDeviceModelPoint from ..common.element import Element -from ..common.exception import PyAMLConfigException +from ..common.exception import PyAMLConfigException, PyAMLException from ..validation import DynamicValidation, register_schema if TYPE_CHECKING: from ..common.holders.element_holder import ElementHolder - from ..control.abstract_impl import RWScalarBoolean - from ..control.insertion_device import RWInsertionDeviceMode - from ..lattice import insertion_device PYAMLCLASS = "InsertionDevice" @@ -95,6 +109,8 @@ class InsertionDevice(Element, DynamicValidation): ``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`` configures live resting setpoints. Enable uses + ``model_operating_point``; neither command modifies that fixed reference. """ def __init__( @@ -109,6 +125,7 @@ def __init__( model_operating_point: dict[str, float | str] | None = None, lattice_names: str | None = None, description: str | None = None, + disabled_operating_point: dict[str, StrictFloat] | None = None, ): super().__init__(name, lattice_names, description) if not device_id.strip(): @@ -135,27 +152,48 @@ def __init__( ) if not key.strip() or not valid: raise PyAMLConfigException(f"{name}.{key}: expected a finite coordinate or string mode") + if disabled_operating_point is not None: + if not disabled_operating_point: + raise PyAMLConfigException(f"{name}: disabled_operating_point must not be empty") + for key, value in disabled_operating_point.items(): + if key not in control_variables: + 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 = copy.deepcopy(control_variables) self._flag_refs = dict(flags or {}) - self._point = dict(model_operating_point) if model_operating_point is not None else None - self._control_variables: dict[str, ReadWriteFloatScalar | None] = dict.fromkeys(self._control_variable_definitions) - self._flags: dict[str, RWScalarBoolean | None] = dict.fromkeys(self._flag_refs) - self.mode: RWInsertionDeviceMode | None = None + self._disabled_point = dict(disabled_operating_point) if disabled_operating_point is not None else None + self._point = ( + RInsertionDeviceModelPoint( + model_operating_point, + {name: definition["unit"] for name, definition in self._control_variable_definitions.items()}, + ) + if model_operating_point is not None + else None + ) + self._control_variables: dict[str, abstract.ReadWriteFloatScalar | None] = dict.fromkeys( + self._control_variable_definitions + ) + self._flags: dict[str, abstract.RWScalarBoolean | 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.model: insertion_device.InsertionDevice | None = None + self._enabled: abstract.RWScalarBoolean | None = None + self._model_maps: tuple[str | None, ...] = () @property - def control_variables(self) -> Mapping[str, ReadWriteFloatScalar | None]: + 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, "RWScalarBoolean | None"]: + def flags(self) -> Mapping[str, abstract.RWScalarBoolean | None]: """Boolean backend controls, or None when unavailable in this holder.""" return MappingProxyType(self._flags) @@ -164,16 +202,49 @@ def flag_references(self) -> Mapping[str, str]: return MappingProxyType(self._flag_refs) @property - def model_operating_point(self) -> Mapping[str, float | str] | None: - return MappingProxyType(self._point) if self._point is not None else None + def model_operating_point(self) -> RInsertionDeviceModelPoint | None: + """Configured model reference, independent of the holder or hardware state.""" + 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.""" + return { + "device_id": self.device_id, + "description": self.description, + "operating_point": dict(self._point) if self._point is not None else None, + "units": dict(self._point.units) if self._point is not None else {}, + "maps": self._model_maps, + } + + @property + def enabled(self) -> abstract.RWScalarBoolean: + """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, ReadWriteFloatScalar | None] | None = None, - model: "insertion_device.InsertionDevice | None" = None, - flags: Mapping[str, "RWScalarBoolean | None"] | None = None, - mode: "RWInsertionDeviceMode | None" = None, + control_variables: Mapping[str, abstract.ReadWriteFloatScalar | None] | None = None, + enabled: abstract.RWScalarBoolean | None = None, + flags: Mapping[str, abstract.RWScalarBoolean | None] | None = None, + mode: abstract.RWInsertionDeviceMode | None = None, + model_maps: tuple[str | None, ...] = (), ) -> Self: """Return a per-peer copy; defaults give metadata-only access.""" obj = copy.copy(self) @@ -184,7 +255,8 @@ def attach( 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.model = model + obj._enabled = enabled + obj._model_maps = model_maps return obj def _fill_device(self, holder: "ElementHolder") -> None: diff --git a/pyaml/lattice/abstract_impl.py b/pyaml/lattice/abstract_impl.py index a734a587..7109bec0 100644 --- a/pyaml/lattice/abstract_impl.py +++ b/pyaml/lattice/abstract_impl.py @@ -21,6 +21,74 @@ # ------------------------------------------------------------------------------ +class RWInsertionDeviceControlVariable(abstract.ReadWriteFloatScalar): + """Expose the shared control-variable interface while rejecting model writes.""" + + def __init__(self, name: str, value: float, unit: str): + self._name = name + self._value = value + self._unit = unit + + def get(self) -> float: + return self._value + + def readback(self) -> float: + """Return the model reference, not a hardware readback.""" + return self._value + + def unit(self) -> str: + return self._unit + + def get_range(self) -> list[float]: + return [self._value, self._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): + self._name = name + self._mode = mode + + def get(self) -> str: + return self._mode + + def set(self, value: str) -> None: + if value != self._mode: + raise PyAMLException(f"{self._name}: fixed model operating point does not support mode {value!r}") + + +class RWInsertionDeviceEnabled(abstract.RWScalarBoolean): + """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 + + def _effective_lengths(elements: list[at.Element]) -> list[float]: """ Return the lengths used to convert between integrated strengths and polynom coefficients. diff --git a/pyaml/lattice/insertion_device.py b/pyaml/lattice/insertion_device.py deleted file mode 100644 index 2a275465..00000000 --- a/pyaml/lattice/insertion_device.py +++ /dev/null @@ -1,105 +0,0 @@ -"""Fixed-operating-point insertion-device accessors for pyAT.""" - -import copy -from typing import TYPE_CHECKING - -import at - -from ..common.abstract import ReadWriteFloatScalar -from ..common.exception import PyAMLException -from ..insertion_device import insertion_device - -if TYPE_CHECKING: - from ..common.holders.element_holder import ElementHolder - - -class RWInsertionDeviceControlVariable(ReadWriteFloatScalar): - """Expose the shared control-variable interface while rejecting model writes.""" - - def __init__(self, name: str, value: float, unit: str): - self._name = name - self._value = value - self._unit = unit - - def get(self) -> float: - return self._value - - def readback(self) -> float: - """Return the model reference, not a hardware readback.""" - return self._value - - def unit(self) -> str: - return self._unit - - def get_range(self) -> list[float]: - return [self._value, self._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 InsertionDevice: - """Linked kickmap segment(s) and their fixed reference, independent of hardware.""" - - def __init__(self, device: insertion_device.InsertionDevice, kickmaps: list[at.InsertionDeviceKickMap]): - point = 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") - if device.control_mode is not None and "mode" not in point: - raise PyAMLException(f"{device.name}: model_operating_point must include mode") - self._name = device.name - self._point = dict(point) - self._kickmaps = tuple(kickmaps) - self._reference = { - "device_id": device.device_id, - "description": device.description, - "operating_point": dict(point), - "units": {name: definition["unit"] for name, definition in device._control_variable_definitions.items()}, - "maps": tuple(getattr(element, "Filename_in", None) for element in kickmaps), - } - - @property - def reference(self) -> dict: - """Return reference coordinates/provenance, never live hardware values.""" - return copy.deepcopy(self._reference) - - @property - def mode(self) -> str | None: - value = self._point.get("mode") - return value if isinstance(value, str) else None - - @mode.setter - def mode(self, value: str) -> None: - if self.mode is None or value != self.mode: - raise PyAMLException(f"{self._name}: fixed model operating point does not support mode {value!r}") - - @property - def enabled(self) -> bool: - 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") - return states.pop() - - def enable(self) -> None: - """Restore kickmap tracking through pyAT, without changing its reference.""" - for element in self._kickmaps: - element.enable() - - def disable(self) -> None: - """Use pyAT's same-length drift/identity approximation, not hardware motion.""" - for element in self._kickmaps: - element.disable() - - def attach(self, device: insertion_device.InsertionDevice, peer: "ElementHolder") -> insertion_device.InsertionDevice: - control_variables = {} - for name, definition in device._control_variable_definitions.items(): - value = self._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}", float(value), definition["unit"] - ) - return device.attach(peer, control_variables, self) diff --git a/pyaml/lattice/simulator.py b/pyaml/lattice/simulator.py index d4bc06e9..6a724c6d 100644 --- a/pyaml/lattice/simulator.py +++ b/pyaml/lattice/simulator.py @@ -18,7 +18,7 @@ from ..common.holders.element_holder import ElementHolder from ..configuration import ROOT from ..diagnostics.tune_monitor import BetatronTuneMonitor -from ..insertion_device import insertion_device +from ..insertion_device import InsertionDevice from ..lattice.abstract_impl import ( BPMHScalarAggregator, BPMScalarAggregator, @@ -29,6 +29,9 @@ RWBpmTiltScalar, RWHardwareArray, RWHardwareScalar, + RWInsertionDeviceControlVariable, + RWInsertionDeviceEnabled, + RWInsertionDeviceMode, RWRFATFrequencyScalar, RWRFATotalVoltageScalar, RWRFFrequencyScalar, @@ -48,7 +51,6 @@ from ..tuning_tools.measurement_tool import MeasurementTool from ..tuning_tools.tuning_tool import TuningTool from ..validation import DynamicValidation, register_schema -from .insertion_device import InsertionDevice from .lattice_elements_linker import LatticeElementsLinker from .twiss_in import TwissIn @@ -247,7 +249,7 @@ def create_bpm_aggregators(self, bpms: list[BPM]) -> list[ScalarAggregator]: aggv.add_elem(e) return [agg, aggh, aggv] - def _fill_insertion_device(self, device: insertion_device.InsertionDevice) -> None: + def _fill_insertion_device(self, device: InsertionDevice) -> None: kickmaps = [] for element in self.get_at_elems(device): if not isinstance(element, at.InsertionDeviceKickMap): @@ -255,8 +257,25 @@ def _fill_insertion_device(self, device: insertion_device.InsertionDevice) -> No kickmaps.append(element) if not kickmaps: raise PyAMLException(f"{device.name}: no insertion-device kickmaps found") - model = InsertionDevice(device, kickmaps) - self.insertion_device.add(model.attach(device, self)) + point = 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: + if point.mode is None: + raise PyAMLException(f"{device.name}: model_operating_point must include mode") + mode = RWInsertionDeviceMode(device.name, 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}", 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)) def _fill_magnet(self, magnet: Magnet) -> None: current = ( diff --git a/tests/test_insertion_device.py b/tests/test_insertion_device.py index e339117f..e3da4d0a 100644 --- a/tests/test_insertion_device.py +++ b/tests/test_insertion_device.py @@ -7,7 +7,8 @@ from pyaml import PyAMLConfigException, PyAMLException from pyaml.accelerator import Accelerator -from pyaml.common.abstract import ReadWriteFloatScalar +from pyaml.common import abstract +from pyaml.common.abstract_impl import RInsertionDeviceModelPoint from pyaml.common.element import Element from pyaml.configuration.factory import Factory from pyaml.control.abstract_impl import RWScalarBoolean @@ -122,6 +123,7 @@ def test_configuration_supports_control_variable_families(id_lattice_file, decla "lattice_names": "list(MAP)", "control_variables": control_variables, "model_operating_point": point, + "disabled_operating_point": {name: 0.0 for name in control_variables}, } device = Factory.build(SchemaValidator.validate_to_dict(config)) simulator = Simulator("design", id_lattice_file) @@ -131,7 +133,8 @@ def test_configuration_supports_control_variable_families(id_lattice_file, decla for name, definition in control_variables.items(): assert attached.control_variables[name].get() == point[name] assert attached.control_variables[name].unit() == definition["unit"] - assert attached.model.reference["operating_point"] == point + 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 @@ -144,6 +147,10 @@ def test_configuration_supports_control_variable_families(id_lattice_file, decla ({"control_variables": {"gap": {"unit": "mm", "access": "read"}}}, "expected only unit, backend and movement_flag"), ({"control_variables": {"gap": {"unit": "mm", "backend": ""}}}, "backend must not be empty"), ({"model_operating_point": {"gap": float("inf")}}, "finite coordinate"), + ({"disabled_operating_point": {}}, "must not be empty"), + ({"disabled_operating_point": {"missing": 0.0}}, "requires a configured control variable"), + ({"disabled_operating_point": {"gap": float("nan")}}, "requires a finite setpoint"), + ({"disabled_operating_point": {"gap": True}}, "valid number"), ({"model_operating_point": {}}, "include every configured control variable"), ({"control_mode": "MODE"}, "include mode"), ({"lattice_names": "list(D)"}, "expected InsertionDeviceKickMap"), @@ -167,6 +174,8 @@ def test_holder_registration_associations_and_add_rollback(id_lattice_file): copies = [] for holder in machine.modes().values(): device = holder.insertion_device.get("ID") + assert type(device) is InsertionDevice + assert isinstance(device.enabled, abstract.RWScalarBoolean) copies.append(device) assert holder["ID"] is device assert holder.insertion_device.all() == [device] @@ -199,7 +208,7 @@ def test_live_attachment_binds_hardware_separately_from_model(id_lattice_file): live = machine.live.insertion_device.get("ID") design = machine.design.insertion_device.get("ID") gap = live.control_variables["gap"] - assert isinstance(gap, ReadWriteFloatScalar) + assert isinstance(gap, abstract.ReadWriteFloatScalar) assert gap.readback() == 8.0 assert gap.get() == 9.0 assert gap.get_range() == [2.0, 30.0] @@ -210,12 +219,22 @@ def test_live_attachment_binds_hardware_separately_from_model(id_lattice_file): assert live.flag_references["moving"] == "MOVING" assert live.control_mode == "MODE" assert live.mode.get() == "parallel" - assert live.model is None - assert isinstance(design.control_variables["gap"], ReadWriteFloatScalar) + assert live.enabled.get() is True + assert design.mode.get() == "parallel" + assert isinstance(design.control_variables["gap"], abstract.ReadWriteFloatScalar) assert source.control_variables["gap"] is None assert source.mode is None assert source.flags == {"moving": None, "orbit_ff": None} 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, "mode": "parallel"} + assert point.units == {"gap": "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" assert "InsertionDevice" in repr(live) @@ -246,12 +265,12 @@ def test_same_class_binds_mechanical_and_current_control_variables(names): assert type(attached) is InsertionDevice assert set(attached.control_variables) == set(names) for variable in attached.control_variables.values(): - assert isinstance(variable, ReadWriteFloatScalar) + assert isinstance(variable, abstract.ReadWriteFloatScalar) variable.set(5.0) assert variable.get() == 5.0 assert variable.readback() == 0.0 assert variable.unit() == unit - assert attached.model is None + assert attached.enabled.get() is True assert source.peer is None @@ -266,7 +285,7 @@ def test_writable_and_unavailable_control_variables_are_distinguishable(): control.fill_device([source]) device = control.insertion_device.get("ID") gap = device.control_variables["gap"] - assert isinstance(gap, ReadWriteFloatScalar) + assert isinstance(gap, abstract.ReadWriteFloatScalar) assert gap.readback() == 8.0 assert gap.get() == 9.0 assert gap.get_range() == [2.0, 30.0] @@ -282,7 +301,7 @@ def test_set_and_wait_uses_only_boolean_movement_flag(monkeypatch, moving_values backend = control.get_device_access("GAP") moving = control.get_device_access("MOVING") sleep = Mock() - monkeypatch.setattr("pyaml.control.insertion_device.time.sleep", sleep) + 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")), @@ -368,7 +387,7 @@ def test_optional_controls_and_hardware_motion_do_not_change_model(id_lattice_fi machine = _machine(id_lattice_file, [source], controls=[control]) live = machine.live.insertion_device.get("ID") design = machine.design.insertion_device.get("ID") - reference = design.model.reference + reference = design.model_reference live.control_variables["gap"].set_and_wait(12.0) set_attribute("GAP", 12.0) live.mode.set("antiparallel") @@ -379,60 +398,230 @@ def test_optional_controls_and_hardware_motion_do_not_change_model(id_lattice_fi assert live.flags["orbit_ff"].get() is False assert design.control_variables["gap"].get() == 4.0 assert design.control_variables["gap"].get_range() == [4.0, 4.0] - assert design.model.mode == "parallel" + assert design.mode.get() == "parallel" + assert live.model_operating_point["gap"] == 4.0 + assert live.model_operating_point.mode == "parallel" with patch.object(control, "get_device_access", side_effect=AssertionError("Model must not access hardware")): - design.model.disable() - design.model.enable() - assert design.model.reference == reference + design.disable() + design.enable() + assert design.model_reference == reference 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 + reference = device.model_reference assert variable.readback() == variable.get() == 4.0 for disabled in (False, True): if disabled: - device.model.disable() - device.model.mode = "parallel" + 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.model.mode = "antiparallel" + device.mode.set("antiparallel") assert variable.get() == 4.0 - assert device.model.reference == reference + assert device.model_reference == reference reference["operating_point"]["gap"] = 20.0 - assert device.model.reference["operating_point"]["gap"] == 4.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()]) - model = machine.design.insertion_device.get("ID").model + 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 = model.reference + 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] - assert model.enabled - model.disable() - model.disable() - assert not model.enabled + 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").model.enabled - assert machine.live.insertion_device.get("ID").model is None - model.enable() - model.enable() - assert model.enabled + 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 model.reference == reference + 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 + 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 + + +def test_enabled_accessors_reject_nonboolean_writes(id_lattice_file): + machine = _machine(id_lattice_file, [_device()]) + for holder in machine.modes().values(): + device = holder.insertion_device.get("ID") + with pytest.raises(PyAMLException, match="boolean enabled state"): + device.enabled.set(1) + assert device.enabled.get() is True + + +def test_unattached_enabled_state_is_unavailable(): + device = _device() + for command in (device.enable, device.disable): + with pytest.raises(PyAMLException, match="before attachment"): + command() + + +@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]) From b2cdf6089a47721d8abe880b3d79f6b8df9a67a6 Mon Sep 17 00:00:00 2001 From: gubaidulinvadim Date: Thu, 26 Nov 2026 11:37:26 +0100 Subject: [PATCH 07/10] Renamed RWScalarBoolean to RWBooleanScalar --- pyaml/common/abstract.py | 2 +- pyaml/control/abstract_impl.py | 6 +++--- pyaml/control/controlsystem.py | 6 +++--- pyaml/insertion_device/insertion_device.py | 14 +++++++------- pyaml/lattice/abstract_impl.py | 2 +- tests/test_insertion_device.py | 10 +++++----- 6 files changed, 20 insertions(+), 20 deletions(-) diff --git a/pyaml/common/abstract.py b/pyaml/common/abstract.py index 51a8f071..7c2ddb3e 100644 --- a/pyaml/common/abstract.py +++ b/pyaml/common/abstract.py @@ -11,7 +11,7 @@ from numpy import array, double -class RWScalarBoolean(metaclass=ABCMeta): +class RWBooleanScalar(metaclass=ABCMeta): """Define backend-independent boolean get/set access.""" @abstractmethod diff --git a/pyaml/control/abstract_impl.py b/pyaml/control/abstract_impl.py index 2d6c2002..7d6601ed 100644 --- a/pyaml/control/abstract_impl.py +++ b/pyaml/control/abstract_impl.py @@ -30,7 +30,7 @@ # ------------------------------------------------------------------------------ -class RWScalarBoolean(abstract.RWScalarBoolean): +class RWBooleanScalar(abstract.RWBooleanScalar): """Expose a backend boolean through reusable get/set accessors.""" def __init__(self, device: DeviceAccess): @@ -73,7 +73,7 @@ def set(self, value: str) -> None: class RWInsertionDeviceControlVariable(abstract.ReadWriteFloatScalar): """Write gap/phase variables with movement flags or currents without them.""" - def __init__(self, device: DeviceAccess, unit: str, moving: abstract.RWScalarBoolean | None = None): + 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}" @@ -112,7 +112,7 @@ def set_and_wait(self, value: float) -> None: time.sleep(0.1) -class RWInsertionDeviceEnabled(abstract.RWScalarBoolean): +class RWInsertionDeviceEnabled(abstract.RWBooleanScalar): """Apply live operating points and retain pyAML's logical enabled state.""" def __init__( diff --git a/pyaml/control/controlsystem.py b/pyaml/control/controlsystem.py index d5eaa181..864b6dd2 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -23,6 +23,7 @@ CSStrengthScalarAggregator, RBetatronTuneArray, RBpmArray, + RWBooleanScalar, RWBpmOffsetArray, RWBpmTiltScalar, RWHardwareArray, @@ -33,7 +34,6 @@ RWRFFrequencyScalar, RWRFPhaseScalar, RWRFVoltageScalar, - RWScalarBoolean, RWSerializedStrengthScalar, RWStrengthArray, RWStrengthScalar, @@ -229,10 +229,10 @@ def _fill_insertion_device(self, device: InsertionDevice) -> None: continue backend = self.get_device_access(definition["backend"]) moving = ( - RWScalarBoolean(self.get_device_access(definition["movement_flag"])) if "movement_flag" in definition else None + 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: RWScalarBoolean(self.get_device_access(ref)) for name, ref in device.flag_references.items()} + 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 diff --git a/pyaml/insertion_device/insertion_device.py b/pyaml/insertion_device/insertion_device.py index 46070094..b656587f 100644 --- a/pyaml/insertion_device/insertion_device.py +++ b/pyaml/insertion_device/insertion_device.py @@ -49,7 +49,7 @@ 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 ``RWScalarBoolean``. +``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 @@ -180,11 +180,11 @@ def __init__( self._control_variables: dict[str, abstract.ReadWriteFloatScalar | None] = dict.fromkeys( self._control_variable_definitions ) - self._flags: dict[str, abstract.RWScalarBoolean | None] = dict.fromkeys(self._flag_refs) + 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.RWScalarBoolean | None = None + self._enabled: abstract.RWBooleanScalar | None = None self._model_maps: tuple[str | None, ...] = () @property @@ -193,7 +193,7 @@ def control_variables(self) -> Mapping[str, abstract.ReadWriteFloatScalar | None return MappingProxyType(self._control_variables) @property - def flags(self) -> Mapping[str, abstract.RWScalarBoolean | None]: + def flags(self) -> Mapping[str, abstract.RWBooleanScalar | None]: """Boolean backend controls, or None when unavailable in this holder.""" return MappingProxyType(self._flags) @@ -223,7 +223,7 @@ def model_reference(self) -> dict: } @property - def enabled(self) -> abstract.RWScalarBoolean: + 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") @@ -241,8 +241,8 @@ def attach( self, peer: "ElementHolder", control_variables: Mapping[str, abstract.ReadWriteFloatScalar | None] | None = None, - enabled: abstract.RWScalarBoolean | None = None, - flags: Mapping[str, abstract.RWScalarBoolean | 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, ...] = (), ) -> Self: diff --git a/pyaml/lattice/abstract_impl.py b/pyaml/lattice/abstract_impl.py index 7109bec0..c9e43035 100644 --- a/pyaml/lattice/abstract_impl.py +++ b/pyaml/lattice/abstract_impl.py @@ -64,7 +64,7 @@ def set(self, value: str) -> None: raise PyAMLException(f"{self._name}: fixed model operating point does not support mode {value!r}") -class RWInsertionDeviceEnabled(abstract.RWScalarBoolean): +class RWInsertionDeviceEnabled(abstract.RWBooleanScalar): """Toggle kickmap tracking and retain pyAML's logical enabled state.""" def __init__(self, name: str, kickmaps: list[at.InsertionDeviceKickMap]): diff --git a/tests/test_insertion_device.py b/tests/test_insertion_device.py index e3da4d0a..7eb5b1a9 100644 --- a/tests/test_insertion_device.py +++ b/tests/test_insertion_device.py @@ -11,7 +11,7 @@ from pyaml.common.abstract_impl import RInsertionDeviceModelPoint from pyaml.common.element import Element from pyaml.configuration.factory import Factory -from pyaml.control.abstract_impl import RWScalarBoolean +from pyaml.control.abstract_impl import RWBooleanScalar from pyaml.control.controlsystem import ControlSystem from pyaml.control.readback_value import Value from pyaml.insertion_device import InsertionDevice @@ -175,7 +175,7 @@ def test_holder_registration_associations_and_add_rollback(id_lattice_file): for holder in machine.modes().values(): device = holder.insertion_device.get("ID") assert type(device) is InsertionDevice - assert isinstance(device.enabled, abstract.RWScalarBoolean) + assert isinstance(device.enabled, abstract.RWBooleanScalar) copies.append(device) assert holder["ID"] is device assert holder.insertion_device.all() == [device] @@ -213,7 +213,7 @@ def test_live_attachment_binds_hardware_separately_from_model(id_lattice_file): assert gap.get() == 9.0 assert gap.get_range() == [2.0, 30.0] assert "phase" not in live.control_variables - assert isinstance(live.flags["moving"], RWScalarBoolean) + assert isinstance(live.flags["moving"], RWBooleanScalar) assert live.flags["moving"].get() is False assert live.flags["orbit_ff"].get() is True assert live.flag_references["moving"] == "MOVING" @@ -363,13 +363,13 @@ def test_boolean_scalar_reads_boolean_value(value): control = _control() backend = control.get_device_access("FF") with patch.object(backend, "readback", return_value=value): - assert RWScalarBoolean(backend).get() is bool(value.value if isinstance(value, Value) else value) + assert RWBooleanScalar(backend).get() is bool(value.value if isinstance(value, Value) else value) def test_boolean_scalar_writes_and_rejects_nonboolean_values(): control = _control() backend = control.get_device_access("FF") - flag = RWScalarBoolean(backend) + flag = RWBooleanScalar(backend) flag.set(False) assert flag.get() is False with pytest.raises(PyAMLException, match="boolean flag"): From 30bb4e10e29b6fcee18569f85fcb71e7f2490d74 Mon Sep 17 00:00:00 2001 From: gubaidulinvadim Date: Thu, 26 Nov 2026 15:51:11 +0100 Subject: [PATCH 08/10] Added NamedValue for validation. InsertionDevice is now using it. --- pyaml/apidoc/gen_api.py | 2 + pyaml/configuration/__init__.py | 2 + pyaml/configuration/named_value.py | 31 +++++ pyaml/insertion_device/__init__.py | 3 +- pyaml/insertion_device/control_variable.py | 26 ++++ pyaml/insertion_device/insertion_device.py | 133 +++++++++++++++------ tests/configuration/test_factory.py | 19 ++- tests/test_insertion_device.py | 52 ++++++-- 8 files changed, 217 insertions(+), 51 deletions(-) create mode 100644 pyaml/configuration/named_value.py create mode 100644 pyaml/insertion_device/control_variable.py diff --git a/pyaml/apidoc/gen_api.py b/pyaml/apidoc/gen_api.py index 556664c3..fae9e8a7 100644 --- a/pyaml/apidoc/gen_api.py +++ b/pyaml/apidoc/gen_api.py @@ -10,6 +10,8 @@ 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/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..1823e10b --- /dev/null +++ b/pyaml/configuration/named_value.py @@ -0,0 +1,31 @@ +"""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. + + Configuration + ------------- + .. code-block:: yaml + + - type: pyaml.configuration.named_value + name: gap + value: 4.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/insertion_device/__init__.py b/pyaml/insertion_device/__init__.py index dddbb5fc..4cfd62d3 100644 --- a/pyaml/insertion_device/__init__.py +++ b/pyaml/insertion_device/__init__.py @@ -2,8 +2,9 @@ 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"] +__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 index b656587f..fd478086 100644 --- a/pyaml/insertion_device/insertion_device.py +++ b/pyaml/insertion_device/insertion_device.py @@ -1,6 +1,6 @@ """Insertion-device holding class, independent of facility control systems. -Example (the lattice already contains the kickmap):: +Object-based configuration (the lattice already contains the kickmap):: - type: pyaml.insertion_device name: APPLE01 @@ -8,11 +8,34 @@ lattice_names: ID02 description: Kickmap measured at 4 mm gap and zero phase. control_variables: - gap: {unit: mm, backend: APPLE01_GAP, movement_flag: APPLE01_GAP_MOVING} - phase: {unit: mm, backend: APPLE01_PHASE, movement_flag: APPLE01_MOVING} + - 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: {gap: 4.0, phase: 0.0, mode: parallel} - disabled_operating_point: {gap: 30.0, phase: 0.0} + 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 @@ -29,17 +52,36 @@ 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:: +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: - ps1: {unit: A, backend: EM01_PS1} - ps2: {unit: A, backend: EM01_PS2} - ps3: {unit: A, backend: EM01_PS3} - model_operating_point: {ps1: 100.0, ps2: 0.0, ps3: 0.0} + - 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 @@ -76,13 +118,13 @@ from types import MappingProxyType from typing import TYPE_CHECKING, Self -from pydantic import StrictFloat - 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 @@ -94,22 +136,24 @@ class InsertionDevice(Element, DynamicValidation): """Hold control variables and references to other pyAML elements. - ``control_variables`` configures units and opaque backend references. + ``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 flat: numeric coordinates and optional string - ``mode``. Missing coordinates never imply zero. Additional provenance may + ``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`` configures live resting setpoints. Enable uses + ``disabled_operating_point`` lists named numeric live resting setpoints. Enable uses ``model_operating_point``; neither command modifies that fixed reference. """ @@ -117,46 +161,59 @@ def __init__( self, name: str, device_id: str, - control_variables: dict[str, dict[str, str]] | None = None, + 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: dict[str, float | str] | None = None, + model_operating_point: list[NamedValue] | None = None, lattice_names: str | None = None, description: str | None = None, - disabled_operating_point: dict[str, StrictFloat] | None = None, + disabled_operating_point: 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 key, definition in control_variables.items(): - if not key.strip() or not definition.get("unit", "").strip(): - raise PyAMLConfigException(f"{name}: each control variable requires a name and unit") - if set(definition) - {"unit", "backend", "movement_flag"}: - raise PyAMLConfigException(f"{name}.{key}: expected only unit, backend and movement_flag") - for field in ("backend", "movement_flag"): - if field in definition and not definition[field].strip(): - raise PyAMLConfigException(f"{name}.{key}: {field} must not be empty") + for field, entries in ( + ("control_variables", control_variables), + ("model_operating_point", model_operating_point), + ("disabled_operating_point", disabled_operating_point), + ): + 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") - for key, value in (model_operating_point or {}).items(): + for key, value in (model_values or {}).items(): valid = ( isinstance(value, str) and bool(value.strip()) if key == "mode" - else (isinstance(value, (int, float)) and math.isfinite(value)) + else isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) ) - if not key.strip() or not valid: + if not valid: raise PyAMLConfigException(f"{name}.{key}: expected a finite coordinate or string mode") - if disabled_operating_point is not None: - if not disabled_operating_point: + 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_operating_point.items(): - if key not in control_variables: + 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" ) @@ -166,15 +223,15 @@ def __init__( self.control_mode = control_mode self.orbit_feedforward_name = orbit_feedforward self.tune_feedforward_name = tune_feedforward - self._control_variable_definitions = copy.deepcopy(control_variables) + self._control_variable_definitions = definitions self._flag_refs = dict(flags or {}) - self._disabled_point = dict(disabled_operating_point) if disabled_operating_point is not None else None + self._disabled_point = disabled_values self._point = ( RInsertionDeviceModelPoint( - model_operating_point, + model_values, {name: definition["unit"] for name, definition in self._control_variable_definitions.items()}, ) - if model_operating_point is not None + if model_values is not None else None ) self._control_variables: dict[str, abstract.ReadWriteFloatScalar | None] = dict.fromkeys( diff --git a/tests/configuration/test_factory.py b/tests/configuration/test_factory.py index 692706bc..488d9ed2 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,20 @@ def test_factory_build_default(): assert obj.name == "simple" +@pytest.mark.parametrize("value", [4.0, "parallel", True, {"labels": ["a", "b"]}]) +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 + with pytest.raises(PyAMLConfigException, match="nonempty name"): + NamedValue(" ", value) + + @pytest.mark.parametrize( "test_file", [ diff --git a/tests/test_insertion_device.py b/tests/test_insertion_device.py index 7eb5b1a9..e18cb398 100644 --- a/tests/test_insertion_device.py +++ b/tests/test_insertion_device.py @@ -10,11 +10,12 @@ from pyaml.common import abstract from pyaml.common.abstract_impl import RInsertionDeviceModelPoint from pyaml.common.element import Element -from pyaml.configuration.factory import Factory +from pyaml.configuration import NamedValue +from pyaml.configuration.factory import ELEMENT_REGISTRY, Factory from pyaml.control.abstract_impl import RWBooleanScalar from pyaml.control.controlsystem import ControlSystem from pyaml.control.readback_value import Value -from pyaml.insertion_device import InsertionDevice +from pyaml.insertion_device import ControlVariable, InsertionDevice from pyaml.lattice.simulator import Simulator from pyaml.validation.validator import SchemaValidator @@ -80,6 +81,13 @@ def _device(**overrides): "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) @@ -121,9 +129,16 @@ def test_configuration_supports_control_variable_families(id_lattice_file, decla "name": "ID", "device_id": "SERIAL", "lattice_names": "list(MAP)", - "control_variables": control_variables, - "model_operating_point": point, - "disabled_operating_point": {name: 0.0 for name in control_variables}, + "control_variables": [ + {"type": "pyaml.insertion_device.control_variable", "name": 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) @@ -136,6 +151,8 @@ def test_configuration_supports_control_variable_families(id_lattice_file, decla 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( @@ -143,23 +160,38 @@ def test_configuration_supports_control_variable_families(id_lattice_file, decla [ ({"control_variables": {}}, "at least one control variable"), ({"control_variables": None}, "at least one control variable"), - ({"control_variables": {"gap": {}}}, "requires a name and unit"), - ({"control_variables": {"gap": {"unit": "mm", "access": "read"}}}, "expected only unit, backend and movement_flag"), + ({"control_variables": {"gap": {"unit": ""}}}, "requires a name and unit"), + ({"control_variables": {"gap": {"unit": "mm", "access": "read"}}}, "unexpected keyword argument"), ({"control_variables": {"gap": {"unit": "mm", "backend": ""}}}, "backend must not be empty"), ({"model_operating_point": {"gap": float("inf")}}, "finite coordinate"), ({"disabled_operating_point": {}}, "must not be empty"), ({"disabled_operating_point": {"missing": 0.0}}, "requires a configured control variable"), - ({"disabled_operating_point": {"gap": float("nan")}}, "requires a finite setpoint"), - ({"disabled_operating_point": {"gap": True}}, "valid number"), + ({"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"), ({"model_operating_point": {}}, "include every configured control variable"), ({"control_mode": "MODE"}, "include mode"), ({"lattice_names": "list(D)"}, "expected InsertionDeviceKickMap"), ({"lattice_names": "list(MISSING)"}, "not found in lattice"), + ( + {"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", + ), + ( + {"disabled_operating_point": [NamedValue("gap", 30.0), NamedValue("gap", 20.0)]}, + "duplicate names in disabled_operating_point", + ), ], ) def test_invalid_configuration_or_mapping_is_rejected(id_lattice_file, overrides, error): simulator = Simulator("design", id_lattice_file) - with pytest.raises((PyAMLException, PyAMLConfigException), match=error): + with pytest.raises((PyAMLException, PyAMLConfigException, TypeError), match=error): simulator.fill_device([_device(**overrides)]) assert not simulator.insertion_device.all() assert all(element.PassMethod == "IdTablePass" for element in simulator.ring[:2]) From 73cb540787f1e8b9a80736ff8f5b4796cef4b10f Mon Sep 17 00:00:00 2001 From: gubaidulinvadim Date: Thu, 26 Nov 2026 16:30:58 +0100 Subject: [PATCH 09/10] Reduced number of tests --- tests/configuration/test_factory.py | 7 +- tests/test_insertion_device.py | 222 ++++++++++------------------ 2 files changed, 79 insertions(+), 150 deletions(-) diff --git a/tests/configuration/test_factory.py b/tests/configuration/test_factory.py index 488d9ed2..772960a4 100644 --- a/tests/configuration/test_factory.py +++ b/tests/configuration/test_factory.py @@ -17,7 +17,7 @@ def test_factory_build_default(): assert obj.name == "simple" -@pytest.mark.parametrize("value", [4.0, "parallel", True, {"labels": ["a", "b"]}]) +@pytest.mark.parametrize("value", [True, {"labels": ["a", "b"]}]) def test_named_value_configuration(value): obj = Factory.build( SchemaValidator.validate_to_dict({"type": "pyaml.configuration.named_value", "name": "setting", "value": value}) @@ -27,8 +27,11 @@ def test_named_value_configuration(value): 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(" ", value) + NamedValue(" ", 4.0) @pytest.mark.parametrize( diff --git a/tests/test_insertion_device.py b/tests/test_insertion_device.py index e18cb398..d820f933 100644 --- a/tests/test_insertion_device.py +++ b/tests/test_insertion_device.py @@ -13,24 +13,12 @@ from pyaml.configuration import NamedValue from pyaml.configuration.factory import ELEMENT_REGISTRY, Factory from pyaml.control.abstract_impl import RWBooleanScalar -from pyaml.control.controlsystem import ControlSystem 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 _NoHardware(ControlSystem): - def name(self): - return "live" - - def get_aggregator(self): - raise AssertionError("ID metadata attachment must not access hardware") - - def get_device_access(self, ref): - raise AssertionError("ID metadata attachment must not resolve hardware") - - class _Feedforward(Element): def _fill_device(self, holder): obj = copy.copy(self) @@ -124,13 +112,18 @@ def _machine(path, devices=None, controls=None): ], ) 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, **definition} + {"type": "pyaml.insertion_device.control_variable", "name": name, "backend": name, **definition} for name, definition in control_variables.items() ], "model_operating_point": [ @@ -143,11 +136,21 @@ def test_configuration_supports_control_variable_families(id_lattice_file, decla 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 @@ -159,22 +162,15 @@ def test_configuration_supports_control_variable_families(id_lattice_file, decla ("overrides", "error"), [ ({"control_variables": {}}, "at least one control variable"), - ({"control_variables": None}, "at least one control variable"), ({"control_variables": {"gap": {"unit": ""}}}, "requires a name and unit"), - ({"control_variables": {"gap": {"unit": "mm", "access": "read"}}}, "unexpected keyword argument"), ({"control_variables": {"gap": {"unit": "mm", "backend": ""}}}, "backend must not be empty"), ({"model_operating_point": {"gap": float("inf")}}, "finite coordinate"), - ({"disabled_operating_point": {}}, "must not be empty"), ({"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"), - ({"model_operating_point": {}}, "include every configured control variable"), - ({"control_mode": "MODE"}, "include mode"), - ({"lattice_names": "list(D)"}, "expected InsertionDeviceKickMap"), - ({"lattice_names": "list(MISSING)"}, "not found in lattice"), ( {"control_variables": [ControlVariable("gap", "mm"), ControlVariable("gap", "mm")]}, "duplicate names in control_variables", @@ -183,15 +179,24 @@ def test_configuration_supports_control_variable_families(id_lattice_file, decla {"model_operating_point": [NamedValue("gap", 4.0), NamedValue("gap", 5.0)]}, "duplicate names in model_operating_point", ), - ( - {"disabled_operating_point": [NamedValue("gap", 30.0), NamedValue("gap", 20.0)]}, - "duplicate names in disabled_operating_point", - ), ], ) -def test_invalid_configuration_or_mapping_is_rejected(id_lattice_file, overrides, error): +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, PyAMLConfigException, TypeError), match=error): + 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]) @@ -217,8 +222,6 @@ def test_holder_registration_associations_and_add_rollback(id_lattice_file): 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="Duplicate element"): - machine.add(source) with pytest.raises(PyAMLException, match="MISSING"): machine.add(_device(name="BAD_ID", orbit_feedforward="MISSING")) for holder in machine.modes().values(): @@ -228,15 +231,28 @@ def test_holder_registration_associations_and_add_rollback(id_lattice_file): 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", }, ) - machine = _machine(id_lattice_file, [source]) + 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") gap = live.control_variables["gap"] @@ -244,85 +260,39 @@ def test_live_attachment_binds_hardware_separately_from_model(id_lattice_file): assert gap.readback() == 8.0 assert gap.get() == 9.0 assert gap.get_range() == [2.0, 30.0] - assert "phase" not in live.control_variables + 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.flag_references["moving"] == "MOVING" - assert live.control_mode == "MODE" assert live.mode.get() == "parallel" - assert live.enabled.get() is True - assert design.mode.get() == "parallel" - assert isinstance(design.control_variables["gap"], abstract.ReadWriteFloatScalar) - assert source.control_variables["gap"] is None - assert source.mode is None - assert source.flags == {"moving": None, "orbit_ff": None} 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, "mode": "parallel"} - assert point.units == {"gap": "mm"} + 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" - assert "InsertionDevice" in repr(live) - - -def test_control_variable_without_backend_remains_unavailable(id_lattice_file): - machine = _machine(id_lattice_file, [_device(control_variables={"gap": {"unit": "mm"}})], controls=[_NoHardware()]) - live = machine.live.insertion_device.get("ID") - assert live.control_variables == {"gap": None} - assert live.flags == {} - assert live.mode is None - assert machine.design.insertion_device.get("ID").control_variables["gap"].get() == 4.0 - - -@pytest.mark.parametrize( - "names", - [("gap",), ("phase",), ("gap", "parallel", "antiparallel"), ("ps1", "ps2", "ps3")], -) -def test_same_class_binds_mechanical_and_current_control_variables(names): - from tango.pyaml.attribute_store import set_attribute - - unit = "A" if names[0] == "ps1" else "mm" - control = _control() - for name in names: - set_attribute(name, 0.0, unit=unit, range=(-100.0, 100.0), readback=0.0) - source = _device(control_variables={name: {"unit": unit, "backend": name} for name in names}) - control.fill_device([source]) - attached = control.insertion_device.get("ID") - assert type(attached) is InsertionDevice - assert set(attached.control_variables) == set(names) - for variable in attached.control_variables.values(): - assert isinstance(variable, abstract.ReadWriteFloatScalar) - variable.set(5.0) - assert variable.get() == 5.0 - assert variable.readback() == 0.0 - assert variable.unit() == unit - assert attached.enabled.get() is True - assert source.peer is None - - -def test_writable_and_unavailable_control_variables_are_distinguishable(): - source = _device( - control_variables={ - "gap": {"unit": "mm", "backend": "GAP"}, - "phase": {"unit": "mm"}, - } - ) - control = _control() - control.fill_device([source]) - device = control.insertion_device.get("ID") - gap = device.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 device.control_variables["phase"] is None - assert "current" not in device.control_variables + 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)]]) @@ -390,20 +360,14 @@ def test_unit_mismatch_does_not_register_device(): assert not control.insertion_device.all() -@pytest.mark.parametrize("value", [False, True, Value(False), Value(True)]) -def test_boolean_scalar_reads_boolean_value(value): - control = _control() - backend = control.get_device_access("FF") - with patch.object(backend, "readback", return_value=value): - assert RWBooleanScalar(backend).get() is bool(value.value if isinstance(value, Value) else value) - - -def test_boolean_scalar_writes_and_rejects_nonboolean_values(): +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"): @@ -411,40 +375,13 @@ def test_boolean_scalar_writes_and_rejects_nonboolean_values(): flag.get() -def test_optional_controls_and_hardware_motion_do_not_change_model(id_lattice_file): - from tango.pyaml.attribute_store import set_attribute - - control = _control() - source = _device(control_mode="MODE", flags={"orbit_ff": "FF"}, model_operating_point={"gap": 4.0, "mode": "parallel"}) - machine = _machine(id_lattice_file, [source], controls=[control]) - live = machine.live.insertion_device.get("ID") - design = machine.design.insertion_device.get("ID") - reference = design.model_reference - live.control_variables["gap"].set_and_wait(12.0) - set_attribute("GAP", 12.0) - live.mode.set("antiparallel") - live.flags["orbit_ff"].set(False) - assert live.control_variables["gap"].get() == 12.0 - assert live.control_variables["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["gap"].get_range() == [4.0, 4.0] - assert design.mode.get() == "parallel" - assert live.model_operating_point["gap"] == 4.0 - assert live.model_operating_point.mode == "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 - - 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() @@ -470,6 +407,8 @@ def test_model_on_off_preserves_split_maps_and_tracking(id_lattice_file): 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) @@ -507,6 +446,9 @@ def test_live_enable_disable_apply_points_and_keep_logical_state(): 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") @@ -625,22 +567,6 @@ def test_live_enable_disable_failures_do_not_update_logical_state(command, ref): assert device.control_variables["gap"].get() == 4.0 -def test_enabled_accessors_reject_nonboolean_writes(id_lattice_file): - machine = _machine(id_lattice_file, [_device()]) - for holder in machine.modes().values(): - device = holder.insertion_device.get("ID") - with pytest.raises(PyAMLException, match="boolean enabled state"): - device.enabled.set(1) - assert device.enabled.get() is True - - -def test_unattached_enabled_state_is_unavailable(): - device = _device() - for command in (device.enable, device.disable): - with pytest.raises(PyAMLException, match="before attachment"): - command() - - @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) From 56da2154bb8ad7b5f0550d6b555fd16c030f26d3 Mon Sep 17 00:00:00 2001 From: gubaidulinvadim Date: Mon, 30 Nov 2026 10:29:43 +0100 Subject: [PATCH 10/10] First pass at adding multiple kickmaps --- pyaml/configuration/named_value.py | 6 + pyaml/insertion_device/insertion_device.py | 131 ++++++++++++--- pyaml/lattice/abstract_impl.py | 103 +++++++++++- pyaml/lattice/simulator.py | 22 ++- tests/configuration/test_factory.py | 2 +- tests/test_insertion_device.py | 185 +++++++++++++++++++++ 6 files changed, 413 insertions(+), 36 deletions(-) diff --git a/pyaml/configuration/named_value.py b/pyaml/configuration/named_value.py index 1823e10b..b4e25a7b 100644 --- a/pyaml/configuration/named_value.py +++ b/pyaml/configuration/named_value.py @@ -14,6 +14,8 @@ class NamedValue(DynamicValidation): 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 ------------- @@ -22,6 +24,10 @@ class NamedValue(DynamicValidation): - 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): diff --git a/pyaml/insertion_device/insertion_device.py b/pyaml/insertion_device/insertion_device.py index fd478086..a2f975c6 100644 --- a/pyaml/insertion_device/insertion_device.py +++ b/pyaml/insertion_device/insertion_device.py @@ -108,8 +108,34 @@ 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. -``model_operating_point`` exposes the same read-only -``RInsertionDeviceModelPoint`` in live and simulator holders. +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 @@ -128,6 +154,7 @@ if TYPE_CHECKING: from ..common.holders.element_holder import ElementHolder + from ..lattice.abstract_impl import InsertionDeviceWorkingPoints PYAMLCLASS = "InsertionDevice" @@ -155,6 +182,12 @@ class InsertionDevice(Element, DynamicValidation): 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__( @@ -170,6 +203,7 @@ def __init__( 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(): @@ -180,6 +214,7 @@ def __init__( ("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}") @@ -201,14 +236,31 @@ def __init__( 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") - for key, value in (model_values or {}).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") + 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") @@ -226,14 +278,9 @@ def __init__( self._control_variable_definitions = definitions self._flag_refs = dict(flags or {}) self._disabled_point = disabled_values - self._point = ( - RInsertionDeviceModelPoint( - model_values, - {name: definition["unit"] for name, definition in self._control_variable_definitions.items()}, - ) - if model_values is not None - else None - ) + 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 ) @@ -244,6 +291,36 @@ def __init__( 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.""" @@ -260,7 +337,9 @@ def flag_references(self) -> Mapping[str, str]: @property def model_operating_point(self) -> RInsertionDeviceModelPoint | None: - """Configured model reference, independent of the holder or hardware state.""" + """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 @@ -271,13 +350,17 @@ def disabled_operating_point(self) -> Mapping[str, float] | None: @property def model_reference(self) -> dict: """Return a snapshot of model settings and provenance, never live values.""" - return { + point = self.model_operating_point + reference = { "device_id": self.device_id, "description": self.description, - "operating_point": dict(self._point) if self._point is not None else None, - "units": dict(self._point.units) if self._point is not None else {}, - "maps": self._model_maps, + "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: @@ -302,6 +385,7 @@ def attach( 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) @@ -314,6 +398,7 @@ def attach( 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: diff --git a/pyaml/lattice/abstract_impl.py b/pyaml/lattice/abstract_impl.py index c9e43035..35c6f870 100644 --- a/pyaml/lattice/abstract_impl.py +++ b/pyaml/lattice/abstract_impl.py @@ -5,6 +5,8 @@ magnet strengths, hardware values, BPM readings, RF parameters, and tune data. """ +from collections.abc import Callable, Mapping + import at import numpy as np from numpy.typing import NDArray @@ -12,6 +14,7 @@ from ..common import abstract from ..common.abstract_aggregator import ScalarAggregator +from ..common.abstract_impl import RInsertionDeviceModelPoint from ..common.exception import PyAMLException from ..magnet.model import MagnetModel from .polynom_info import PolynomInfo @@ -21,26 +24,112 @@ # ------------------------------------------------------------------------------ +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, unit: str): + 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 + return self._value() if callable(self._value) else self._value def readback(self) -> float: """Return the model reference, not a hardware readback.""" - return self._value + return self.get() def unit(self) -> str: return self._unit def get_range(self) -> list[float]: - return [self._value, self._value] + 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})") @@ -52,15 +141,15 @@ def set_and_wait(self, value: float) -> None: class RWInsertionDeviceMode(abstract.RWInsertionDeviceMode): """Expose the fixed reference mode through the shared mode interface.""" - def __init__(self, name: str, mode: str): + def __init__(self, name: str, mode: str | Callable[[], str]): self._name = name self._mode = mode def get(self) -> str: - return self._mode + return self._mode() if callable(self._mode) else self._mode def set(self, value: str) -> None: - if value != self._mode: + if value != self.get(): raise PyAMLException(f"{self._name}: fixed model operating point does not support mode {value!r}") diff --git a/pyaml/lattice/simulator.py b/pyaml/lattice/simulator.py index 6a724c6d..1b32eaf4 100644 --- a/pyaml/lattice/simulator.py +++ b/pyaml/lattice/simulator.py @@ -23,6 +23,7 @@ BPMHScalarAggregator, BPMScalarAggregator, BPMVScalarAggregator, + InsertionDeviceWorkingPoints, RBetatronTuneArray, RBpmArray, RWBpmOffsetArray, @@ -257,25 +258,36 @@ def _fill_insertion_device(self, device: InsertionDevice) -> None: kickmaps.append(element) if not kickmaps: raise PyAMLException(f"{device.name}: no insertion-device kickmaps found") - point = device.model_operating_point + 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: + 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, point.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}", float(value), definition["unit"] + 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)) + 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 = ( diff --git a/tests/configuration/test_factory.py b/tests/configuration/test_factory.py index 772960a4..7e764ecf 100644 --- a/tests/configuration/test_factory.py +++ b/tests/configuration/test_factory.py @@ -17,7 +17,7 @@ def test_factory_build_default(): assert obj.name == "simple" -@pytest.mark.parametrize("value", [True, {"labels": ["a", "b"]}]) +@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}) diff --git a/tests/test_insertion_device.py b/tests/test_insertion_device.py index d820f933..84e74af6 100644 --- a/tests/test_insertion_device.py +++ b/tests/test_insertion_device.py @@ -60,6 +60,26 @@ def id_lattice_file(tmp_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", @@ -255,6 +275,9 @@ def test_live_attachment_binds_hardware_separately_from_model(id_lattice_file): 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 @@ -583,3 +606,165 @@ def test_design_initial_enabled_state_comes_from_consistent_kickmaps(id_lattice_ 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)