Skip to content

Commit 93f366c

Browse files
Add per-magnet function lists, strengths/hardwares array accessors and completed partial requests for serialized magnets (#461)
1 parent e1170d7 commit 93f366c

8 files changed

Lines changed: 505 additions & 50 deletions

File tree

‎pyaml/arrays/magnet_array.py‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -73,18 +73,16 @@ def set(self, value: np.array, wait_seconds_after: float = None):
7373
nvalue = np.ones(self.__nb) * value if isinstance(value, float) else value
7474
if not self.__aggregator:
7575
# Magnets of a series share one power supply: it is written once, from the strengths of the
76-
# magnets of the series present in the array
76+
# magnets of the series present in the array, the others keeping their current strength
7777
series: dict[int, tuple[Magnet, dict[int, float]]] = {}
7878
for idx, m in enumerate(self.__magnets):
7979
if m.model is not None and m.model.shares_power_supply():
8080
series.setdefault(id(m.model), (m, {}))[1][m.strength.index()] = nvalue[idx]
8181
else:
8282
m.strength.set(nvalue[idx])
8383
for m, requested in series.values():
84-
if len(requested) == 1:
85-
m.strength.set(next(iter(requested.values())))
86-
else:
87-
m.hardware.set(m.model.compute_hardware_values_partial(None, requested)[0])
84+
current_hardware = np.array([m.hardware.get()])
85+
m.hardware.set(m.model.compute_hardware_values_partial(current_hardware, requested)[0])
8886
else:
8987
self.__aggregator.set(nvalue)
9088

‎pyaml/control/abstract_impl.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,8 @@ def add_magnet(self, magnet: Magnet, devs: list[DeviceAccess]):
431431
Hardware devices associated with the magnet model.
432432
"""
433433
# Magnets of a serialized group share the serialized model (one power supply for N strengths):
434-
# the power-supply current is computed by the model from the strengths of the magnets present in the array.
434+
# the power-supply current is computed by the model from the strengths of the magnets present in the array,
435+
# the others keeping their current strength.
435436
is_indexed = isinstance(magnet.strength, (abstract.RWMapper, RWSerializedStrengthScalar))
436437
strengthIndex = magnet.strength.index() if is_indexed else 0
437438
if magnet.model not in self.__models:

‎pyaml/lattice/simulator.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -271,12 +271,12 @@ def _fill_serialized_magnets(self, magnets: SerializedMagnets) -> None:
271271
strengths = []
272272
for index, magnet in enumerate(magnets.get_magnets()):
273273
current = (
274-
RWHardwareScalar(self.get_at_elems(magnet), magnets.polynom, magnets.model.get_sub_model(index))
274+
RWHardwareScalar(self.get_at_elems(magnet), magnets.polynoms[index], magnets.model.get_sub_model(index))
275275
if magnets.model.has_hardware()
276276
else None
277277
)
278278
strength = (
279-
RWStrengthScalar(self.get_at_elems(magnet), magnets.polynom, magnets.model.get_sub_model(index))
279+
RWStrengthScalar(self.get_at_elems(magnet), magnets.polynoms[index], magnets.model.get_sub_model(index))
280280
if magnets.model.has_physics()
281281
else None
282282
)

‎pyaml/magnet/linear_serialized_model.py‎

Lines changed: 55 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
logger = logging.getLogger(__name__)
2323

24-
# Relative spread above which the currents requested by members of a series are considered inconsistent
24+
# Relative gap above which strengths requested for a series are considered unreachable with a single hardware value
2525
_SPREAD_RTOL = 1e-6
2626

2727

@@ -180,6 +180,8 @@ class LinearSerializedMagnetModel(MagnetModel, DynamicValidation):
180180
Return the average strength of the series for a hardware value.
181181
compute_hardware_from_mean_strength(strength)
182182
Return the hardware value giving an average strength of the series.
183+
compute_hardware_from_strengths(strengths)
184+
Return the hardware value for a requested strength of each magnet of the series.
183185
shares_power_supply()
184186
Return True, all the magnets of the series share one power supply.
185187
get_strength_units()
@@ -355,37 +357,37 @@ def compute_strengths(self, currents: np.array) -> np.array:
355357
return np.array([model.compute_strengths([current])[0] for model in self.__sub_models])
356358

357359
def compute_hardware_values_partial(
358-
self, current_hardware: np.ndarray | None, strengths_by_index: dict[int, float]
360+
self, current_hardware: np.ndarray, strengths_by_index: dict[int, float]
359361
) -> np.ndarray:
360362
"""
361363
Convert the strengths of some magnets of the series to the shared hardware value.
362364
363-
Each requested strength implies a hardware value through its own submodel. The power supply gets the mean of
364-
the hardware values implied by the requested magnets only: the magnets that are not requested do not take part.
365-
A warning is logged when the requested strengths are not consistent with a single hardware value.
365+
The magnets that are not requested keep the strength given by the current hardware value. The completed
366+
strengths are then converted by :meth:`compute_hardware_from_strengths`, which logs a warning when they
367+
cannot all be reached with a single hardware value.
366368
367369
Parameters
368370
----------
369-
current_hardware : np.array | None
370-
Current hardware value of the series. Not used: the requested strengths define the hardware value.
371+
current_hardware : np.array
372+
Current hardware value of the series, one value per power supply.
371373
strengths_by_index : dict[int, float]
372374
Requested strengths, indexed by the position of the magnet in the series.
373375
374376
Returns
375377
-------
376378
np.array
377-
Hardware value of the power supply.
379+
Hardware value of the power supply, with the shape of ``current_hardware``.
380+
381+
Raises
382+
------
383+
PyAMLException
384+
If ``current_hardware`` does not hold one value per power supply of the series.
378385
"""
379-
currents = np.array(
380-
[self.__sub_models[idx].compute_hardware_values([strength])[0] for idx, strength in strengths_by_index.items()]
381-
)
382-
current = np.mean(currents)
383-
if np.ptp(currents) > _SPREAD_RTOL * max(abs(current), 1.0):
384-
logger.warning(
385-
f"Inconsistent strengths requested for magnets {list(strengths_by_index.keys())} of a series on "
386-
f"{self._powerconverter}: implied hardware values {currents}, the mean {current} is applied"
387-
)
388-
return np.array([current])
386+
_check_len(current_hardware, "current_hardware", len(self.get_device_names()))
387+
strengths = self.compute_strengths(current_hardware)
388+
for idx, strength in strengths_by_index.items():
389+
strengths[idx] = strength
390+
return np.array([self.compute_hardware_from_strengths(strengths)])
389391

390392
def compute_mean_strength(self, current: float) -> float:
391393
"""
@@ -436,6 +438,41 @@ def compute_hardware_from_mean_strength(self, strength: float) -> float:
436438
)
437439
return float(np.interp(strength, strengths, currents))
438440

