diff --git a/pyaml/arrays/magnet_array.py b/pyaml/arrays/magnet_array.py index 49457208..1fda133f 100644 --- a/pyaml/arrays/magnet_array.py +++ b/pyaml/arrays/magnet_array.py @@ -12,6 +12,7 @@ from ..common.abstract_aggregator import ScalarAggregator from ..common.exception import PyAMLException from ..magnet.magnet import Magnet +from ..magnet.trim_coil_model import TrimCoilModel from .element_array import ElementArray @@ -108,15 +109,21 @@ def set(self, value: np.array, wait_seconds_after: float = None): # magnets of the series present in the array, the others following the resulting hardware value. # A serialized family has no series index: its own strength accessor writes its power supply. series: dict[int, tuple[Magnet, dict[int, float]]] = {} + trims: list[tuple[Magnet, float]] = [] for idx, m in enumerate(self.__magnets): series_index = m.series_index - if series_index is not None: + if isinstance(m.model, TrimCoilModel): + trims.append((m, nvalue[idx])) + elif series_index is not None: series.setdefault(id(m.model), (m, {}))[1][series_index] = nvalue[idx] else: m.strength.set(nvalue[idx]) for m, requested in series.values(): current_hardware = np.array([m.hardware.get()]) m.hardware.set(m.model.compute_hardware_values_partial(current_hardware, requested)[0]) + # Set trims at the final main current, after family and grouped member writes. + for m, strength in trims: + m.strength.set(strength) else: self.__aggregator.set(nvalue) diff --git a/pyaml/common/holders/element_holder.py b/pyaml/common/holders/element_holder.py index f7378371..8a4fddf0 100644 --- a/pyaml/common/holders/element_holder.py +++ b/pyaml/common/holders/element_holder.py @@ -209,6 +209,10 @@ def _fill_combined_function_magnet(self, magnet: CombinedFunctionMagnet) -> None def _fill_serialized_magnets(self, magnets: SerializedMagnets) -> None: pass + @abstractmethod + def _fill_serialized_magnets_with_trims(self, magnets: SerializedMagnets) -> None: + pass + @abstractmethod def _fill_bpm(self, bpm: BPM) -> None: pass diff --git a/pyaml/control/controlsystem.py b/pyaml/control/controlsystem.py index 13a6b4d5..ff357514 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -248,6 +248,10 @@ def _fill_serialized_magnets(self, magnets: SerializedMagnets) -> None: for magnet in attached_magnets[1:]: self.magnet.add(magnet) + def _fill_serialized_magnets_with_trims(self, magnets: SerializedMagnets) -> None: + # To be implemented in next PR, now it is dummy for test not to fail. + pass + def _fill_bpm(self, bpm: BPM) -> None: position_devices = self.get_devices_access(bpm.get_pos_devices()) tilt_devices = self.get_devices_access([bpm.get_tilt_device()]) diff --git a/pyaml/lattice/simulator.py b/pyaml/lattice/simulator.py index aea7921e..3638f051 100644 --- a/pyaml/lattice/simulator.py +++ b/pyaml/lattice/simulator.py @@ -27,7 +27,9 @@ RWBpmOffsetArray, RWBpmTiltScalar, RWHardwareArray, + RWHardwareMainWithTrim, RWHardwareScalar, + RWHardwareTrim, RWRFATFrequencyScalar, RWRFATotalVoltageScalar, RWRFFrequencyScalar, @@ -36,12 +38,16 @@ RWSerializedHardware, RWSerializedStrength, RWStrengthArray, + RWStrengthMain, RWStrengthScalar, + RWStrengthTrim, + RWStrengthTuple, update_bpm_transform_matrix, ) from ..magnet.cfm_magnet import CombinedFunctionMagnet from ..magnet.magnet import Magnet from ..magnet.serialized_magnet import SerializedMagnets +from ..magnet.serialized_magnet_trims import SerializedMagnetsWithTrims from ..rf.rf_plant import RFPlant, RWTotalVoltage from ..rf.rf_transmitter import RFTransmitter from ..tuning_tools.measurement_tool import MeasurementTool @@ -294,6 +300,38 @@ def _fill_serialized_magnets(self, magnets: SerializedMagnets) -> None: for magnet in attached_magnets[1:]: self.magnet.add(magnet) + def _fill_serialized_magnets_with_trims(self, magnets: SerializedMagnetsWithTrims) -> None: + currents, strengths = [], [] + trim_strengths, trim_currents = {}, {} + trims_by_element = {trim.element: trim for trim in magnets.model.trims} + for index, magnet in enumerate(magnets.get_magnets()): + model = magnets.model.get_sub_model(index) + elements = self.get_at_elems(magnet) + strength = RWStrengthScalar(elements, magnet.polynom, model) + trim = trims_by_element.get(magnet.name) + if trim is None: + current = RWHardwareScalar(elements, magnet.polynom, model) + else: + pair = RWStrengthTuple(strength, (strength.get(), 0.0)) + trim_strengths[trim.name] = RWStrengthTrim(pair) + trim_currents[trim.name] = RWHardwareTrim(pair, model, trim.trim_factor, hardware_unit=trim.hardware_unit) + strength = RWStrengthMain(pair) + current = RWHardwareMainWithTrim(strength, trim_currents[trim.name], model) + strengths.append(strength) + currents.append(current) + linked_currents = [RWSerializedHardware(currents, index) for index in range(len(magnets))] + linked_strengths = [RWSerializedStrength(strengths, currents, index, magnets.model) for index in range(len(magnets))] + attached = magnets.attach( + self, + linked_strengths, + linked_currents, + [trim_strengths[trim.name] for trim in magnets.model.trims], + [trim_currents[trim.name] for trim in magnets.model.trims], + ) + self.serialized_magnet.add(attached[0]) + for magnet in attached[1:]: + self.magnet.add(magnet) + def _fill_bpm(self, bpm: BPM) -> None: bpm_elt = self.get_at_elems(bpm)[0] if not hasattr(bpm_elt, "Tilt"): diff --git a/pyaml/magnet/linear_serialized_with_trims_model.py b/pyaml/magnet/linear_serialized_with_trims_model.py new file mode 100644 index 00000000..ac5715f6 --- /dev/null +++ b/pyaml/magnet/linear_serialized_with_trims_model.py @@ -0,0 +1,133 @@ +"""Serialized magnet excitation model with independently powered trim coils.""" + +from ..common.exception import PyAMLException +from ..validation import register_schema +from .curve import Curve +from .linear_serialized_model import LinearSerializedMagnetModel +from .trim_coil import TrimCoil + +PYAMLCLASS = "LinearSerializedMagnetWithTrimsModel" + + +@register_schema +class LinearSerializedMagnetWithTrimsModel(LinearSerializedMagnetModel): + """ + Extend a serialized magnet model with incremental trim strengths. + + The inherited conversions and device names describe the main series only. + Trim conversions take the main current explicitly and use the calibrated + submodel of the addressed member. For its excitation function ``f``, + ``trim_strength = f(main_current + trim_factor * trim_current) - f(main_current)``. + Trim currents are physical supply currents; the signed factor converts them + to equivalent main-coil currents. Inversion uses the submodel's existing + interpolation and clipping conventions. + + Parameters + ---------- + curves : Curve or list[Curve] + Main excitation curves, as in :class:`LinearSerializedMagnetModel`. + trims : list[TrimCoil] + Trim definitions containing ``element``, ``name``, ``powerconverter``, + and optionally ``trim_factor`` (default 1) and ``hardware_unit`` + (defaulting to the main hardware unit). List order defines trim indices. + calibration_factors, calibration_offsets, crosstalk, polarities, powerconverter, unit, hardware_unit + Main-series parameters, passed to :class:`LinearSerializedMagnetModel`. + + Notes + ----- + Call ``set_elements(elements)`` to resolve trim targets and initialize the + main submodels, then set the magnetic rigidity before converting strengths. + Members without a trim definition remain ordinary series members. + + Configuration + ------------- + .. code-block:: yaml + + type: pyaml.magnet.linear_serialized_with_trims_model + unit: rad + hardware_unit: A + curves: + type: pyaml.magnet.csvcurve + file: sr/magnet_models/serialized_strength.csv + powerconverter: mag/mySeries/current + trims: + - class: pyaml.magnet.trim_coil.TrimCoil + element: D1 + name: TRIM_D1 + trim_factor: 1.0 + hardware_unit: A + powerconverter: mag/D1/trim_current + """ + + def __init__( + self, + curves: Curve | list[Curve], + trims: list[TrimCoil], + calibration_factors: float | list[float] | None = None, + calibration_offsets: float | list[float] | None = None, + polarities: int | list[int] | None = None, + powerconverter: str | None = None, + unit: str | None = None, + hardware_unit: str | None = None, + ): + """Initialize the main series and its trim definitions.""" + super().__init__( + curves=curves, + calibration_factors=calibration_factors, + calibration_offsets=calibration_offsets, + polarities=polarities, + powerconverter=powerconverter, + unit=unit, + hardware_unit=hardware_unit, + ) + self.trims = list(trims) + self._trim_indices: list[int] | None = None + for key in ("element", "name"): + if len({getattr(trim, key) for trim in self.trims}) != len(self.trims): + raise PyAMLException(f"Trim {key} values must be unique") + + def set_elements(self, elements: list[str]): + """Initialize main submodels and resolve trim targets against member names.""" + indices = [] + for trim in self.trims: + if elements.count(trim.element) != 1: + raise PyAMLException(f"Trim target {trim.element} must identify exactly one series member") + if trim.name in elements: + raise PyAMLException(f"Trim name {trim.name} conflicts with a series member") + indices.append(elements.index(trim.element)) + self.set_number_of_magnets(len(elements)) + self._trim_indices = indices + + def set_number_of_magnets(self, nb_magnets: int): + """Rebuild main submodels and invalidate any previous trim mapping.""" + super().set_number_of_magnets(nb_magnets) + self._trim_indices = None + + def _trim_sub_model(self, trim_index: int): + """Return the main excitation model addressed by a trim.""" + if self._trim_indices is None: + raise PyAMLException("Call set_elements before converting trim strengths") + if not 0 <= trim_index < len(self.trims): + raise IndexError(trim_index) + return self.get_sub_model(self._trim_indices[trim_index]) + + def compute_trim_strength(self, trim_index: int, main_current: float, trim_current: float) -> float: + """Return the incremental trim strength at the supplied main current.""" + model = self._trim_sub_model(trim_index) + total_current = main_current + self.trims[trim_index].trim_factor * trim_current + return float(model.compute_strengths([total_current])[0] - model.compute_strengths([main_current])[0]) + + def compute_trim_current(self, trim_index: int, main_current: float, trim_strength: float) -> float: + """Return the physical trim current giving an incremental strength.""" + model = self._trim_sub_model(trim_index) + main_strength = model.compute_strengths([main_current])[0] + total_current = model.compute_hardware_values([main_strength + trim_strength])[0] + return float((total_current - main_current) / self.trims[trim_index].trim_factor) + + def get_trim_device_names(self) -> list[str]: + """Return trim supply names in trim configuration order.""" + return [trim.powerconverter for trim in self.trims] + + def get_trim_hardware_units(self) -> list[str | None]: + """Return trim current units in trim configuration order.""" + return [trim.hardware_unit if trim.hardware_unit is not None else self._hardware_unit for trim in self.trims] diff --git a/pyaml/magnet/serialized_magnet.py b/pyaml/magnet/serialized_magnet.py index 4217304f..04f45d5e 100644 --- a/pyaml/magnet/serialized_magnet.py +++ b/pyaml/magnet/serialized_magnet.py @@ -685,7 +685,8 @@ def attach( Virtual magnets of the group, each bound to ``peer``. """ l = [] - n_ser_mag = SerializedMagnets(self._name, self.functions, self.__elements, self.model, self.description, peer) + # Use type(self) instead of SerializedMagnets for using the attach method in SerializedMagnetsWithTrims + n_ser_mag = type(self)(self._name, self.functions, self.__elements, self.model, self.description, peer) if self.model.has_hardware(): n_ser_mag.__hardwares = ReadWriteSerializedHardware(hardwares, self.model) n_ser_mag.__hardwares_array = ReadWriteSerializedHardwareArray(hardwares, self.model) diff --git a/pyaml/magnet/serialized_magnet_trims.py b/pyaml/magnet/serialized_magnet_trims.py new file mode 100644 index 00000000..651fe2ac --- /dev/null +++ b/pyaml/magnet/serialized_magnet_trims.py @@ -0,0 +1,72 @@ +from typing import TYPE_CHECKING + +from .. import PyAMLException +from ..common.element import __pyaml_repr__ +from ..configuration.factory import ELEMENT_REGISTRY +from ..validation import register_schema +from .function_mapping import function_map +from .linear_serialized_with_trims_model import LinearSerializedMagnetWithTrimsModel +from .magnet import Magnet +from .model import MagnetModel +from .serialized_magnet import SerializedMagnets +from .trim_coil_model import TrimCoilModel + +if TYPE_CHECKING: + from ..common.holders.element_holder import ElementHolder + + +@register_schema +class SerializedMagnetsWithTrims(SerializedMagnets): + """A serialized magnet family with independently powered trim coils. + + Main-family behavior is inherited from SerializedMagnets. Each trim defined + by the serialized model creates a separate magnet with its target member's + function and lattice element. Each trim model references the serialized + model's excitation curves. Attached trims are exposed separately from the + main family members. + """ + + def __init__( + self, + name: str, + function: list[str] | str, + elements: list[str] | str, + model: LinearSerializedMagnetWithTrimsModel, + description: str | None = None, + peer=None, + ): + """Initialize the main family and declare its additional trim magnets.""" + if not isinstance(model, LinearSerializedMagnetWithTrimsModel): + raise PyAMLException(f"{name}: a LinearSerializedMagnetWithTrimsModel is required") + if any(trim.name == name for trim in model.trims): + raise PyAMLException(f"Trim name conflicts with serialized family {name}") + super().__init__(name, function, elements, model, description, peer) + self._trim_magnets: list[Magnet] = [] + if peer is None: + model.set_elements(self.names()) + for trim_index, trim in enumerate(model.trims): + index = self.names().index(trim.element) + magnet = function_map[self.functions[index]]( + name=trim.name, + model=TrimCoilModel(model, trim_index), + lattice_names=f"list({trim.element})", + ) + ELEMENT_REGISTRY.register(magnet) + self._trim_magnets.append(magnet) + + def attach(self, peer, strengths, hardwares, trim_strengths, trim_hardwares) -> list[Magnet]: + """Attach the main family and its separately exposed trim magnets.""" + attached = super().attach(peer, strengths, hardwares) + trims = [ + magnet.attach(peer, strength, hardware) + for magnet, strength, hardware in zip(self._trim_magnets, trim_strengths, trim_hardwares, strict=True) + ] + attached[0]._trim_magnets = trims + return attached + trims + + def get_trim_magnets(self) -> list[Magnet]: + """Return trim magnets separately from the main family members.""" + return self._trim_magnets + + def _fill_device(self, holder: "ElementHolder") -> None: + holder._fill_serialized_magnets_with_trims(self) diff --git a/pyaml/magnet/trim_coil.py b/pyaml/magnet/trim_coil.py new file mode 100644 index 00000000..340c6e28 --- /dev/null +++ b/pyaml/magnet/trim_coil.py @@ -0,0 +1,52 @@ +"""Configuration of a trim coil on a serialized magnet.""" + +import numpy as np + +from ..common.exception import PyAMLException +from ..validation import DynamicValidation, register_schema + +PYAMLCLASS = "TrimCoil" + + +@register_schema +class TrimCoil(DynamicValidation): + """ + Define a trim coil and its current scaling relative to the main coil. + + Parameters + ---------- + element : str + Name of the main series member. + name : str + Name of the additional trim magnet. + powerconverter : str + Trim power-converter device reference. + trim_factor : float, optional + Signed trim-to-main current factor. Must be finite and nonzero. + Defaults to +1. + hardware_unit : str or None, optional + Trim current unit. None inherits the main hardware unit. + + Notes + ----- + This object describes a coil; it does not create or control a magnet. + """ + + def __init__( + self, + element: str, + name: str, + powerconverter: str, + trim_factor: float = 1.0, + hardware_unit: str | None = None, + ): + """Initialize a trim definition.""" + if not element or not name or not powerconverter: + raise PyAMLException("Trim element, name and powerconverter must be nonempty") + if not np.isfinite(trim_factor) or trim_factor == 0: + raise PyAMLException("trim_factor must be finite and nonzero") + self.element = element + self.name = name + self.powerconverter = powerconverter + self.trim_factor = trim_factor + self.hardware_unit = hardware_unit diff --git a/pyaml/magnet/trim_coil_model.py b/pyaml/magnet/trim_coil_model.py new file mode 100644 index 00000000..195c240f --- /dev/null +++ b/pyaml/magnet/trim_coil_model.py @@ -0,0 +1,56 @@ +"""Trim-coil conversion and metadata backed by the serialized magnet model.""" + +import numpy as np + +from ..common.exception import PyAMLException +from .linear_serialized_with_trims_model import LinearSerializedMagnetWithTrimsModel +from .model import MagnetModel + + +class TrimCoilModel(MagnetModel): + """Describe one trim supply without defining independent excitation curves. + + Instances are created by SerializedMagnetsWithTrims. The trim index follows + the serialized model's trim configuration order, not its main-member order. + Conversions require an explicit main current. The model performs no device + reads and retains no current values between calls. + """ + + def __init__(self, serialized_model: LinearSerializedMagnetWithTrimsModel, trim_index: int): + self.serialized_model = serialized_model + self.trim_index = trim_index + + def get_device_names(self) -> list[str]: + """Return the trim's independent power-converter reference.""" + return [self.serialized_model.get_trim_device_names()[self.trim_index]] + + def get_strength_units(self) -> list[str]: + """Use the strength unit of the main member carrying this trim.""" + return self.serialized_model._trim_sub_model(self.trim_index).get_strength_units() + + def get_hardware_units(self) -> list[str | None]: + """Use the configured trim unit, or inherit the main hardware unit.""" + return [self.serialized_model.get_trim_hardware_units()[self.trim_index]] + + def set_magnet_rigidity(self, brho): + """Forward rigidity to the model owning the excitation curves.""" + self.serialized_model.set_magnet_rigidity(brho) + + def compute_strengths(self, hardware_values, main_current: float | None = None) -> np.ndarray: + """Return the incremental strength for one trim current at the main current. + + Calibration, signed trim factors and clipping follow the serialized + model's conversion. The result is a one-element array. + """ + if main_current is None: + raise PyAMLException("Trim strength conversion requires the main current") + return np.array([self.serialized_model.compute_trim_strength(self.trim_index, main_current, hardware_values[0])]) + + def compute_hardware_values(self, strengths, main_current: float | None = None) -> np.ndarray: + """Return one trim current for an incremental strength at the main current. + + Inversion and clipping follow the serialized model's conversion. + """ + if main_current is None: + raise PyAMLException("Trim current conversion requires the main current") + return np.array([self.serialized_model.compute_trim_current(self.trim_index, main_current, strengths[0])]) diff --git a/tests/common/test_element_holder.py b/tests/common/test_element_holder.py index d7f66540..983bb898 100644 --- a/tests/common/test_element_holder.py +++ b/tests/common/test_element_holder.py @@ -30,6 +30,9 @@ def _fill_combined_function_magnet(self, magnet) -> None: def _fill_serialized_magnets(self, magnets) -> None: raise AssertionError("Unexpected serialized magnet dispatch") + def _fill_serialized_magnets_with_trims(self, magnets) -> None: + raise AssertionError("Unexpected serialized magnet with trims dispatch") + def _fill_bpm(self, bpm) -> None: raise AssertionError("Unexpected BPM dispatch") diff --git a/tests/lattice/test_serialized_trims_attachment.py b/tests/lattice/test_serialized_trims_attachment.py new file mode 100644 index 00000000..5efdbad3 --- /dev/null +++ b/tests/lattice/test_serialized_trims_attachment.py @@ -0,0 +1,59 @@ +"""Simulator attachment and main/trim writes, without control-system dependencies.""" + +import at +import numpy as np +import pytest + +from pyaml.lattice.abstract_impl import RWStrengthScalar +from pyaml.lattice.simulator import Simulator +from pyaml.magnet.inline_curve import InlineCurve +from pyaml.magnet.linear_serialized_with_trims_model import LinearSerializedMagnetWithTrimsModel +from pyaml.magnet.serialized_magnet_trims import SerializedMagnetsWithTrims +from pyaml.magnet.trim_coil import TrimCoil + + +def test_serialized_trim_simulator_attachment(tmp_path): + path = tmp_path / "ring.mat" + at.save_lattice(at.Lattice([at.Dipole(name, 1, 0.01) for name in ["D1", "D2"]], energy=6e9), path) + simulator = Simulator("design", str(path)) + model = LinearSerializedMagnetWithTrimsModel( + curves=InlineCurve([[0, 0], [1, 1], [2, 4], [3, 9]]), + trims=[TrimCoil("D2", "T2", "trim/current", trim_factor=-2, hardware_unit="trim A")], + powerconverter="main/current", + unit="rad", + hardware_unit="A", + ) + family = SerializedMagnetsWithTrims("series", "B0", ["D1", "D2"], model) + model.set_magnet_rigidity(1.0) + simulator.fill_device([family]) + attached = simulator.serialized_magnet["series"] + trim = simulator.magnet["T2"] + assert isinstance(attached, SerializedMagnetsWithTrims) + assert attached.get_trim_magnets() == [trim] + assert attached.names() == ["D1", "D2"] + assert len(attached) == 2 + assert trim.peer is simulator + assert simulator.get_at_elems(trim) == simulator.get_at_elems(attached[1]) + assert trim.hardware.unit() == "trim A" + np.testing.assert_allclose(attached.strengths.get(), [0.01, 0.01]) + assert trim.strength.get() == 0 + attached.hardware.set(1.0) + trim.hardware.set(-0.25) + assert trim.strength.get() == pytest.approx(1.5) + # Main-strength writes currently preserve trim current, not trim strength. + attached.strength.set(model.compute_mean_strength(2.0)) + assert trim.hardware.get() == pytest.approx(-0.25) + assert trim.strength.get() == pytest.approx(2.5) + trim.strength.set(1.0) + assert attached.hardware.get() == pytest.approx(2.0) + assert trim.hardware.get() == pytest.approx(-0.1) + attached.strengths.set(model.compute_strengths([1.0])) + assert trim.hardware.get() == pytest.approx(-0.1) + attached[1].strength.set(model.compute_strengths([2.0])[1]) + assert trim.hardware.get() == pytest.approx(-0.1) + attached.hardwares.set(np.array([1.0, 1.0])) + assert trim.hardware.get() == pytest.approx(-0.1) + for index, member in enumerate(attached): + total = RWStrengthScalar(simulator.get_at_elems(member), member.polynom, model.get_sub_model(index)) + expected = member.strength.get() + (trim.strength.get() if index == 1 else 0) + assert total.get() == pytest.approx(expected) diff --git a/tests/magnet/test_linear_serialized_with_trims_model.py b/tests/magnet/test_linear_serialized_with_trims_model.py new file mode 100644 index 00000000..833829ae --- /dev/null +++ b/tests/magnet/test_linear_serialized_with_trims_model.py @@ -0,0 +1,89 @@ +import numpy as np +import pytest + +from pyaml.common.exception import PyAMLException +from pyaml.configuration.factory import Factory +from pyaml.magnet.linear_serialized_with_trims_model import LinearSerializedMagnetWithTrimsModel +from pyaml.magnet.trim_coil import TrimCoil +from pyaml.magnet.trim_coil_model import TrimCoilModel + + +@pytest.fixture +def model(): + result = Factory.build( + { + "type": "pyaml.magnet.linear_serialized_with_trims_model", + "curves": { + "type": "pyaml.magnet.inline_curve", + "mat": [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16]], + }, + "calibration_factors": [1, 2, 3], + "calibration_offsets": 0.5, + "unit": "rad", + "hardware_unit": "A", + "powerconverter": "main/current", + "trims": [ + { + "class": "pyaml.magnet.trim_coil.TrimCoil", + "element": "D3", + "name": "T3", + "powerconverter": "trim3/current", + "trim_factor": -0.5, + }, + { + "class": "pyaml.magnet.trim_coil.TrimCoil", + "element": "D1", + "name": "T1", + "powerconverter": "trim1/current", + "trim_factor": 0.5, + }, + ], + } + ) + result.set_elements(["D1", "D2", "D3"]) + result.set_magnet_rigidity(2.0) + return result + + +def test_configuration_and_main_series(model): + assert isinstance(model, LinearSerializedMagnetWithTrimsModel) + assert model.get_device_names() == ["main/current"] + assert model.get_trim_device_names() == ["trim3/current", "trim1/current"] + assert model.get_trim_hardware_units() == ["A", "A"] + assert model.get_strength_units() == ["rad"] * 3 + strengths = model.compute_strengths([2.0]) + np.testing.assert_allclose(strengths, [2.25, 4.25, 6.25]) + np.testing.assert_allclose(model.compute_hardware_values(strengths), [2.0]) + assert model.compute_mean_strength(2.0) == pytest.approx(4.25) + + +def test_trim_conversions_at_different_main_currents(model): + # Trim order differs from member order; offsets cancel in the difference. + for index, trim_current, expected in [(0, -1.0, 3.75), (1, 1.0, 1.25)]: + strength = model.compute_trim_strength(index, 2.0, trim_current) + assert strength == pytest.approx(expected) + assert model.compute_trim_current(index, 2.0, strength) == pytest.approx(trim_current) + assert model.compute_trim_strength(index, 1.0, trim_current) != pytest.approx(strength) + assert model.compute_trim_strength(index, 2.0, 0.0) == pytest.approx(0.0) + model.set_magnet_rigidity(4.0) + assert model.compute_trim_strength(1, 2.0, 1.0) == pytest.approx(0.625) + + +def test_trim_coil_model_conversions(model): + trim = TrimCoilModel(model, 0) + strengths = trim.compute_strengths([-1.0], main_current=2.0) + np.testing.assert_allclose(strengths, [3.75]) + np.testing.assert_allclose(trim.compute_hardware_values(strengths, main_current=2.0), [-1.0]) + np.testing.assert_allclose(trim.compute_strengths([-1.0], main_current=1.0), [2.25]) + # No operating point is retained, even after successful conversions. + for convert in (trim.compute_strengths, trim.compute_hardware_values): + with pytest.raises(PyAMLException, match="requires the main current"): + convert([0.0]) + + +def test_trim_target_binding(model): + with pytest.raises(PyAMLException, match="Trim target"): + model.set_elements(["D1", "D2", "UNKNOWN"]) + model.set_number_of_magnets(3) + with pytest.raises(PyAMLException, match="set_elements"): + model.compute_trim_strength(0, 2.0, 1.0) diff --git a/tests/magnet/test_serialized_magnets_with_trims.py b/tests/magnet/test_serialized_magnets_with_trims.py new file mode 100644 index 00000000..d99947f3 --- /dev/null +++ b/tests/magnet/test_serialized_magnets_with_trims.py @@ -0,0 +1,85 @@ +"""YAML loading and holder access for serialized families and their trim magnets.""" + +import at +import pytest +import yaml + +from pyaml.accelerator import Accelerator +from pyaml.lattice.abstract_impl import RWStrengthScalar +from pyaml.magnet.serialized_magnet_trims import SerializedMagnetsWithTrims + + +@pytest.fixture +def trim_config(tmp_path): + lattice_file = tmp_path / "ring.mat" + ring = at.Lattice( + [at.Dipole(name, 1.0, bending_angle=0.01) for name in ["DF8B-C04", "DF8D-C04", "DD5D-C04"]], + energy=6e9, + ) + at.save_lattice(ring, lattice_file) + config = { + "type": "pyaml.accelerator", + "facility": "ESRF", + "machine": "sr", + "energy": 6e9, + "simulators": [{"type": "pyaml.lattice.simulator", "name": "design", "lattice": str(lattice_file)}], + "devices": [ + { + "class": "pyaml.magnet.serialized_magnet_trims.SerializedMagnetsWithTrims", + "name": "series", + "function": "B0", + "elements": ["DF8B-C04", "DF8D-C04", "DD5D-C04"], + "model": { + "class": "pyaml.magnet.linear_serialized_with_trims_model.LinearSerializedMagnetWithTrimsModel", + "unit": "rad", + "hardware_unit": "A", + "curves": {"type": "pyaml.magnet.inline_curve", "mat": [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16]]}, + "powerconverter": "test/series/main/current", + "trims": [ + { + "class": "pyaml.magnet.trim_coil.TrimCoil", + "element": "DF8D-C04", + "name": "T2", + "trim_factor": -2.0, + "hardware_unit": "trim A", + "powerconverter": "test/series/trim2/current", + }, + { + "class": "pyaml.magnet.trim_coil.TrimCoil", + "element": "DF8B-C04", + "name": "T1", + "powerconverter": "test/series/trim1/current", + }, + ], + }, + } + ], + } + + filename = tmp_path / "trims.yaml" + filename.write_text(yaml.safe_dump(config)) + return Accelerator.load(str(filename)) + + +def test_yaml_and_trim_holders(trim_config): + holder = trim_config.design + family = holder.serialized_magnet.get("series") + assert isinstance(family, SerializedMagnetsWithTrims) + assert family.names() == ["DF8B-C04", "DF8D-C04", "DD5D-C04"] + assert len(family) == len(family.get_magnets()) == 3 + assert [trim.name for trim in family.get_trim_magnets()] == ["T2", "T1"] + assert holder.magnet.get("T2") is family.get_trim_magnets()[0] + assert set(holder.magnet["T*"].names()) == {"T1", "T2"} + for trim, member, unit in [(holder.magnet["T2"], family[1], "trim A"), (holder.magnet["T1"], family[0], "A")]: + assert type(trim) is type(member) + assert trim.model.serialized_model is family.model + assert not trim.model.shares_power_supply() + assert holder.get_at_elems(trim) == holder.get_at_elems(member) + assert trim.series_index is None + assert trim.hardware.unit() == unit + assert trim.strength.unit() == "rad" + assert trim.strength.get() == 0 + total = RWStrengthScalar( + holder.get_at_elems(member), member.polynom, member.model.get_sub_model(family.names().index(member.name)) + ) + assert total.get() == pytest.approx(member.strength.get())