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
9 changes: 8 additions & 1 deletion pyaml/arrays/magnet_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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)

Expand Down
4 changes: 4 additions & 0 deletions pyaml/common/holders/element_holder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions pyaml/control/controlsystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()])
Expand Down
38 changes: 38 additions & 0 deletions pyaml/lattice/simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@
RWBpmOffsetArray,
RWBpmTiltScalar,
RWHardwareArray,
RWHardwareMainWithTrim,
RWHardwareScalar,
RWHardwareTrim,
RWRFATFrequencyScalar,
RWRFATotalVoltageScalar,
RWRFFrequencyScalar,
Expand All @@ -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
Expand Down Expand Up @@ -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"):
Expand Down
133 changes: 133 additions & 0 deletions pyaml/magnet/linear_serialized_with_trims_model.py
Original file line number Diff line number Diff line change
@@ -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]
3 changes: 2 additions & 1 deletion pyaml/magnet/serialized_magnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
72 changes: 72 additions & 0 deletions pyaml/magnet/serialized_magnet_trims.py
Original file line number Diff line number Diff line change
@@ -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)
52 changes: 52 additions & 0 deletions pyaml/magnet/trim_coil.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading