Skip to content
Merged
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/apidoc/gen_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"pyaml.common.holders.element_holder",
"pyaml.common.holders.sub_holders",
"pyaml.common.holders.rf_holder",
"pyaml.common.switch_element",
"pyaml.configuration.factory",
"pyaml.configuration.fileloader",
"pyaml.configuration.manager",
Expand Down
15 changes: 15 additions & 0 deletions pyaml/common/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,21 @@

from .units import AcceptsQuantity


class RWBooleanScalar(metaclass=ABCMeta):
"""Define backend-independent boolean get/set access."""

@abstractmethod
def get(self) -> bool:
"""Return the boolean state."""
pass

@abstractmethod
def set(self, value: bool) -> None:
"""Write the boolean state."""
pass


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


Expand Down
5 changes: 5 additions & 0 deletions pyaml/common/holders/element_holder.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from ...configuration.unbound_element import UnboundElement
from ...tuning_tools.measurement_tool import MeasurementTool
from ...tuning_tools.tuning_tool import TuningTool
from ..switch_element import SwitchElement


class ElementHolder(metaclass=ABCMeta):
Expand Down Expand Up @@ -197,6 +198,10 @@ def fill_device(self, elements: list[Element]):
for element in elements:
element._fill_device(self)

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}")

@abstractmethod
def _fill_magnet(self, magnet: Magnet) -> None:
pass
Expand Down
150 changes: 150 additions & 0 deletions pyaml/common/switch_element.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
"""Switchable accelerator functionality without a required lattice counterpart."""

import copy
from typing import TYPE_CHECKING, Self

from ..validation import DynamicValidation, register_schema
from . import abstract
from .element import Element
from .exception import PyAMLException

if TYPE_CHECKING:
from .holders.element_holder import ElementHolder

PYAMLCLASS = "SwitchElement"


@register_schema
class SwitchElement(Element, DynamicValidation):
"""
Enable or disable accelerator functionality through one boolean channel.

Parameters
----------
name : str
Unique element name, for example ``SOFB`` or ``FOFB``.
device : str
Opaque backend reference to one writable boolean channel. Status is
read from that channel's actual readback, not its requested setpoint.
Simulator modes do not resolve this reference.
description : str | None, optional
Human-readable description of the functionality.

Attributes
----------
enabled
Boolean get/set accessor, shared by control-system and simulator modes.

Methods
-------
attach(peer, enabled)
Return a copy bound to a peer and its boolean accessor.
enable()
Write True through the boolean accessor.
disable()
Write False through the boolean accessor.
is_enabled()
Return actual boolean readback, not the commanded state.

Notes
-----
Control-system access uses the reusable RWBooleanScalar adapter: get()
reads the backend readback (including numeric 0/1 flags) and set() writes
a Python boolean through DeviceAccess.set(). Value metadata is unwrapped;
this interface adds no quality, waiting, or completion policy. Backend
Comment thread
gubaidulinvadim marked this conversation as resolved.
Resolved
errors propagate. Construction and attachment never initialize hardware.
A missing control-system channel does not prevent configuration loading;
reading or writing its accessor raises an explicit error instead.

Each simulator attachment starts disabled and maintains independent state
without looking up or modifying a lattice element. This element does not
implement measurement preparation or automatic state restoration.

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

- class: pyaml.common.switch_element.SwitchElement
name: SOFB
device: SOFB_ENABLED
description: Slow orbit feedback

Examples
--------
With this element configured in an accelerator named ``sr``:

.. code-block:: python

feedback = sr.live["SOFB"]
feedback.disable()
enabled = feedback.enabled.get()
feedback.enabled.set(True)
feedback.enable()

simulated_feedback = sr.design["SOFB"]
assert simulated_feedback.enabled.get() is False
simulated_feedback.enabled.set(True) # Does not affect hardware or the lattice.
"""

__pyaml_repr_exclude__ = ("enabled",)

def __init__(self, name: str, device: str, description: str | None = None):
"""Initialize the element configuration without accessing hardware."""
super().__init__(name=name, description=description)
self.device = device
self._enabled: abstract.RWBooleanScalar | None = None

def attach(self, peer: "ElementHolder", enabled: abstract.RWBooleanScalar) -> Self:
"""
Return a copy bound to a peer and its boolean state interface.

Parameters
----------
peer : ElementHolder
Control system or simulator owning this runtime element.
enabled : abstract.RWBooleanScalar
Boolean get/set interface owned by this attachment.

Returns
-------
Self
Attached copy; the original configuration remains unattached.
"""
obj = copy.copy(self)
obj._enabled = enabled
obj._peer = peer
return obj

@property
def enabled(self) -> abstract.RWBooleanScalar:
"""Return the boolean get/set accessor for this holder."""
if self._enabled is None:
raise PyAMLException(f"{self.name}: enabled state is unavailable before attachment")
return self._enabled

def enable(self) -> None:
"""Enable the functionality through its boolean accessor."""
self.enabled.set(True)

def disable(self) -> None:
"""Disable the functionality through its boolean accessor."""
self.enabled.set(False)

def is_enabled(self) -> bool:
"""
Return actual boolean readback, not the commanded state.

Returns
-------
bool
Whether the functionality is enabled.

Raises
------
PyAMLException
If unattached, or if the backend value is not a boolean flag.
"""
return self.enabled.get()

def _fill_device(self, holder: "ElementHolder") -> None:
holder._fill_switch_element(self)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about an if statement here that does the _fill_switch_element itself based on the type of the element holder?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's what would've needed to be done in _fill_unbound_element. I don't see much difference between another def() and another if(). Same number of lines of code. But it could be done.

34 changes: 34 additions & 0 deletions pyaml/control/abstract_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,44 @@
from ..magnet.model import MagnetModel
from ..rf.rf_plant import RFPlant
from ..rf.rf_transmitter import RFTransmitter
from .readback_value import Value

# ------------------------------------------------------------------------------


class RWBooleanScalar(abstract.RWBooleanScalar):
"""
Expose a backend boolean through reusable get/set accessors.

An unavailable device is reported only when read or written. ``name`` gives
diagnostic context when there is no device to supply its own name.
"""

def __init__(self, device: DeviceAccess | None, name: str = "Boolean channel"):
self._device = device
self._name = name

def get(self) -> bool:
device = self._require_device()
value = device.readback()
if isinstance(value, Value):
value = value.value
if value not in (False, True):
raise PyAMLException(f"{device.name()}: expected a boolean flag, got {value!r}")
return bool(value)

def set(self, value: bool) -> None:
device = self._require_device()
if not isinstance(value, bool):
raise PyAMLException(f"{device.name()}: expected a boolean flag, got {value!r}")
device.set(value)

def _require_device(self) -> DeviceAccess:
if self._device is None:
raise PyAMLException(f"{self._name} is unavailable")
return self._device


def check_range(values: Any, dev_range: Any) -> bool:
"""
Check whether values are within given ranges.
Expand Down
7 changes: 7 additions & 0 deletions pyaml/control/controlsystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from ..common.abstract_aggregator import ScalarAggregator
from ..common.exception import PyAMLConfigException, PyAMLException
from ..common.holders.element_holder import ElementHolder
from ..common.switch_element import SwitchElement
from ..common.units import SI_ANGLE, SI_FREQUENCY, SI_POSITION, SI_TUNE, SI_VOLTAGE, is_frequency_unit
from ..configuration.unbound_element import UnboundElement
from ..control.abstract_impl import (
Expand All @@ -25,6 +26,7 @@
CSStrengthScalarAggregator,
RBetatronTuneArray,
RBpmArray,
RWBooleanScalar,
RWBpmOffsetArray,
RWBpmTiltScalar,
RWHardwareArray,
Expand Down Expand Up @@ -360,6 +362,11 @@ def _fill_betatron_tune_monitor(self, monitor: BetatronTuneMonitor) -> None:
def _fill_tool(self, tool: TuningTool | MeasurementTool) -> None:
self.add_tool(tool.attach(self))

def _fill_switch_element(self, element: SwitchElement) -> None:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a shame that we need to keep adding new "_fill" functions every time we need to define a new element. Maybe we could categorize this as a "tool" and use _fill_tool?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like it so much because it does not share a type with TuningTool or MeasurementTool, and the functionality is closer to an element. But maybe typing it as TuningTool is ok. But I agree that these fill* methods need to be revised somehow.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then maybe it could use _fill_unbound_element if it is left uncategorized?

@gubaidulinvadim gubaidulinvadim Nov 26, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like it either... It reduces the number of functions, but the lines of code are roughly the same. In fact, I don't like this unbound element so much.

device = self.get_device_access(element.device)
enabled = RWBooleanScalar(device, name=f"{element.name}: switch channel {element.device!r}")
self._add(self._ALL, element.attach(self, enabled))

def _fill_unbound_element(self, element: UnboundElement) -> None:
if self.name() not in element._control_modes:
return
Expand Down
18 changes: 18 additions & 0 deletions pyaml/lattice/abstract_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,24 @@
# ------------------------------------------------------------------------------


class RWBooleanScalar(abstract.RWBooleanScalar):
"""Maintain an initially disabled boolean state independent of the lattice."""

def __init__(self, name: str):
self._name = name
self._enabled = False

def get(self) -> bool:
"""Return the simulated boolean state."""
return self._enabled

def set(self, value: bool) -> None:
"""Store a boolean without accessing the lattice."""
if not isinstance(value, bool):
raise PyAMLException(f"{self._name}: expected a boolean flag, got {value!r}")
self._enabled = value


def _effective_lengths(elements: list[at.Element]) -> list[float]:
"""
Return the lengths used to convert between integrated strengths and polynom coefficients.
Expand Down
5 changes: 5 additions & 0 deletions pyaml/lattice/simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from ..common.element import Element, __pyaml_repr__
from ..common.exception import PyAMLException
from ..common.holders.element_holder import ElementHolder
from ..common.switch_element import SwitchElement
from ..configuration import ROOT
from ..diagnostics.tune_monitor import BetatronTuneMonitor
from ..lattice.abstract_impl import (
Expand All @@ -24,6 +25,7 @@
BPMVScalarAggregator,
RBetatronTuneArray,
RBpmArray,
RWBooleanScalar,
RWBpmOffsetArray,
RWBpmTiltScalar,
RWHardwareArray,
Expand Down Expand Up @@ -340,6 +342,9 @@ def _fill_betatron_tune_monitor(self, monitor: BetatronTuneMonitor) -> None:
def _fill_tool(self, tool: TuningTool | MeasurementTool) -> None:
self.add_tool(tool.attach(self))

def _fill_switch_element(self, element: SwitchElement) -> None:
self._add(self._ALL, element.attach(self, RWBooleanScalar(element.name)))

def _fill_unbound_element(self, element: "UnboundElement") -> None:
pass

Expand Down
Loading
Loading