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
1 change: 1 addition & 0 deletions pyaml/accelerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,7 @@ def add(self, element: Element) -> None:
holder._BPMS,
holder._RFPLANT,
holder._RFTRANSMITTER,
holder._INSERTION_DEVICES,
holder._DIAG,
holder._TOOLS,
)
Expand Down
3 changes: 3 additions & 0 deletions pyaml/apidoc/gen_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@

modules = [
"pyaml.accelerator",
"pyaml.insertion_device",
"pyaml.insertion_device.control_variable",
"pyaml.configuration.named_value",
"pyaml.arrays.array",
"pyaml.arrays.bpm",
"pyaml.arrays.bpm_array",
Expand Down
14 changes: 14 additions & 0 deletions pyaml/common/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,20 @@ def set(self, value: bool) -> None:
pass


class RWInsertionDeviceMode(metaclass=ABCMeta):
"""Define the optional mode interface shared by live and design accessors."""

@abstractmethod
def get(self) -> str:
"""Return the mode."""
pass

@abstractmethod
def set(self, value: str) -> None:
"""Request a mode."""
pass


# Float ----------------------------------------------------------------


Expand Down
30 changes: 30 additions & 0 deletions pyaml/common/abstract_impl.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""Backend-independent implementations of PyAML read/write interfaces."""

from collections.abc import Iterator, Mapping
from types import MappingProxyType


class RInsertionDeviceModelPoint(Mapping[str, float | str]):
"""Read-only reference settings and units, independent of live hardware."""

def __init__(self, settings: Mapping[str, float | str], units: Mapping[str, str]):
self._settings = MappingProxyType(dict(settings))
self._units = MappingProxyType(dict(units))

def __getitem__(self, name: str) -> float | str:
return self._settings[name]

def __iter__(self) -> Iterator[str]:
return iter(self._settings)

def __len__(self) -> int:
return len(self._settings)

@property
def units(self) -> Mapping[str, str]:
return self._units

@property
def mode(self) -> str | None:
value = self._settings.get("mode")
return value if isinstance(value, str) else None
15 changes: 15 additions & 0 deletions pyaml/common/holders/element_holder.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from ...arrays.element_array import ElementArray
from ...diagnostics.tune_monitor import BetatronTuneMonitor
from ...insertion_device import InsertionDevice
from ...magnet.cfm_magnet import CombinedFunctionMagnet
from ...magnet.magnet import Magnet
from ...magnet.serialized_magnet import SerializedMagnets
Expand All @@ -22,6 +23,7 @@
from .sub_holders import (
CombinedFunctionMagnetHolder,
CombinedFunctionMagnetsHolder,
InsertionDeviceHolder,
MagnetHolder,
MagnetsHolder,
SerializedMagnetHolder,
Expand Down Expand Up @@ -57,6 +59,8 @@ class ElementHolder(metaclass=ABCMeta):
``magnets`` arrays. ``serialized_magnets`` is a deprecated alias of ``magnets`` arrays.
rf
RF plant and transmitters of this mode.
insertion_device
Individual insertion devices and their control variables.
diagnostic
Diagnostics of this mode, with typed default-name access.
tool
Expand Down Expand Up @@ -97,6 +101,7 @@ def __init__(self):
self._BPMS: dict[str, BPM] = {}
self._RFPLANT: dict[str, RFPlant] = {}
self._RFTRANSMITTER: dict[str, RFTransmitter] = {}
self._INSERTION_DEVICES: dict[str, InsertionDevice] = {}
self._DIAG: dict[str, Element] = {}
self._TOOLS: dict[str, Element] = {}
self._ALL: dict[str, Element] = {}
Expand All @@ -108,6 +113,7 @@ def __init__(self):
BPM: self._BPMS,
RFPlant: self._RFPLANT,
RFTransmitter: self._RFTRANSMITTER,
InsertionDevice: self._INSERTION_DEVICES,
}

# Array handle
Expand All @@ -124,6 +130,7 @@ def __init__(self):
self._combined_function_magnet_holder = CombinedFunctionMagnetHolder(self)
self._combined_function_magnets_holder = CombinedFunctionMagnetsHolder(self)
self._rf_holder = RFHolder(self)
self._insertion_device_holder = InsertionDeviceHolder(self)
self._diagnostic_holder = DiagnosticHolder(self)
self._tool_holder = ToolHolder(self)

Expand All @@ -134,6 +141,11 @@ def peer(self) -> "Accelerator":

# Sub holders ----------------------------------------------------------------

@property
def insertion_device(self) -> InsertionDeviceHolder:
"""Return this mode's insertion devices."""
return self._insertion_device_holder

@property
def magnet(self) -> MagnetHolder:
"""Return the magnet."""
Expand Down Expand Up @@ -198,6 +210,9 @@ def fill_device(self, elements: list[Element]):
for element in elements:
element._fill_device(self)

def _fill_insertion_device(self, device: InsertionDevice) -> None:
raise PyAMLException(f"{device.name}: insertion devices are unsupported by {self.__class__.__name__}")

def _fill_switch_element(self, element: "SwitchElement") -> None:
"""Reject switches unless the backend supports their binding."""
raise PyAMLException(f"{self.__class__.__name__} does not support switch element {element.name}")
Expand Down
9 changes: 9 additions & 0 deletions pyaml/common/holders/sub_holders.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from ...arrays.bpm_array import BPMArray
from ...arrays.cfm_magnet_array import CombinedFunctionMagnetArray
from ...arrays.magnet_array import MagnetArray
from ...arrays.serialized_magnet_array import SerializedMagnetsArray
from ...insertion_device import InsertionDevice
from ...magnet.cfm_magnet import CombinedFunctionMagnet
from ...magnet.magnet import Magnet
from ...magnet.serialized_magnet import SerializedMagnets
Expand All @@ -17,6 +19,13 @@
from .element_holder import ElementHolder


class InsertionDeviceHolder(GenericElementHolder[InsertionDevice]):
"""Provide typed access to individual insertion devices."""

def __init__(self, peer: "ElementHolder"):
super().__init__(peer, peer._INSERTION_DEVICES, "Insertion device")


class MagnetHolder(GenericElementHolder[Magnet]):
"""
Provide access to individual magnet elements.
Expand Down
2 changes: 2 additions & 0 deletions pyaml/configuration/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
from .factory import Factory
from .fileloader import ROOT
from .manager import ConfigurationManager, UnsupportedConfigurationRootError
from .named_value import NamedValue

__all__ = [
"ConfigurationManager",
"UnsupportedConfigurationRootError",
"Factory",
"ROOT",
"NamedValue",
]
37 changes: 37 additions & 0 deletions pyaml/configuration/named_value.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""Reusable named values for object-based configuration."""

from typing import Any

from ..common.exception import PyAMLConfigException
from ..validation import DynamicValidation, register_schema

PYAMLCLASS = "NamedValue"


@register_schema
class NamedValue(DynamicValidation):
"""Associate a nonempty name with a value without registering an element.

The consuming class validates value types, allowed names and uniqueness.
Values are not coerced to a common scalar type.
A scalar, a one-item list and a multi-item list are all accepted; consumers
decide how list entries correspond to their configuration.

Configuration
-------------
.. code-block:: yaml

- type: pyaml.configuration.named_value
name: gap
value: 4.0

- type: pyaml.configuration.named_value
name: gap
value: [4.0, 8.0]
"""

def __init__(self, name: str, value: Any):
if not name.strip():
raise PyAMLConfigException("NamedValue requires a nonempty name")
self.name = name
self.value = value
135 changes: 135 additions & 0 deletions pyaml/control/abstract_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
strengths, BPM readings, and RF quantities.
"""

import time
from collections.abc import Mapping
from typing import Any

import numpy as np
Expand All @@ -15,6 +17,8 @@
from .. import PyAMLException
from ..common import abstract
from ..common.abstract_aggregator import ScalarAggregator
from ..common.abstract_impl import RInsertionDeviceModelPoint
from ..common.exception import PyAMLConfigException
from ..common.units import SI_ANGLE, SI_FREQUENCY, SI_POSITION, SI_TUNE, SI_VOLTAGE, common_unit
from ..control.deviceaccess import DeviceAccess
from ..control.deviceaccesslist import DeviceAccessList
Expand Down Expand Up @@ -61,6 +65,137 @@ def _require_device(self) -> DeviceAccess:
return self._device


class RWInsertionDeviceMode(abstract.RWInsertionDeviceMode):
"""Expose an optional mode; the control system owns allowed transitions."""

def __init__(self, device: DeviceAccess):
self._device = device

def get(self) -> str:
value = self._device.readback()
if isinstance(value, Value):
value = value.value
if not isinstance(value, str) or not value.strip():
raise PyAMLException(f"{self._device.name()}: expected a nonempty string mode, got {value!r}")
return value

def set(self, value: str) -> None:
if not isinstance(value, str) or not value.strip():
raise PyAMLException(f"{self._device.name()}: expected a nonempty string mode, got {value!r}")
self._device.set(value)


class RWInsertionDeviceControlVariable(abstract.ReadWriteFloatScalar):
"""Write gap/phase variables with movement flags or currents without them."""

def __init__(self, device: DeviceAccess, unit: str, moving: abstract.RWBooleanScalar | None = None):
if device.unit() != unit:
raise PyAMLConfigException(
f"{device.name()}: backend unit {device.unit()!r} does not match configured unit {unit!r}"
)
self._device = device
self._unit = unit
self.moving = moving

def get(self) -> float:
"""Return the requested setpoint."""
return float(self._device.get())

def readback(self) -> float:
"""Return the measured control-variable value."""
return float(self._device.readback())

def unit(self) -> str:
return self._unit

def get_range(self) -> list[float | None]:
return self._device.get_range()

def set(self, value: float) -> None:
if not check_range(value, self.get_range()):
raise PyAMLException(format_out_of_range_message(value, self._device))
self._device.set(value)

def set_and_wait(self, value: float) -> None:
"""Set a gap or phase/shift variable and wait while its movement flag is true."""
if self.moving is None:
raise PyAMLException(
f"{self._device.name()}: set_and_wait requires a movement_flag; use set() for current variables"
)
self.set(value)
while self.moving.get():
time.sleep(0.1)


class RWInsertionDeviceEnabled(abstract.RWBooleanScalar):
"""Apply live operating points and retain pyAML's logical enabled state."""

def __init__(
self,
name: str,
control_variables: Mapping[str, RWInsertionDeviceControlVariable | None],
point: RInsertionDeviceModelPoint | None,
disabled_point: Mapping[str, float] | None,
mode: RWInsertionDeviceMode | None,
):
self._name = name
self._control_variables = dict(control_variables)
self._point = point
self._disabled_point = dict(disabled_point) if disabled_point is not None else None
self._mode = mode
self._enabled = True
if self._disabled_point:
variables = self._variables(self._disabled_point)
self._enabled = not all(variable.get() == target for _, variable, target in variables)

def get(self) -> bool:
"""Return logical state, not measured completion or external changes."""
return self._enabled

def _variables(self, targets: Mapping[str, float]) -> list[tuple[str, RWInsertionDeviceControlVariable, float]]:
variables = []
for name, target in targets.items():
variable = self._control_variables.get(name)
if variable is None:
raise PyAMLException(f"{self._name}.{name}: control variable is unavailable")
variables.append((name, variable, target))
return variables

def set(self, value: bool) -> None:
if not isinstance(value, bool):
raise PyAMLException(f"{self._name}: expected a boolean enabled state, got {value!r}")
mode = None
if value:
if self._point is None or not set(self._control_variables).issubset(self._point):
raise PyAMLException(
f"{self._name}: model_operating_point must include every configured control variable to enable"
)
targets = {}
for name in self._control_variables:
target = self._point[name]
if not isinstance(target, (int, float)):
raise PyAMLException(f"{self._name}.{name}: numeric model reference is required")
targets[name] = float(target)
if self._mode is not None:
mode = self._point.mode
if mode is None:
raise PyAMLException(f"{self._name}: model_operating_point must include mode to enable")
else:
if not self._disabled_point:
raise PyAMLException(f"{self._name}: disabled_operating_point is required to disable")
targets = self._disabled_point
variables = self._variables(targets)
for name, variable, target in variables:
limits = variable.get_range()
if not check_range(target, limits):
raise PyAMLException(f"{self._name}.{name}: value {target!r} is out of range {limits}")
for _, variable, target in variables:
variable.set(target)
if mode is not None and self._mode is not None:
self._mode.set(mode)
self._enabled = value


def check_range(values: Any, dev_range: Any) -> bool:
"""
Check whether values are within given ranges.
Expand Down
Loading
Loading