441+
def compute_hardware_from_strengths(self, strengths: np.ndarray) -> float:
442+
"""
443+
Return the hardware value for a requested strength of each magnet of the series.
444+
445+
The series has a single hardware value, so it solves ``sum(f_i(I)) == sum(k_i)`` for ``I``. When the requested
446+
strengths cannot all be reached with one hardware value, the result is a compromise and a warning is logged.
447+
448+
Parameters
449+
----------
450+
strengths : np.ndarray
451+
Requested strength ``k_i`` of each magnet of the series, in declaration order.
452+
453+
Returns
454+
-------
455+
float
456+
Hardware value of the power supply.
457+
458+
Raises
459+
------
460+
PyAMLException
461+
If the number of strengths does not match the number of magnets, or if the average strength is not
462+
monotonic in the hardware value.
463+
"""
464+
strengths = np.asarray(strengths, dtype=float)
465+
_check_len(strengths, "strengths", self.__nbMagnets)
466+
current = self.compute_hardware_from_mean_strength(float(np.mean(strengths)))
467+
gaps = self.compute_strengths([current]) - strengths
468+
if np.any(np.abs(gaps) > _SPREAD_RTOL * np.maximum(np.abs(strengths), 1.0)):
469+
worst = int(np.argmax(np.abs(gaps)))
470+
logger.warning(
471+
f"Inconsistent strengths requested for the series on {self._powerconverter}: the hardware value "
472+
f"{current} misses the requested strengths by up to {gaps[worst]:.3g} (magnet {worst})"
473+
)
474+
return current
475+
439476
def shares_power_supply(self) -> bool:
440477
"""Return True, all the magnets of the series share one power supply."""
441478
return True

0 commit comments

Comments
 (0)