diff --git a/pyaml/control/abstract_impl.py b/pyaml/control/abstract_impl.py index 98a8c3614..1832700ca 100644 --- a/pyaml/control/abstract_impl.py +++ b/pyaml/control/abstract_impl.py @@ -852,6 +852,64 @@ def set_magnet_rigidity(self, brho: np.double): self.__model.set_magnet_rigidity(brho) +class RWStrengthTrim(RWStrengthScalar): + """Expose the incremental strength produced by a trim power supply. + + For the member magnet's excitation model ``f``, the trim strength is + ``f(I + trim_factor * I_trim) - f(I)``. Setting that strength changes only + the trim supply; the main current is read once per operation. + + Parameters + ---------- + model : MagnetModel + Single-magnet model converting equivalent main-coil current to strength. + main_dev : DeviceAccess + Main power-supply current device, used only for reading. + trim_dev : DeviceAccess + Physical trim-current device, used for reading and writing. + trim_factor : float + Nonzero signed factor converting physical trim current to equivalent + main-coil current. Defaults to 1.0. + + Notes + ----- + Conversion and inversion use the supplied model's existing behavior. + Device limits apply to the physical trim current. Hardware access can use + the existing ``RWHardwareScalar`` bound to ``trim_dev``. + """ + + def __init__(self, model: MagnetModel, main_dev: DeviceAccess, trim_dev: DeviceAccess, trim_factor: float = 1.0): + if trim_factor == 0: + raise ValueError("trim_factor must be nonzero") + super().__init__(model, trim_dev) + self.__model = model + self.__main_dev = main_dev + self.__trim_dev = trim_dev + self.__trim_factor = trim_factor + + def get(self) -> float: + """Return the trim contribution at the current main-supply setpoint.""" + main_current = self.__main_dev.get() + trim_current = self.__trim_dev.get() + main_strength = self.__model.compute_strengths([main_current])[0] + total_strength = self.__model.compute_strengths([main_current + self.__trim_factor * trim_current])[0] + return total_strength - main_strength + + def set(self, value: float): + """Convert incremental strength and write only the trim supply. + + Raise PyAMLException when the calculated physical trim current is + outside the trim device's configured range. + """ + main_current = self.__main_dev.get() + main_strength = self.__model.compute_strengths([main_current])[0] + total_current = self.__model.compute_hardware_values([main_strength + value])[0] + trim_current = (total_current - main_current) / self.__trim_factor + if not check_range(trim_current, self.__trim_dev.get_range()): + raise PyAMLException(format_out_of_range_message(trim_current, self.__trim_dev)) + self.__trim_dev.set(trim_current) + + class RWSerializedStrengthScalar(RWStrengthScalar): """ Expose the strength of one magnet of a serialized group. diff --git a/pyaml/lattice/abstract_impl.py b/pyaml/lattice/abstract_impl.py index 04a5dc660..2fb78bb39 100644 --- a/pyaml/lattice/abstract_impl.py +++ b/pyaml/lattice/abstract_impl.py @@ -294,6 +294,183 @@ def get_model(self) -> MagnetModel: # ------------------------------------------------------------------------------ +class RWStrengthTuple: + """Control two contributions whose sum is written to one scalar strength. + + Parameters + ---------- + total_accessor : abstract.ReadWriteFloatScalar + Accessor for the total integrated strength. It owns the conversion to + lattice coefficients, including signs, lengths, and bending angles. + initial : tuple[float, float] + Initial contributions in the underlying accessor's unit. Construction + writes their sum to the underlying accessor once. + + Notes + ----- + ``get()`` returns their stored values, not a decomposition of lattice readback. + All writes must go through this tuple: direct writes to the underlying + accessor are unsupported. ``set(pair)`` reapplies the authoritative total. + + A successful write stores the new pair only after the underlying write + returns. On failure the stored pair is unchanged; any partial effects of a + failing underlying accessor cannot be rolled back here. + """ + + def __init__(self, total_accessor: abstract.ReadWriteFloatScalar, initial: tuple[float, float]): + self._total_accessor = total_accessor + self.set(initial) + + def get(self) -> tuple[float, float]: + """Return an immutable pair of the stored contributions.""" + return self._values + + def set(self, values: tuple[float, float]): + """Write the sum of the supplied pair, then store its contributions.""" + main, trim = values + self._total_accessor.set(main + trim) + self._values = values + + def unit(self) -> str: + """Return the shared physical unit of both contributions.""" + return self._total_accessor.unit() + + def set_and_wait(self, values: tuple[float, float]): + """Waiting for lattice strength convergence is not implemented.""" + raise NotImplementedError("Not implemented yet.") + + +# ------------------------------------------------------------------------------ + + +class RWStrengthTrim(abstract.ReadWriteFloatScalar): + """Expose the trim contribution of a simulated main/trim strength pair. + + Reads and writes address only the second contribution of ``strengths``. + No current conversion is performed; the tuple writes the summed strength + through its underlying lattice accessor. + """ + + def __init__(self, strengths: RWStrengthTuple): + self._strengths = strengths + + def get(self) -> float: + """Return the stored trim strength.""" + return self._strengths.get()[1] + + def set(self, value: float): + """Update the trim strength while preserving the main contribution.""" + main, _ = self._strengths.get() + self._strengths.set((main, value)) + + def unit(self) -> str: + return self._strengths.unit() + + def set_and_wait(self, value: float): + raise NotImplementedError("Not implemented yet.") + + +class RWStrengthMain(RWStrengthTrim): + """Expose the main contribution of a simulated main/trim pair.""" + + def get(self) -> float: + return self._strengths.get()[0] + + def set(self, value: float): + _, trim = self._strengths.get() + self._strengths.set((value, trim)) + + +class RWHardwareTrim(abstract.ReadWriteFloatScalar): + """Expose physical trim current for a simulated main/trim strength pair. + + Parameters + ---------- + strengths : RWStrengthTuple + Main and incremental trim strengths sharing one lattice component. + model : MagnetModel + Single-magnet excitation model, including its inverse conversion. + trim_factor : float + Nonzero signed factor converting physical trim current to equivalent + main-coil current. Defaults to 1.0. + hardware_unit : str or None + Trim supply unit, defaulting to the main member's hardware unit. + + Notes + ----- + For excitation curve ``f``, readback is + ``(inverse_f(main + trim) - inverse_f(main)) / trim_factor``. + Writes preserve the main strength and set the trim contribution to + ``f(inverse_f(main) + trim_factor * current) - main``. + Like RWHardwareScalar, readback follows the model's inverse convention; + currents are not independently retained for non-unique inverses. + + The family must preserve trim currents explicitly when changing the shared + main supply: read the trim currents before updating the main contributions, + then reapply them at the new operating point. + """ + + def __init__( + self, strengths: RWStrengthTuple, model: MagnetModel, trim_factor: float = 1.0, hardware_unit: str | None = None + ): + if trim_factor == 0: + raise ValueError("trim_factor must be nonzero") + self._strengths = strengths + self._model = model + self._trim_factor = trim_factor + self._hardware_unit = hardware_unit + + def get(self) -> float: + main, trim = self._strengths.get() + main_current = self._model.compute_hardware_values([main])[0] + total_current = self._model.compute_hardware_values([main + trim])[0] + return (total_current - main_current) / self._trim_factor + + def set(self, value: float): + main, _ = self._strengths.get() + main_current = self._model.compute_hardware_values([main])[0] + total = self._model.compute_strengths([main_current + self._trim_factor * value])[0] + self._strengths.set((main, total - main)) + + def unit(self) -> str: + return self._model.get_hardware_units()[0] if self._hardware_unit is None else self._hardware_unit + + def get_model(self) -> MagnetModel: + return self._model + + def set_and_wait(self, value: float): + raise NotImplementedError("Not implemented yet.") + + +class RWHardwareMainWithTrim(abstract.ReadWriteFloatScalar): + """Convert main strength to current, preserving trim current on writes.""" + + def __init__(self, strength: RWStrengthMain, trim_hardware: RWHardwareTrim, model: MagnetModel): + self._strength = strength + self._trim_hardware = trim_hardware + self._model = model + + def get(self) -> float: + return self._model.compute_hardware_values([self._strength.get()])[0] + + def set(self, value: float): + trim_current = self._trim_hardware.get() + self._strength.set(self._model.compute_strengths([value])[0]) + self._trim_hardware.set(trim_current) + + def unit(self) -> str: + return self._model.get_hardware_units()[0] + + def get_model(self) -> MagnetModel: + return self._model + + def set_and_wait(self, value: float): + raise NotImplementedError("Not implemented yet.") + + +# ------------------------------------------------------------------------------ + + class RWSerializedHardware(abstract.ReadWriteFloatScalar): """ Hardware value of one magnet of a serialized group. diff --git a/tests/control/test_strength_trim.py b/tests/control/test_strength_trim.py new file mode 100644 index 000000000..1c9936182 --- /dev/null +++ b/tests/control/test_strength_trim.py @@ -0,0 +1,67 @@ +from unittest.mock import Mock + +import numpy as np +import pytest + +from pyaml import PyAMLException +from pyaml.control.abstract_impl import RWStrengthTrim +from pyaml.control.deviceaccess import DeviceAccess +from pyaml.magnet.model import MagnetModel + + +@pytest.fixture +def trim_setup(): + # Nonlinear, invertible excitation curve with a nonzero strength offset. + model = Mock(spec=MagnetModel) + model.compute_strengths.side_effect = lambda currents: np.asarray(currents) ** 3 + 7.0 + model.compute_hardware_values.side_effect = lambda strengths: np.cbrt(np.asarray(strengths) - 7.0) + main = Mock(spec=DeviceAccess) + main.get.return_value = 2.0 + trim = Mock(spec=DeviceAccess) + trim.get.return_value = 0.5 + trim.get_range.return_value = [-2.0, 2.0] + trim.name.return_value = "trim/current" + trim.unit.return_value = "A" + trim.set.side_effect = lambda value: setattr(trim.get, "return_value", value) + return model, main, trim + + +def test_read_trim_strength_tracks_main_current(trim_setup): + model, main, trim = trim_setup + strength = RWStrengthTrim(model, main, trim) + assert strength.get() == pytest.approx(7.625) # f(2.5) - f(2) + + main.get.return_value = 3.0 + assert strength.get() == pytest.approx(15.875) # f(3.5) - f(3) + trim.set.assert_not_called() + main.set.assert_not_called() + + +def test_write_trim_strength_with_signed_scaling(trim_setup): + model, main, trim = trim_setup + strength = RWStrengthTrim(model, main, trim, trim_factor=-2.0) + strength.set(19.0) # f(3) - f(2): equivalent current increases by 1 A. + trim.set.assert_called_once_with(pytest.approx(-0.5)) + assert strength.get() == pytest.approx(19.0) + + main.get.return_value = 3.0 + strength.set(19.0) + assert trim.get.return_value == pytest.approx((np.cbrt(46.0) - 3.0) / -2.0) + assert strength.get() == pytest.approx(19.0) + main.set.assert_not_called() + + +def test_out_of_range_rejects_trim_write(trim_setup): + model, main, trim = trim_setup + trim.get_range.return_value = [-0.25, 0.25] + strength = RWStrengthTrim(model, main, trim) + with pytest.raises(PyAMLException, match="Values out of range"): + strength.set(19.0) + main.set.assert_not_called() + trim.set.assert_not_called() + + +def test_zero_factor_is_rejected(trim_setup): + model, main, trim = trim_setup + with pytest.raises(ValueError, match="nonzero"): + RWStrengthTrim(model, main, trim, 0.0) diff --git a/tests/lattice/test_strength_tuple.py b/tests/lattice/test_strength_tuple.py new file mode 100644 index 000000000..0d3a398d6 --- /dev/null +++ b/tests/lattice/test_strength_tuple.py @@ -0,0 +1,121 @@ +from unittest.mock import Mock + +import at +import numpy as np +import pytest + +from pyaml.common.abstract import ReadWriteFloatScalar +from pyaml.lattice.abstract_impl import RWStrengthScalar, RWStrengthTuple +from pyaml.magnet.hcorrector import HCorrector +from pyaml.magnet.identity_model import IdentityMagnetModel +from pyaml.magnet.vcorrector import VCorrector + + +@pytest.fixture +def total(): + accessor = Mock(spec=ReadWriteFloatScalar) + accessor.unit.return_value = "rad" + return accessor + + +def test_initialization_and_paired_writes(total): + strengths = RWStrengthTuple(total, initial=(2.0, 0.5)) + total.set.assert_called_once_with(2.5) + assert strengths.get() == (2.0, 0.5) + assert isinstance(strengths.get(), tuple) + total.get.assert_not_called() + + assert strengths.unit() == "rad" + total.unit.return_value = "1/m" + assert strengths.unit() == "1/m" + + previous = strengths.get() + total.set.reset_mock() + strengths.set((3.0, strengths.get()[1])) + total.set.assert_called_once_with(3.5) + assert strengths.get() == (3.0, 0.5) + assert previous == (2.0, 0.5) + + total.set.reset_mock() + strengths.set((strengths.get()[0], -0.5)) + total.set.assert_called_once_with(2.5) + assert strengths.get() == (3.0, -0.5) + + total.set.reset_mock() + strengths.set((np.float64(4.0), np.int64(1))) + total.set.assert_called_once_with(5.0) + assert strengths.get() == (4.0, 1.0) + + +@pytest.mark.parametrize( + "values, error", + [ + ((), ValueError), + ((1,), ValueError), + ((1, 2, 3), ValueError), + (None, TypeError), + (1, TypeError), + ], +) +def test_invalid_pairs_do_not_write(total, values, error): + with pytest.raises(error): + RWStrengthTuple(total, initial=values) + total.set.assert_not_called() + + strengths = RWStrengthTuple(total, initial=(1, 2)) + total.set.reset_mock() + with pytest.raises(error): + strengths.set(values) + total.set.assert_not_called() + assert strengths.get() == (1, 2) + + +def test_failed_writes_preserve_pair(total): + strengths = RWStrengthTuple(total, initial=(1, 2)) + total.set.side_effect = RuntimeError("write failed") + with pytest.raises(RuntimeError, match="write failed"): + strengths.set((3, 4)) + assert strengths.get() == (1, 2) + with pytest.raises(RuntimeError, match="write failed"): + RWStrengthTuple(total, initial=(3, 4)) + + +def test_waiting_has_no_side_effects(total): + strengths = RWStrengthTuple(total, initial=(1, 2)) + total.reset_mock() + with pytest.raises(NotImplementedError): + strengths.set_and_wait((3, 4)) + assert total.mock_calls == [] + assert strengths.get() == (1, 2) + + +@pytest.mark.parametrize("polynom", [HCorrector.polynom, VCorrector.polynom]) +@pytest.mark.parametrize("lengths", [(0.0,), (0.4,), (0.0, 0.0), (0.2, 0.6)]) +def test_lattice_integration(polynom, lengths): + elements = [at.Dipole(f"B{i}", length, 0.01 * (i + 1)) for i, length in enumerate(lengths)] + model = IdentityMagnetModel(physics="COR", unit="rad") + total = RWStrengthScalar(elements, polynom, model) + strengths = RWStrengthTuple(total, initial=(0.03, 0.005)) + effective_length = sum(lengths) or len(lengths) + bend = sum(e.BendingAngle for e in elements) if polynom.attName == "PolynomB" else 0.0 + + def check_total(expected): + assert total.get() == pytest.approx(expected) + for element in elements: + coefficient = getattr(element, polynom.attName)[0] + assert coefficient == pytest.approx((expected - bend) / (polynom.sign * effective_length)) + + check_total(0.035) + strengths.set((strengths.get()[0], -0.002)) + check_total(0.028) + strengths.set((0.04, strengths.get()[1])) + check_total(0.038) + strengths.set((0.02, 0.003)) + check_total(0.023) + assert [e.BendingAngle for e in elements] == [0.01 * (i + 1) for i in range(len(elements))] + + # The tuple owns the decomposition; an explicit paired write restores its total. + total.set(0.1) + assert strengths.get() == (0.02, 0.003) + strengths.set(strengths.get()) + check_total(0.023) diff --git a/tests/lattice/test_trim_accessors.py b/tests/lattice/test_trim_accessors.py new file mode 100644 index 000000000..05138a8dc --- /dev/null +++ b/tests/lattice/test_trim_accessors.py @@ -0,0 +1,69 @@ +from unittest.mock import Mock + +import at +import numpy as np +import pytest + +from pyaml.lattice.abstract_impl import RWHardwareTrim, RWStrengthScalar, RWStrengthTrim, RWStrengthTuple +from pyaml.magnet.hcorrector import HCorrector +from pyaml.magnet.identity_model import IdentityMagnetModel + + +def test_strength_trim_preserves_main_and_updates_lattice(): + element = at.Dipole("BEND", 0.4, 0.02) + model = IdentityMagnetModel(physics="COR", unit="rad") + total = RWStrengthScalar([element], HCorrector.polynom, model) + strengths = RWStrengthTuple(total, initial=(0.03, 0.005)) + trim = RWStrengthTrim(strengths) + + assert trim.get() == 0.005 + trim.set(-0.002) + assert strengths.get() == (0.03, -0.002) + assert total.get() == pytest.approx(0.028) + assert element.PolynomB[0] == pytest.approx(-0.02) + assert element.BendingAngle == 0.02 + assert trim.unit() == "rad" + + +def test_hardware_trim_uses_nonlinear_model_and_signed_scaling(): + model = Mock() + model.compute_strengths.side_effect = lambda currents: np.asarray(currents) ** 3 + 7.0 + model.compute_hardware_values.side_effect = lambda strengths: np.cbrt(np.asarray(strengths) - 7.0) + model.get_hardware_units.return_value = ["A"] + total = Mock() + strengths = RWStrengthTuple(total, initial=(15.0, 19.0)) # f(2), f(3) - f(2) + trim_strength = RWStrengthTrim(strengths) + hardware = RWHardwareTrim(strengths, model, trim_factor=-2.0) + + assert hardware.get() == pytest.approx(-0.5) + total.set.reset_mock() + hardware.set(0.5) # Effective current 2 - 2 * 0.5 = 1. + assert strengths.get() == pytest.approx((15.0, -7.0)) + total.set.assert_called_once_with(pytest.approx(8.0)) + assert hardware.get() == pytest.approx(0.5) + + trim_strength.set(19.0) + assert hardware.get() == pytest.approx(-0.5) + assert hardware.unit() == "A" + assert hardware.get_model() is model + + # Family integration can preserve physical trim current at a new operating point. + current = hardware.get() + strengths.set((34.0, trim_strength.get())) # Main current is now 3. + hardware.set(current) + assert strengths.get() == pytest.approx((34.0, 37.0)) # f(4) - f(3) + assert hardware.get() == pytest.approx(current) + + +def test_failed_hardware_conversion_preserves_strengths(): + total = Mock() + strengths = RWStrengthTuple(total, initial=(1.0, 0.2)) + total.set.reset_mock() + model = Mock() + model.compute_hardware_values.side_effect = ValueError("conversion failed") + hardware = RWHardwareTrim(strengths, model) + + with pytest.raises(ValueError, match="conversion failed"): + hardware.set(0.5) + assert strengths.get() == (1.0, 0.2) + total.set.assert_not_called()