diff --git a/pyaml/control/controlsystem.py b/pyaml/control/controlsystem.py index ff357514..df7df304 100644 --- a/pyaml/control/controlsystem.py +++ b/pyaml/control/controlsystem.py @@ -34,12 +34,15 @@ RWSerializedStrengthScalar, RWStrengthArray, RWStrengthScalar, + RWStrengthTrim, ) from ..diagnostics.atune_monitor import ABetatronTuneMonitor from ..diagnostics.tune_monitor import BetatronTuneMonitor 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 ..magnet.trim_coil_model import TrimCoilModel from ..rf.rf_plant import RFPlant, RWTotalVoltage from ..rf.rf_transmitter import RFTransmitter from ..tuning_tools.measurement_tool import MeasurementTool @@ -149,8 +152,11 @@ def create_magnet_strength_aggregator(self, magnets: list[Magnet]) -> ScalarAggr ------- ScalarAggregator | None Strength aggregator, or ``None`` when the backend does not use - aggregators. + aggregators or the array contains trims requiring the main current. """ + # Scalar access handles the main-current dependency and writes mains before trims. + if any(isinstance(m.model, TrimCoilModel) for m in magnets): + return None agg = self._create_scalar_aggregator() if agg is None: return None @@ -248,9 +254,26 @@ 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_serialized_magnets_with_trims(self, magnets: SerializedMagnetsWithTrims) -> None: + """Bind the shared main supply and each independent trim supply.""" + main_device = self.get_device_access(magnets.model.get_device_names()[0]) + currents, strengths = [], [] + for index in range(magnets.get_nb_magnets()): + sub_model = magnets.model.get_sub_model(index) + currents.append(RWHardwareScalar(sub_model, main_device)) + strengths.append(RWSerializedStrengthScalar(sub_model, main_device, index, magnets.model)) + + trim_currents, trim_strengths = [], [] + for trim, magnet in zip(magnets.model.trims, magnets.get_trim_magnets(), strict=True): + device = self.get_device_access(trim.powerconverter) + sub_model = magnets.model.get_sub_model(magnets.names().index(trim.element)) + trim_currents.append(RWHardwareScalar(magnet.model, device)) + trim_strengths.append(RWStrengthTrim(sub_model, main_device, device, trim.trim_factor)) + + attached = magnets.attach(self, strengths, currents, trim_strengths, trim_currents) + self.serialized_magnet.add(attached[0]) + for magnet in attached[1:]: + self.magnet.add(magnet) def _fill_bpm(self, bpm: BPM) -> None: position_devices = self.get_devices_access(bpm.get_pos_devices()) diff --git a/tests/control/test_strength_trim.py b/tests/control/test_strength_trim.py index 1c993618..c6ad4120 100644 --- a/tests/control/test_strength_trim.py +++ b/tests/control/test_strength_trim.py @@ -4,9 +4,16 @@ import pytest from pyaml import PyAMLException +from pyaml.arrays.magnet_array import MagnetArray from pyaml.control.abstract_impl import RWStrengthTrim +from pyaml.control.controlsystem import ControlSystemAdapter from pyaml.control.deviceaccess import DeviceAccess +from pyaml.control.deviceaccesslist import DeviceAccessList +from pyaml.magnet.inline_curve import InlineCurve +from pyaml.magnet.linear_serialized_with_trims_model import LinearSerializedMagnetWithTrimsModel from pyaml.magnet.model import MagnetModel +from pyaml.magnet.serialized_magnet_trims import SerializedMagnetsWithTrims +from pyaml.magnet.trim_coil import TrimCoil @pytest.fixture @@ -65,3 +72,75 @@ 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) + + +@pytest.fixture +def attached_trim_controls(trim_setup, monkeypatch): + _, main_device, trim_device = trim_setup + main_device.get.return_value = 1.0 + main_device.get_range.return_value = [0.0, 3.0] + main_device.set.side_effect = lambda value: setattr(main_device.get, "return_value", value) + trim_device.get.return_value = -0.25 + devices = {"main/current": main_device, "trim/current": trim_device} + controls = ControlSystemAdapter() + monkeypatch.setattr(controls, "get_device_access", devices.__getitem__) + 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) + controls.fill_device([family]) + return controls, model, main_device, trim_device + + +def test_control_attachment_and_independent_trim_supply(attached_trim_controls): + controls, model, main_device, trim_device = attached_trim_controls + attached = controls.serialized_magnet["series"] + trim = controls.magnet["T2"] + + assert isinstance(attached, SerializedMagnetsWithTrims) + assert attached.names() == ["D1", "D2"] + assert attached.get_trim_magnets() == [trim] + assert trim.peer is controls + assert trim.hardware.unit() == "trim A" + assert trim.strength.unit() == "rad" + assert trim.strength.get() == pytest.approx(1.5) + + attached.strength.set(model.compute_mean_strength(2.0)) + np.testing.assert_allclose(attached.hardwares.get(), [2.0, 2.0]) + assert trim.hardware.get() == pytest.approx(-0.25) + assert trim.strength.get() == pytest.approx(2.5) + trim_device.set.assert_not_called() + + main_device.set.reset_mock() + trim.strength.set(1.0) + assert trim.hardware.get() == pytest.approx(-0.1) + assert trim.strength.get() == pytest.approx(1.0) + trim.hardware.set(-0.25) + assert trim.strength.get() == pytest.approx(2.5) + main_device.set.assert_not_called() + + +@pytest.mark.parametrize("use_family", [True, False]) +def test_control_array_with_trim_uses_scalar_strengths(attached_trim_controls, monkeypatch, use_family): + controls, model, main_device, trim_device = attached_trim_controls + monkeypatch.setattr(controls, "get_aggregator", lambda: Mock(spec=DeviceAccessList)) + family = controls.serialized_magnet["series"] + trim = controls.magnet["T2"] + main = family if use_family else family[1] + magnets = [trim, main] + assert controls.create_magnet_strength_aggregator(magnets) is None + assert controls.create_magnet_strength_aggregator([main]) is not None + assert controls.create_magnet_hardware_aggregator(magnets) is not None + array = MagnetArray("mixed", magnets) + main_strength = model.compute_mean_strength(2.0) if use_family else model.compute_strengths([2.0])[1] + + array.strengths.set([1.0, main_strength]) + + np.testing.assert_allclose(array.strengths.get(), [1.0, main_strength]) + main_device.set.assert_called_once_with(pytest.approx(2.0)) + trim_device.set.assert_called_once_with(pytest.approx(-0.1))