Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions pyaml/control/abstract_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
177 changes: 177 additions & 0 deletions pyaml/lattice/abstract_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
67 changes: 67 additions & 0 deletions tests/control/test_strength_trim.py
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading