Merge pull request 'widget development' (#105) from feat/widget-development into main
CI for debye_bec / test (push) Failing after 1m47s
CI for debye_bec / test (push) Failing after 1m47s
Reviewed-on: #105
This commit was merged in pull request #105.
This commit is contained in:
commit
fe983e4b54
84 files changed
+26695
-2254
No files matched your search
@@ -0,0 +1,396 @@
|
||||
"""Module to automatically set the gains for the selected amplifiers"""
|
||||
|
||||
import builtins
|
||||
import time
|
||||
from bisect import bisect_right
|
||||
|
||||
import xraydb
|
||||
from bec_lib import bec_logger
|
||||
|
||||
from ...devices.absorber import STATUS as ABS_STATUS
|
||||
from ...devices.eh_shutter import STATUS as EH_PH_STATUS
|
||||
from ...devices.ionization_chambers.ionization_chamber_enums import AmplifierEnable
|
||||
from ...devices.nidaq.nidaq_enums import EpicsMode, NidaqState
|
||||
from ...devices.op_shutter import STATUS as OP_PH_STATUS
|
||||
from .beamline import BeamlineId, get_beamline_id
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
EMIN = -200 # Minimum energy will be edge energy - EMIN
|
||||
EMAX = 1000 # Maximum energy will be edge energy + EMAX
|
||||
|
||||
MIN_RING_CURRENT = 1 # Minimum ring current to use auto-gain
|
||||
NOMINAL_RING_CURRENT = 400 # Nominal ring current of SLS2
|
||||
|
||||
TIMEOUT_PUT_PV = 5 # Timeout to set a PV
|
||||
|
||||
MONO_VELOCITY = 20 # Move velocity in deg/s (only X01DA)
|
||||
TIMEOUT_MONO_MOVE = 30 # Timeout to finish a movement on the mono
|
||||
|
||||
AVAILABLE_GAINS_X01DA = [1e6, 1e7, 5e7, 1e8, 1e9] # ascending order
|
||||
AVAILABLE_GAINS_X10DA = [1e6, 1e7, 1e8, 1e9, 1e10] # ascending order
|
||||
MIN_SIGNAL = 0.05 # Minimum signal to count as valid signal
|
||||
FULL_SCALE_V = 10.0 # NIDAQ AI full-scale range
|
||||
SAFETY_MARGIN = 0.9 # keep max signal under 90% of full scale
|
||||
|
||||
|
||||
def wait_for_signal(signal, value, timeout: float) -> None:
|
||||
"""Function to wait for a signal to reach a certain value.
|
||||
|
||||
Args:
|
||||
signal: Signal to read from
|
||||
value: Target value the signal should reach
|
||||
timeout(float): Timeout in seconds before a TimeoutError is raised
|
||||
|
||||
"""
|
||||
start = time.time()
|
||||
while time.time() - start < timeout:
|
||||
if signal.get() == value:
|
||||
return
|
||||
raise TimeoutError(f"Signal {signal} did not reach value {value} within {timeout} seconds.")
|
||||
|
||||
|
||||
class AutoGainError(Exception):
|
||||
"""AutoGain specific error"""
|
||||
|
||||
|
||||
class AutoGainCore:
|
||||
"""Module to automatically set the gains for the selected amplifiers"""
|
||||
|
||||
def __init__(self):
|
||||
dev = builtins.__dict__.get("dev")
|
||||
bec = builtins.__dict__.get("bec")
|
||||
if dev is None:
|
||||
raise AutoGainError("Did not get dev")
|
||||
if bec is None:
|
||||
raise AutoGainError("Did not get bec")
|
||||
self.dev = dev
|
||||
self.bec = bec
|
||||
self.beamline = get_beamline_id()
|
||||
if self.beamline == BeamlineId.X01DA:
|
||||
self.available_gains = AVAILABLE_GAINS_X01DA
|
||||
else:
|
||||
self.available_gains = AVAILABLE_GAINS_X10DA
|
||||
self.linked_channels = None
|
||||
self.prohibited_gains = {}
|
||||
|
||||
def allowed_gains(self, amplifier):
|
||||
"""Returns a list of gains which are allowed for the amplifier"""
|
||||
if amplifier in self.prohibited_gains:
|
||||
gains = self.available_gains.copy()
|
||||
for prohibited_gain in self.prohibited_gains[amplifier]:
|
||||
gains.remove(prohibited_gain)
|
||||
return gains
|
||||
return self.available_gains
|
||||
|
||||
def start(
|
||||
self,
|
||||
element: str,
|
||||
edge: str,
|
||||
amplifier: list[str] | None = None,
|
||||
link_ic0_ic1: bool = True,
|
||||
comp_ring_current: bool = True,
|
||||
prohibited_gains: dict | None = None,
|
||||
) -> dict:
|
||||
"""Start the auto-gain sequence. Measure the signals of the specified
|
||||
amplifiers and set the gains accordingly. Makes sure there is actually beam available.
|
||||
|
||||
Note:
|
||||
If 'ic0' and 'ic1' are in the amplifier argument, the same gain will be assigned
|
||||
to both amplifiers to get the best glitch removal during processing later.
|
||||
|
||||
Args:
|
||||
element(str): Element which defines the energy at which the gain will be set, e.g. 'Cu'
|
||||
edge(str): Corresponding edge, e.g. 'L1'
|
||||
amplifier(list[str]): Amplifiers where auto-gain should be applied to
|
||||
Defaults to all amplifiers ->
|
||||
X01DA = ['ic0', 'ic1', 'ic2', 'pips']
|
||||
X10DA = ['ic0', 'ic1', 'ic2']
|
||||
link_ic0_ic1(bool): Apply same gain to ic0 and ic1. Defaults to True
|
||||
comp_ring_current(bool): Respects the current ring current and calculates the gain(s)
|
||||
for a nominal ring current of 400 mA. Defaults to True
|
||||
prohibited_gains(dict): Gains which are not allowed to be used.
|
||||
E.g.: {'ic0': [1e6]}. Defaults to None
|
||||
|
||||
Raises:
|
||||
If NIDAQ is not in measurement mode
|
||||
If Ring current is below 5 mA
|
||||
If Absorber, OP Photon Shutter or EH Photon Shutter is closed
|
||||
If a bec scan is running
|
||||
If the energy for the supplied element/edge cannot be found
|
||||
If the energy is outside the movement range of the monochromator
|
||||
If a selected amplifier is switched off
|
||||
If the high voltage of a selected ionization chamber is not enabled or < 1000 V
|
||||
If the gas filling of a selected ionization chamber is not OK
|
||||
If the ring current drops to 0 mA during the measurement (beamdump)
|
||||
"""
|
||||
|
||||
if link_ic0_ic1:
|
||||
self.linked_channels = {"ic0", "ic1"}
|
||||
else:
|
||||
self.linked_channels = {}
|
||||
|
||||
if prohibited_gains is None:
|
||||
self.prohibited_gains = {}
|
||||
else:
|
||||
self.prohibited_gains = prohibited_gains
|
||||
|
||||
if amplifier is None:
|
||||
if self.beamline == BeamlineId.X01DA:
|
||||
amplifier = ["ic0", "ic1", "ic2", "pips"]
|
||||
else:
|
||||
amplifier = ["ic0", "ic1", "ic2"]
|
||||
|
||||
# Make sure NIDAQ is in standby mode
|
||||
if self.dev.nidaq.state.get() != NidaqState.STANDBY:
|
||||
raise AutoGainError("NIDAQ was not in Standby mode, cannot proceed.")
|
||||
|
||||
# Check for beam availability
|
||||
if self._get_ring_current() < MIN_RING_CURRENT:
|
||||
raise AutoGainError(f"Ring current is below {MIN_RING_CURRENT} mA")
|
||||
if self.dev.abs.status.get() != ABS_STATUS.OPEN:
|
||||
raise AutoGainError("Absorber is closed, no beam")
|
||||
if self.dev.op_sh.status.get() != OP_PH_STATUS.NOT_CLOSED:
|
||||
raise AutoGainError("OP Photon Shutter is closed, no beam")
|
||||
if self.dev.eh_sh.status.get() != EH_PH_STATUS.NOT_CLOSED:
|
||||
raise AutoGainError("EH Photon Shutter is closed, no beam")
|
||||
|
||||
# Check if no scan is running
|
||||
scan_id = self.bec.queue.scan_storage.current_scan_id
|
||||
if len(scan_id) > 0:
|
||||
raise AutoGainError(f"Scan with ID {scan_id} is currently running, cannot continue")
|
||||
|
||||
# Get edge energy
|
||||
energy = xraydb.xray_edge(element, edge, True)
|
||||
if energy is None:
|
||||
raise ValueError(f"Could not find edge energy for element/edge {element}/{edge}")
|
||||
emin = energy + EMIN
|
||||
emax = energy + EMAX
|
||||
|
||||
# Check range of mono (only X01DA)
|
||||
if self.beamline == BeamlineId.X01DA:
|
||||
low_limit = self.dev.mo1_bragg.low_lim.get()
|
||||
high_limit = self.dev.mo1_bragg.high_lim.get()
|
||||
if emin < low_limit or emax > high_limit:
|
||||
raise ValueError(
|
||||
f"Chosen element/edge {element}/{edge} with edge energy of {energy}"
|
||||
+ " is outside of accessible range of monochromator "
|
||||
+ f"{low_limit:.1f} eV - {high_limit:.1f} eV"
|
||||
)
|
||||
# X10DA energy axis (goniometer) does not have lo/hi limits
|
||||
|
||||
# Map amplifier names to their NIDAQ channels
|
||||
channel_map = {
|
||||
"ic0": {"signal": self.dev.nidaq.ai0, "self.dev": self.dev.ic0},
|
||||
"ic1": {"signal": self.dev.nidaq.ai2, "self.dev": self.dev.ic1},
|
||||
"ic2": {"signal": self.dev.nidaq.ai4, "self.dev": self.dev.ic2},
|
||||
"pips": {"signal": self.dev.nidaq.ai6, "self.dev": self.dev.pips},
|
||||
}
|
||||
active_channels = {name: ch for name, ch in channel_map.items() if name in amplifier}
|
||||
|
||||
# Tests only for X01DA:
|
||||
if self.beamline == BeamlineId.X01DA:
|
||||
# Check if amplifieres are switched on (only X01DA)
|
||||
for name, ch in active_channels.items():
|
||||
if ch["self.dev"].amp.cOnOff.get() != AmplifierEnable.ON:
|
||||
raise AutoGainError(f"Amplifier of self.device {name} is not enabled")
|
||||
|
||||
# Check high voltage on ionization chambers (only X01DA)
|
||||
for name, ch in active_channels.items():
|
||||
if name != "pips":
|
||||
if ch["self.dev"].hv_en.ena.get() != 1:
|
||||
raise AutoGainError(
|
||||
f"High voltage of ionization chamber {name} is not enabled"
|
||||
)
|
||||
if ch["self.dev"].hv.hv_v.get() < 1000:
|
||||
raise AutoGainError(f"HV voltage of ionization chamber {name} is < 1000")
|
||||
if ch["self.dev"].hv.grid_v.get() < 1000:
|
||||
raise AutoGainError(f"Grid voltage of ionization chamber {name} is < 1000")
|
||||
|
||||
# Check gas filling of ionization chambers (only X01DA)
|
||||
for name, ch in active_channels.items():
|
||||
if name != "pips":
|
||||
if ch["self.dev"].gmes.status.get() != 1:
|
||||
raise AutoGainError(f"Gas filling of ionization chamber {name} is not OK")
|
||||
|
||||
# Get initial monochromator position and velocity
|
||||
if self.beamline == BeamlineId.X01DA:
|
||||
init_pos = self.dev.mo1_bragg.position
|
||||
init_vel = self.dev.mo1_bragg.velocity.get()
|
||||
else:
|
||||
init_pos = self.dev.mo1_rotx_energy.get()
|
||||
init_vel = None
|
||||
|
||||
# Get initial gains
|
||||
for name, ch in active_channels.items():
|
||||
ch["init_gain"] = ch["self.dev"].amp.cGain_ENUM.get()
|
||||
|
||||
logger.info("All checks done, start preparing for measurement")
|
||||
|
||||
results = {}
|
||||
|
||||
try:
|
||||
logger.info(f"Move mono to start of {emin} eV")
|
||||
if self.beamline == BeamlineId.X01DA:
|
||||
self.dev.mo1_bragg.velocity.put(MONO_VELOCITY)
|
||||
wait_for_signal(self.dev.mo1_bragg.velocity, MONO_VELOCITY, timeout=TIMEOUT_PUT_PV)
|
||||
status = self.dev.mo1_bragg.move(emin)
|
||||
else:
|
||||
status = self.dev.mo1_rotx_energy.move(emin)
|
||||
status.wait(TIMEOUT_MONO_MOVE)
|
||||
|
||||
# Set NIDAQ to max mode
|
||||
self.dev.nidaq.epics_mode.put(EpicsMode.MAX)
|
||||
wait_for_signal(self.dev.nidaq.epics_mode, EpicsMode.MAX, timeout=TIMEOUT_PUT_PV)
|
||||
|
||||
# Set gains to lowest gain
|
||||
for name, ch in active_channels.items():
|
||||
lowest_gain = self.allowed_gains(name)[0]
|
||||
ch["self.dev"].set_gain(lowest_gain)
|
||||
ch["gain"] = lowest_gain
|
||||
|
||||
time.sleep(0.5)
|
||||
|
||||
remeasure = True
|
||||
logger.info(f"Start measurement from {emin} eV to {emax} eV")
|
||||
while remeasure:
|
||||
# Rest max values of NIDAQ signals
|
||||
self.dev.nidaq.epics_max_reset.put(True)
|
||||
time.sleep(0.2)
|
||||
|
||||
# Create temporary storage for max signal per channel
|
||||
data = {name: 0 for name in active_channels}
|
||||
|
||||
# Measure current ring current
|
||||
ring_current_1 = self._get_ring_current()
|
||||
logger.info(f"Ring current right before measurement: {ring_current_1} mA")
|
||||
if ring_current_1 < MIN_RING_CURRENT:
|
||||
raise AutoGainError(
|
||||
f"Ring current dropped below {MIN_RING_CURRENT} mA right before measurement"
|
||||
)
|
||||
|
||||
# Scan range, recording the peak NIDAQ signal per channel
|
||||
if self.beamline == BeamlineId.X01DA:
|
||||
self.dev.mo1_bragg.move(emax).wait(timeout=TIMEOUT_MONO_MOVE)
|
||||
else:
|
||||
self.dev.mo1_rotx_energy.move(emax).wait(timeout=TIMEOUT_MONO_MOVE)
|
||||
for name, ch in active_channels.items():
|
||||
data[name] = max(data[name], ch["signal"].get())
|
||||
|
||||
# Measure current ring current again
|
||||
ring_current_2 = self._get_ring_current()
|
||||
logger.info(f"Ring current right after measurement: {ring_current_2} mA")
|
||||
if ring_current_2 < MIN_RING_CURRENT:
|
||||
raise AutoGainError(
|
||||
f"Ring current dropped below {MIN_RING_CURRENT} mA during measurement"
|
||||
)
|
||||
ring_current = (ring_current_1 + ring_current_2) / 2
|
||||
|
||||
# Move back to first monochromator position
|
||||
if self.beamline == BeamlineId.X01DA:
|
||||
status = self.dev.mo1_bragg.move(emin)
|
||||
else:
|
||||
status = self.dev.mo1_rotx_energy.move(emin)
|
||||
|
||||
# Choose gain per channel based on the max signal recorded during the scan
|
||||
remeasure = False
|
||||
processed = set()
|
||||
|
||||
for name, ch in active_channels.items():
|
||||
if name in processed:
|
||||
continue
|
||||
|
||||
# ic0/ic1 must always end up with the same gain -> treat whichever of
|
||||
# them are present (one or both) as a single group for this decision
|
||||
if name in self.linked_channels:
|
||||
group_names = [n for n in self.linked_channels if n in active_channels]
|
||||
else:
|
||||
group_names = [name]
|
||||
|
||||
group_signals = []
|
||||
for gname in group_names:
|
||||
gsig = data[gname]
|
||||
logger.info(f"Raw signal for device {gname} is {gsig} V")
|
||||
if comp_ring_current:
|
||||
gsig = gsig * NOMINAL_RING_CURRENT / ring_current
|
||||
logger.info(f"Compensate for ring current, new raw signal is {gsig} V")
|
||||
group_signals.append(gsig)
|
||||
|
||||
# worst case: the weakest signal drives "need more gain",
|
||||
# the strongest signal drives "don't saturate"
|
||||
raw_signal_min = min(group_signals)
|
||||
raw_signal_max = max(group_signals)
|
||||
gain_ref = ch[
|
||||
"gain"
|
||||
] # linked channels always share gain, so any member's value works
|
||||
label = "/".join(group_names)
|
||||
|
||||
if raw_signal_min < MIN_SIGNAL:
|
||||
logger.info(f"Raw signal for {label} is below {MIN_SIGNAL}")
|
||||
if gain_ref == self.allowed_gains(name)[-1]:
|
||||
logger.warning(
|
||||
f"Amplifier of {label} at highest gain {gain_ref} and still not"
|
||||
+ f" measured signal above {MIN_SIGNAL}"
|
||||
)
|
||||
else:
|
||||
next_gain = self.allowed_gains(name)[
|
||||
bisect_right(self.allowed_gains(name), gain_ref * 100) - 1
|
||||
]
|
||||
for gname in group_names:
|
||||
active_channels[gname]["self.dev"].set_gain(next_gain)
|
||||
active_channels[gname]["gain"] = next_gain
|
||||
time.sleep(0.5)
|
||||
logger.info(f"Setting gain of {label} to {next_gain:.0e} and remeasure")
|
||||
remeasure = True
|
||||
else:
|
||||
gain = max(
|
||||
(
|
||||
g
|
||||
for g in self.allowed_gains(name)
|
||||
if raw_signal_max / gain_ref * g <= FULL_SCALE_V * SAFETY_MARGIN
|
||||
),
|
||||
default=min(self.allowed_gains(name)),
|
||||
)
|
||||
for gname in group_names:
|
||||
active_channels[gname]["self.dev"].set_gain(gain)
|
||||
active_channels[gname]["gain"] = gain
|
||||
logger.info(f"Calculated final gain for {label} of {gain:.0e}")
|
||||
results[label] = {
|
||||
"gain": gain,
|
||||
"max_signal": raw_signal_max / gain_ref * gain,
|
||||
}
|
||||
|
||||
processed.update(group_names)
|
||||
|
||||
# Wait for mono to return to start position
|
||||
status.wait(TIMEOUT_MONO_MOVE)
|
||||
except Exception as e:
|
||||
logger.error("Error during measurement, reset gains to their initial values")
|
||||
for name, ch in active_channels.items():
|
||||
ch["self.dev"].amp.cGain_ENUM.put(ch["init_gain"])
|
||||
raise AutoGainError(f"During execution of auto-gain, an exception occured: {e}") from e
|
||||
|
||||
# Reset NIDAQ to mean mode
|
||||
self.dev.nidaq.epics_mode.put(EpicsMode.MEAN)
|
||||
wait_for_signal(self.dev.nidaq.epics_mode, EpicsMode.MEAN, timeout=TIMEOUT_PUT_PV)
|
||||
|
||||
# Wait for mono to move to initial position and reset velocity
|
||||
if self.beamline == BeamlineId.X01DA:
|
||||
status = self.dev.mo1_bragg.move(init_pos)
|
||||
status.wait(TIMEOUT_MONO_MOVE)
|
||||
self.dev.mo1_bragg.velocity.put(init_vel)
|
||||
wait_for_signal(self.dev.mo1_bragg.velocity, init_vel, timeout=TIMEOUT_PUT_PV)
|
||||
else:
|
||||
status = self.dev.mo1_rotx_energy.move(init_pos)
|
||||
status.wait(TIMEOUT_MONO_MOVE)
|
||||
|
||||
return results
|
||||
|
||||
def _get_ring_current(self) -> float:
|
||||
ring_current = 0
|
||||
retries = 0
|
||||
while ring_current == 0 and retries < 10:
|
||||
ring_current = self.dev.curr.get()
|
||||
retries += 1
|
||||
time.sleep(0.01)
|
||||
return ring_current
|
||||
+10
-13
@@ -1,12 +1,20 @@
|
||||
import socket
|
||||
from enum import Enum
|
||||
|
||||
from bec_lib import bec_logger
|
||||
|
||||
from .types import BeamlineId
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
|
||||
class BeamlineId(str, Enum):
|
||||
"""
|
||||
Identifier for supported beamlines.
|
||||
"""
|
||||
|
||||
X01DA = "x01da"
|
||||
X10DA = "x10da"
|
||||
|
||||
|
||||
def get_beamline_id() -> BeamlineId:
|
||||
"""
|
||||
Based on the bec servers hostname, tries to extract the beamline
|
||||
@@ -38,14 +46,3 @@ def get_beamline_id() -> BeamlineId:
|
||||
raise ValueError(f"Wrong selection {bl}")
|
||||
else:
|
||||
raise ValueError("Cannot open digital twin without a beamline")
|
||||
|
||||
|
||||
def get_parameters():
|
||||
beamline = get_beamline_id()
|
||||
if beamline == "x01da":
|
||||
from . import x01da_parameters as parameters
|
||||
elif beamline == "x10da":
|
||||
from . import x10da_parameters as parameters
|
||||
else:
|
||||
raise ValueError(f"Unknown beamline: {beamline}")
|
||||
return parameters
|
||||
File renamed without changes.
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,280 @@
|
||||
"""Move an axis through BEC"""
|
||||
|
||||
import threading
|
||||
import time
|
||||
from typing import Callable
|
||||
|
||||
from bec_lib import bec_logger
|
||||
|
||||
# pylint: disable=E0402
|
||||
from ....devices.absorber import STATUS as ABS_STATUS
|
||||
from ..beamline import BeamlineId
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
|
||||
class MotionOutcome:
|
||||
DONE = "done"
|
||||
FAILED = "failed"
|
||||
CANCELLED = "cancelled" # stopped by the user, or aborted because another motor failed
|
||||
|
||||
|
||||
class MotionWorker:
|
||||
"""
|
||||
Executes motion on the specified motor and includes some safety during
|
||||
motion for certain motors. Pure Python / Qt-independent: reports
|
||||
progress via plain callables instead of Qt signals, so it can run on
|
||||
any thread (or be unit-tested without a QApplication).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
beamline: BeamlineId,
|
||||
dev,
|
||||
motor,
|
||||
target_pos: float,
|
||||
on_position_changed: Callable[[float], None] | None = None,
|
||||
on_error: Callable[[], None] | None = None,
|
||||
on_finished: Callable[[], None] | None = None,
|
||||
):
|
||||
self.beamline = beamline
|
||||
self.dev = dev
|
||||
self.motor = motor
|
||||
self._target = target_pos
|
||||
self._stop_flag = threading.Event()
|
||||
self.on_position_changed = on_position_changed
|
||||
self.on_error = on_error
|
||||
self.on_finished = on_finished
|
||||
self.last_exception: Exception | None = None
|
||||
|
||||
logger.info(f"motion worker init for motor {motor}")
|
||||
|
||||
def _emit_position_changed(self, pos: float):
|
||||
if self.on_position_changed is not None:
|
||||
self.on_position_changed(pos)
|
||||
|
||||
def _emit_error(self):
|
||||
if self.on_error is not None:
|
||||
self.on_error()
|
||||
|
||||
def _emit_finished(self):
|
||||
if self.on_finished is not None:
|
||||
self.on_finished()
|
||||
|
||||
def stop(self):
|
||||
"""Sets the stop flag"""
|
||||
self._stop_flag.set()
|
||||
|
||||
def run(self):
|
||||
"""Prepares the movement based on the axis (motor)"""
|
||||
logger.info(f"Run motor {self.motor}")
|
||||
match self.motor:
|
||||
case (
|
||||
"sldi_gapx"
|
||||
| "sldi_gapy"
|
||||
| "sldi_centerx"
|
||||
| "sldi_centery"
|
||||
| "sl1_gapx"
|
||||
| "sl1_gapy"
|
||||
| "sl1_centerx"
|
||||
| "sl1_centery"
|
||||
| "bm1_try"
|
||||
| "sl2_gapx"
|
||||
| "sl2_gapy"
|
||||
| "sl2_centerx"
|
||||
| "sl2_centery"
|
||||
| "bm2_try"
|
||||
| "es0wi_try"
|
||||
| "es1_try"
|
||||
| "es2_try"
|
||||
| "ot_try"
|
||||
| "ot_rotx"
|
||||
| "ot_es1_trz"
|
||||
| "ot_es2_trz"
|
||||
| "es1ic0_try"
|
||||
| "es1ic1_try"
|
||||
| "es1ic2_try"
|
||||
):
|
||||
self.motion()
|
||||
case "cm_trx":
|
||||
self.motion(
|
||||
abs_closed=True,
|
||||
surveyed_axes=[{"device": self.dev["cm_roty"], "abs_tol": 0.05}],
|
||||
)
|
||||
case "cm_roty":
|
||||
self.motion(
|
||||
abs_closed=True, surveyed_axes=[{"device": self.dev["cm_trx"], "abs_tol": 0.05}]
|
||||
)
|
||||
case "cm_try":
|
||||
self.motion(
|
||||
abs_closed=True,
|
||||
surveyed_axes=[
|
||||
{"device": self.dev["cm_rotx"], "abs_tol": 0.05},
|
||||
{"device": self.dev["cm_rotz"], "abs_tol": 0.05},
|
||||
],
|
||||
)
|
||||
case "cm_rotx":
|
||||
self.motion(
|
||||
abs_closed=True,
|
||||
surveyed_axes=[
|
||||
{"device": self.dev["cm_try"], "abs_tol": 0.05},
|
||||
{"device": self.dev["cm_rotz"], "abs_tol": 0.05},
|
||||
],
|
||||
)
|
||||
case "cm_rotz":
|
||||
self.motion(
|
||||
abs_closed=True,
|
||||
surveyed_axes=[
|
||||
{"device": self.dev["cm_try"], "abs_tol": 0.05},
|
||||
{"device": self.dev["cm_rotx"], "abs_tol": 0.05},
|
||||
],
|
||||
)
|
||||
case "cm_bnd":
|
||||
if self.beamline == "x01da":
|
||||
p1 = (
|
||||
1 / (self.dev.cm_bnd_radius.read()["cm_bnd_radius"]["value"] * 1e3) + 0.0284
|
||||
) / 2e-6
|
||||
p2 = (1 / (self._target * 1e3) + 0.0284) / 2e-6
|
||||
else:
|
||||
p1 = 541900 / self.dev.cm_bnd_radius.read()["cm_bnd_radius"]["value"] - 32570
|
||||
p2 = 541900 / self._target - 32570
|
||||
self._target = p2 - p1
|
||||
self.motion(relative=True, rb={"device": self.dev["cm_bnd_radius"]})
|
||||
case "mo1_try" | "mo1_trx" | "mo1_roty":
|
||||
self.motion(abs_closed=True)
|
||||
case "mo1_bragg_angle":
|
||||
if self.beamline == "x01da":
|
||||
self.motion()
|
||||
else: # x10da needs to move goniometer
|
||||
self.motion(alias="mo1_rotx")
|
||||
case "fm_trx":
|
||||
self.motion(
|
||||
abs_closed=True,
|
||||
surveyed_axes=[{"device": self.dev["fm_roty"], "abs_tol": 0.05}],
|
||||
)
|
||||
case "fm_roty":
|
||||
self.motion(
|
||||
abs_closed=True, surveyed_axes=[{"device": self.dev["fm_trx"], "abs_tol": 0.05}]
|
||||
)
|
||||
case "fm_try":
|
||||
if self.beamline == "x01da":
|
||||
abs_tol = 0.05
|
||||
else: # superxas mirror less stable thus needs higher tolerance
|
||||
abs_tol = 0.2
|
||||
self.motion(
|
||||
abs_closed=True,
|
||||
surveyed_axes=[
|
||||
{"device": self.dev["fm_rotx"], "abs_tol": abs_tol},
|
||||
{"device": self.dev["fm_rotz"], "abs_tol": abs_tol},
|
||||
],
|
||||
)
|
||||
case "fm_rotx":
|
||||
if self.beamline == "x01da":
|
||||
abs_tol = 0.05
|
||||
else: # superxas mirror less stable thus needs higher tolerance
|
||||
abs_tol = 0.2
|
||||
self.motion(
|
||||
abs_closed=True,
|
||||
surveyed_axes=[
|
||||
{"device": self.dev["fm_try"], "abs_tol": abs_tol},
|
||||
{"device": self.dev["fm_rotz"], "abs_tol": abs_tol},
|
||||
],
|
||||
)
|
||||
case "fm_rotz":
|
||||
if self.beamline == "x01da":
|
||||
abs_tol = 0.05
|
||||
else: # superxas mirror less stable thus needs higher tolerance
|
||||
abs_tol = 0.2
|
||||
self.motion(
|
||||
abs_closed=True,
|
||||
surveyed_axes=[
|
||||
{"device": self.dev["fm_try"], "abs_tol": abs_tol},
|
||||
{"device": self.dev["fm_rotx"], "abs_tol": abs_tol},
|
||||
],
|
||||
)
|
||||
case "fm_bnd":
|
||||
if self.beamline == "x01da":
|
||||
p1 = (
|
||||
1 / (self.dev.fm_bnd_radius.read()["fm_bnd_radius"]["value"] * 1e3)
|
||||
+ 4.28e-5
|
||||
) / 1.84e-9
|
||||
p2 = (1 / (self._target * 1e3) + 4.28e-5) / 1.84e-9
|
||||
else:
|
||||
p1 = (
|
||||
593088.7 / self.dev.fm_bnd_radius.read()["fm_bnd_radius"]["value"]
|
||||
+ 26124.41
|
||||
)
|
||||
p2 = 593088.7 / self._target + 26124.41
|
||||
self._target = p2 - p1
|
||||
self.motion(relative=True, rb={"device": self.dev["fm_bnd_radius"]})
|
||||
case _:
|
||||
logger.warning(f"Motor {self.motor} not integrated in digital twin!")
|
||||
|
||||
def motion(
|
||||
self,
|
||||
abs_closed: bool = False,
|
||||
relative: bool = False,
|
||||
rb=None,
|
||||
surveyed_axes=None,
|
||||
alias=None,
|
||||
):
|
||||
"""
|
||||
Moves an axis while surverying a set of axes (if set).
|
||||
Example surveyed_axes:
|
||||
[{'device': bec_device_object, 'abs_tol': 0.1},]
|
||||
|
||||
Args:
|
||||
surveyed_axes (list): List of dictionaries of devices
|
||||
"""
|
||||
logger.info(f"Move axis {self.motor} to target {self._target}, move_relative={relative}")
|
||||
try:
|
||||
if alias:
|
||||
self.motor = alias
|
||||
if abs_closed:
|
||||
if self.dev.abs.status.get() == ABS_STATUS.OPEN:
|
||||
status = self.dev.abs.close(wait=True)
|
||||
if surveyed_axes is not None:
|
||||
for surv_ax in surveyed_axes:
|
||||
surv_ax["name"] = surv_ax["device"].dotted_name
|
||||
surv_ax["old_value"] = surv_ax["device"].read(cached=True)[surv_ax["name"]][
|
||||
"value"
|
||||
]
|
||||
if rb is not None:
|
||||
rb["name"] = rb["device"].dotted_name
|
||||
status = self.dev[self.motor].move(self._target, relative=relative)
|
||||
last_check = time.time()
|
||||
update_interval = 0.1
|
||||
while status.status == "RUNNING":
|
||||
now = time.time()
|
||||
if time.time() - last_check < update_interval:
|
||||
time.sleep(0.01)
|
||||
continue
|
||||
last_check = now
|
||||
if self._stop_flag.is_set():
|
||||
self.dev[self.motor].stop()
|
||||
self._stop_flag.clear()
|
||||
if rb is not None:
|
||||
self._emit_position_changed(
|
||||
rb["device"].read(cached=False)[rb["name"]]["value"]
|
||||
)
|
||||
else:
|
||||
self._emit_position_changed(
|
||||
self.dev[self.motor].read(cached=False)[self.motor]["value"]
|
||||
)
|
||||
if surveyed_axes is not None:
|
||||
for surv_ax in surveyed_axes:
|
||||
fb = surv_ax["device"].read(cached=True)[surv_ax["name"]]["value"]
|
||||
if abs(fb - surv_ax["old_value"]) > surv_ax["abs_tol"]:
|
||||
self.dev[self.motor].stop()
|
||||
self.last_exception = RuntimeError(
|
||||
f"{surv_ax['name']} deviated beyond tolerance {surv_ax['abs_tol']} during {self.motor} move"
|
||||
)
|
||||
self._emit_error()
|
||||
self._emit_finished()
|
||||
return
|
||||
self._emit_finished()
|
||||
except Exception as e:
|
||||
logger.error(f"Error during movement of {self.motor}: {e}")
|
||||
self.last_exception = e
|
||||
self._emit_error()
|
||||
self._emit_finished()
|
||||
+8
-2
@@ -27,12 +27,15 @@ class ConfigDict(TypedDict):
|
||||
mo1_mode (str): MO1 mode.
|
||||
mo1_xtal (str): MO1 crystal.
|
||||
mo1_bragg (float): MO1 Bragg angle.
|
||||
mo1_roty (float): MO1 Azimuthal angle.
|
||||
fm_rotx (float): FM rotation x.
|
||||
fm_stripe (str): FM stripe name.
|
||||
fm_trx (float): FM translation x.
|
||||
fm_qy (float): FM qy value.
|
||||
fm_gain_height (int): FM gain height.
|
||||
smpl (float): Sample value.
|
||||
ot_es1_trz (float): Position of ES1 table.
|
||||
es1man_trz (float): Position of Sample Manipulator TRZ
|
||||
smpl_to_xrd (float): Sample to XRD detector distance
|
||||
"""
|
||||
|
||||
energy: float
|
||||
@@ -44,12 +47,15 @@ class ConfigDict(TypedDict):
|
||||
mo1_mode: str
|
||||
mo1_xtal: str
|
||||
mo1_bragg: float
|
||||
mo1_roty: float
|
||||
fm_rotx: float
|
||||
fm_stripe: str
|
||||
fm_trx: float
|
||||
fm_qy: None | float
|
||||
fm_gain_height: int
|
||||
smpl: float
|
||||
ot_es1_trz: float
|
||||
es1man_trz: float
|
||||
smpl_to_xrd: None | float
|
||||
|
||||
|
||||
class DataDict(TypedDict):
|
||||
+6
@@ -13,6 +13,12 @@ mo1_try:
|
||||
range: [[-30, -0.1], [0.1, 30]]
|
||||
offset: [-1.78, -1.78]
|
||||
|
||||
mo1_roty:
|
||||
modifier:
|
||||
axis: mo1_trx
|
||||
range: [[-30, -0.1], [0.1, 30]] # Si311, Si111
|
||||
offset: [-136.80017, -89.15503]
|
||||
|
||||
sl1_centery:
|
||||
offset: -1.2
|
||||
|
||||
+1
-1
@@ -320,4 +320,4 @@ vacuum_pipes = pipe(
|
||||
)
|
||||
|
||||
Walls = namedtuple("walls", ["start", "end", "height"])
|
||||
walls = Walls(start=[13999.30], end=[13999 + 75.5 + 30], height=[[-20, 25]])
|
||||
walls = Walls(start=[13999.30], end=[13999 + 75.5 + 30], height=[[-20, 25]]) # WBBS
|
||||
+6
@@ -11,6 +11,12 @@ mo1_trx:
|
||||
range: [[-30, -0.1], [0.1, 30]]
|
||||
offset: [-4.3, 0]
|
||||
|
||||
mo1_roty:
|
||||
modifier:
|
||||
axis: mo1_trx
|
||||
range: [[-30, -0.1], [0.1, 30]] # Si111, Si311
|
||||
offset: [-116.400, -137.605]
|
||||
|
||||
sl1_centery:
|
||||
offset: -55.54
|
||||
|
||||
+299
-296
@@ -1,296 +1,299 @@
|
||||
"""
|
||||
X10DA / SuperXAS Beamline Parameters.
|
||||
This file describes the parameter of each component of the SuperXAS beamline
|
||||
to be used for raytracing and geometrical calculations.
|
||||
"""
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
import numpy as np
|
||||
import xrt.backends.raycing.materials as rm
|
||||
|
||||
# XRT definitions
|
||||
filterBeryl = rm.Material("Be", rho=1.85, kind="plate") # pyright: ignore[reportArgumentType]
|
||||
filterDiamond = rm.Material("C", rho=3.52, kind="plate") # pyright: ignore[reportArgumentType]
|
||||
filterGraphite = rm.Material("C", rho=2.266, kind="plate") # pyright: ignore[reportArgumentType]
|
||||
|
||||
stripeSi = rm.Material("Si", rho=2.33) # pyright: ignore[reportArgumentType]
|
||||
stripePt = rm.Material("Pt", rho=21.45) # pyright: ignore[reportArgumentType]
|
||||
stripeRh = rm.Material("Rh", rho=12.41) # pyright: ignore[reportArgumentType]
|
||||
stripeCr = rm.Material("Cr", rho=7.14) # pyright: ignore[reportArgumentType]
|
||||
stripePyrex = rm.Material(
|
||||
"Si", rho=2.20
|
||||
) # Use Si as bare element and the density of SiO2 # pyright: ignore[reportArgumentType]
|
||||
|
||||
si111_1 = rm.CrystalSi(hkl=(1, 1, 1), tK=77) # first xtal surface
|
||||
si311_1 = rm.CrystalSi(hkl=(3, 1, 1), tK=77) # first xtal surface
|
||||
si333_1 = rm.CrystalSi(hkl=(3, 3, 3), tK=77) # first xtal surface
|
||||
si511_1 = rm.CrystalSi(hkl=(5, 1, 1), tK=77) # first xtal surface
|
||||
si111_2 = rm.CrystalSi(hkl=(1, 1, 1), tK=77) # second xtal surface
|
||||
si311_2 = rm.CrystalSi(hkl=(3, 1, 1), tK=77) # second xtal surface
|
||||
si333_2 = rm.CrystalSi(hkl=(3, 3, 3), tK=77) # second xtal surface
|
||||
si511_2 = rm.CrystalSi(hkl=(5, 1, 1), tK=77) # second xtal surface
|
||||
|
||||
filterDiamond = rm.Material("C", rho=3.52, kind="plate") # pyright: ignore[reportArgumentType]
|
||||
filterBe = rm.Material("Be", rho=1.85, kind="plate") # pyright: ignore[reportArgumentType]
|
||||
filterSi3N4 = rm.Material(
|
||||
["Si", "N"], quantities=[3, 4], rho=3.44, kind="plate"
|
||||
) # pyright: ignore[reportArgumentType]
|
||||
filterAl = rm.Material("Al", rho=2.69, kind="plate") # pyright: ignore[reportArgumentType]
|
||||
filterGraphite = rm.Material("C", rho=2.266, kind="plate") # pyright: ignore[reportArgumentType]
|
||||
|
||||
# General parameters
|
||||
sourceHeight = 0
|
||||
|
||||
# Synchrotron
|
||||
synchrotron = namedtuple(
|
||||
"synchrotron", ["eE", "eI", "eEspread", "eEpsilonX", "eEpsilonZ", "betaX", "betaZ"]
|
||||
)
|
||||
|
||||
sls1 = synchrotron(
|
||||
eE=2.4, eI=0.4, eEspread=0.878e-3, eEpsilonX=5.63, eEpsilonZ=0.007, betaX=0.45, betaZ=14.4
|
||||
)
|
||||
|
||||
sls2 = synchrotron(
|
||||
eE=2.7, eI=0.4, eEspread=1.147e-3, eEpsilonX=0.156, eEpsilonZ=0.01, betaX=0.18, betaZ=4.6
|
||||
)
|
||||
|
||||
# Source
|
||||
bendingMagnet = namedtuple("bendingMagnet", ["name", "center", "sync", "B0"])
|
||||
|
||||
sls1_14t = bendingMagnet(name="FE-BM-SLS1-1.4T", center=(0, 0, 0), sync=sls1, B0=1.4)
|
||||
|
||||
sls2_21t = bendingMagnet(name="FE-BM-SLS2-2.1T", center=(0, 0, 0), sync=sls2, B0=2.1)
|
||||
|
||||
sls2_35t = bendingMagnet(name="FE-BM-SLS2-3.5T", center=(0, 0, 0), sync=sls2, B0=3.5)
|
||||
|
||||
sls2_50t = bendingMagnet(name="FE-BM-SLS2-5.0T", center=(0, 0, 0), sync=sls2, B0=5.0)
|
||||
|
||||
# FE slits
|
||||
fe_slits = namedtuple("slits", ["name", "center", "center1", "center2", "maxDivH", "maxDivV"])
|
||||
|
||||
feSlits = fe_slits(
|
||||
name="FE-SLITS",
|
||||
center=(0, 6117, sourceHeight),
|
||||
center1=(0, 5038.4, sourceHeight),
|
||||
center2=(0, 5282.9, sourceHeight),
|
||||
maxDivH=1.8e-3,
|
||||
maxDivV=0.8e-3,
|
||||
)
|
||||
|
||||
# Filters
|
||||
filt = namedtuple(
|
||||
"filt", ["name", "center", "pitch", "limPhysX", "limPhysY", "surface", "material", "thickness"]
|
||||
)
|
||||
|
||||
feWindow = filt(
|
||||
name="FE-WINDOW",
|
||||
center=(0.0, 6158, sourceHeight),
|
||||
pitch=np.pi / 2,
|
||||
limPhysX=(-6, 6),
|
||||
limPhysY=(-3.0, 3.0),
|
||||
surface="None",
|
||||
material=filterDiamond,
|
||||
thickness=0.1,
|
||||
)
|
||||
feWindow = feWindow._replace(
|
||||
surface="CVD Diamond window {0:0.0f} $\\mu$m".format(feWindow.thickness * 1e3)
|
||||
)
|
||||
|
||||
feFilt = filt(
|
||||
name="FE-FI",
|
||||
center=(0.0, 6590, sourceHeight),
|
||||
pitch=np.pi / 2,
|
||||
limPhysX=(-15, 15),
|
||||
limPhysY=(-10, 10),
|
||||
surface="None",
|
||||
material=filterGraphite,
|
||||
thickness=0.25,
|
||||
)
|
||||
feFilt = feFilt._replace(surface="Graphite filter {0:0.0f} $\\mu$m".format(feFilt.thickness * 1e3))
|
||||
|
||||
# Collimating mirror
|
||||
collimatingMirror = namedtuple(
|
||||
"collimatingMirror",
|
||||
[
|
||||
"name",
|
||||
"center",
|
||||
"surface",
|
||||
"material",
|
||||
"limPhysX",
|
||||
"limPhysY",
|
||||
"limOptX",
|
||||
"limOptY",
|
||||
"R",
|
||||
"pitch",
|
||||
"jack1",
|
||||
"jack2",
|
||||
"jack3",
|
||||
"tx1",
|
||||
"tx2",
|
||||
],
|
||||
)
|
||||
|
||||
cm = collimatingMirror(
|
||||
name="FE-CM",
|
||||
center=[0, 7560.8, sourceHeight],
|
||||
surface=("Pt", "Si", "Rh"),
|
||||
material=(stripePt, stripeSi, stripeRh),
|
||||
limPhysX=(-30, 30),
|
||||
limPhysY=(-600, 600),
|
||||
limOptX=((-21, -0.5, 11), (-4, 9.5, 23)),
|
||||
limOptY=((-500, -500, -500), (500, 500, 500)),
|
||||
R=[3e6, 15e6],
|
||||
pitch=[1.4e-3, 4.5e-3],
|
||||
jack1=[0.0, 7210.0, 0.0], # Tripod X, Y, Z (global)
|
||||
jack2=[-210.0, 8310.0, 0.0],
|
||||
jack3=[210.0, 8310.0, 0.0],
|
||||
tx1=[0.0, -575.5], # X-Stage 1 [x, y] (local)
|
||||
tx2=[0.0, 575],
|
||||
) # X-Stage 2
|
||||
|
||||
apertures = namedtuple("apertures", ["name", "center", "opening"])
|
||||
|
||||
fePS = apertures(
|
||||
name="FE-PS", center=[0, 8760, sourceHeight], opening=[-39 / 2, 39 / 2, -10, 29]
|
||||
) # left, right, bottom, top
|
||||
|
||||
opWbBsBlock = apertures(
|
||||
name="OP-WB-BS-BLOCK", center=[0.0, 13606 - 135, sourceHeight], opening=[-18.0, 18.0, 42, 76]
|
||||
) # left, right, bottom, top
|
||||
|
||||
opSlits1 = apertures(
|
||||
name="OP-SLITS 1", center=[0, 14145 - 135, sourceHeight], opening=[-35 / 2, 35 / 2, 47.5, 82.5]
|
||||
)
|
||||
|
||||
# OP Beam Monitors
|
||||
op_bm = namedtuple("op_bm", ["name", "center"])
|
||||
|
||||
opBM1 = op_bm(name="OP Beam Monitor 1", center=(0, 14525 - 135, sourceHeight))
|
||||
|
||||
opBM2 = op_bm(name="OP Beam Monitor 2", center=(0, 17161.6 - 135, sourceHeight))
|
||||
|
||||
# Monochromator
|
||||
monochromator = namedtuple(
|
||||
"monochromator",
|
||||
[
|
||||
"name",
|
||||
"center",
|
||||
"xtal",
|
||||
"material1",
|
||||
"material2",
|
||||
"xtalWidth",
|
||||
"xtalOffsetX",
|
||||
"xtalLength1",
|
||||
"xtalLength2",
|
||||
"xtalGap",
|
||||
"rotOffset",
|
||||
"heightOffset",
|
||||
"braggLim",
|
||||
"jack1",
|
||||
"jack2",
|
||||
"jack3",
|
||||
"tx",
|
||||
],
|
||||
)
|
||||
|
||||
mo1 = monochromator(
|
||||
name="OP-CCM1",
|
||||
center=[0.0, 11670 - 135, sourceHeight],
|
||||
xtal=("Si311", "Si111"),
|
||||
material1=(si311_1, si111_1),
|
||||
material2=(si311_2, si111_2),
|
||||
xtalWidth=(20, 20),
|
||||
xtalOffsetX=(19.2, -19.2),
|
||||
xtalLength1=(60, 60),
|
||||
xtalLength2=(60, 60),
|
||||
xtalGap=(8, 8),
|
||||
rotOffset=6, # not sure what it is
|
||||
heightOffset=8.5, # not sure what it is
|
||||
braggLim=[4, 35],
|
||||
jack1=[0.0, 11350.0, 0.0], # Tripod not available!
|
||||
jack2=[-400.0, 12350.0, 0.0],
|
||||
jack3=[400.0, 12350.0, 0.0],
|
||||
tx=0.0,
|
||||
) # X-Stage [x]
|
||||
|
||||
# Focusing mirror
|
||||
focusingMirror = namedtuple(
|
||||
"focusingMirror",
|
||||
[
|
||||
"name",
|
||||
"center",
|
||||
"surfaceToroid",
|
||||
"materialToroid",
|
||||
"limPhysXToroid",
|
||||
"limPhysYToroid",
|
||||
"limOptXToroid",
|
||||
"limOptYToroid",
|
||||
"R",
|
||||
"pitch",
|
||||
"r",
|
||||
"xToroid",
|
||||
"hToroid",
|
||||
"jack1",
|
||||
"jack2",
|
||||
"jack3",
|
||||
"tx1",
|
||||
"tx2",
|
||||
],
|
||||
)
|
||||
|
||||
OFFSET_TRX = 46.8735
|
||||
|
||||
fm = focusingMirror(
|
||||
name="OP-FM",
|
||||
center=[0.0, 15580 - 135, sourceHeight],
|
||||
surfaceToroid=("Rh", "Pt"),
|
||||
materialToroid=(stripeRh, stripePt),
|
||||
limPhysXToroid=(-54.0, 54.0),
|
||||
limPhysYToroid=(-565.0, 565.0),
|
||||
limOptXToroid=(
|
||||
(43.388 + OFFSET_TRX, -4.865 + OFFSET_TRX),
|
||||
(4.865 + OFFSET_TRX, -40.882 + OFFSET_TRX),
|
||||
),
|
||||
limOptYToroid=((-500.0, -500.0), (500.0, 500.0)),
|
||||
R=[3e6, 15e6],
|
||||
pitch=[1.4e-3, 4.5e-3],
|
||||
r=[30, 20],
|
||||
xToroid=[24.126 + OFFSET_TRX, -22 + OFFSET_TRX], # offset in local x
|
||||
hToroid=[7.0, 11.3], # depth of the cylinder at x = xCylinder1 and x = xCylinder2.
|
||||
jack1=[0.0, 14980.0, 0.0],
|
||||
jack2=[-75.0, 16180.0, 0.0],
|
||||
jack3=[75.0, 16180.0, 0.0],
|
||||
tx1=[0.0, -575.0], # X-Stage 1 [x, y]
|
||||
tx2=[0.0, 575.0],
|
||||
) # X-Stage 2 [x, y]
|
||||
|
||||
# Entry wall experimental hutch: 21593 mm from source (SLS2)
|
||||
|
||||
# Exit window
|
||||
ehWindow = filt(
|
||||
name="EH-WINDOW",
|
||||
center=(0.0, 22063, sourceHeight),
|
||||
pitch=np.pi / 2,
|
||||
limPhysX=(-10.0, 10.0),
|
||||
limPhysY=(17.5, 92.5),
|
||||
surface="None",
|
||||
material=filterBe,
|
||||
thickness=0.25,
|
||||
)
|
||||
ehWindow = ehWindow._replace(
|
||||
surface="Beryllium window {0:0.0f} $\\mu$m".format(ehWindow.thickness * 1e3)
|
||||
)
|
||||
|
||||
# Sample
|
||||
sample = namedtuple("sample", ["name", "center"])
|
||||
|
||||
es1 = sample(name="ES1", center=[0, 23823, sourceHeight])
|
||||
es2 = sample(name="ES2", center=[0, 25843, sourceHeight])
|
||||
|
||||
# Ionization chambers
|
||||
ic = namedtuple("sample", ["name", "center"])
|
||||
|
||||
es1ic0 = ic(name="ES1 IC0", center=[0, 23633, sourceHeight])
|
||||
es1ic1 = ic(name="ES1 IC1", center=[0, 24383, sourceHeight])
|
||||
es1ic2 = ic(name="ES1 IC2", center=[0, 24723, sourceHeight])
|
||||
"""
|
||||
X10DA / SuperXAS Beamline Parameters.
|
||||
This file describes the parameter of each component of the SuperXAS beamline
|
||||
to be used for raytracing and geometrical calculations.
|
||||
"""
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
import numpy as np
|
||||
import xrt.backends.raycing.materials as rm
|
||||
|
||||
# XRT definitions
|
||||
filterBeryl = rm.Material("Be", rho=1.85, kind="plate") # pyright: ignore[reportArgumentType]
|
||||
filterDiamond = rm.Material("C", rho=3.52, kind="plate") # pyright: ignore[reportArgumentType]
|
||||
filterGraphite = rm.Material("C", rho=2.266, kind="plate") # pyright: ignore[reportArgumentType]
|
||||
|
||||
stripeSi = rm.Material("Si", rho=2.33) # pyright: ignore[reportArgumentType]
|
||||
stripePt = rm.Material("Pt", rho=21.45) # pyright: ignore[reportArgumentType]
|
||||
stripeRh = rm.Material("Rh", rho=12.41) # pyright: ignore[reportArgumentType]
|
||||
stripeCr = rm.Material("Cr", rho=7.14) # pyright: ignore[reportArgumentType]
|
||||
stripePyrex = rm.Material(
|
||||
"Si", rho=2.20
|
||||
) # Use Si as bare element and the density of SiO2 # pyright: ignore[reportArgumentType]
|
||||
|
||||
si111_1 = rm.CrystalSi(hkl=(1, 1, 1), tK=77) # first xtal surface
|
||||
si311_1 = rm.CrystalSi(hkl=(3, 1, 1), tK=77) # first xtal surface
|
||||
si333_1 = rm.CrystalSi(hkl=(3, 3, 3), tK=77) # first xtal surface
|
||||
si511_1 = rm.CrystalSi(hkl=(5, 1, 1), tK=77) # first xtal surface
|
||||
si111_2 = rm.CrystalSi(hkl=(1, 1, 1), tK=77) # second xtal surface
|
||||
si311_2 = rm.CrystalSi(hkl=(3, 1, 1), tK=77) # second xtal surface
|
||||
si333_2 = rm.CrystalSi(hkl=(3, 3, 3), tK=77) # second xtal surface
|
||||
si511_2 = rm.CrystalSi(hkl=(5, 1, 1), tK=77) # second xtal surface
|
||||
|
||||
filterDiamond = rm.Material("C", rho=3.52, kind="plate") # pyright: ignore[reportArgumentType]
|
||||
filterBe = rm.Material("Be", rho=1.85, kind="plate") # pyright: ignore[reportArgumentType]
|
||||
filterSi3N4 = rm.Material(
|
||||
["Si", "N"], quantities=[3, 4], rho=3.44, kind="plate"
|
||||
) # pyright: ignore[reportArgumentType]
|
||||
filterAl = rm.Material("Al", rho=2.69, kind="plate") # pyright: ignore[reportArgumentType]
|
||||
filterGraphite = rm.Material("C", rho=2.266, kind="plate") # pyright: ignore[reportArgumentType]
|
||||
|
||||
# General parameters
|
||||
sourceHeight = 0
|
||||
|
||||
# Synchrotron
|
||||
synchrotron = namedtuple(
|
||||
"synchrotron", ["eE", "eI", "eEspread", "eEpsilonX", "eEpsilonZ", "betaX", "betaZ"]
|
||||
)
|
||||
|
||||
sls1 = synchrotron(
|
||||
eE=2.4, eI=0.4, eEspread=0.878e-3, eEpsilonX=5.63, eEpsilonZ=0.007, betaX=0.45, betaZ=14.4
|
||||
)
|
||||
|
||||
sls2 = synchrotron(
|
||||
eE=2.7, eI=0.4, eEspread=1.147e-3, eEpsilonX=0.156, eEpsilonZ=0.01, betaX=0.18, betaZ=4.6
|
||||
)
|
||||
|
||||
# Source
|
||||
bendingMagnet = namedtuple("bendingMagnet", ["name", "center", "sync", "B0"])
|
||||
|
||||
sls1_14t = bendingMagnet(name="FE-BM-SLS1-1.4T", center=(0, 0, 0), sync=sls1, B0=1.4)
|
||||
|
||||
sls2_21t = bendingMagnet(name="FE-BM-SLS2-2.1T", center=(0, 0, 0), sync=sls2, B0=2.1)
|
||||
|
||||
sls2_35t = bendingMagnet(name="FE-BM-SLS2-3.5T", center=(0, 0, 0), sync=sls2, B0=3.5)
|
||||
|
||||
sls2_50t = bendingMagnet(name="FE-BM-SLS2-5.0T", center=(0, 0, 0), sync=sls2, B0=5.0)
|
||||
|
||||
# FE slits
|
||||
fe_slits = namedtuple("slits", ["name", "center", "center1", "center2", "maxDivH", "maxDivV"])
|
||||
|
||||
feSlits = fe_slits(
|
||||
name="FE-SLITS",
|
||||
center=(0, 6117, sourceHeight),
|
||||
center1=(0, 5038.4, sourceHeight),
|
||||
center2=(0, 5282.9, sourceHeight),
|
||||
maxDivH=1.8e-3,
|
||||
maxDivV=0.8e-3,
|
||||
)
|
||||
|
||||
# Filters
|
||||
filt = namedtuple(
|
||||
"filt", ["name", "center", "pitch", "limPhysX", "limPhysY", "surface", "material", "thickness"]
|
||||
)
|
||||
|
||||
feWindow = filt(
|
||||
name="FE-WINDOW",
|
||||
center=(0.0, 6158, sourceHeight),
|
||||
pitch=np.pi / 2,
|
||||
limPhysX=(-6, 6),
|
||||
limPhysY=(-3.0, 3.0),
|
||||
surface="None",
|
||||
material=filterDiamond,
|
||||
thickness=0.1,
|
||||
)
|
||||
feWindow = feWindow._replace(
|
||||
surface="CVD Diamond window {0:0.0f} $\\mu$m".format(feWindow.thickness * 1e3)
|
||||
)
|
||||
|
||||
feFilt = filt(
|
||||
name="FE-FI",
|
||||
center=(0.0, 6590, sourceHeight),
|
||||
pitch=np.pi / 2,
|
||||
limPhysX=(-15, 15),
|
||||
limPhysY=(-10, 10),
|
||||
surface="None",
|
||||
material=filterGraphite,
|
||||
thickness=0.25,
|
||||
)
|
||||
feFilt = feFilt._replace(surface="Graphite filter {0:0.0f} $\\mu$m".format(feFilt.thickness * 1e3))
|
||||
|
||||
# Collimating mirror
|
||||
collimatingMirror = namedtuple(
|
||||
"collimatingMirror",
|
||||
[
|
||||
"name",
|
||||
"center",
|
||||
"surface",
|
||||
"material",
|
||||
"limPhysX",
|
||||
"limPhysY",
|
||||
"limOptX",
|
||||
"limOptY",
|
||||
"R",
|
||||
"pitch",
|
||||
"jack1",
|
||||
"jack2",
|
||||
"jack3",
|
||||
"tx1",
|
||||
"tx2",
|
||||
],
|
||||
)
|
||||
|
||||
cm = collimatingMirror(
|
||||
name="FE-CM",
|
||||
center=[0, 7560.8, sourceHeight],
|
||||
surface=("Pt", "Si", "Rh"),
|
||||
material=(stripePt, stripeSi, stripeRh),
|
||||
limPhysX=(-30, 30),
|
||||
limPhysY=(-600, 600),
|
||||
limOptX=((-21, -0.5, 11), (-4, 9.5, 23)),
|
||||
limOptY=((-500, -500, -500), (500, 500, 500)),
|
||||
R=[3e6, 15e6],
|
||||
pitch=[1.4e-3, 4.5e-3],
|
||||
jack1=[0.0, 7210.0, 0.0], # Tripod X, Y, Z (global)
|
||||
jack2=[-210.0, 8310.0, 0.0],
|
||||
jack3=[210.0, 8310.0, 0.0],
|
||||
tx1=[0.0, -575.5], # X-Stage 1 [x, y] (local)
|
||||
tx2=[0.0, 575],
|
||||
) # X-Stage 2
|
||||
|
||||
apertures = namedtuple("apertures", ["name", "center", "opening"])
|
||||
|
||||
fePS = apertures(
|
||||
name="FE-PS", center=[0, 8760, sourceHeight], opening=[-39 / 2, 39 / 2, -10, 29]
|
||||
) # left, right, bottom, top
|
||||
|
||||
opWbBsBlock = apertures(
|
||||
name="OP-WB-BS-BLOCK", center=[0.0, 13606 - 135, sourceHeight], opening=[-18.0, 18.0, 42, 76]
|
||||
) # left, right, bottom, top
|
||||
|
||||
opSlits1 = apertures(
|
||||
name="OP-SLITS 1", center=[0, 14145 - 135, sourceHeight], opening=[-35 / 2, 35 / 2, 47.5, 82.5]
|
||||
)
|
||||
|
||||
# OP Beam Monitors
|
||||
op_bm = namedtuple("op_bm", ["name", "center"])
|
||||
|
||||
opBM1 = op_bm(name="OP Beam Monitor 1", center=(0, 14525 - 135, sourceHeight))
|
||||
|
||||
opBM2 = op_bm(name="OP Beam Monitor 2", center=(0, 17161.6 - 135, sourceHeight))
|
||||
|
||||
# Monochromator
|
||||
monochromator = namedtuple(
|
||||
"monochromator",
|
||||
[
|
||||
"name",
|
||||
"center",
|
||||
"xtal",
|
||||
"material1",
|
||||
"material2",
|
||||
"xtalWidth",
|
||||
"xtalOffsetX",
|
||||
"xtalLength1",
|
||||
"xtalLength2",
|
||||
"xtalGap",
|
||||
"rotOffset",
|
||||
"heightOffset",
|
||||
"braggLim",
|
||||
"jack1",
|
||||
"jack2",
|
||||
"jack3",
|
||||
"tx",
|
||||
],
|
||||
)
|
||||
|
||||
mo1 = monochromator(
|
||||
name="OP-CCM1",
|
||||
center=[0.0, 11670 - 135, sourceHeight],
|
||||
xtal=("Si311", "Si111"),
|
||||
material1=(si311_1, si111_1),
|
||||
material2=(si311_2, si111_2),
|
||||
xtalWidth=(20, 20),
|
||||
xtalOffsetX=(19.2, -19.2),
|
||||
xtalLength1=(60, 60),
|
||||
xtalLength2=(60, 60),
|
||||
xtalGap=(8, 8),
|
||||
rotOffset=6, # not sure what it is
|
||||
heightOffset=8.5, # not sure what it is
|
||||
braggLim=[4, 35],
|
||||
jack1=[0.0, 11350.0, 0.0], # Tripod not available!
|
||||
jack2=[-400.0, 12350.0, 0.0],
|
||||
jack3=[400.0, 12350.0, 0.0],
|
||||
tx=0.0,
|
||||
) # X-Stage [x]
|
||||
|
||||
# Focusing mirror
|
||||
focusingMirror = namedtuple(
|
||||
"focusingMirror",
|
||||
[
|
||||
"name",
|
||||
"center",
|
||||
"surfaceToroid",
|
||||
"materialToroid",
|
||||
"limPhysXToroid",
|
||||
"limPhysYToroid",
|
||||
"limOptXToroid",
|
||||
"limOptYToroid",
|
||||
"R",
|
||||
"pitch",
|
||||
"r",
|
||||
"xToroid",
|
||||
"hToroid",
|
||||
"jack1",
|
||||
"jack2",
|
||||
"jack3",
|
||||
"tx1",
|
||||
"tx2",
|
||||
],
|
||||
)
|
||||
|
||||
OFFSET_TRX = 46.8735
|
||||
|
||||
fm = focusingMirror(
|
||||
name="OP-FM",
|
||||
center=[0.0, 15580 - 135, sourceHeight],
|
||||
surfaceToroid=("Rh", "Pt"),
|
||||
materialToroid=(stripeRh, stripePt),
|
||||
limPhysXToroid=(-54.0, 54.0),
|
||||
limPhysYToroid=(-565.0, 565.0),
|
||||
limOptXToroid=(
|
||||
(43.388 + OFFSET_TRX, -4.865 + OFFSET_TRX),
|
||||
(4.865 + OFFSET_TRX, -40.882 + OFFSET_TRX),
|
||||
),
|
||||
limOptYToroid=((-500.0, -500.0), (500.0, 500.0)),
|
||||
R=[3e6, 15e6],
|
||||
pitch=[1.4e-3, 4.5e-3],
|
||||
r=[30, 20],
|
||||
xToroid=[24.126 + OFFSET_TRX, -22 + OFFSET_TRX], # offset in local x
|
||||
hToroid=[7.0, 11.3], # depth of the cylinder at x = xCylinder1 and x = xCylinder2.
|
||||
jack1=[0.0, 14980.0, 0.0],
|
||||
jack2=[-75.0, 16180.0, 0.0],
|
||||
jack3=[75.0, 16180.0, 0.0],
|
||||
tx1=[0.0, -575.0], # X-Stage 1 [x, y]
|
||||
tx2=[0.0, 575.0],
|
||||
) # X-Stage 2 [x, y]
|
||||
|
||||
# Entry wall experimental hutch: 21593 mm from source (SLS2)
|
||||
|
||||
# Exit window
|
||||
ehWindow = filt(
|
||||
name="EH-WINDOW",
|
||||
center=(0.0, 22063, sourceHeight),
|
||||
pitch=np.pi / 2,
|
||||
limPhysX=(-10.0, 10.0),
|
||||
limPhysY=(17.5, 92.5),
|
||||
surface="None",
|
||||
material=filterBe,
|
||||
thickness=0.25,
|
||||
)
|
||||
ehWindow = ehWindow._replace(
|
||||
surface="Beryllium window {0:0.0f} $\\mu$m".format(ehWindow.thickness * 1e3)
|
||||
)
|
||||
|
||||
# Sample
|
||||
sample = namedtuple("sample", ["name", "center"])
|
||||
|
||||
es1 = sample(name="ES1", center=[0, 23823, sourceHeight])
|
||||
es2 = sample(name="ES2", center=[0, 25843, sourceHeight])
|
||||
|
||||
# Ionization chambers
|
||||
ic = namedtuple("sample", ["name", "center"])
|
||||
|
||||
es1ic0 = ic(name="ES1 IC0", center=[0, 23633, sourceHeight])
|
||||
es1ic1 = ic(name="ES1 IC1", center=[0, 24383, sourceHeight])
|
||||
es1ic2 = ic(name="ES1 IC2", center=[0, 24723, sourceHeight])
|
||||
|
||||
Walls = namedtuple("walls", ["start", "end", "height"])
|
||||
walls = Walls(start=[13472], end=[13472 + 354], height=[[-20, 36]]) # WBBS
|
||||
@@ -1,82 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import builtins
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from bec_lib import bec_logger
|
||||
from debye_bec.devices.absorber import STATUS as ABS_STATUS
|
||||
|
||||
logger = bec_logger.logger
|
||||
# import builtins to avoid linter errors
|
||||
dev = builtins.__dict__.get("dev")
|
||||
|
||||
class MoveToLabelError(Exception):
|
||||
"""Exception for the MoveToLabel function"""
|
||||
|
||||
def move_to_label():
|
||||
"""
|
||||
Function to move several motors to a specific position defined in the label dict.
|
||||
"""
|
||||
|
||||
label = get_device_conditions(label="digitalTwin")
|
||||
|
||||
# Get absorber status and close if open
|
||||
logger.info("Check Frontend Absorber Status")
|
||||
abs_was_open = dev.abs.status.get() == ABS_STATUS.OPEN
|
||||
if abs_was_open:
|
||||
logger.info(" Close Frontend Absorber")
|
||||
status = dev.abs.close()
|
||||
status.wait()
|
||||
|
||||
# Move Frontend Slits
|
||||
logger.info("Move Frontend Slits into position")
|
||||
devices = ["sldi_centerx", "sldi_centery", "sldi_gapx", "sldi_gapy"]
|
||||
matches = {key: label[key] for key in devices if key in label}
|
||||
statuses = []
|
||||
for device in matches.values():
|
||||
statuses.append(device['device'].move(device['value']))
|
||||
for status in statuses:
|
||||
status.wait(timeout=30)
|
||||
|
||||
# Move Collimating mirror
|
||||
logger.info("Move Collimating Mirror into position")
|
||||
if "cm_rotx" in label: # pitch
|
||||
logger.info(" Move pitch into position")
|
||||
surveyed_movement(
|
||||
axis=label['cm_rotx'],
|
||||
surveyed_axes= [
|
||||
{'device': dev.cm_rotz, 'abs_tol': 0.1},
|
||||
]
|
||||
)
|
||||
|
||||
# Restore absorber position
|
||||
logger.info("Restore Frontend Absorber Status")
|
||||
if abs_was_open:
|
||||
status = dev.abs.open()
|
||||
status.wait()
|
||||
|
||||
|
||||
def surveyed_movement(axis, surveyed_axes):
|
||||
"""
|
||||
Moves an axis while surverying a set of axes.
|
||||
|
||||
Args:
|
||||
axis (DeviceCondition): Device condition
|
||||
surveyed_axes (list): List of dicts (same format as DeviceCondition)
|
||||
|
||||
Raises:
|
||||
If during movement of axis, one of the surveyed axes moves out of tolerance.
|
||||
"""
|
||||
|
||||
for surv_ax in surveyed_axes:
|
||||
surv_ax['old_value'] = surv_ax['device'].read()
|
||||
status = axis['device'].move(axis['value'])
|
||||
while status.status == 'RUNNING':
|
||||
for surv_ax in surveyed_axes:
|
||||
if abs(surv_ax['device'].read() - surv_ax['old_value']) > surv_ax['abs_tol']:
|
||||
axis['device'].stop()
|
||||
raise MoveToLabelError(
|
||||
f"During movement of {axis['device'].name}, {surv_ax['device'].name} " +
|
||||
f"started to move unexpectedly (old pos: {surv_ax['old_value']}, " +
|
||||
f"current pos: {surv_ax['device'].read()})"
|
||||
)
|
||||
@@ -34,3 +34,18 @@ to setup the prompts.
|
||||
"""
|
||||
|
||||
# pylint: disable=invalid-name, unused-import, import-error, undefined-variable, unused-variable, unused-argument, no-name-in-module
|
||||
|
||||
from bec_lib import bec_logger
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
logger.info("Using the Debye startup script.")
|
||||
|
||||
from debye_bec.bec_ipython_client.plugins.auto_gain_core import AutoGainCore
|
||||
from debye_bec.bec_ipython_client.plugins.digital_twin_core.digital_twin_core import DigitalTwinCore
|
||||
|
||||
digital_twin = DigitalTwinCore()
|
||||
logger.success("Digital Twin Core loaded. Use 'digital_twin' to access it.")
|
||||
|
||||
auto_gain = AutoGainCore()
|
||||
logger.success("Auto-Gain module loaded. Use 'auto_gain' to access it.")
|
||||
Whitespace-only changes.
@@ -0,0 +1,209 @@
|
||||
"""
|
||||
Auto Gain: Custom BEC widget to automatically set gains.
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
from bec_lib import bec_logger
|
||||
from bec_widgets.utils.bec_dispatcher import BECDispatcher
|
||||
from bec_widgets.utils.bec_widget import BECWidget
|
||||
from bec_widgets.utils.colors import apply_theme, get_accent_colors
|
||||
from bec_widgets.utils.error_popups import SafeSlot
|
||||
|
||||
# pylint: disable=E0611
|
||||
from qtpy.QtCore import QObject, QThread, Signal
|
||||
from qtpy.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
|
||||
|
||||
from ....bec_ipython_client.plugins.auto_gain_core import AutoGainCore
|
||||
from ....bec_ipython_client.plugins.beamline import BeamlineId, get_beamline_id
|
||||
from ..edge_selector import EdgeSelector
|
||||
from .qt_widgets import CheckBox, Group, MatrixSelector, MyButton, TextIndicator
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
|
||||
class Worker(QObject):
|
||||
progress = Signal(str)
|
||||
completed = Signal(int)
|
||||
|
||||
@SafeSlot(dict)
|
||||
def start(self, config: dict):
|
||||
success = False
|
||||
try:
|
||||
core = AutoGainCore()
|
||||
self.progress.emit(f"AutoGain started with config {config}")
|
||||
results = core.start(
|
||||
config["element"],
|
||||
config["edge"],
|
||||
amplifier=config["all_amplifiers"],
|
||||
link_ic0_ic1=config["link_ic0_ic1"],
|
||||
comp_ring_current=config["compensate_ring_current"],
|
||||
prohibited_gains=config["prohibited_gains"],
|
||||
)
|
||||
lines = [
|
||||
f"{amp} set to gain {res['gain']:.0e}, max signal {res['max_signal']:.3f} V"
|
||||
for amp, res in results.items()
|
||||
]
|
||||
self.progress.emit("\n".join(lines))
|
||||
success = True
|
||||
except Exception as exc:
|
||||
logger.exception("Auto gain failed")
|
||||
self.progress.emit(f"Error: {exc}")
|
||||
finally:
|
||||
self.completed.emit(success)
|
||||
|
||||
|
||||
class AutoGain(BECWidget, QWidget):
|
||||
"""
|
||||
Main widget of auto gain widget.
|
||||
"""
|
||||
|
||||
PLUGIN = True
|
||||
ICON_NAME = "tune"
|
||||
|
||||
start_worker = Signal(dict)
|
||||
|
||||
def __init__(self, show_control: bool = True, *arg, parent=None, **kwargs):
|
||||
super().__init__(parent=parent, *arg, **kwargs)
|
||||
self.get_bec_shortcuts()
|
||||
|
||||
self.beamline = get_beamline_id()
|
||||
|
||||
central = QWidget()
|
||||
self.root_layout = QVBoxLayout(central)
|
||||
|
||||
self.edge_selector_button = MyButton("Choose", "default")
|
||||
self.edge_label = QLabel("No edge selected")
|
||||
self.edge_group = Group(
|
||||
"Edge selection", [self.edge_selector_button, self.edge_label], orientation="horizontal"
|
||||
)
|
||||
self.edge_element = None
|
||||
self.edge_edge = None
|
||||
self.edge_energy = None
|
||||
|
||||
self.root_layout.addWidget(self.edge_group)
|
||||
|
||||
self.ic0_check = CheckBox("ic0", "IC0")
|
||||
self.ic1_check = CheckBox("ic1", "IC1")
|
||||
self.ic2_check = CheckBox("ic2", "IC2")
|
||||
self.pips_check = CheckBox("pips", "PIPS")
|
||||
if self.beamline == BeamlineId.X01DA:
|
||||
self.apply_group = Group(
|
||||
"Apply auto gain on",
|
||||
[self.ic0_check, self.ic1_check, self.ic2_check, self.pips_check],
|
||||
)
|
||||
else: # PIPS of X10DA has fixed gain amplifier
|
||||
self.apply_group = Group(
|
||||
"Apply auto gain on", [self.ic0_check, self.ic1_check, self.ic2_check]
|
||||
)
|
||||
self.root_layout.addWidget(self.apply_group)
|
||||
|
||||
self.link_ic0_ic1 = CheckBox("link_ic0_ic1", "Link IC0/IC1 gains")
|
||||
|
||||
self.comp_ring_current = CheckBox("comp_ring_current", "Calculate for 400 mA ring current")
|
||||
|
||||
self.prohibited_gains = MatrixSelector("Prohibited gains", beamline=self.beamline)
|
||||
|
||||
self.expert_group = Group(
|
||||
"Expert settings", [self.link_ic0_ic1, self.comp_ring_current, self.prohibited_gains]
|
||||
)
|
||||
|
||||
self.root_layout.addWidget(self.expert_group)
|
||||
|
||||
self.start_button = MyButton("Start", "success")
|
||||
self.status = TextIndicator(label="Status")
|
||||
self.status.setText("Standby")
|
||||
self.status.setColor(get_accent_colors().default.name())
|
||||
|
||||
self.control_group = Group("Control", [self.start_button, self.status])
|
||||
|
||||
if show_control:
|
||||
self.root_layout.addWidget(self.control_group)
|
||||
|
||||
self.root_layout.addStretch()
|
||||
|
||||
self.setLayout(self.root_layout)
|
||||
self.setWindowTitle("Auto Gain")
|
||||
|
||||
self.edge_selector_button.clicked.connect(self._update_edge)
|
||||
self.start_button.clicked.connect(self._start)
|
||||
|
||||
self.worker = Worker()
|
||||
self.start_worker.connect(self.worker.start)
|
||||
self.worker_thread = QThread()
|
||||
self.worker.moveToThread(self.worker_thread)
|
||||
|
||||
self.worker.progress.connect(self._update_status)
|
||||
self.worker.completed.connect(self._complete)
|
||||
self.worker.completed.connect(self.worker_thread.quit)
|
||||
|
||||
def _update_edge(self, *_):
|
||||
dlg = EdgeSelector(self)
|
||||
if dlg.exec_():
|
||||
self.edge_element = dlg.selected_element
|
||||
self.edge_edge = dlg.selected_edge
|
||||
self.edge_energy = dlg.selected_energy
|
||||
self.edge_label.setText(
|
||||
f"{dlg.selected_element}, {dlg.selected_edge}-edge, {dlg.selected_energy:0.1f} eV"
|
||||
)
|
||||
|
||||
def _start(self):
|
||||
if not self.worker_thread.isRunning():
|
||||
self.start_button.setEnabled(False)
|
||||
self.status.setColor(get_accent_colors().warning.name())
|
||||
self.worker_thread.start()
|
||||
self.start_worker.emit(self.get_config())
|
||||
|
||||
def _update_status(self, text):
|
||||
self.status.setText(text)
|
||||
|
||||
def _complete(self, *_):
|
||||
self.start_button.setEnabled(True)
|
||||
self.status.setColor(get_accent_colors().success.name())
|
||||
|
||||
def load_config(self, config: dict):
|
||||
self.edge_element = config["element"]
|
||||
self.edge_edge = config["edge"]
|
||||
self.edge_energy = config["energy"]
|
||||
self.ic0_check.setChecked(config["ic0"])
|
||||
self.ic1_check.setChecked(config["ic1"])
|
||||
self.ic2_check.setChecked(config["ic2"])
|
||||
self.pips_check.setChecked(config["pips"])
|
||||
self.link_ic0_ic1.setChecked(config["link_ic0_ic1"])
|
||||
self.comp_ring_current.setChecked(config["compensate_ring_current"])
|
||||
self.prohibited_gains.set_selection(config["prohibited_gains"])
|
||||
|
||||
def get_config(self) -> dict:
|
||||
if self.edge_element is None or self.edge_edge is None:
|
||||
raise ValueError("Choose an absorption edge first.")
|
||||
amplifier_checks = [
|
||||
(self.ic0_check, "ic0"),
|
||||
(self.ic1_check, "ic1"),
|
||||
(self.ic2_check, "ic2"),
|
||||
(self.pips_check, "pips"),
|
||||
]
|
||||
amplifiers = [name for check, name in amplifier_checks if check.isChecked()]
|
||||
if not amplifiers:
|
||||
raise ValueError("Select at least one amplifier for auto gain.")
|
||||
return {
|
||||
"element": self.edge_element,
|
||||
"edge": self.edge_edge,
|
||||
"energy": self.edge_energy,
|
||||
"ic0": self.ic0_check.isChecked(),
|
||||
"ic1": self.ic1_check.isChecked(),
|
||||
"ic2": self.ic2_check.isChecked(),
|
||||
"pips": self.pips_check.isChecked(),
|
||||
"all_amplifiers": amplifiers,
|
||||
"link_ic0_ic1": self.link_ic0_ic1.isChecked(),
|
||||
"compensate_ring_current": self.comp_ring_current.isChecked(),
|
||||
"prohibited_gains": self.prohibited_gains.selection(),
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app = QApplication(sys.argv)
|
||||
apply_theme("light")
|
||||
dispatcher = BECDispatcher(gui_id="auto_gain")
|
||||
win = AutoGain()
|
||||
win.show()
|
||||
sys.exit(app.exec_())
|
||||
@@ -0,0 +1 @@
|
||||
{'files': ['auto_gain.py']}
|
||||
@@ -0,0 +1,57 @@
|
||||
# Copyright (C) 2022 The Qt Company Ltd.
|
||||
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
|
||||
|
||||
from bec_widgets.utils.bec_designer import designer_material_icon
|
||||
from qtpy.QtDesigner import QDesignerCustomWidgetInterface
|
||||
from qtpy.QtWidgets import QWidget
|
||||
|
||||
from .auto_gain import AutoGain
|
||||
|
||||
DOM_XML = """
|
||||
<ui language='c++'>
|
||||
<widget class='AutoGain' name='auto_gain'>
|
||||
</widget>
|
||||
</ui>
|
||||
"""
|
||||
|
||||
|
||||
class AutoGainPlugin(QDesignerCustomWidgetInterface): # pragma: no cover
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._form_editor = None
|
||||
|
||||
def createWidget(self, parent):
|
||||
if parent is None:
|
||||
return QWidget()
|
||||
t = AutoGain(parent)
|
||||
return t
|
||||
|
||||
def domXml(self):
|
||||
return DOM_XML
|
||||
|
||||
def group(self):
|
||||
return ""
|
||||
|
||||
def icon(self):
|
||||
return designer_material_icon(AutoGain.ICON_NAME)
|
||||
|
||||
def includeFile(self):
|
||||
return "auto_gain"
|
||||
|
||||
def initialize(self, form_editor):
|
||||
self._form_editor = form_editor
|
||||
|
||||
def isContainer(self):
|
||||
return False
|
||||
|
||||
def isInitialized(self):
|
||||
return self._form_editor is not None
|
||||
|
||||
def name(self):
|
||||
return "AutoGain"
|
||||
|
||||
def toolTip(self):
|
||||
return "AutoGain"
|
||||
|
||||
def whatsThis(self):
|
||||
return self.toolTip()
|
||||
@@ -0,0 +1,195 @@
|
||||
from bec_widgets.utils.colors import get_accent_colors
|
||||
from qtpy.QtCore import Qt
|
||||
|
||||
# pylint: disable=E0611
|
||||
from qtpy.QtWidgets import (
|
||||
QCheckBox,
|
||||
QGridLayout,
|
||||
QGroupBox,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLayout,
|
||||
QPushButton,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from ....bec_ipython_client.plugins.beamline import BeamlineId
|
||||
|
||||
LABEL_WIDTH = 118
|
||||
ROW_MARGINS = (4, 0, 4, 0)
|
||||
ROW_SPACING = 6
|
||||
|
||||
|
||||
class Group(QGroupBox):
|
||||
def __init__(self, label, objs, orientation="vertical"):
|
||||
super().__init__(label)
|
||||
if orientation == "vertical":
|
||||
self._layout = QVBoxLayout(self)
|
||||
elif orientation == "horizontal":
|
||||
self._layout = QHBoxLayout(self)
|
||||
else:
|
||||
raise ValueError(f"Orientation {orientation} is not supported!")
|
||||
for obj in objs:
|
||||
if isinstance(obj, QWidget):
|
||||
self._layout.addWidget(obj)
|
||||
elif isinstance(obj, QLayout):
|
||||
self._layout.addLayout(obj)
|
||||
|
||||
|
||||
class CheckBox(QWidget):
|
||||
def __init__(self, identifier="", label=""):
|
||||
super().__init__()
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(*ROW_MARGINS)
|
||||
layout.setSpacing(ROW_SPACING)
|
||||
self.identifier = identifier
|
||||
self.label = QLabel(label)
|
||||
self.label.setFixedWidth(LABEL_WIDTH)
|
||||
self.label.setWordWrap(True)
|
||||
layout.addWidget(self.label)
|
||||
self.checkbox = QCheckBox()
|
||||
layout.addWidget(self.checkbox)
|
||||
|
||||
def setChecked(self, set_checked: bool = True):
|
||||
self.checkbox.setChecked(set_checked)
|
||||
|
||||
def isChecked(self):
|
||||
return self.checkbox.isChecked()
|
||||
|
||||
|
||||
class MatrixSelector(QWidget):
|
||||
"""Checkbox matrix for selecting amplifier/value combinations.
|
||||
|
||||
Displays a grid with one row per amplifier (IC0, IC1, IC2, PIPS) and one
|
||||
column per value (1e6, 1e7, 5e7, 1e8, 1e9). Each cell is a checkbox, so any
|
||||
combination of rows and columns can be selected independently.
|
||||
|
||||
Use `selection()` to read the current state as a dict mapping the
|
||||
lowercase row name to a list of the selected column values (as floats),
|
||||
e.g. ``{"ic0": [1e6], "ic1": [1e6, 5e7]}``. Rows with no checked boxes are
|
||||
omitted.
|
||||
|
||||
Attributes:
|
||||
ROWS (list[str]): Row titles, in display order.
|
||||
COLS (list[str]): Column titles, in display order. These are also
|
||||
parsed with ``float()`` to produce the values returned by
|
||||
`selection()`.
|
||||
checks (dict[tuple[str, str], QCheckBox]): Checkboxes keyed by
|
||||
``(row, col)`` using the original title strings.
|
||||
|
||||
Example:
|
||||
>>> selector = MatrixSelector()
|
||||
>>> my_layout.addWidget(selector)
|
||||
>>> selector.selection()
|
||||
{'ic0': [1000000.0], 'ic1': [1000000.0, 50000000.0]}
|
||||
"""
|
||||
|
||||
ROWS_X01DA = ["IC0", "IC1", "IC2", "PIPS"]
|
||||
COLS_X01DA = ["1e6", "1e7", "5e7", "1e8", "1e9"]
|
||||
|
||||
ROWS_X10DA = ["IC0", "IC1", "IC2"]
|
||||
COLS_X10DA = ["1e6", "1e7", "1e8", "1e9", "1e10"]
|
||||
|
||||
def __init__(self, label: str, beamline: BeamlineId, parent=None):
|
||||
super().__init__(parent)
|
||||
if beamline == BeamlineId.X01DA:
|
||||
self.cols = self.COLS_X01DA
|
||||
self.rows = self.ROWS_X01DA
|
||||
else:
|
||||
self.cols = self.COLS_X10DA
|
||||
self.rows = self.ROWS_X10DA
|
||||
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(*ROW_MARGINS)
|
||||
layout.setSpacing(ROW_SPACING)
|
||||
self.label = QLabel(label)
|
||||
self.label.setFixedWidth(LABEL_WIDTH)
|
||||
self.label.setWordWrap(True)
|
||||
layout.addWidget(self.label)
|
||||
|
||||
grid_layout = QGridLayout()
|
||||
|
||||
# Column headers
|
||||
for c, col in enumerate(self.cols, start=1):
|
||||
grid_layout.addWidget(QLabel(col), 0, c, alignment=Qt.AlignmentFlag.AlignCenter)
|
||||
|
||||
# Row headers + checkboxes
|
||||
self.checks = {}
|
||||
for r, row in enumerate(self.rows, start=1):
|
||||
grid_layout.addWidget(QLabel(row), r, 0)
|
||||
for c, col in enumerate(self.cols, start=1):
|
||||
cb = QCheckBox()
|
||||
grid_layout.addWidget(cb, r, c, alignment=Qt.AlignmentFlag.AlignCenter)
|
||||
self.checks[(row, col)] = cb
|
||||
|
||||
layout.addLayout(grid_layout)
|
||||
layout.addStretch()
|
||||
|
||||
def selection(self):
|
||||
"""Return e.g. {"ic0": [1e6], "ic1": [1e6, 5e7]}; rows with no selection are omitted."""
|
||||
result = {}
|
||||
for row in self.rows:
|
||||
values = [float(col) for col in self.cols if self.checks[(row, col)].isChecked()]
|
||||
if values:
|
||||
result[row.lower()] = values
|
||||
return result
|
||||
|
||||
def set_selection(self, selection):
|
||||
"""Set the checkboxes from a dict as returned by `selection()`.
|
||||
|
||||
Rows not present in `selection` are cleared. Values that don't match
|
||||
any column are ignored.
|
||||
"""
|
||||
# Normalize keys to lowercase and values to floats for comparison
|
||||
wanted = {key.lower(): {float(v) for v in values} for key, values in selection.items()}
|
||||
for row in self.rows:
|
||||
row_values = wanted.get(row.lower(), set())
|
||||
for col in self.cols:
|
||||
cb = self.checks[(row, col)]
|
||||
cb.setChecked(float(col) in row_values)
|
||||
|
||||
|
||||
class MyButton(QPushButton):
|
||||
def __init__(self, text="", color="default", parent=None):
|
||||
self.color = color
|
||||
super().__init__(text, parent)
|
||||
self.apply_theme()
|
||||
|
||||
def apply_theme(self):
|
||||
if self.isEnabled():
|
||||
colors = get_accent_colors()
|
||||
color = getattr(colors, self.color).name()
|
||||
self.setStyleSheet(f"QPushButton {{ background-color: {color}; color: white; }}")
|
||||
else:
|
||||
self.setStyleSheet(
|
||||
"QPushButton {{background-color: rgb(120, 120, 120); color: white;}}"
|
||||
)
|
||||
|
||||
def setEnabled(self, enable: bool = True):
|
||||
super().setEnabled(enable)
|
||||
self.apply_theme()
|
||||
|
||||
|
||||
class TextIndicator(QWidget):
|
||||
def __init__(self, label):
|
||||
super().__init__()
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(*ROW_MARGINS)
|
||||
layout.setSpacing(ROW_SPACING)
|
||||
self.label = QLabel(label)
|
||||
self.label.setFixedWidth(LABEL_WIDTH)
|
||||
self.label.setWordWrap(True)
|
||||
layout.addWidget(self.label)
|
||||
self.text = QLabel("-")
|
||||
self.text.setAlignment(Qt.AlignTop) # type: ignore
|
||||
layout.addWidget(self.text)
|
||||
|
||||
def setLabel(self, label) -> None:
|
||||
self.label.setText(label)
|
||||
|
||||
def setText(self, text):
|
||||
self.text.setText(text)
|
||||
|
||||
def setColor(self, color: str):
|
||||
self.text.setStyleSheet(f"QLabel {{color:{color}}}")
|
||||
@@ -0,0 +1,15 @@
|
||||
def main(): # pragma: no cover
|
||||
from qtpy import PYSIDE6
|
||||
|
||||
if not PYSIDE6:
|
||||
print("PYSIDE6 is not available in the environment. Cannot patch designer.")
|
||||
return
|
||||
from PySide6.QtDesigner import QPyDesignerCustomWidgetCollection
|
||||
|
||||
from .auto_gain_plugin import AutoGainPlugin
|
||||
|
||||
QPyDesignerCustomWidgetCollection.addCustomWidget(AutoGainPlugin())
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
main()
|
||||
@@ -13,13 +13,40 @@ logger = bec_logger.logger
|
||||
|
||||
|
||||
_Widgets = {
|
||||
"AutoGain": "AutoGain",
|
||||
"DataViewer": "DataViewer",
|
||||
"DigitalTwin": "DigitalTwin",
|
||||
"RestartServer": "RestartServer",
|
||||
"ScanControlXAS": "ScanControlXAS",
|
||||
"Scheduler": "Scheduler",
|
||||
"TemperatureController": "TemperatureController",
|
||||
}
|
||||
|
||||
|
||||
class AutoGain(RPCBase):
|
||||
"""Main widget of auto gain widget."""
|
||||
|
||||
_IMPORT_MODULE = "debye_bec.bec_widgets.widgets.auto_gain.auto_gain"
|
||||
|
||||
@rpc_call
|
||||
def remove(self):
|
||||
"""
|
||||
Cleanup the BECConnector
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def attach(self):
|
||||
"""
|
||||
None
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def detach(self):
|
||||
"""
|
||||
Detach the widget from its parent dock widget (if widget is in the dock), making it a floating widget.
|
||||
"""
|
||||
|
||||
|
||||
class DataViewer(RPCBase):
|
||||
"""Main widget of Data Viewer"""
|
||||
|
||||
@@ -69,7 +96,7 @@ class DigitalTwin(RPCBase):
|
||||
|
||||
|
||||
class RestartServer(RPCBase):
|
||||
"""Main widget of server restart widget"""
|
||||
"""Main widget of server restart widget."""
|
||||
|
||||
_IMPORT_MODULE = "debye_bec.bec_widgets.widgets.restart_server.restart_server"
|
||||
|
||||
@@ -115,3 +142,150 @@ class ScanControlXAS(RPCBase):
|
||||
"""
|
||||
Take a screenshot of the dock area and save it to a file.
|
||||
"""
|
||||
|
||||
|
||||
class Scheduler(RPCBase):
|
||||
"""Schedule, persist and execute a sequence of BEC actions."""
|
||||
|
||||
_IMPORT_MODULE = "debye_bec.bec_widgets.widgets.scheduler.scheduler"
|
||||
|
||||
@rpc_call
|
||||
def run_schedule(self, first_item: "int" = 0, retry_unfinished: "bool" = False) -> "None":
|
||||
"""
|
||||
Start (or continue) executing the schedule.
|
||||
|
||||
Already COMPLETED items are skipped. Does nothing if the schedule is already running.
|
||||
|
||||
Args:
|
||||
first_item: Index of the item to start with; items above it are ignored.
|
||||
retry_unfinished: If True, FAILED and ABORTED items are executed again.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def pause_schedule(self) -> "None":
|
||||
"""
|
||||
Pause after the currently running item(s) have finished.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def abort_schedule(self) -> "None":
|
||||
"""
|
||||
Pause now: cancel running scans/moves, interrupt delays and stop the schedule.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def reset_schedule(self) -> "None":
|
||||
"""
|
||||
Mark all items PENDING again and clear their execution state (not while running).
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def get_status(self) -> "dict":
|
||||
"""
|
||||
The complete schedule (definition and execution state) as a JSON-compatible dict.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def add_item(
|
||||
self,
|
||||
action: "str",
|
||||
params: "dict | None" = None,
|
||||
index: "int | None" = None,
|
||||
wait_for_completion: "bool" = True,
|
||||
pause_on_failure: "bool" = False,
|
||||
pause_on_state: "bool" = False,
|
||||
) -> "str":
|
||||
"""
|
||||
Insert a new PENDING item.
|
||||
|
||||
Args:
|
||||
action: Registered action name, e.g. "scan", "move", "delay", "wait_for_parent".
|
||||
params: JSON-serialisable parameters of the action, e.g.
|
||||
`{"device": "samx", "value": 1.0, "relative": False}` for "move" or
|
||||
`{"seconds": 60}` for "delay".
|
||||
index: Insert position (0 = first). Clamped so the item never lands before an item
|
||||
that has already started. Defaults to the end.
|
||||
wait_for_completion: If False, the following items start while this one runs.
|
||||
pause_on_failure: Pause the schedule if this item fails.
|
||||
pause_on_state: Only start while all beamline states are VALID/WARNING.
|
||||
|
||||
Returns:
|
||||
The id of the new item.
|
||||
|
||||
Raises:
|
||||
ValueError: Unknown action.
|
||||
TypeError: Parameters are not JSON-serialisable.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def edit_item(
|
||||
self,
|
||||
item_id: "str",
|
||||
action: "str",
|
||||
params: "dict | None" = None,
|
||||
wait_for_completion: "bool" = True,
|
||||
pause_on_failure: "bool" = False,
|
||||
pause_on_state: "bool" = False,
|
||||
) -> "None":
|
||||
"""
|
||||
Replace the definition of an item that has not started yet (see `add_item` for the
|
||||
arguments).
|
||||
|
||||
Raises:
|
||||
RuntimeError: The item has already started or finished.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def delete_item(self, item_id: "str") -> "None":
|
||||
"""
|
||||
Remove an item that has not started yet.
|
||||
|
||||
Raises:
|
||||
RuntimeError: The item has already started or finished.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def move_item(self, item_id: "str", new_index: "int") -> "None":
|
||||
"""
|
||||
Move an item that has not started yet to `new_index` (never before an item that has
|
||||
already started).
|
||||
|
||||
Raises:
|
||||
RuntimeError: The item has already started or finished.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def move_item_up(self, item_id: "str") -> "None":
|
||||
"""
|
||||
Swap an item with the one above it.
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def move_item_down(self, item_id: "str") -> "None":
|
||||
"""
|
||||
Swap an item with the one below it.
|
||||
"""
|
||||
|
||||
|
||||
class TemperatureController(RPCBase):
|
||||
"""Waveform with predefined curves and one status label."""
|
||||
|
||||
_IMPORT_MODULE = "debye_bec.bec_widgets.widgets.temperature_controller.temperature_controller"
|
||||
|
||||
@rpc_call
|
||||
def remove(self):
|
||||
"""
|
||||
Cleanup the BECConnector
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def attach(self):
|
||||
"""
|
||||
None
|
||||
"""
|
||||
|
||||
@rpc_call
|
||||
def detach(self):
|
||||
"""
|
||||
Detach the widget from its parent dock widget (if widget is in the dock), making it a floating widget.
|
||||
"""
|
||||
@@ -55,6 +55,7 @@ class DataViewer(BECWidget, QWidget):
|
||||
self.current_row = 0
|
||||
|
||||
self.input.scan_sel.currentItemChanged_connect(self.scan_sel_changed)
|
||||
self.input.scan_sel.itemDoubleClicked_connect(self.scan_sel_double_click)
|
||||
self.input.load_button.clicked_connect(self.load_scan_from_history)
|
||||
self.input.load_from_folder_button.clicked_connect(self.load_scan_from_folder)
|
||||
self.viewer.unload_button.clicked_connect(self.unload_all_scans)
|
||||
@@ -77,6 +78,12 @@ class DataViewer(BECWidget, QWidget):
|
||||
"""Updates the current row value of the scan selection list"""
|
||||
self.current_row = kwargs["value"]().row()
|
||||
|
||||
@SafeSlot()
|
||||
def scan_sel_double_click(self, *_, **kwargs):
|
||||
"""Updates the current row value of the scan selection list and loads the scan"""
|
||||
self.current_row = kwargs["value"]().row()
|
||||
self.load_scan_from_history()
|
||||
|
||||
@SafeSlot()
|
||||
def open_in_file_manager(self, *_):
|
||||
"""Open the scan folder in the systems default file manager"""
|
||||
|
||||
@@ -190,11 +190,11 @@ class DataView(QWidget):
|
||||
|
||||
if is_2d:
|
||||
n_rows, _ = data.shape
|
||||
row_data = data[0].astype(np.float32)
|
||||
row_data = data[0].astype(np.float64)
|
||||
else:
|
||||
row_data = data.reshape(-1).astype(np.float32)
|
||||
row_data = data.reshape(-1).astype(np.float64)
|
||||
|
||||
x = np.arange(row_data.size, dtype=np.float32)
|
||||
x = np.arange(row_data.size, dtype=np.float64)
|
||||
|
||||
self.plot_widget = pg.PlotWidget()
|
||||
plot_item = self.plot_widget.getPlotItem()
|
||||
@@ -233,8 +233,8 @@ class DataView(QWidget):
|
||||
|
||||
def on_row_changed(row):
|
||||
current_row_label.setText(str(row))
|
||||
new_data = data[row].astype(np.float32)
|
||||
new_x = np.arange(new_data.size, dtype=np.float32)
|
||||
new_data = data[row].astype(np.float64)
|
||||
new_x = np.arange(new_data.size, dtype=np.float64)
|
||||
curve.setData(new_x, new_data)
|
||||
plot_item.enableAutoRange() # type: ignore[attr-defined]
|
||||
|
||||
@@ -382,7 +382,7 @@ class DataView(QWidget):
|
||||
for c in range(show_cols):
|
||||
val = flat[r, c]
|
||||
txt = (
|
||||
f"{val:.6g}"
|
||||
f"{val:.12g}"
|
||||
if is_float
|
||||
else f"{val:.4g}" if is_complex else str(val.decode()) if is_bytes else str(val)
|
||||
)
|
||||
|
||||
@@ -105,6 +105,17 @@ class ListWidget(QWidget):
|
||||
)
|
||||
)
|
||||
|
||||
def itemDoubleClicked_connect(self, func):
|
||||
"""Connect a function to Double Click event."""
|
||||
self.value.itemDoubleClicked.connect(
|
||||
partial(
|
||||
func,
|
||||
identifier=self.identifier,
|
||||
value_obj=self.value,
|
||||
value=lambda: self.value.currentIndex(),
|
||||
)
|
||||
)
|
||||
|
||||
def setDisabled(self, disable):
|
||||
self.value.setDisabled(disable)
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
# pylint: skip-file
|
||||
|
||||
designer_plugins = {
|
||||
"AutoGain": ("debye_bec.bec_widgets.widgets.auto_gain.auto_gain", "AutoGain"),
|
||||
"DataViewer": ("debye_bec.bec_widgets.widgets.data_viewer.data_viewer", "DataViewer"),
|
||||
"DigitalTwin": ("debye_bec.bec_widgets.widgets.digital_twin.digital_twin", "DigitalTwin"),
|
||||
"RestartServer": (
|
||||
@@ -15,11 +16,19 @@ designer_plugins = {
|
||||
"debye_bec.bec_widgets.widgets.scan_control_xas.scan_control_xas",
|
||||
"ScanControlXAS",
|
||||
),
|
||||
"Scheduler": ("debye_bec.bec_widgets.widgets.scheduler.scheduler", "Scheduler"),
|
||||
"TemperatureController": (
|
||||
"debye_bec.bec_widgets.widgets.temperature_controller.temperature_controller",
|
||||
"TemperatureController",
|
||||
),
|
||||
}
|
||||
|
||||
widget_icons = {
|
||||
"AutoGain": "tune",
|
||||
"DataViewer": "find_in_page",
|
||||
"DigitalTwin": "lightbulb",
|
||||
"RestartServer": "restart_alt",
|
||||
"ScanControlXAS": "tune",
|
||||
"Scheduler": "assignment_add",
|
||||
"TemperatureController": "mode_heat",
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
from .beamline import get_parameters
|
||||
|
||||
parameters = get_parameters()
|
||||
@@ -0,0 +1,339 @@
|
||||
"""
|
||||
Find the azimuthal (phi) setting of a monochromator crystal by matching
|
||||
glitches detected in a real measured spectrum against a line list exported
|
||||
by XOP's MARE "spaghetti" tool.
|
||||
|
||||
Pipeline
|
||||
--------
|
||||
1. parse_xop_macro(path) -- read an XOP MARE-glitches .pro macro and
|
||||
extract, for every reflection, (hkl,
|
||||
alpha0, k, p2/4, fh). These four numbers
|
||||
fully determine that reflection's glitch
|
||||
energy as a function of azimuth phi via
|
||||
XOP's own formula:
|
||||
|
||||
lambda(phi) = 1 / sqrt((k/cos(phi-alpha0))^2 + p2/4)
|
||||
E(phi) = hc / lambda(phi)
|
||||
|
||||
2. detect_glitches(E, I) -- find dip positions in a real measured
|
||||
(energy, intensity) scan: smooth to get a
|
||||
baseline, subtract, find negative peaks
|
||||
in the residual.
|
||||
|
||||
3. find_azimuth(...) -- for a grid of candidate phi, compute every
|
||||
reflection's predicted glitch energy,
|
||||
score how well the detected dip energies
|
||||
line up with predicted (fh-weighted)
|
||||
lines, and return the best-fit phi.
|
||||
|
||||
Self-test at the bottom regenerates synthetic "measured" glitches at a
|
||||
known phi from the XOP line list itself and checks that find_azimuth
|
||||
recovers that phi -- a good sanity check before trusting it on real data.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
import numpy as np
|
||||
from scipy.optimize import minimize_scalar
|
||||
from scipy.signal import find_peaks, savgol_filter
|
||||
|
||||
HC = 12398.42 # eV * Angstrom
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 1. Parse an XOP MARE-glitches macro
|
||||
# ----------------------------------------------------------------------
|
||||
def parse_xop_macro(path):
|
||||
"""
|
||||
Returns a list of dicts: {hkl: (h,k,l), alpha0: deg, k: float,
|
||||
p2_4: float, fh: float}, one per reflection line in the macro.
|
||||
|
||||
XOP prints one comment line per reflection with columns:
|
||||
h k l alpha0 k p2/4 th2 th2 th2 th3 th3 th3
|
||||
lambda lambda lambda BrgAngU BrgAngG fh
|
||||
(18 numeric columns). We parse those lines directly rather than the
|
||||
'y3 = 1D/sqrt(...)' code lines -- same numbers, simpler regex.
|
||||
|
||||
A handful of lines in real XOP output have a formatting bug where two
|
||||
columns run together with no separating space (e.g. an l=-1 column
|
||||
immediately followed by a tiny alpha0 like 8.5e-7, printed as
|
||||
'-18.53774E-007'). Those are detected (h,k,l must be integers) and
|
||||
skipped rather than silently mis-parsed.
|
||||
"""
|
||||
reflections = []
|
||||
skipped = 0
|
||||
with open(path) as f:
|
||||
for line in f:
|
||||
line = line.rstrip("\n")
|
||||
if not line.startswith(";"):
|
||||
continue
|
||||
tokens = line[1:].split()
|
||||
if len(tokens) != 18:
|
||||
if len(tokens) >= 4 and re.match(r"^-?\d+$", tokens[0]):
|
||||
skipped += (
|
||||
1 # looks like a corrupted data line (columns ran together)
|
||||
)
|
||||
continue # otherwise a header/comment/label line -- not data
|
||||
try:
|
||||
vals = [float(t) for t in tokens]
|
||||
except ValueError:
|
||||
continue # header row (e.g. "h k l alpha0 ...") -- not data
|
||||
h, k, l = vals[0], vals[1], vals[2]
|
||||
if not all(abs(x - round(x)) < 1e-6 for x in (h, k, l)):
|
||||
skipped += 1 # corrupted line (merged columns)
|
||||
continue
|
||||
alpha0, k_param, p2_4 = vals[3], vals[4], vals[5]
|
||||
fh = vals[-1]
|
||||
reflections.append(
|
||||
dict(
|
||||
hkl=(int(h), int(k), int(l)),
|
||||
alpha0=alpha0,
|
||||
k=k_param,
|
||||
p2_4=p2_4,
|
||||
fh=fh,
|
||||
)
|
||||
)
|
||||
print(
|
||||
f"parse_xop_macro: parsed {len(reflections)} reflections, "
|
||||
f"skipped {skipped} malformed line(s)"
|
||||
)
|
||||
return reflections
|
||||
|
||||
|
||||
def filter_reflections(reflections, max_h=None, max_k=None, max_l=None, min_fh=None):
|
||||
"""
|
||||
Return only the reflections with |h|<=max_h, |k|<=max_k, |l|<=max_l
|
||||
and fh>=min_fh. Any limit left as None means "no limit" on that axis.
|
||||
Useful for cutting a large XOP line list (hundreds of reflections)
|
||||
down to the strong, low-index ones that actually matter.
|
||||
"""
|
||||
out = []
|
||||
for r in reflections:
|
||||
h, k, l = r["hkl"]
|
||||
if max_h is not None and abs(h) > max_h:
|
||||
continue
|
||||
if max_k is not None and abs(k) > max_k:
|
||||
continue
|
||||
if max_l is not None and abs(l) > max_l:
|
||||
continue
|
||||
if min_fh is not None and r["fh"] < min_fh:
|
||||
continue
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 2. Predict glitch energies at a given azimuth from the parsed line list
|
||||
# ----------------------------------------------------------------------
|
||||
def predicted_energies(reflections, phi_deg, energy_range=None):
|
||||
"""
|
||||
Returns (E_pred, fh, hkl_list) for every reflection whose glitch falls
|
||||
at a finite, real energy at this azimuth (optionally restricted to
|
||||
energy_range = (Emin, Emax)).
|
||||
"""
|
||||
alpha0 = np.array([r["alpha0"] for r in reflections])
|
||||
kpar = np.array([r["k"] for r in reflections])
|
||||
p24 = np.array([r["p2_4"] for r in reflections])
|
||||
fh = np.array([r["fh"] for r in reflections])
|
||||
hkl = [r["hkl"] for r in reflections]
|
||||
|
||||
cosval = np.cos(np.radians(phi_deg - alpha0))
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
term = kpar / cosval
|
||||
E = HC * np.sqrt(term**2 + p24)
|
||||
|
||||
valid = np.isfinite(E)
|
||||
if energy_range is not None:
|
||||
lo, hi = energy_range
|
||||
valid &= (E >= lo) & (E <= hi)
|
||||
|
||||
idx = np.where(valid)[0]
|
||||
return E[idx], fh[idx], [hkl[i] for i in idx]
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 3. Detect glitches (dips) in a real measured spectrum -- split into
|
||||
# reusable steps so a GUI can recompute/redraw each one live.
|
||||
# ----------------------------------------------------------------------
|
||||
def sanitize_window(smooth_window, smooth_order, n_points):
|
||||
"""Coerce a smoothing window into something savgol_filter will accept:
|
||||
odd, >= smooth_order + 2, and not larger than the data."""
|
||||
w = min(smooth_window, n_points - (1 - n_points % 2))
|
||||
if w % 2 == 0:
|
||||
w -= 1
|
||||
w = max(w, smooth_order + 2 if (smooth_order + 2) % 2 == 1 else smooth_order + 3)
|
||||
return w
|
||||
|
||||
|
||||
def compute_baseline(energy, intensity, smooth_window=51, smooth_order=3):
|
||||
"""
|
||||
Sorts by energy and returns (energy_sorted, intensity_sorted, baseline,
|
||||
residual). This is step 1 (smoothing) on its own, so a GUI can redraw
|
||||
the baseline/residual live as the window/order controls move.
|
||||
"""
|
||||
energy = np.asarray(energy, dtype=float)
|
||||
intensity = np.asarray(intensity, dtype=float)
|
||||
order = np.argsort(energy)
|
||||
energy, intensity = energy[order], intensity[order]
|
||||
w = sanitize_window(smooth_window, smooth_order, len(intensity))
|
||||
baseline = savgol_filter(intensity, w, smooth_order)
|
||||
residual = intensity - baseline
|
||||
return energy, intensity, baseline, residual
|
||||
|
||||
|
||||
def find_dips(energy, residual, prominence=None, prominence_sigma=3.0):
|
||||
"""
|
||||
Step 2 (peak finding) on its own, so a GUI can redraw just the
|
||||
detected-dip markers as the prominence control moves, without
|
||||
recomputing the baseline. Returns (glitch_energies, prominences,
|
||||
prominence_used).
|
||||
"""
|
||||
if prominence is None:
|
||||
prominence = prominence_sigma * np.std(residual)
|
||||
peaks, props = find_peaks(-residual, prominence=prominence)
|
||||
return energy[peaks], props["prominences"], prominence
|
||||
|
||||
|
||||
def detect_glitches(
|
||||
energy,
|
||||
intensity,
|
||||
smooth_window=51,
|
||||
smooth_order=3,
|
||||
prominence=None,
|
||||
prominence_sigma=3.0,
|
||||
):
|
||||
"""
|
||||
Convenience wrapper chaining compute_baseline + find_dips for
|
||||
non-interactive use (see find_crystal_azimuth). Returns
|
||||
(glitch_energies, prominences) as before.
|
||||
"""
|
||||
energy, intensity, baseline, residual = compute_baseline(
|
||||
energy, intensity, smooth_window, smooth_order
|
||||
)
|
||||
glitch_E, prom, _ = find_dips(energy, residual, prominence, prominence_sigma)
|
||||
return glitch_E, prom
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 4. Score a candidate azimuth against the detected glitches
|
||||
# ----------------------------------------------------------------------
|
||||
def azimuth_score(phi_deg, reflections, detected_energies, energy_range, sigma_eV=3.0):
|
||||
"""
|
||||
For each detected glitch energy, find the best-matching predicted
|
||||
line (weighted by its fh, discounted by a Gaussian in energy
|
||||
distance) and sum those best-match scores. High score = many detected
|
||||
dips coincide with real, strong predicted lines at this phi.
|
||||
"""
|
||||
E_pred, fh, _ = predicted_energies(reflections, phi_deg, energy_range)
|
||||
if len(E_pred) == 0 or len(detected_energies) == 0:
|
||||
return 0.0
|
||||
diffs = detected_energies[:, None] - E_pred[None, :]
|
||||
gauss = np.exp(-0.5 * (diffs / sigma_eV) ** 2)
|
||||
weighted = gauss * fh[None, :]
|
||||
return weighted.max(axis=1).sum()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 5. Main search: scan phi, then refine locally
|
||||
# ----------------------------------------------------------------------
|
||||
def find_azimuth(
|
||||
reflections, detected_energies, energy_range, phi_grid=None, sigma_eV=3.0
|
||||
):
|
||||
"""
|
||||
Returns (phi_best, score_best, phi_grid, scores) so the coarse scan
|
||||
can be plotted as a diagnostic (a clean single maximum is a good
|
||||
sign; multiple comparable peaks means the data is ambiguous, e.g. too
|
||||
few glitches in range, or a real point-group ambiguity).
|
||||
"""
|
||||
detected_energies = np.asarray(detected_energies, dtype=float)
|
||||
if phi_grid is None:
|
||||
phi_grid = np.arange(0.0, 180.0, 0.5)
|
||||
|
||||
scores = np.array(
|
||||
[
|
||||
azimuth_score(p, reflections, detected_energies, energy_range, sigma_eV)
|
||||
for p in phi_grid
|
||||
]
|
||||
)
|
||||
i_best = int(np.argmax(scores))
|
||||
phi_coarse = phi_grid[i_best]
|
||||
|
||||
res = minimize_scalar(
|
||||
lambda p: -azimuth_score(
|
||||
p, reflections, detected_energies, energy_range, sigma_eV
|
||||
),
|
||||
bounds=(phi_coarse - 0.1, phi_coarse + 0.1),
|
||||
method="bounded",
|
||||
)
|
||||
return res.x, -res.fun, phi_grid, scores
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# 6. End-to-end convenience wrapper
|
||||
# ----------------------------------------------------------------------
|
||||
def find_crystal_azimuth(
|
||||
macro_path,
|
||||
energy,
|
||||
intensity,
|
||||
energy_range,
|
||||
smooth_window=51,
|
||||
smooth_order=3,
|
||||
prominence=None,
|
||||
sigma_eV=3.0,
|
||||
phi_grid=None,
|
||||
):
|
||||
"""
|
||||
One-call pipeline: parse the XOP macro, detect glitches in the
|
||||
measurement, and return the best-fit azimuth.
|
||||
"""
|
||||
reflections = parse_xop_macro(macro_path)
|
||||
glitch_E, glitch_prom = detect_glitches(
|
||||
energy, intensity, smooth_window, smooth_order, prominence
|
||||
)
|
||||
print(
|
||||
f"find_crystal_azimuth: detected {len(glitch_E)} candidate glitches "
|
||||
f"in [{energy_range[0]}, {energy_range[1]}] eV"
|
||||
)
|
||||
phi_best, score_best, phi_grid, scores = find_azimuth(
|
||||
reflections, glitch_E, energy_range, phi_grid, sigma_eV
|
||||
)
|
||||
return dict(
|
||||
phi_deg=phi_best,
|
||||
score=score_best,
|
||||
glitch_energies=glitch_E,
|
||||
glitch_prominences=glitch_prom,
|
||||
phi_grid=phi_grid,
|
||||
scores=scores,
|
||||
reflections=reflections,
|
||||
)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Self-test: regenerate synthetic glitches at a KNOWN phi from the macro
|
||||
# itself, then check find_azimuth recovers it. No real measurement needed.
|
||||
# ----------------------------------------------------------------------
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
|
||||
macro_path = sys.argv[1] if len(sys.argv) > 1 else "sample_xop.pro"
|
||||
true_phi = float(sys.argv[2]) if len(sys.argv) > 2 else -20.0
|
||||
energy_range = (4000.0, 12000.0)
|
||||
|
||||
reflections = parse_xop_macro(macro_path)
|
||||
E_true, fh_true, hkl_true = predicted_energies(reflections, true_phi, energy_range)
|
||||
|
||||
# keep only reasonably strong lines, as a real measurement would only
|
||||
# show glitches with non-negligible structure factor
|
||||
keep = fh_true > np.percentile(fh_true, 50) if len(fh_true) else []
|
||||
synthetic_glitches = E_true[keep]
|
||||
print(
|
||||
f"Self-test: {len(synthetic_glitches)} synthetic glitches at true phi={true_phi}"
|
||||
)
|
||||
|
||||
phi_best, score_best, phi_grid, scores = find_azimuth(
|
||||
reflections, synthetic_glitches, energy_range
|
||||
)
|
||||
print(
|
||||
f"Self-test: recovered phi = {phi_best:.2f} deg "
|
||||
f"(true = {true_phi} deg), score = {score_best:.2f}"
|
||||
)
|
||||
@@ -1,297 +0,0 @@
|
||||
"""
|
||||
Calculates the positions of axes based on a beamline config
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
from bec_lib import bec_logger
|
||||
|
||||
from .. import parameters as bl
|
||||
from ..types import BeamlineId, ConfigDict
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
|
||||
def calc_positions(beamline: BeamlineId, cfg: ConfigDict) -> dict[str, dict[str, float]]:
|
||||
"""
|
||||
Calculates the positions of axes based on a beamline config.
|
||||
|
||||
Args:
|
||||
cfg(ConfigDict): Dictionary with beamline config
|
||||
|
||||
Returns:
|
||||
dict[str, dict[str, float]]: Dictionary mapping device names to dictionaries
|
||||
containing a "value" key with the corresponding float value (position).
|
||||
"""
|
||||
|
||||
pos = {}
|
||||
|
||||
## FE slits
|
||||
trxr = -np.arctan(cfg["h_acc"]) * bl.feSlits.center1[1]
|
||||
trxw = (
|
||||
(np.arctan(cfg["h_acc"]) * bl.feSlits.center1[1])
|
||||
/ bl.feSlits.center1[1]
|
||||
* bl.feSlits.center2[1]
|
||||
)
|
||||
tryb = -np.arctan(cfg["v_acc"]) * bl.feSlits.center1[1]
|
||||
tryt = (
|
||||
(np.arctan(cfg["v_acc"]) * bl.feSlits.center1[1])
|
||||
/ bl.feSlits.center1[1]
|
||||
* bl.feSlits.center2[1]
|
||||
)
|
||||
|
||||
xgap = trxw - trxr
|
||||
ygap = tryt - tryb
|
||||
|
||||
pos["sldi_gapx"] = {"value": xgap}
|
||||
pos["sldi_gapy"] = {"value": ygap}
|
||||
|
||||
## Collimating Mirror
|
||||
obj_dist = bl.cm.center[1] # object distance
|
||||
beam_vs = 2 * obj_dist * np.tan(cfg["v_acc"]) # vertical size of beam after CM
|
||||
|
||||
# TRX
|
||||
if cfg["cm_stripe"] in bl.cm.surface:
|
||||
index = bl.cm.surface.index(cfg["cm_stripe"])
|
||||
else:
|
||||
raise ValueError(f"Requested stripe {cfg['cm_stripe']} not found in parameters!")
|
||||
cm_trx = -(bl.cm.limOptX[0][index] + bl.cm.limOptX[1][index]) / 2
|
||||
pos["cm_trx"] = {"value": cm_trx}
|
||||
|
||||
# TRY
|
||||
height = obj_dist * np.tan(cfg["v_acc"]) ** 2 * 1 / np.tan(cfg["cm_pitch"])
|
||||
pos["cm_try"] = {"value": height}
|
||||
|
||||
# Pitch
|
||||
pos["cm_rotx"] = {
|
||||
"value": -cfg["cm_pitch"] * 1e3
|
||||
} # invert and convert to mrad (same as EGU of rotx axis)
|
||||
|
||||
# Bending Radius
|
||||
radius = (
|
||||
2.0 * obj_dist / np.sin(cfg["cm_pitch"])
|
||||
) # Elements of modern X-ray Physics, page 108 ff.
|
||||
pos["cm_bnd_radius"] = {"value": radius * 1e-6} # Convert to km
|
||||
|
||||
## Monochromator
|
||||
if cfg["mo1_mode"] == "Monochromatic":
|
||||
# Add 2x CM pitch to the bragg angle
|
||||
bragg = cfg["mo1_bragg"]
|
||||
elif cfg["mo1_mode"] == "Pinkbeam":
|
||||
# Align xtal surfaces parallel to beam
|
||||
bragg = 0
|
||||
else:
|
||||
raise ValueError("Monochromator mode not supported")
|
||||
pos["mo1_bragg_angle"] = {"value": bragg / np.pi * 180} # Bragg angle in deg
|
||||
|
||||
# TRY, Height
|
||||
l = bl.mo1.xtalGap[0] / np.sin(cfg["mo1_bragg"])
|
||||
yhor = l * np.cos(2.0 * (cfg["mo1_bragg"] + cfg["cm_pitch"]))
|
||||
yver = yhor * np.tan(2.0 * cfg["cm_pitch"])
|
||||
|
||||
if cfg["mo1_mode"] == "Monochromatic":
|
||||
beam_offset_mo1 = (
|
||||
l * np.sin(2.0 * (cfg["mo1_bragg"] + cfg["cm_pitch"])) - yver
|
||||
) # Resultat ist korrekt!
|
||||
elif cfg["mo1_mode"] == "Pinkbeam":
|
||||
beam_offset_mo1 = 0
|
||||
else:
|
||||
raise ValueError("Monochromator mode not supported")
|
||||
|
||||
def csc(a):
|
||||
return 1 / np.sin(a)
|
||||
|
||||
def cot(a):
|
||||
return 1 / np.tan(a)
|
||||
|
||||
# calculate height of center of first crystal surface
|
||||
f = bl.mo1.rotOffset # rotation offset, mm
|
||||
d = bl.mo1.heightOffset # xtal height offset, mm
|
||||
c = d * csc(cfg["mo1_bragg"]) - f * cot(cfg["mo1_bragg"])
|
||||
|
||||
# Calculate height of center of rotation
|
||||
b = np.sqrt(
|
||||
d**2 * csc(cfg["mo1_bragg"]) ** 2
|
||||
- 2 * d * f * cot(cfg["mo1_bragg"]) * csc(cfg["mo1_bragg"])
|
||||
+ f**2 * cot(cfg["mo1_bragg"]) ** 2
|
||||
+ f**2
|
||||
)
|
||||
h = np.cos(np.pi / 2 - np.arctan(f / c) - cfg["mo1_bragg"] - 2 * cfg["cm_pitch"]) * b
|
||||
h2 = ((bl.mo1.center[1] - bl.cm.center[1]) - np.sqrt(b**2 - h**2)) * np.tan(2 * cfg["cm_pitch"])
|
||||
height_mo1_real = (
|
||||
h + h2
|
||||
) # per design, the height should not change if the pitch of the CM is not changed!
|
||||
if cfg["mo1_mode"] == "Monochromatic":
|
||||
pass
|
||||
elif cfg["mo1_mode"] == "Pinkbeam":
|
||||
height_mo1_real = (
|
||||
height_mo1_real - 13
|
||||
) # Move down to let beam pass between both crystal without touching copper cooler
|
||||
else:
|
||||
raise ValueError("Monochromator mode not supported")
|
||||
pos["mo1_try"] = {"value": height_mo1_real}
|
||||
|
||||
# TRX, Crystal selection
|
||||
if cfg["mo1_mode"] == "Monochromatic":
|
||||
xtal = cfg["mo1_xtal"].translate(
|
||||
str.maketrans("", "", "()")
|
||||
) # Remove brackets from xtal name to conform with parameters
|
||||
if xtal in bl.mo1.xtal:
|
||||
index = bl.mo1.xtal.index(xtal)
|
||||
else:
|
||||
raise ValueError(f"Requested xtal {xtal} not found in parameters!")
|
||||
pos["mo1_trx"] = {"value": bl.mo1.xtalOffsetX[index]}
|
||||
else:
|
||||
pos["mo1_trx"] = {"value": 0}
|
||||
|
||||
diag = bl.mo1.xtalGap[0] / np.sin(cfg["mo1_bragg"]) # Calculations for Mono
|
||||
dz = diag * np.cos(2 * (cfg["cm_pitch"] + cfg["mo1_bragg"]))
|
||||
|
||||
## Slits 1
|
||||
d = bl.opSlits1.center[1] - bl.cm.center[1] - dz
|
||||
sl1_beam_height = d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1
|
||||
pos["sl1_centery"] = {"value": sl1_beam_height}
|
||||
pos["sl1_gapy"] = {"value": beam_vs}
|
||||
|
||||
## Beam Monitor 1
|
||||
d = bl.opBM1.center[1] - bl.cm.center[1] - dz
|
||||
bm1_beam_height = d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1
|
||||
pos["bm1_try"] = {"value": bm1_beam_height}
|
||||
|
||||
## Focusing Mirror
|
||||
p = bl.fm.center[1]
|
||||
q = cfg["smpl"] - bl.fm.center[1]
|
||||
f = (p * q) / (p + q) # focal length
|
||||
|
||||
# Bender radius
|
||||
if cfg["fm_qy"] is None:
|
||||
radius = 2 * q / np.sin(cfg["fm_rotx"]) # ideal bending radius for focused beam
|
||||
else:
|
||||
radius = (
|
||||
2 * cfg["fm_qy"] / np.sin(cfg["fm_rotx"])
|
||||
) # ideal bending radius for unfocused beam
|
||||
pos["fm_bnd_radius"] = {"value": radius * 1e-6} # Convert to km
|
||||
|
||||
# Pitch
|
||||
d = bl.fm.center[1] - bl.cm.center[1] - dz
|
||||
fm_rotx = (
|
||||
2 * cfg["cm_pitch"] - cfg["fm_rotx"]
|
||||
) # calculate pitch in absolute values (according to horizontal plane)
|
||||
pos["fm_rotx"] = {
|
||||
"value": -fm_rotx * 1e3
|
||||
} # invert and convert to mrad (same as EGU of rotx axis)
|
||||
|
||||
if cfg["fm_stripe"] in ("Rh (toroid)", "Pt (toroid)"):
|
||||
|
||||
# TRY
|
||||
if cfg["fm_stripe"] == "Rh (toroid)":
|
||||
r = bl.fm.r[0]
|
||||
h_cyl = bl.fm.hToroid[0]
|
||||
else: # PT toroid
|
||||
r = bl.fm.r[1]
|
||||
h_cyl = bl.fm.hToroid[1]
|
||||
width_beam = 2 * bl.fm.center[1] * np.tan(cfg["h_acc"] * 1e-3)
|
||||
alpha = np.arccos(1 - width_beam**2 / (2 * r**2))
|
||||
h = r - (r * np.cos(alpha / 2))
|
||||
fm_beam_height = (d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1) * cfg["fm_gain_height"]
|
||||
fm_height = (d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1 - h_cyl + h / 2) * cfg[
|
||||
"fm_gain_height"
|
||||
]
|
||||
pos["fm_try"] = {"value": fm_height}
|
||||
|
||||
# TRX
|
||||
if cfg["fm_stripe"] == "Rh (toroid)":
|
||||
x_cyl = -bl.fm.xToroid[0]
|
||||
else:
|
||||
x_cyl = -bl.fm.xToroid[1]
|
||||
pos["fm_trx"] = {"value": x_cyl}
|
||||
|
||||
elif cfg["fm_stripe"] in ("Rh (flat)", "Pt (flat)"):
|
||||
|
||||
# TRY
|
||||
fm_height = (d * np.tan(2 * cfg["cm_pitch"]) + beam_offset_mo1) * cfg["fm_gain_height"]
|
||||
fm_beam_height = fm_height
|
||||
pos["fm_try"] = {"value": fm_height}
|
||||
|
||||
# TRX
|
||||
if cfg["fm_stripe"] == "Rh (flat)":
|
||||
x_flat = -bl.fm.xFlat[0]
|
||||
else:
|
||||
x_flat = -bl.fm.xFlat[1]
|
||||
pos["fm_trx"] = {"value": x_flat}
|
||||
|
||||
else:
|
||||
raise ValueError("FM Stripe selection not valid")
|
||||
|
||||
pos["fm_roty"] = {"value": 0}
|
||||
pos["fm_rotz"] = {"value": 0}
|
||||
|
||||
## Slits 2
|
||||
if hasattr(bl, "opSlits2"):
|
||||
d = bl.opSlits2.center[1] - bl.fm.center[1]
|
||||
sl2_beam_height = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"]))
|
||||
pos["sl2_centery"] = {"value": sl2_beam_height}
|
||||
pos["sl2_gapy"] = {"value": beam_vs}
|
||||
|
||||
## Beam Monitor 2
|
||||
d = bl.opBM2.center[1] - bl.fm.center[1]
|
||||
bm2_beam_height = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"]))
|
||||
pos["bm2_try"] = {"value": bm2_beam_height}
|
||||
|
||||
## Optical Table
|
||||
|
||||
if beamline == "x01da":
|
||||
# TRY
|
||||
d = bl.ehWindow.center[1] - bl.fm.center[1]
|
||||
ot_height = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"]))
|
||||
pos["ot_try"] = {"value": ot_height}
|
||||
|
||||
# Pitch
|
||||
ot_pitch = -(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])
|
||||
pos["ot_rotx"] = {"value": ot_pitch * 1e3}
|
||||
|
||||
# TRZ ES1
|
||||
ot_es1_trz = cfg["smpl"]
|
||||
pos["ot_es1_trz"] = {"value": ot_es1_trz}
|
||||
|
||||
# ES0 exit window
|
||||
pos["es0wi_try"] = {
|
||||
"value": 5
|
||||
} # At 5mm, the middle of the window is 500 mm from the table (neutral position)
|
||||
else:
|
||||
# Exit window height
|
||||
d = bl.ehWindow.center[1] - bl.fm.center[1]
|
||||
es0wi_try = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"]))
|
||||
pos["es0wi_try"] = {"value": es0wi_try}
|
||||
|
||||
# ES1 table height
|
||||
d = bl.es1.center[1] - bl.fm.center[1]
|
||||
es1_try = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"]))
|
||||
pos["es1_try"] = {"value": es1_try}
|
||||
|
||||
# IC0 height
|
||||
d = bl.es1ic0.center[1] - bl.fm.center[1]
|
||||
es1ic0_try = (
|
||||
fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - es1_try
|
||||
)
|
||||
pos["es1ic0_try"] = {"value": es1ic0_try}
|
||||
|
||||
# IC1 height
|
||||
d = bl.es1ic1.center[1] - bl.fm.center[1]
|
||||
es1ic1_try = (
|
||||
fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - es1_try
|
||||
)
|
||||
pos["es1ic1_try"] = {"value": es1ic1_try}
|
||||
|
||||
# IC2 height
|
||||
d = bl.es1ic2.center[1] - bl.fm.center[1]
|
||||
es1ic2_try = (
|
||||
fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"])) - es1_try
|
||||
)
|
||||
pos["es1ic2_try"] = {"value": es1ic2_try}
|
||||
|
||||
# ES2 table height
|
||||
d = bl.es2.center[1] - bl.fm.center[1]
|
||||
es2_try = fm_beam_height - d * np.tan(-(2 * cfg["cm_pitch"] - 2 * cfg["fm_rotx"]))
|
||||
pos["es2_try"] = {"value": es2_try}
|
||||
|
||||
return pos
|
||||
@@ -1,70 +0,0 @@
|
||||
"""
|
||||
Calculates the sideview coordinates based on a beamline config.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .. import parameters as bl
|
||||
from ..types import ConfigDict, DataDict
|
||||
|
||||
|
||||
def calc_sideview(cfg: ConfigDict) -> DataDict:
|
||||
"""
|
||||
Calculates the sideview coordinates based on a beamline config.
|
||||
|
||||
Args:
|
||||
cfg(ConfigDict): Dictionary with beamline config
|
||||
|
||||
Returns:
|
||||
DataDict: Sideview data
|
||||
"""
|
||||
|
||||
beam: DataDict = {"x": [], "y": []}
|
||||
|
||||
beam["x"] = []
|
||||
beam["y"] = []
|
||||
beam["x"].append(0) # Source
|
||||
beam["y"].append(bl.sourceHeight)
|
||||
beam["x"].append(bl.cm.center[1]) # CM
|
||||
beam["y"].append(bl.sourceHeight)
|
||||
if cfg["mo1_mode"] == "Monochromatic":
|
||||
diag = bl.mo1.xtalGap[0] / np.sin(cfg["mo1_bragg"]) # Calculations for Mono
|
||||
dy = diag * np.sin(2 * (cfg["cm_pitch"] + cfg["mo1_bragg"]))
|
||||
dz = diag * np.cos(2 * (cfg["cm_pitch"] + cfg["mo1_bragg"]))
|
||||
beam["x"].append(bl.mo1.center[1] - dz / 2) # Mono 1.1
|
||||
beam["y"].append(
|
||||
bl.sourceHeight
|
||||
+ np.tan(2 * cfg["cm_pitch"]) * (bl.mo1.center[1] - dz / 2 - bl.cm.center[1])
|
||||
)
|
||||
beam["x"].append(bl.mo1.center[1] + dz / 2) # Mono 1.2
|
||||
beam["y"].append(
|
||||
bl.sourceHeight
|
||||
+ np.tan(2 * cfg["cm_pitch"]) * (bl.mo1.center[1] - dz / 2 - bl.cm.center[1])
|
||||
+ dy
|
||||
)
|
||||
beam["x"].append(bl.fm.center[1]) # FM
|
||||
beam["y"].append(
|
||||
bl.sourceHeight
|
||||
+ np.tan(2 * cfg["cm_pitch"]) * (bl.fm.center[1] - bl.cm.center[1] - dz)
|
||||
+ dy
|
||||
)
|
||||
beam["x"].append(cfg["smpl"]) # Experiment
|
||||
beam["y"].append(
|
||||
bl.sourceHeight
|
||||
+ np.tan(2 * cfg["cm_pitch"]) * (bl.fm.center[1] - bl.cm.center[1] - dz)
|
||||
+ dy
|
||||
+ np.tan(2 * (cfg["cm_pitch"] - cfg["fm_rotx"])) * (cfg["smpl"] - bl.fm.center[1])
|
||||
)
|
||||
elif cfg["mo1_mode"] == "Pinkbeam":
|
||||
beam["x"].append(bl.fm.center[1]) # FM
|
||||
beam["y"].append(
|
||||
bl.sourceHeight + np.tan(2 * cfg["cm_pitch"]) * (bl.fm.center[1] - bl.cm.center[1])
|
||||
)
|
||||
beam["x"].append(cfg["smpl"]) # Experiment
|
||||
beam["y"].append(
|
||||
bl.sourceHeight
|
||||
+ np.tan(2 * cfg["cm_pitch"]) * (bl.fm.center[1] - bl.cm.center[1])
|
||||
+ np.tan(2 * (cfg["cm_pitch"] - cfg["fm_rotx"])) * (cfg["smpl"] - bl.fm.center[1])
|
||||
)
|
||||
|
||||
return beam
|
||||
@@ -1,159 +0,0 @@
|
||||
"""
|
||||
Calculates the surface coordinates based on a beamline config.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
import numpy as np
|
||||
from bec_lib import bec_logger
|
||||
|
||||
from .. import parameters as bl
|
||||
from ..types import ConfigDict, SurfaceDict
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
|
||||
def calc_surfaces(cfg: ConfigDict) -> SurfaceDict:
|
||||
"""
|
||||
Calculates the surface coordinates based on a beamline config.
|
||||
|
||||
Args:
|
||||
cfg(ConfigDict): Dictionary with beamline config
|
||||
|
||||
Returns:
|
||||
SurfaceDict: Surface data
|
||||
"""
|
||||
|
||||
out: SurfaceDict = {
|
||||
"cm": {"x": [], "y": []},
|
||||
"mo1_1": {"x": [], "y": []},
|
||||
"mo1_2": {"x": [], "y": []},
|
||||
"fm": {"x": [], "y": []},
|
||||
}
|
||||
|
||||
# Collimating mirror
|
||||
l = 2 * bl.cm.center[1] * np.tan(cfg["v_acc"]) / np.sin(cfg["cm_pitch"])
|
||||
|
||||
w1 = 2 * (bl.cm.center[1] - l / 2) * np.tan(cfg["h_acc"])
|
||||
w2 = 2 * (bl.cm.center[1] + l / 2) * np.tan(cfg["h_acc"])
|
||||
|
||||
# index = bl.cm.surface.index(cfg["cm_stripe"])
|
||||
|
||||
cen = -cfg["cm_trx"]
|
||||
|
||||
out["cm"]["x"] = [cen - w1 / 2, cen - w2 / 2, cen + w2 / 2, cen + w1 / 2]
|
||||
out["cm"]["y"] = [-l / 2, l / 2, l / 2, -l / 2]
|
||||
|
||||
# Monochromator
|
||||
# calculate height of center of first crystal surface
|
||||
c = bl.mo1.heightOffset * 1 / np.sin(cfg["mo1_bragg"]) - bl.mo1.rotOffset * 1 / np.tan(
|
||||
cfg["mo1_bragg"]
|
||||
)
|
||||
e = bl.mo1.xtalGap[0] / np.tan(cfg["mo1_bragg"]) - c
|
||||
|
||||
xtal = cfg["mo1_xtal"].translate(
|
||||
str.maketrans("", "", "()")
|
||||
) # Remove brackets from xtal name to conform with parameters
|
||||
index = bl.mo1.xtal.index(xtal)
|
||||
|
||||
xtal_pos = bl.mo1.xtalOffsetX[index]
|
||||
xtal_length_1 = bl.mo1.xtalLength1[index]
|
||||
xtal_length_2 = bl.mo1.xtalLength2[index]
|
||||
|
||||
width_beam = 2 * bl.mo1.center[1] * np.tan(cfg["h_acc"])
|
||||
|
||||
height_beam = 2 * bl.cm.center[1] * np.tan(cfg["v_acc"])
|
||||
w = height_beam / np.sin(cfg["mo1_bragg"])
|
||||
|
||||
if cfg["mo1_mode"] == "Monochromatic":
|
||||
out["mo1_1"]["x"] = [
|
||||
xtal_pos - width_beam / 2,
|
||||
xtal_pos + width_beam / 2,
|
||||
xtal_pos + width_beam / 2,
|
||||
xtal_pos - width_beam / 2,
|
||||
]
|
||||
out["mo1_1"]["y"] = [
|
||||
xtal_length_1 / 2 - c - w / 2,
|
||||
xtal_length_1 / 2 - c - w / 2,
|
||||
xtal_length_1 / 2 - c + w / 2,
|
||||
xtal_length_1 / 2 - c + w / 2,
|
||||
]
|
||||
out["mo1_2"]["x"] = [
|
||||
xtal_pos - width_beam / 2,
|
||||
xtal_pos + width_beam / 2,
|
||||
xtal_pos + width_beam / 2,
|
||||
xtal_pos - width_beam / 2,
|
||||
]
|
||||
out["mo1_2"]["y"] = [
|
||||
-xtal_length_2 / 2 + e - w / 2,
|
||||
-xtal_length_2 / 2 + e - w / 2,
|
||||
-xtal_length_2 / 2 + e + w / 2,
|
||||
-xtal_length_2 / 2 + e + w / 2,
|
||||
]
|
||||
else: # Pinkbeam
|
||||
out["mo1_1"]["x"] = []
|
||||
out["mo1_1"]["y"] = []
|
||||
out["mo1_2"]["x"] = []
|
||||
out["mo1_2"]["y"] = []
|
||||
|
||||
if cfg["fm_stripe"] is None:
|
||||
return out
|
||||
# Focusing mirror
|
||||
if cfg["fm_stripe"] in ("Rh (toroid)", "Pt (toroid)"):
|
||||
surface = bl.fm.surfaceToroid
|
||||
stripe = re.sub(r"\s*\(.*?\)", "", cfg["fm_stripe"]).strip()
|
||||
index = surface.index(stripe)
|
||||
r = bl.fm.r[index]
|
||||
else:
|
||||
surface = bl.fm.surfaceFlat
|
||||
stripe = re.sub(r"\s*\(.*?\)", "", cfg["fm_stripe"]).strip()
|
||||
index = surface.index(stripe)
|
||||
r = bl.fm.r[index]
|
||||
off = -cfg["fm_trx"]
|
||||
|
||||
width_beam = 2 * bl.fm.center[1] * np.tan(cfg["h_acc"])
|
||||
|
||||
if cfg["fm_stripe"] in ("Rh (toroid)", "Pt (toroid)"):
|
||||
|
||||
l = height_beam / np.sin(cfg["fm_rotx"])
|
||||
alpha = np.arccos(1 - width_beam**2 / (2 * r**2))
|
||||
h = r - (r * np.cos(alpha / 2))
|
||||
z = h / np.tan(cfg["fm_rotx"])
|
||||
|
||||
x = [off - width_beam / 2, off - width_beam / 2]
|
||||
y = [l / 2 - z / 2, -l / 2 - z / 2]
|
||||
|
||||
res = 20
|
||||
x_elipse = np.linspace(0, np.pi, res)
|
||||
y_elipse = np.linspace(0, np.pi, res)
|
||||
x_elipse = [-width_beam / 2 * np.cos(i) + off for i in x_elipse]
|
||||
y_elipse = [width_beam * np.sin(i) * z / width_beam - l / 2 - z / 2 for i in y_elipse]
|
||||
|
||||
x.extend(x_elipse)
|
||||
y.extend(y_elipse)
|
||||
|
||||
x.extend([off + width_beam / 2, off + width_beam / 2])
|
||||
y.extend([-l / 2 - z / 2, l / 2 - z / 2])
|
||||
|
||||
res = 50
|
||||
x_elipse = np.linspace(np.pi, 0, res)
|
||||
y_elipse = np.linspace(np.pi, 0, res)
|
||||
x_elipse = [-width_beam / 2 * np.cos(i) + off for i in x_elipse]
|
||||
y_elipse = [width_beam * np.sin(i) * z / width_beam + l / 2 - z / 2 for i in y_elipse]
|
||||
|
||||
x.extend(x_elipse)
|
||||
y.extend(y_elipse)
|
||||
|
||||
out["fm"]["x"] = x
|
||||
out["fm"]["y"] = y
|
||||
|
||||
else: # flat surface, no toroid
|
||||
l = height_beam / np.sin(cfg["fm_rotx"])
|
||||
|
||||
w1 = 2 * (bl.fm.center[1] - l / 2) * np.tan(cfg["h_acc"])
|
||||
w2 = 2 * (bl.fm.center[1] + l / 2) * np.tan(cfg["h_acc"])
|
||||
|
||||
out["fm"]["x"] = [off - w1 / 2, off + w1 / 2, off + w2 / 2, off - w2 / 2]
|
||||
out["fm"]["y"] = [-l / 2, -l / 2, l / 2, l / 2]
|
||||
|
||||
return out
|
||||
@@ -1,519 +0,0 @@
|
||||
"""
|
||||
Various calculations for the digital twin
|
||||
"""
|
||||
|
||||
import re
|
||||
from typing import Literal, cast
|
||||
|
||||
import numpy as np
|
||||
from bec_lib import bec_logger
|
||||
from scipy.interpolate import UnivariateSpline
|
||||
from xrt.backends.raycing.physconsts import AVOGADRO, CHeVcm
|
||||
|
||||
from .. import parameters as bl
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
H = 6.62606957e-34
|
||||
E = 1.602176634e-19
|
||||
C = 299792458
|
||||
RE = 2.8179e-15
|
||||
|
||||
|
||||
def sldi_gap_to_acc(sldi_gapx: float, sldi_gapy: float) -> tuple[float, float]:
|
||||
"""
|
||||
Calculate the slits acceptance based on the gap values
|
||||
|
||||
Args:
|
||||
sldi_gapx(float): GAPX value of the slits in mm
|
||||
sldi_gapy(float): GAPY value of the slits in mm
|
||||
|
||||
Returns:
|
||||
tuple[float, float]: Horizontal and vertical acceptance in rad
|
||||
"""
|
||||
d1 = bl.feSlits.center1[1]
|
||||
d2 = bl.feSlits.center2[1]
|
||||
h_acc = np.tan(sldi_gapx / (d2 + d1))
|
||||
v_acc = np.tan(sldi_gapy / (d2 + d1))
|
||||
return h_acc, v_acc
|
||||
|
||||
|
||||
def cm_trx_to_stripe(cm_trx: float) -> str | None:
|
||||
"""
|
||||
Based on the trx value of the collimating mirror, return
|
||||
the correct stripe
|
||||
|
||||
Args:
|
||||
cm_trx(float): Collimating mirror trx value
|
||||
|
||||
Returns
|
||||
str | None: Stripe of the mirror, None if not found
|
||||
"""
|
||||
cm_stripe = None
|
||||
for name, low, high in zip(bl.cm.surface, bl.cm.limOptX[0], bl.cm.limOptX[1]):
|
||||
if low <= cm_trx <= high:
|
||||
cm_stripe = name
|
||||
return cm_stripe
|
||||
|
||||
|
||||
def cm_stripe_to_trx(cm_stripe: str) -> float | None:
|
||||
"""
|
||||
Based on the stripe of the collimating mirror, return
|
||||
the trx value
|
||||
|
||||
Args:
|
||||
cm_stripe(str): Stripe of the collimating mirror
|
||||
|
||||
Returns:
|
||||
float | None: TRX value of the stripe. None if not found
|
||||
"""
|
||||
for name, low, high in zip(bl.cm.surface, bl.cm.limOptX[0], bl.cm.limOptX[1]):
|
||||
if cm_stripe == name:
|
||||
return -(low + high) / 2
|
||||
return None
|
||||
|
||||
|
||||
def fm_trx_to_stripe(fm_trx: float) -> str | None:
|
||||
"""
|
||||
Based on the trx value of the focusing mirror, return
|
||||
the correct stripe
|
||||
|
||||
Args:
|
||||
fm_trx(float): focusing mirror trx value
|
||||
|
||||
Returns
|
||||
str | None: Stripe of the mirror, None if not found
|
||||
"""
|
||||
fm_stripe = None
|
||||
if hasattr(bl.fm, "surfaceFlat"):
|
||||
for name, low, high in zip(bl.fm.surfaceFlat, bl.fm.limOptXFlat[1], bl.fm.limOptXFlat[0]):
|
||||
if low <= fm_trx <= high:
|
||||
fm_stripe = name + " (flat)"
|
||||
for name, low, high in zip(bl.fm.surfaceToroid, bl.fm.limOptXToroid[1], bl.fm.limOptXToroid[0]):
|
||||
if low <= fm_trx <= high:
|
||||
fm_stripe = name + " (toroid)"
|
||||
return fm_stripe
|
||||
|
||||
|
||||
def fm_stripe_to_trx(fm_stripe: str) -> float | None:
|
||||
"""
|
||||
Based on the stripe of the focusing mirror, return
|
||||
the trx value
|
||||
|
||||
Args:
|
||||
fm_stripe(str): Stripe of the focusing mirror
|
||||
|
||||
Returns:
|
||||
float | None: TRX value of the stripe. None if not found
|
||||
"""
|
||||
if hasattr(bl.fm, "surfaceFlat"):
|
||||
for name, low, high in zip(bl.fm.surfaceFlat, bl.fm.limOptXFlat[1], bl.fm.limOptXFlat[0]):
|
||||
if fm_stripe == name + " (flat)":
|
||||
return (low + high) / 2
|
||||
for name, low, high in zip(bl.fm.surfaceToroid, bl.fm.limOptXToroid[1], bl.fm.limOptXToroid[0]):
|
||||
if fm_stripe == name + " (toroid)":
|
||||
return -(low + high) / 2
|
||||
return None
|
||||
|
||||
|
||||
def mo1_energy_resolution(xtal: Literal["Si111", "Si311"], energy: float) -> float:
|
||||
"""
|
||||
Calculate the energy resolution of the monochromator
|
||||
|
||||
Args:
|
||||
xtal(str): Xtal name. "Si111" or "Si311"
|
||||
energy(float): Energy in eV
|
||||
|
||||
Returns:
|
||||
float: Energy resolution in eV
|
||||
"""
|
||||
index = bl.mo1.xtal.index(xtal)
|
||||
crystal = bl.mo1.material1[index]
|
||||
|
||||
dtheta = np.linspace(-30, 90, 601)
|
||||
theta = crystal.get_Bragg_angle(energy) + dtheta * 1e-6
|
||||
refl = np.abs(crystal.get_amplitude(energy, np.sin(theta))[0]) ** 2 # single crystal
|
||||
|
||||
refl2 = refl**2 # DCM with parallel crystals
|
||||
|
||||
# FWHM of the DCM curve
|
||||
spline = UnivariateSpline(dtheta, refl2 - refl2.max() / 2, s=0)
|
||||
roots = cast(np.ndarray, spline.roots())
|
||||
r1, r2 = float(roots[0]), float(roots[1])
|
||||
fwhm_rad = (r2 - r1) * 1e-6 # µrad → rad
|
||||
|
||||
# Energy resolution
|
||||
theta_b = crystal.get_Bragg_angle(energy)
|
||||
de_over_e = fwhm_rad / np.tan(theta_b)
|
||||
de = de_over_e * energy
|
||||
|
||||
# logger.info(f"DCM FWHM : {r2-r1:.2f} µrad")
|
||||
# logger.info(f"ΔE/E : {dE_over_E:.2e}")
|
||||
# logger.info(f"ΔE : {dE:.3f} eV at {E} eV")
|
||||
|
||||
return de
|
||||
|
||||
|
||||
def cm_reflectivity(cm_stripe: str, cm_pitch: float, energy: float) -> float:
|
||||
"""
|
||||
Calculate the reflectivity of the mirror stripe based
|
||||
on the pitch and energy.
|
||||
|
||||
Args:
|
||||
cm_stripe(str): Mirror stripe
|
||||
cm_pitch(float): Pitch of the mirror (beam incidence angle)
|
||||
energy(float): Energy of the beam in eV
|
||||
|
||||
Returns:
|
||||
float: Reflectivity [0-1]
|
||||
"""
|
||||
if cm_stripe is None:
|
||||
return np.nan
|
||||
index = bl.cm.surface.index(cm_stripe)
|
||||
rs, _ = bl.cm.material[index].get_amplitude(energy, np.sin(cm_pitch))[0:2]
|
||||
refl = abs(rs) ** 2
|
||||
return refl
|
||||
|
||||
|
||||
def fm_reflectivity(fm_stripe: str, fm_pitch: float, energy: float) -> float:
|
||||
"""
|
||||
Calculate the reflectivity of the mirror stripe based
|
||||
on the pitch and energy.
|
||||
|
||||
Args:
|
||||
cm_stripe(str): Mirror stripe
|
||||
cm_pitch(float): Pitch of the mirror (beam incidence angle)
|
||||
energy(float): Energy of the beam in eV
|
||||
|
||||
Returns:
|
||||
float: Reflectivity [0-1]
|
||||
"""
|
||||
if fm_stripe is None:
|
||||
return np.nan
|
||||
if fm_stripe in ("Rh (toroid)", "Pt (toroid)"):
|
||||
surface = bl.fm.surfaceToroid
|
||||
material = bl.fm.materialToroid
|
||||
stripe = re.sub(r"\s*\(.*?\)", "", fm_stripe).strip()
|
||||
index = surface.index(stripe)
|
||||
else:
|
||||
surface = bl.fm.surfaceFlat
|
||||
material = bl.fm.materialFlat
|
||||
stripe = re.sub(r"\s*\(.*?\)", "", fm_stripe).strip()
|
||||
index = surface.index(stripe)
|
||||
rs, _ = material[index].get_amplitude(energy, np.sin(fm_pitch))[0:2]
|
||||
refl = abs(rs) ** 2
|
||||
return refl
|
||||
|
||||
|
||||
def mo1_bragg_angle(
|
||||
mo_mode: Literal["Monochromatic", "Pinkbeam"], d_spacing: float, energy: float, cm_pitch: float
|
||||
) -> tuple[float, float]:
|
||||
"""
|
||||
Calculate the bragg angle of the monochromator.
|
||||
Corrects for the collimating mirror pitch.
|
||||
|
||||
Args:
|
||||
mo_mode(str): Monochromator mode. "Monochromatic" or "Pinkbeam"
|
||||
d_spacing(float): D-spacing of the crystal in Angstrom
|
||||
energy(float): Energy of the beam in eV
|
||||
cm_pitch(float): Pitch of collimating mirror in rad
|
||||
|
||||
Returns:
|
||||
tuple[float, float]: Bragg angle and corrected bragg angle
|
||||
"""
|
||||
wl = C * H / (E * energy)
|
||||
val = wl / (2 * d_spacing * 1e-10)
|
||||
bragg_angle = 0
|
||||
if val > -1 and val < 1:
|
||||
bragg_angle = np.asin(val)
|
||||
if mo_mode == "Monochromatic":
|
||||
# Add 2x CM pitch to the bragg angle
|
||||
bragg_angle_cor = (2 * cm_pitch) + bragg_angle
|
||||
else:
|
||||
# Align xtal surfaces parallel to beam
|
||||
bragg_angle_cor = 2 * cm_pitch
|
||||
return bragg_angle, bragg_angle_cor
|
||||
|
||||
|
||||
def fm_ideal_pitch(
|
||||
fm_focus: Literal["Defocused", "Focused", "Manual"],
|
||||
fm_stripe: str,
|
||||
smpl: float,
|
||||
sldi_hacc: float | None = None,
|
||||
sldi_vacc: float | None = None,
|
||||
fm_focx: float | None = None,
|
||||
fm_focy: float | None = None,
|
||||
) -> tuple[float, float | None]:
|
||||
"""
|
||||
Calculates the ideal pitch for the focusing mirror depending on the
|
||||
focusing strategy.
|
||||
If "Defocused" is chosed, sldi_hacc, sldi_vacc, fm_focx and fm_focy
|
||||
must be provided.
|
||||
|
||||
Args:
|
||||
fm_focus(str): Focus strategy. "Defocused", "Focused" or "Manual
|
||||
fm_stripe(str): Mirror stripe
|
||||
smpl(float): Sample position in mm from source
|
||||
sldi_hacc(float): Horizontal acceptance of frontend slits. Defaults to None
|
||||
sldi_vacc(float): Vertical acceptance of frontend slits. Defaults to None
|
||||
fm_focx(float): Requested horizontal spot size in mm. Defaults to None
|
||||
fm_focy(float): Requested vertical spot size in mm. Defaults to None
|
||||
|
||||
Returns:
|
||||
tuple[float, float | None]: Pitch of mirror in rad, qy in mm
|
||||
"""
|
||||
|
||||
# logger.info("Calculate pitch and qy now...")
|
||||
# logger.info(f"sldi_hacc: {sldi_hacc}")
|
||||
# logger.info(f"sldi_vacc: {sldi_vacc}")
|
||||
# logger.info(f"fm_stripe: {fm_stripe}")
|
||||
# logger.info(f"smpl: {smpl}")
|
||||
p_cm = bl.cm.center[1] # posCM
|
||||
p = bl.fm.center[1] # posFM
|
||||
q = smpl - bl.fm.center[1] # dist posFM to posEX
|
||||
if fm_focus == "Defocused":
|
||||
assert sldi_hacc is not None, "sldi_hacc must be provided for Defocused mode"
|
||||
assert sldi_vacc is not None, "sldi_vacc must be provided for Defocused mode"
|
||||
assert fm_focx is not None, "fm_focx must be provided for Defocused mode"
|
||||
assert fm_focy is not None, "fm_focy must be provided for Defocused mode"
|
||||
a = 2 * np.tan(sldi_hacc) * bl.fm.center[1] # Beam width at focusing mirror
|
||||
# logger.info(f"a: {a}")
|
||||
# logger.info(f"sldi_hacc: {sldi_hacc}")
|
||||
# logger.info(f"bl.fm.center[1]: {bl.fm.center[1]}")
|
||||
# logger.info(f"p: {p}")
|
||||
# logger.info(f"q: {q}")
|
||||
b = (
|
||||
2 * np.tan(sldi_vacc) * bl.cm.center[1]
|
||||
) # Beam height at focusing mirror (collimated beam)
|
||||
x = fm_focx
|
||||
# logger.info(f"x: {x}")
|
||||
x = 0.098821 * x**2 + 0.512344 * x # polynom to correct for spot size
|
||||
# logger.info(f"x (corrected): {x}")
|
||||
y = fm_focy
|
||||
y = 3.183562 * y**2 + 1.258364 * y # polynom to correct for spot size
|
||||
qx = q + x * p / a
|
||||
qy = q + y * p_cm / b
|
||||
f = (p * qx) / (p + qx) # focal length
|
||||
# logger.info(f"qx: {qx}")
|
||||
# logger.info(f"f: {f}")
|
||||
else: # Calculate for focused beam on sample in "manual" and "focused" mode
|
||||
qy = None
|
||||
f = (p * q) / (p + q) # focal length
|
||||
pitch = 0
|
||||
if "Rh" in fm_stripe:
|
||||
pitch = np.arcsin(bl.fm.r[0] / (2 * f)) # ideal pitch for FM
|
||||
if "Pt" in fm_stripe:
|
||||
pitch = np.arcsin(bl.fm.r[1] / (2 * f)) # ideal pitch for FM
|
||||
# logger.info(f"fm_pitch: {pitch}")
|
||||
# logger.info(f"qy: {qy}")
|
||||
return pitch, qy
|
||||
|
||||
|
||||
def calc_beamsize(
|
||||
sldi_hacc: float,
|
||||
sldi_vacc: float,
|
||||
fm_stripe: str,
|
||||
fm_pitch: float,
|
||||
fm_radius: float,
|
||||
smpl: float,
|
||||
) -> tuple[float, float | None]:
|
||||
"""
|
||||
Calculate the resulting beamsize according to the input parameters
|
||||
|
||||
Args:
|
||||
sldi_hacc(float): Horizontal acceptance of frontend slits
|
||||
sldi_vacc(float): Vertical acceptance of frontend slits
|
||||
fm_stripe(str): Mirror stripe
|
||||
fm_pitch(float): Focusing mirror pitch in rad
|
||||
fm_radius(float): Focusing mirror bender radius in m
|
||||
smpl(float): Sample position in mm from source
|
||||
|
||||
Returns:
|
||||
tuple[float, float | None]: horizontal spot size, vertical spot size, both in mm
|
||||
"""
|
||||
|
||||
# logger.info("Calculate beamsize now...")
|
||||
# logger.info(f"sldi_hacc: {sldi_hacc}")
|
||||
# logger.info(f"sldi_vacc: {sldi_vacc}")
|
||||
# logger.info(f"fm_stripe: {fm_stripe}")
|
||||
# logger.info(f"fm_pitch: {fm_pitch}")
|
||||
# logger.info(f"fm_radius: {fm_radius}")
|
||||
# logger.info(f"smpl: {smpl}")
|
||||
p_cm = bl.cm.center[1] # posCM
|
||||
p = bl.fm.center[1] # posFM
|
||||
q = smpl - bl.fm.center[1] # dist posFM to posEX
|
||||
qy = fm_radius * np.sin(fm_pitch) / 2
|
||||
a = 2 * np.tan(sldi_hacc) * bl.fm.center[1] # Beam width at focusing mirror
|
||||
b = 2 * np.tan(sldi_vacc) * bl.cm.center[1] # Beam height at focusing mirror (collimated beam)
|
||||
f = 0
|
||||
if "Rh" in fm_stripe:
|
||||
f = bl.fm.r[0] / (2 * np.sin(fm_pitch))
|
||||
if "Pt" in fm_stripe:
|
||||
f = bl.fm.r[1] / (2 * np.sin(fm_pitch))
|
||||
qx = p * f / (p - f)
|
||||
x = a * (qx - q) / p
|
||||
y = b * (qy - q) / p_cm
|
||||
# Change this | to a plus if calculation is not correct
|
||||
fm_focx = -4 * (64043 - 125000 * np.sqrt(0.26249637 + 0.395284 * x)) / 98821
|
||||
# Change this | to a plus if calculation is not correct
|
||||
fm_focy = -1 * (314591 - 250000 * np.sqrt(1.58347995 + 12.734248 * y)) / 1591781
|
||||
# logger.info(f"f: {f}")
|
||||
# logger.info(f"qx: {qx}")
|
||||
# logger.info(f"qy: {qy}")
|
||||
# logger.info(f"fm_focx: {fm_focx}")
|
||||
# logger.info(f"fm_focy: {fm_focy}")
|
||||
return fm_focx, fm_focy
|
||||
|
||||
|
||||
def cm_critical_angle(cm_stripe: Literal["Si", "Pt", "Rh"], energy) -> float:
|
||||
"""
|
||||
Calculate the critical angle of the mirror stripe
|
||||
|
||||
Args:
|
||||
cm_stripe(str): Mirror stripe. "Si", "Pt" or "Rh"
|
||||
energy(float): Energy in eV
|
||||
|
||||
Returns:
|
||||
float: Critical angle in rad
|
||||
"""
|
||||
if cm_stripe == "Si":
|
||||
stripe = bl.stripeSi
|
||||
elif cm_stripe == "Pt":
|
||||
stripe = bl.stripePt
|
||||
else:
|
||||
stripe = bl.stripeRh
|
||||
w = CHeVcm / 100 / energy # convert energy [eV] to wavelength [m]
|
||||
f1 = stripe.elements[0].Z + np.real(stripe.elements[0].get_f1f2(energy))
|
||||
number_density = stripe.rho * 1e3 * AVOGADRO / (stripe.elements[0].mass / 1e3)
|
||||
critical_angle = np.sqrt(number_density * RE * w**2 * f1 / np.pi)
|
||||
return critical_angle
|
||||
|
||||
|
||||
def mirror_surface_geometries(
|
||||
mirror: Literal["cm", "fm_toroid", "fm_flat"],
|
||||
) -> dict[str, tuple[float, float, float, float]]:
|
||||
"""
|
||||
Return the mirror stripe geometries
|
||||
|
||||
Args:
|
||||
mirror(str): Mirror. "cm", "fm_toroid" or "fm_flat"
|
||||
|
||||
Returns:
|
||||
dict[str, tuple[float, float, float, float]]: Dictionary mapping surface
|
||||
names to tuples of (x, y, width, height).
|
||||
"""
|
||||
if mirror == "cm":
|
||||
surface = bl.cm.surface
|
||||
lim_opt_x = bl.cm.limOptX
|
||||
lim_opt_y = bl.cm.limOptY
|
||||
elif mirror == "fm_toroid":
|
||||
surface = bl.fm.surfaceToroid
|
||||
lim_opt_x = bl.fm.limOptXToroid
|
||||
lim_opt_y = bl.fm.limOptYToroid
|
||||
elif mirror == "fm_flat":
|
||||
surface = bl.fm.surfaceFlat
|
||||
lim_opt_x = bl.fm.limOptXFlat
|
||||
lim_opt_y = bl.fm.limOptYFlat
|
||||
else:
|
||||
raise ValueError(f"Requested mirror {mirror} not available!")
|
||||
geom = {}
|
||||
for sf, lx, hx, ly, hy in zip(surface, lim_opt_x[0], lim_opt_x[1], lim_opt_y[0], lim_opt_y[1]):
|
||||
geom[sf] = (lx, ly, hx - lx, hy - ly)
|
||||
return geom
|
||||
|
||||
|
||||
def mo_surface_geometries(
|
||||
mo: Literal["mo1"], plane: Literal[0, 1]
|
||||
) -> dict[str, tuple[float, float, float, float]]:
|
||||
"""
|
||||
Return the monochromator xtal geometries
|
||||
|
||||
Args:
|
||||
mo(str): Monochromator. Only "mo1" implemented
|
||||
plane(int): Surface of xtal. 0 and 1 (First and second)
|
||||
|
||||
Returns:
|
||||
dict[str, tuple[float, float, float, float]]: Dictionary mapping surface
|
||||
names to tuples of (x, y, width, height).
|
||||
"""
|
||||
if mo == "mo1":
|
||||
xtal = bl.mo1.xtal
|
||||
xtal_width = bl.mo1.xtalWidth
|
||||
xtal_offset_x = bl.mo1.xtalOffsetX
|
||||
if plane == 0:
|
||||
xtal_length = bl.mo1.xtalLength1
|
||||
else:
|
||||
xtal_length = bl.mo1.xtalLength2
|
||||
else:
|
||||
return {}
|
||||
geom = {}
|
||||
for sf, w, offx, length in zip(xtal, xtal_width, xtal_offset_x, xtal_length):
|
||||
geom[sf] = (offx - w / 2, -length / 2, w, length)
|
||||
return geom
|
||||
|
||||
|
||||
def wall_geometries() -> list[list[float]]:
|
||||
"""
|
||||
Return the wall geometries
|
||||
|
||||
Returns:
|
||||
list[list[float]]: List of [x, y, width, height] geometry values for each wall.
|
||||
"""
|
||||
geom = []
|
||||
if not hasattr(bl, "walls"):
|
||||
return geom
|
||||
for i, _ in enumerate(bl.walls.start):
|
||||
geom.append(
|
||||
[
|
||||
bl.walls.start[i],
|
||||
bl.walls.height[i][0],
|
||||
bl.walls.end[i] - bl.walls.start[i],
|
||||
bl.walls.height[i][1] - bl.walls.height[i][0],
|
||||
]
|
||||
)
|
||||
return geom
|
||||
|
||||
|
||||
def pipe_geometries() -> list[dict[str, np.ndarray]]:
|
||||
"""
|
||||
Return the wall geometries
|
||||
|
||||
Returns:
|
||||
list[dict[str, np.ndarray]]: List of dictionaries with keys "x" and "y",
|
||||
each containing a numpy array of two float values representing
|
||||
the start and end coordinates of the pipe top and bottom edges.
|
||||
"""
|
||||
pipes = []
|
||||
if not hasattr(bl, "vacuum_pipes"):
|
||||
return pipes
|
||||
for i, _ in enumerate(bl.vacuum_pipes.center):
|
||||
top = bl.vacuum_pipes.center[i] + bl.vacuum_pipes.diameter[i] / 2 + bl.sourceHeight
|
||||
bottom = bl.vacuum_pipes.center[i] - bl.vacuum_pipes.diameter[i] / 2 + bl.sourceHeight
|
||||
pipes.append(
|
||||
{
|
||||
"x": np.array([bl.vacuum_pipes.start[i], bl.vacuum_pipes.end[i]]),
|
||||
"y": np.array([top, top]),
|
||||
}
|
||||
)
|
||||
pipes.append(
|
||||
{
|
||||
"x": np.array([bl.vacuum_pipes.start[i], bl.vacuum_pipes.end[i]]),
|
||||
"y": np.array([bottom, bottom]),
|
||||
}
|
||||
)
|
||||
return pipes
|
||||
|
||||
|
||||
def table_to_smpl_pos(table: str) -> float:
|
||||
"""
|
||||
Return the sample position based on the table name.
|
||||
|
||||
Args:
|
||||
table (str): Table name, e.g. ES1 or ES2
|
||||
"""
|
||||
|
||||
if table == bl.es1.name:
|
||||
return bl.es1.center[1]
|
||||
if table == bl.es2.name:
|
||||
return bl.es2.center[1]
|
||||
raise ValueError(f"Table {table} not found in beamline parameter file")
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,171 @@
|
||||
"""
|
||||
GlitchesPreview: QDialog to preview monochromator glitches
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pyqtgraph as pg
|
||||
import xraydb
|
||||
from bec_lib import bec_logger
|
||||
from bec_widgets.utils.colors import Colors, get_accent_colors
|
||||
from bec_widgets.utils.error_popups import SafeSlot
|
||||
|
||||
# pylint: disable=E0611
|
||||
from qtpy.QtWidgets import QDialog, QHBoxLayout, QLabel, QPushButton, QVBoxLayout
|
||||
|
||||
from .azimuth_calculator import parse_xop_macro, predicted_energies
|
||||
from .widgets.qt_widgets import ComboBox, InputNumberField
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
EV_BELOW = 200
|
||||
EV_ABOVE = 1000
|
||||
|
||||
|
||||
def edge_step(energies, edge_energy, width_ev=1.5):
|
||||
"""Plain logistic step 0 -> 1 (no EXAFS/pre-edge), for a readable
|
||||
visual reference of where a real edge would fall."""
|
||||
x = np.clip(-(energies - edge_energy) / width_ev, -500, 500)
|
||||
return 1.0 / (1.0 + np.exp(x))
|
||||
|
||||
|
||||
class GlitchesPreview(QDialog):
|
||||
"""QDialog to preview monochromator glitches"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent,
|
||||
current_xtal: str,
|
||||
current_azm: float,
|
||||
ranges: dict,
|
||||
element: str | None = "",
|
||||
edge: str | None = "",
|
||||
energy: float = 12000,
|
||||
):
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("Glitches Preview")
|
||||
|
||||
if element != "":
|
||||
self.energy = xraydb.xray_edge(element, edge, energy_only=True)
|
||||
self.energies = np.linspace(self.energy - EV_BELOW, self.energy + EV_ABOVE, 1000)
|
||||
self.mu = edge_step(self.energies, self.energy)
|
||||
else:
|
||||
self.energy = energy
|
||||
self.energies = np.linspace(self.energy - EV_BELOW, self.energy + EV_ABOVE, 1000)
|
||||
self.mu = np.ones(len(self.energies))
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
text = QLabel("Preview of monochromator glitches.")
|
||||
layout.addWidget(text)
|
||||
|
||||
self.xtal_selector = ComboBox("mo1_xtal", "Crystal", ["Si(111)", "Si(311)"])
|
||||
self.xtal_selector.set_current_text(current_xtal)
|
||||
self.xtal_selector.activated_connect(self.change_xtal)
|
||||
self.old_xtal = current_xtal
|
||||
layout.addWidget(self.xtal_selector)
|
||||
|
||||
self.azm_angle = current_azm
|
||||
self.ranges = ranges
|
||||
self.azm_input = None
|
||||
if ranges[current_xtal]["ll"] is not None and ranges[current_xtal]["hl"] is not None:
|
||||
self.azm_input = InputNumberField(
|
||||
"azm_angle",
|
||||
"Azm. Angle",
|
||||
unit="deg",
|
||||
init=self.azm_angle,
|
||||
decimals=3,
|
||||
single_step=0.01,
|
||||
ll=ranges[current_xtal]["ll"],
|
||||
hl=ranges[current_xtal]["hl"],
|
||||
)
|
||||
self.azm_input.value_changed_connect(self.update_plot)
|
||||
layout.addWidget(self.azm_input)
|
||||
accept_text = "Select crystal and azimuthal angle"
|
||||
else:
|
||||
accept_text = "Select crystal"
|
||||
|
||||
self.plot = pg.PlotWidget()
|
||||
self.plot.setLabel("bottom", "Energy", units="eV")
|
||||
self.plot.setLabel("left", "Beam Intensity")
|
||||
self.plot.addLegend()
|
||||
self.plot.setYRange(-0.15, 1.2)
|
||||
color = Colors.golden_angle_color(colormap="plasma", num=1, format="HEX")[0]
|
||||
self.curve_edge = self.plot.plot(pen=pg.mkPen(color=color, width=2))
|
||||
layout.addWidget(self.plot)
|
||||
|
||||
button_layout = QHBoxLayout()
|
||||
self._cancel_button = QPushButton("Close")
|
||||
self._cancel_button.clicked.connect(self.reject)
|
||||
self._cancel_button.setStyleSheet(
|
||||
f"QPushButton {{background-color: {get_accent_colors().default.name()}; color: white;}}"
|
||||
)
|
||||
self._select_button = QPushButton(accept_text)
|
||||
self._select_button.clicked.connect(self.accept)
|
||||
self._select_button.setStyleSheet(
|
||||
f"QPushButton {{background-color: {get_accent_colors().default.name()}; color: white;}}"
|
||||
)
|
||||
|
||||
self._cancel_button.setAutoDefault(False)
|
||||
self._cancel_button.setDefault(False)
|
||||
self._select_button.setAutoDefault(False)
|
||||
self._select_button.setDefault(False)
|
||||
|
||||
button_layout.addStretch()
|
||||
button_layout.addWidget(self._cancel_button)
|
||||
button_layout.addWidget(self._select_button)
|
||||
button_layout.addStretch()
|
||||
|
||||
layout.addLayout(button_layout)
|
||||
|
||||
self.adjustSize()
|
||||
self.setFixedSize(self.sizeHint())
|
||||
|
||||
self.reflections_si111 = parse_xop_macro(
|
||||
Path(__file__).with_name("xop_si111_Si-LN2_8-8-8_4500-60000eV_-180-180deg.pro")
|
||||
)
|
||||
self.reflections_si311 = parse_xop_macro(
|
||||
Path(__file__).with_name("xop_si311_Si-LN2_8-8-8_4500-60000eV_0-360deg.pro")
|
||||
)
|
||||
self.update_plot()
|
||||
|
||||
@SafeSlot()
|
||||
def change_xtal(self, *_, **__):
|
||||
diff = self.azm_angle - self.ranges[self.old_xtal]["ll"]
|
||||
xtal_info = self.ranges[self.xtal_selector.currentText()]
|
||||
self.azm_input.set_range(xtal_info["ll"], xtal_info["hl"])
|
||||
self.azm_input.set_number(xtal_info["ll"] + diff)
|
||||
self.old_xtal = self.xtal_selector.currentText()
|
||||
self.update_plot()
|
||||
|
||||
@SafeSlot()
|
||||
def update_plot(self, *_, **__):
|
||||
if isinstance(self.azm_input, InputNumberField):
|
||||
self.azm_angle = self.azm_input.value()
|
||||
if self.xtal_selector.currentText() == "Si(111)":
|
||||
reflections = self.reflections_si111
|
||||
else:
|
||||
reflections = self.reflections_si311
|
||||
|
||||
e_pred, fh, _ = predicted_energies(
|
||||
reflections, self.azm_angle, (self.energies[0], self.energies[-1])
|
||||
)
|
||||
|
||||
if len(fh) == 0:
|
||||
self.curve_edge.setData(self.energies, self.mu)
|
||||
logger.info(f"phi = {self.azm_angle:.1f} deg | 0 glitches in window")
|
||||
return
|
||||
|
||||
logw = np.log10(fh)
|
||||
wnorm = (
|
||||
(logw - logw.min()) / (logw.max() - logw.min())
|
||||
if logw.max() > logw.min()
|
||||
else np.ones_like(logw)
|
||||
)
|
||||
|
||||
mu = self.mu
|
||||
for e, wn in zip(e_pred, wnorm):
|
||||
depth = 0.02 + 0.08 * wn
|
||||
mu = mu - depth * np.exp(-0.5 * ((self.energies - e) / 1.5) ** 2)
|
||||
|
||||
self.curve_edge.setData(self.energies, mu)
|
||||
@@ -7,7 +7,7 @@ from typing import Union
|
||||
# pylint: disable=E0611
|
||||
from qtpy.QtWidgets import QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget
|
||||
|
||||
from ..types import BeamlineId
|
||||
from .....bec_ipython_client.plugins.beamline import BeamlineId
|
||||
from ..widgets.qt_widgets import (
|
||||
Button,
|
||||
ComboBox,
|
||||
@@ -113,8 +113,32 @@ class InputPanel(QWidget):
|
||||
self.mo1_xtal = ComboBox("mo1_xtal", "Crystal", ["Si111", "Si311"])
|
||||
self.mo1_bragg_angle = NumberIndicator("Bragg Angle", "deg", decimals=1)
|
||||
self.mo1_eres = NumberIndicator("Energy Resolution", "eV", decimals=2)
|
||||
|
||||
if beamline == BeamlineId.X01DA:
|
||||
self.mo1_azm_angle = InputNumberField(
|
||||
"azm_angle",
|
||||
"Azm. Angle",
|
||||
unit="deg",
|
||||
init=0,
|
||||
decimals=3,
|
||||
single_step=0.01,
|
||||
ll=-10,
|
||||
hl=10,
|
||||
)
|
||||
else:
|
||||
self.mo1_azm_angle = NumberIndicator("Azm. Angle", "deg", decimals=3)
|
||||
self.mo1_glitch_preview = Button("Glitches Preview", "Open", enabled=True)
|
||||
|
||||
self.mo1_ass_group = Group(
|
||||
"Monochromator", [self.mo1_mode, self.mo1_xtal, self.mo1_bragg_angle, self.mo1_eres]
|
||||
"Monochromator",
|
||||
[
|
||||
self.mo1_mode,
|
||||
self.mo1_xtal,
|
||||
self.mo1_bragg_angle,
|
||||
self.mo1_eres,
|
||||
self.mo1_azm_angle,
|
||||
self.mo1_glitch_preview,
|
||||
],
|
||||
)
|
||||
|
||||
# Focusing Mirror
|
||||
@@ -173,7 +197,45 @@ class InputPanel(QWidget):
|
||||
|
||||
# Sample
|
||||
self.cm_fm_harm_suppr = NumberIndicator("Total Suppression Factor at x eV", "", decimals=0)
|
||||
self.smpl = self._create_smpl(beamline)
|
||||
|
||||
self.es1man_trz = InputNumberField(
|
||||
"es1man_trz",
|
||||
"Sample Manipulator TRZ",
|
||||
unit="mm",
|
||||
init=0,
|
||||
decimals=1,
|
||||
single_step=1,
|
||||
ll=-60,
|
||||
hl=60,
|
||||
)
|
||||
|
||||
if beamline == BeamlineId.X01DA:
|
||||
self.ot_es1_trz = InputNumberField(
|
||||
"ot_es1_trz",
|
||||
"ES1 Position",
|
||||
unit="mm",
|
||||
init=23511,
|
||||
decimals=0,
|
||||
single_step=100,
|
||||
ll=23000,
|
||||
hl=30000,
|
||||
)
|
||||
self.smpl_to_xrd = InputNumberField(
|
||||
"smpl_to_xrd",
|
||||
"Sample to XRD Det",
|
||||
unit="mm",
|
||||
init=320,
|
||||
decimals=0,
|
||||
single_step=10,
|
||||
ll=320,
|
||||
hl=6000,
|
||||
)
|
||||
self.smpl_group = Group(
|
||||
"Sample Position", [self.ot_es1_trz, self.es1man_trz, self.smpl_to_xrd]
|
||||
)
|
||||
else:
|
||||
self.table = ComboBox("table", "Sample Position", ["ES1", "ES2"])
|
||||
self.smpl_group = Group("Sample Position", [self.es1man_trz])
|
||||
|
||||
# Assemble complete assistant group
|
||||
self.input_group = Group(
|
||||
@@ -186,25 +248,9 @@ class InputPanel(QWidget):
|
||||
self.mo1_ass_group,
|
||||
self.fm_ass_group,
|
||||
self.cm_fm_harm_suppr,
|
||||
self.smpl,
|
||||
self.smpl_group,
|
||||
],
|
||||
)
|
||||
|
||||
self._layout.addWidget(self.input_group)
|
||||
self._layout.addStretch()
|
||||
|
||||
def _create_smpl(self, beamline: BeamlineId) -> Union[InputNumberField, ComboBox]:
|
||||
match beamline:
|
||||
case BeamlineId.X01DA:
|
||||
return InputNumberField(
|
||||
"smpl",
|
||||
"Sample Position",
|
||||
unit="mm",
|
||||
init=23511,
|
||||
decimals=0,
|
||||
single_step=100,
|
||||
ll=23000,
|
||||
hl=30000,
|
||||
)
|
||||
case BeamlineId.X10DA:
|
||||
return ComboBox("smpl", "Sample Position", ["ES1", "ES2"])
|
||||
@@ -7,24 +7,27 @@ from typing import Literal
|
||||
# pylint: disable=E0611
|
||||
from qtpy.QtWidgets import QVBoxLayout, QWidget
|
||||
|
||||
from ..types import BeamlineId
|
||||
from .....bec_ipython_client.plugins.beamline import BeamlineId
|
||||
from ..widgets.move_widget import AbsorberWidget, MoveWidget
|
||||
from ..widgets.qt_widgets import Group
|
||||
from ..widgets.qt_widgets import Button, Group, QLabel
|
||||
|
||||
|
||||
class MoverPanel(QWidget):
|
||||
""" "Panel to move an axis to a certain position"""
|
||||
|
||||
def __init__(self, beamline: BeamlineId, dev, parent=None):
|
||||
def __init__(self, core, beamline: BeamlineId, dev, parent=None):
|
||||
super().__init__(parent)
|
||||
self._layout = QVBoxLayout(self)
|
||||
self._layout.setContentsMargins(4, 4, 4, 4)
|
||||
self._layout.setSpacing(4)
|
||||
|
||||
self.core = core
|
||||
|
||||
self.mover_widgets = []
|
||||
|
||||
# FE Slits
|
||||
self.sldi_gapx = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="sldi_gapx",
|
||||
@@ -36,6 +39,7 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.sldi_gapx)
|
||||
|
||||
self.sldi_gapy = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="sldi_gapy",
|
||||
@@ -55,6 +59,7 @@ class MoverPanel(QWidget):
|
||||
|
||||
# Collimating mirror
|
||||
self.cm_trx = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="cm_trx",
|
||||
@@ -66,6 +71,7 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.cm_trx)
|
||||
|
||||
self.cm_try = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="cm_try",
|
||||
@@ -77,6 +83,7 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.cm_try)
|
||||
|
||||
self.cm_bnd = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="cm_bnd",
|
||||
@@ -88,6 +95,7 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.cm_bnd)
|
||||
|
||||
self.cm_rotx = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="cm_rotx",
|
||||
@@ -104,6 +112,7 @@ class MoverPanel(QWidget):
|
||||
|
||||
# Monochromator
|
||||
self.mo1_bragg_angle = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="mo1_bragg_angle",
|
||||
@@ -115,6 +124,7 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.mo1_bragg_angle)
|
||||
|
||||
self.mo1_trx = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="mo1_trx",
|
||||
@@ -126,6 +136,7 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.mo1_trx)
|
||||
|
||||
self.mo1_try = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="mo1_try",
|
||||
@@ -136,12 +147,30 @@ class MoverPanel(QWidget):
|
||||
)
|
||||
self.mover_widgets.append(self.mo1_try)
|
||||
|
||||
self.mo1_mov_group = Group(
|
||||
"Monochromator", [self.mo1_bragg_angle, self.mo1_trx, self.mo1_try]
|
||||
)
|
||||
if beamline == BeamlineId.X01DA:
|
||||
self.mo1_roty = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="mo1_roty",
|
||||
label="ROTY",
|
||||
unit="deg",
|
||||
decimals=3,
|
||||
deadband=0.01,
|
||||
)
|
||||
self.mover_widgets.append(self.mo1_roty)
|
||||
|
||||
self.mo1_mov_group = Group(
|
||||
"Monochromator", [self.mo1_bragg_angle, self.mo1_trx, self.mo1_try, self.mo1_roty]
|
||||
)
|
||||
else:
|
||||
self.mo1_mov_group = Group(
|
||||
"Monochromator", [self.mo1_bragg_angle, self.mo1_trx, self.mo1_try]
|
||||
)
|
||||
|
||||
# OP Slits 1
|
||||
self.sl1_centery = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="sl1_centery",
|
||||
@@ -153,6 +182,7 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.sl1_centery)
|
||||
|
||||
self.sl1_gapy = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="sl1_gapy",
|
||||
@@ -167,6 +197,7 @@ class MoverPanel(QWidget):
|
||||
|
||||
# OP Beam Monitor 1
|
||||
self.bm1_try = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="bm1_try",
|
||||
@@ -181,6 +212,7 @@ class MoverPanel(QWidget):
|
||||
|
||||
# Focusing Mirror
|
||||
self.fm_trx = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="fm_trx",
|
||||
@@ -192,6 +224,7 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.fm_trx)
|
||||
|
||||
self.fm_try = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="fm_try",
|
||||
@@ -203,6 +236,7 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.fm_try)
|
||||
|
||||
self.fm_bnd = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="fm_bnd",
|
||||
@@ -214,6 +248,7 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.fm_bnd)
|
||||
|
||||
self.fm_rotx = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="fm_rotx",
|
||||
@@ -225,6 +260,7 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.fm_rotx)
|
||||
|
||||
self.fm_roty = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="fm_roty",
|
||||
@@ -236,6 +272,7 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.fm_roty)
|
||||
|
||||
self.fm_rotz = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="fm_rotz",
|
||||
@@ -254,6 +291,7 @@ class MoverPanel(QWidget):
|
||||
if beamline == "x01da":
|
||||
# OP Slits 2
|
||||
self.sl2_centery = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="sl2_centery",
|
||||
@@ -265,6 +303,7 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.sl2_centery)
|
||||
|
||||
self.sl2_gapy = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="sl2_gapy",
|
||||
@@ -279,6 +318,7 @@ class MoverPanel(QWidget):
|
||||
|
||||
# OP Beam Monitor 2
|
||||
self.bm2_try = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="bm2_try",
|
||||
@@ -294,6 +334,7 @@ class MoverPanel(QWidget):
|
||||
if beamline == "x01da":
|
||||
# Optical Table
|
||||
self.ot_try = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="ot_try",
|
||||
@@ -305,6 +346,7 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.ot_try)
|
||||
|
||||
self.ot_rotx = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="ot_rotx",
|
||||
@@ -319,6 +361,7 @@ class MoverPanel(QWidget):
|
||||
|
||||
# Experimental Station 0
|
||||
self.es0wi_try = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="es0wi_try",
|
||||
@@ -334,6 +377,7 @@ class MoverPanel(QWidget):
|
||||
# Experimental Station 1
|
||||
if beamline == "x01da":
|
||||
self.ot_es1_trz = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="ot_es1_trz",
|
||||
@@ -343,9 +387,21 @@ class MoverPanel(QWidget):
|
||||
deadband=5,
|
||||
)
|
||||
self.mover_widgets.append(self.ot_es1_trz)
|
||||
self.es1man_trz = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="es1man_trz",
|
||||
label="MANIP TRZ",
|
||||
unit="mm",
|
||||
decimals=2,
|
||||
deadband=0.1,
|
||||
)
|
||||
self.mover_widgets.append(self.es1man_trz)
|
||||
|
||||
if beamline == "x10da":
|
||||
self.es1_try = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="es1_try",
|
||||
@@ -357,6 +413,7 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.es1_try)
|
||||
|
||||
self.es1ic0_try = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="es1ic0_try",
|
||||
@@ -368,6 +425,7 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.es1ic0_try)
|
||||
|
||||
self.es1ic1_try = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="es1ic1_try",
|
||||
@@ -379,6 +437,7 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.es1ic1_try)
|
||||
|
||||
self.es1ic2_try = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="es1ic2_try",
|
||||
@@ -390,15 +449,29 @@ class MoverPanel(QWidget):
|
||||
self.mover_widgets.append(self.es1ic2_try)
|
||||
|
||||
if beamline == "x01da":
|
||||
self.es1_mov_group = Group("Experimental Station 1", [self.ot_es1_trz])
|
||||
self.es1_mov_group = Group("Experimental Station 1", [self.ot_es1_trz, self.es1man_trz])
|
||||
else:
|
||||
self.es1_mov_group = Group(
|
||||
"Experimental Station 1", [self.es1_try, self.es1ic1_try, self.es1ic2_try]
|
||||
)
|
||||
|
||||
# Experimental Station 2
|
||||
if beamline == "x01da":
|
||||
self.ot_es2_trz = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="ot_es2_trz",
|
||||
label="ES2 TRZ",
|
||||
unit="mm",
|
||||
decimals=0,
|
||||
deadband=5,
|
||||
)
|
||||
self.mover_widgets.append(self.ot_es2_trz)
|
||||
|
||||
if beamline == "x10da":
|
||||
self.es2_try = MoveWidget(
|
||||
core=self.core,
|
||||
beamline=beamline,
|
||||
dev=dev,
|
||||
motor="es2_try",
|
||||
@@ -409,8 +482,20 @@ class MoverPanel(QWidget):
|
||||
)
|
||||
self.mover_widgets.append(self.es2_try)
|
||||
|
||||
if beamline == "x01da":
|
||||
self.es2_mov_group = Group("Experimental Station 2", [self.ot_es2_trz])
|
||||
else:
|
||||
self.es2_mov_group = Group("Experimental Station 2", [self.es2_try])
|
||||
|
||||
# Multi-Mover
|
||||
self.multi_move = Button(label_button="Move Selection", enabled=True, color="success")
|
||||
self.multi_move_info = QLabel(
|
||||
"Not all motors can move together at the same time, digital twin will take care of that."
|
||||
)
|
||||
self.multi_move_info.setFixedWidth(352)
|
||||
self.multi_move_info.setWordWrap(True)
|
||||
self.multi_move_group = Group("Multi Move", [self.multi_move, self.multi_move_info])
|
||||
|
||||
# Assemble complete mover group
|
||||
if beamline == "x01da":
|
||||
self.mover_group = Group(
|
||||
@@ -428,6 +513,8 @@ class MoverPanel(QWidget):
|
||||
self.ot_mov_group,
|
||||
self.es0_mov_group,
|
||||
self.es1_mov_group,
|
||||
self.es2_mov_group,
|
||||
self.multi_move_group,
|
||||
],
|
||||
)
|
||||
else:
|
||||
@@ -445,6 +532,7 @@ class MoverPanel(QWidget):
|
||||
self.es0_mov_group,
|
||||
self.es1_mov_group,
|
||||
self.es2_mov_group,
|
||||
self.multi_move_group,
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@@ -15,13 +15,11 @@ from qtpy.QtGui import QBrush, QColor
|
||||
# pylint: disable=E0611
|
||||
from qtpy.QtWidgets import QApplication, QGraphicsRectItem, QHBoxLayout, QVBoxLayout, QWidget
|
||||
|
||||
from ..calculations.calc_varia import (
|
||||
mirror_surface_geometries,
|
||||
mo_surface_geometries,
|
||||
pipe_geometries,
|
||||
wall_geometries,
|
||||
from .....bec_ipython_client.plugins.digital_twin_core.types import (
|
||||
BeamlineId,
|
||||
DataDict,
|
||||
SurfaceDict,
|
||||
)
|
||||
from ..types import BeamlineId, DataDict, SurfaceDict
|
||||
from ..widgets.qt_widgets import Group
|
||||
|
||||
logger = bec_logger.logger
|
||||
@@ -30,9 +28,10 @@ logger = bec_logger.logger
|
||||
class SurfacePlots(QWidget):
|
||||
"""Plot widget with two curves and legend."""
|
||||
|
||||
def __init__(self, beamline: BeamlineId, parent=None):
|
||||
def __init__(self, beamline: BeamlineId, core, parent=None):
|
||||
super().__init__(parent=parent)
|
||||
self.beamline = beamline
|
||||
self.core = core
|
||||
self._layout = QHBoxLayout(self)
|
||||
self._layout.setContentsMargins(4, 4, 4, 4)
|
||||
self._layout.setSpacing(6)
|
||||
@@ -169,15 +168,15 @@ class SurfacePlots(QWidget):
|
||||
|
||||
for name, plot in self.plots.items():
|
||||
if name == "cm":
|
||||
plot_surface(plot["widget"], mirror_surface_geometries("cm"))
|
||||
plot_surface(plot["widget"], self.core.mirror_surface_geometries("cm"))
|
||||
elif name == "mo1_1":
|
||||
plot_surface(plot["widget"], mo_surface_geometries("mo1", 0))
|
||||
plot_surface(plot["widget"], self.core.mo_surface_geometries("mo1", 0))
|
||||
elif name == "mo1_2":
|
||||
plot_surface(plot["widget"], mo_surface_geometries("mo1", 1))
|
||||
plot_surface(plot["widget"], self.core.mo_surface_geometries("mo1", 1))
|
||||
elif name == "fm":
|
||||
if self.beamline == "x01da":
|
||||
plot_surface(plot["widget"], mirror_surface_geometries("fm_flat"))
|
||||
plot_surface(plot["widget"], mirror_surface_geometries("fm_toroid"))
|
||||
plot_surface(plot["widget"], self.core.mirror_surface_geometries("fm_flat"))
|
||||
plot_surface(plot["widget"], self.core.mirror_surface_geometries("fm_toroid"))
|
||||
else:
|
||||
raise ValueError(f"Plot {name} not found!")
|
||||
for name, plot in self.plots.items():
|
||||
@@ -203,8 +202,9 @@ class SurfacePlots(QWidget):
|
||||
class SideviewPlot(QWidget):
|
||||
"""Plot widget with two curves and legend."""
|
||||
|
||||
def __init__(self, parent=None):
|
||||
def __init__(self, core, parent=None):
|
||||
super().__init__(parent=parent)
|
||||
self.core = core
|
||||
self._layout = QVBoxLayout(self)
|
||||
self._layout.setContentsMargins(4, 4, 4, 4)
|
||||
self._layout.setSpacing(0)
|
||||
@@ -303,7 +303,7 @@ class SideviewPlot(QWidget):
|
||||
|
||||
def plot_vacuum_pipes(self):
|
||||
"""Plot vacuum pipes"""
|
||||
pipes = pipe_geometries()
|
||||
pipes = self.core.pipe_geometries()
|
||||
for pipe in pipes:
|
||||
self.pipes.append(
|
||||
self.plot_widget.plot(
|
||||
@@ -313,7 +313,7 @@ class SideviewPlot(QWidget):
|
||||
|
||||
def plot_walls(self):
|
||||
"""Plot walls"""
|
||||
walls = wall_geometries()
|
||||
walls = self.core.wall_geometries()
|
||||
for wall in walls:
|
||||
rect = QGraphicsRectItem(wall[0], wall[1], wall[2], wall[3])
|
||||
rect.setBrush(QBrush(QColor(*self.color_impenetrable)))
|
||||
|
||||
@@ -27,5 +27,20 @@ class SettingsPanel(QWidget):
|
||||
"Axes Offsets", [self.load_offsets, self.offsets_status, self.show_offsets]
|
||||
)
|
||||
|
||||
self._layout.addWidget(self.offset_group)
|
||||
self.load_from_scan = Button(
|
||||
label="Load from Scan", label_button="Load from Scan", enabled=True
|
||||
)
|
||||
self.load_from_config = Button(
|
||||
label="Load from Config", label_button="Load from Config", enabled=True
|
||||
)
|
||||
self.save_config = Button(label="Save Config", label_button="Save Config", enabled=True)
|
||||
|
||||
self.import_export_group = Group(
|
||||
"Import/Export", [self.load_from_scan, self.load_from_config, self.save_config]
|
||||
)
|
||||
|
||||
# Assemble complete settings group
|
||||
self.settings_group = Group("Settings", [self.offset_group, self.import_export_group])
|
||||
|
||||
self._layout.addWidget(self.settings_group)
|
||||
self._layout.addStretch()
|
||||
@@ -1,7 +1,6 @@
|
||||
"""Move widget to display an axis and also move it through BEC"""
|
||||
|
||||
import threading
|
||||
import time
|
||||
from typing import Literal, Optional
|
||||
|
||||
from bec_lib import bec_logger
|
||||
@@ -11,24 +10,25 @@ from bec_widgets.utils.colors import get_accent_colors
|
||||
# pylint: disable=E0611
|
||||
from qtpy.QtCore import Property # type: ignore[attr-defined]
|
||||
from qtpy.QtCore import Signal # type: ignore[attr-defined]
|
||||
from qtpy.QtCore import QObject, QPropertyAnimation, Qt, QThread
|
||||
from qtpy.QtCore import QObject, QPropertyAnimation, Qt
|
||||
from qtpy.QtGui import QTransform
|
||||
from qtpy.QtWidgets import QApplication, QHBoxLayout, QLabel, QPushButton, QWidget
|
||||
from qtpy.QtWidgets import QApplication, QCheckBox, QHBoxLayout, QLabel, QPushButton, QWidget
|
||||
|
||||
# pylint: disable=E0402
|
||||
from .....devices.absorber import STATUS as ABS_STATUS
|
||||
from ..types import BeamlineId
|
||||
from .....bec_ipython_client.plugins.digital_twin_core.digital_twin_core import DigitalTwinCore
|
||||
from .....bec_ipython_client.plugins.digital_twin_core.motion_worker import (
|
||||
MotionOutcome,
|
||||
MotionWorker,
|
||||
)
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
|
||||
class Status:
|
||||
"""Status class for the axis"""
|
||||
|
||||
IN_POSITION = "in_position" # green mdi.check-circle
|
||||
NOT_IN_POSITION = "not_in_position" # orange mdi.close-circle
|
||||
MOVING = "moving" # blue mdi.loading (spinning)
|
||||
ERROR = "error" # red mdi.alert-circle
|
||||
IN_POSITION = "in_position" # green
|
||||
NOT_IN_POSITION = "not_in_position" # orange
|
||||
QUEUED = "queued" # grey, waiting for another motor group
|
||||
MOVING = "moving" # blue
|
||||
ERROR = "error" # red
|
||||
|
||||
|
||||
class StatusIcon(QWidget):
|
||||
@@ -44,6 +44,7 @@ class StatusIcon(QWidget):
|
||||
Status.NOT_IN_POSITION: ("cancel", "#e6d922"),
|
||||
Status.ERROR: ("warning", "#e74c3c"),
|
||||
Status.MOVING: ("cycle", "#2980b9"),
|
||||
Status.QUEUED: ("hourglass_empty", "#7f8c8d"),
|
||||
}
|
||||
|
||||
def __init__(self, parent=None):
|
||||
@@ -123,223 +124,13 @@ class StatusIcon(QWidget):
|
||||
self._label.setPixmap(icon)
|
||||
|
||||
|
||||
class MotionWorker(QObject):
|
||||
"""
|
||||
Executes motion on the specified motor and includes some safety during
|
||||
motion for certain motors.
|
||||
"""
|
||||
|
||||
class _WorkerSignals(QObject):
|
||||
position_changed = Signal(float)
|
||||
error = Signal()
|
||||
waiting = Signal() # must wait for another subgroup
|
||||
started = Signal() # slot acquired, motion begins
|
||||
finished = Signal()
|
||||
|
||||
def __init__(self, beamline: BeamlineId, dev, motor, target_pos: float):
|
||||
super().__init__()
|
||||
self.beamline = beamline
|
||||
self.dev = dev
|
||||
self.motor = motor
|
||||
self._target = target_pos
|
||||
self._stop_flag = threading.Event()
|
||||
|
||||
def stop(self):
|
||||
"""Sets the stop flag"""
|
||||
self._stop_flag.set()
|
||||
|
||||
def run(self):
|
||||
"""Prepares the movement based on the axis (motor)"""
|
||||
match self.motor:
|
||||
case "sldi_gapx" | "sldi_gapy" | "sldi_centerx" | "sldi_centery":
|
||||
self.motion()
|
||||
case "cm_trx":
|
||||
self.motion(
|
||||
abs_closed=True,
|
||||
surveyed_axes=[{"device": self.dev["cm_roty"], "abs_tol": 0.05}],
|
||||
)
|
||||
case "cm_roty":
|
||||
self.motion(
|
||||
abs_closed=True, surveyed_axes=[{"device": self.dev["cm_trx"], "abs_tol": 0.05}]
|
||||
)
|
||||
case "cm_try":
|
||||
self.motion(
|
||||
abs_closed=True,
|
||||
surveyed_axes=[
|
||||
{"device": self.dev["cm_rotx"], "abs_tol": 0.05},
|
||||
{"device": self.dev["cm_rotz"], "abs_tol": 0.05},
|
||||
],
|
||||
)
|
||||
case "cm_rotx":
|
||||
self.motion(
|
||||
abs_closed=True,
|
||||
surveyed_axes=[
|
||||
{"device": self.dev["cm_try"], "abs_tol": 0.05},
|
||||
{"device": self.dev["cm_rotz"], "abs_tol": 0.05},
|
||||
],
|
||||
)
|
||||
case "cm_rotz":
|
||||
self.motion(
|
||||
abs_closed=True,
|
||||
surveyed_axes=[
|
||||
{"device": self.dev["cm_try"], "abs_tol": 0.05},
|
||||
{"device": self.dev["cm_rotx"], "abs_tol": 0.05},
|
||||
],
|
||||
)
|
||||
case "cm_bnd":
|
||||
if self.beamline == "x01da":
|
||||
p1 = (
|
||||
1 / (self.dev.cm_bnd_radius.read()["cm_bnd_radius"]["value"] * 1e3) + 0.0284
|
||||
) / 2e-6
|
||||
p2 = (1 / (self._target * 1e3) + 0.0284) / 2e-6
|
||||
else:
|
||||
p1 = 541900 / self.dev.cm_bnd_radius.read()["cm_bnd_radius"]["value"] - 32570
|
||||
p2 = 541900 / self._target - 32570
|
||||
self._target = p2 - p1
|
||||
self.motion(relative=True, rb={"device": self.dev["cm_bnd_radius"]})
|
||||
case "mo1_try" | "mo1_trx" | "mo1_roty":
|
||||
self.motion(abs_closed=True)
|
||||
case "mo1_bragg_angle":
|
||||
if self.beamline == "x01da":
|
||||
self.motion()
|
||||
else: # x10da needs to move goniometer
|
||||
self.motion(alias="mo1_rotx")
|
||||
case "sl1_centery" | "sl1_gapy" | "bm1_try":
|
||||
self.motion()
|
||||
case "fm_trx":
|
||||
self.motion(
|
||||
abs_closed=True,
|
||||
surveyed_axes=[{"device": self.dev["fm_roty"], "abs_tol": 0.05}],
|
||||
)
|
||||
case "fm_roty":
|
||||
self.motion(
|
||||
abs_closed=True, surveyed_axes=[{"device": self.dev["fm_trx"], "abs_tol": 0.05}]
|
||||
)
|
||||
case "fm_try":
|
||||
if self.beamline == "x01da":
|
||||
abs_tol = 0.05
|
||||
else: # superxas mirror less stable thus needs higher tolerance
|
||||
abs_tol = 0.2
|
||||
self.motion(
|
||||
abs_closed=True,
|
||||
surveyed_axes=[
|
||||
{"device": self.dev["fm_rotx"], "abs_tol": abs_tol},
|
||||
{"device": self.dev["fm_rotz"], "abs_tol": abs_tol},
|
||||
],
|
||||
)
|
||||
case "fm_rotx":
|
||||
if self.beamline == "x01da":
|
||||
abs_tol = 0.05
|
||||
else: # superxas mirror less stable thus needs higher tolerance
|
||||
abs_tol = 0.2
|
||||
self.motion(
|
||||
abs_closed=True,
|
||||
surveyed_axes=[
|
||||
{"device": self.dev["fm_try"], "abs_tol": abs_tol},
|
||||
{"device": self.dev["fm_rotz"], "abs_tol": abs_tol},
|
||||
],
|
||||
)
|
||||
case "fm_rotz":
|
||||
if self.beamline == "x01da":
|
||||
abs_tol = 0.05
|
||||
else: # superxas mirror less stable thus needs higher tolerance
|
||||
abs_tol = 0.2
|
||||
self.motion(
|
||||
abs_closed=True,
|
||||
surveyed_axes=[
|
||||
{"device": self.dev["fm_try"], "abs_tol": abs_tol},
|
||||
{"device": self.dev["fm_rotx"], "abs_tol": abs_tol},
|
||||
],
|
||||
)
|
||||
case "fm_bnd":
|
||||
if self.beamline == "x01da":
|
||||
p1 = (
|
||||
1 / (self.dev.fm_bnd_radius.read()["fm_bnd_radius"]["value"] * 1e3)
|
||||
+ 4.28e-5
|
||||
) / 1.84e-9
|
||||
p2 = (1 / (self._target * 1e3) + 4.28e-5) / 1.84e-9
|
||||
else:
|
||||
p1 = (
|
||||
593088.7 / self.dev.fm_bnd_radius.read()["fm_bnd_radius"]["value"]
|
||||
+ 26124.41
|
||||
)
|
||||
p2 = 593088.7 / self._target + 26124.41
|
||||
self._target = p2 - p1
|
||||
self.motion(relative=True, rb={"device": self.dev["fm_bnd_radius"]})
|
||||
case "sl2_centery" | "sl2_gapy" | "bm2_try":
|
||||
self.motion()
|
||||
case "ot_try" | "ot_rotx" | "ot_es1_trz":
|
||||
self.motion()
|
||||
case "es0wi_try":
|
||||
self.motion()
|
||||
case "es1_try" | "es2_try":
|
||||
self.motion()
|
||||
case "es1ic0_try" | "es1ic1_try" | "es1ic2_try":
|
||||
self.motion()
|
||||
case _:
|
||||
logger.warning(f"Motor {self.motor} not integrated in digital twin!")
|
||||
|
||||
def motion(
|
||||
self,
|
||||
abs_closed: bool = False,
|
||||
relative: bool = False,
|
||||
rb=None,
|
||||
surveyed_axes=None,
|
||||
alias=None,
|
||||
):
|
||||
"""
|
||||
Moves an axis while surverying a set of axes (if set).
|
||||
Example surveyed_axes:
|
||||
[{'device': bec_device_object, 'abs_tol': 0.1},]
|
||||
|
||||
Args:
|
||||
surveyed_axes (list): List of dictionaries of devices
|
||||
"""
|
||||
try:
|
||||
if alias:
|
||||
self.motor = alias
|
||||
if abs_closed:
|
||||
if self.dev.abs.status.get() == ABS_STATUS.OPEN:
|
||||
status = self.dev.abs.close()
|
||||
# TODO Set timeout to 0.001 and check if it actually raises
|
||||
# (it should not start motion).
|
||||
# Check of behavior of digital twin afterwards.
|
||||
status.wait(timeout=5)
|
||||
if surveyed_axes is not None:
|
||||
for surv_ax in surveyed_axes:
|
||||
surv_ax["name"] = surv_ax["device"].dotted_name
|
||||
surv_ax["old_value"] = surv_ax["device"].read(cached=True)[surv_ax["name"]][
|
||||
"value"
|
||||
]
|
||||
if rb is not None:
|
||||
rb["name"] = rb["device"].dotted_name
|
||||
status = self.dev[self.motor].move(self._target, relative=relative)
|
||||
last_check = time.time()
|
||||
update_interval = 0.1
|
||||
while status.status == "RUNNING":
|
||||
now = time.time()
|
||||
if time.time() - last_check < update_interval:
|
||||
time.sleep(0.01)
|
||||
last_check = now
|
||||
if self._stop_flag.is_set():
|
||||
self.dev[self.motor].stop()
|
||||
self._stop_flag.clear()
|
||||
if rb is not None:
|
||||
self.position_changed.emit(rb["device"].read(cached=True)[rb["name"]]["value"])
|
||||
else:
|
||||
self.position_changed.emit(
|
||||
self.dev[self.motor].read(cached=True)[self.motor]["value"]
|
||||
)
|
||||
if surveyed_axes is not None:
|
||||
for surv_ax in surveyed_axes:
|
||||
fb = surv_ax["device"].read(cached=True)[surv_ax["name"]]["value"]
|
||||
if abs(fb - surv_ax["old_value"]) > surv_ax["abs_tol"]:
|
||||
self.dev[self.motor].stop()
|
||||
self.error.emit()
|
||||
self.finished.emit()
|
||||
break
|
||||
self.finished.emit()
|
||||
except:
|
||||
self.error.emit()
|
||||
self.finished.emit()
|
||||
|
||||
|
||||
class MoveWidget(QWidget):
|
||||
"""
|
||||
@@ -350,10 +141,23 @@ class MoveWidget(QWidget):
|
||||
- Start / Stop button
|
||||
"""
|
||||
|
||||
_STATUS_TOOLTIPS = {Status.QUEUED: "Waiting for other motors to finish"}
|
||||
|
||||
def __init__(
|
||||
self, beamline: BeamlineId, dev, motor, label: str = "", unit=None, decimals=3, deadband=0.0
|
||||
self,
|
||||
core: DigitalTwinCore,
|
||||
beamline,
|
||||
dev,
|
||||
motor,
|
||||
label="",
|
||||
unit=None,
|
||||
decimals=3,
|
||||
deadband=0.0,
|
||||
):
|
||||
super().__init__()
|
||||
self.core = core
|
||||
self._cancel: threading.Event | None = None
|
||||
|
||||
self.fb = 0.0
|
||||
self.target = 0
|
||||
self.beamline = beamline
|
||||
@@ -361,8 +165,9 @@ class MoveWidget(QWidget):
|
||||
self.motor = motor
|
||||
self.deadband = deadband
|
||||
self.status = Status.IN_POSITION
|
||||
self._thread: QThread | None = None
|
||||
self._thread: threading.Thread | None = None
|
||||
self._worker: MotionWorker | None = None
|
||||
self._signals: _WorkerSignals | None = None
|
||||
|
||||
self.text_color = (0, 0, 0)
|
||||
|
||||
@@ -373,6 +178,12 @@ class MoveWidget(QWidget):
|
||||
layout.setContentsMargins(4, 0, 4, 0)
|
||||
layout.setSpacing(4)
|
||||
|
||||
# Checkbox
|
||||
self.checkbox = QCheckBox()
|
||||
self.checkbox.setFixedWidth(20)
|
||||
self.checkbox.setChecked(True)
|
||||
layout.addWidget(self.checkbox)
|
||||
|
||||
# Name
|
||||
self.label = QLabel(label)
|
||||
self.label.setFixedWidth(76)
|
||||
@@ -397,7 +208,7 @@ class MoveWidget(QWidget):
|
||||
# Start / Stop button
|
||||
self.btn_action = QPushButton("Move")
|
||||
self.btn_action.setFixedWidth(64)
|
||||
self.btn_action.setFixedHeight(20)
|
||||
self.btn_action.setFixedHeight(24)
|
||||
self.btn_action.clicked.connect(self._on_button_clicked)
|
||||
layout.addWidget(self.btn_action)
|
||||
self.btn_mode = "start"
|
||||
@@ -437,6 +248,11 @@ class MoveWidget(QWidget):
|
||||
+ f"{{background-color: {get_accent_colors().emergency.name()}; color: white;}}"
|
||||
)
|
||||
|
||||
@property
|
||||
def is_busy(self) -> bool:
|
||||
"""True from start until the finished signal was handled (moving OR queued)."""
|
||||
return self._thread is not None
|
||||
|
||||
def set_target(self, target):
|
||||
"""Change the target value in the ui"""
|
||||
self.target = target
|
||||
@@ -473,13 +289,13 @@ class MoveWidget(QWidget):
|
||||
)
|
||||
|
||||
def _set_status(self, status: str):
|
||||
"""Set the current status icon in the ui"""
|
||||
self.status = status
|
||||
self.status_icon.set_status(status)
|
||||
self.status_icon.setToolTip(self._STATUS_TOOLTIPS.get(status, ""))
|
||||
|
||||
def _on_target_or_fb_changed(self):
|
||||
"""Re-evaluate in-position status whenever the target value changes."""
|
||||
if self.status in (Status.ERROR, Status.MOVING):
|
||||
if self.status in (Status.ERROR, Status.MOVING, Status.QUEUED):
|
||||
return
|
||||
if abs(self.fb - self.target) <= self.deadband:
|
||||
self._set_status(Status.IN_POSITION)
|
||||
@@ -487,35 +303,78 @@ class MoveWidget(QWidget):
|
||||
self._set_status(Status.NOT_IN_POSITION)
|
||||
|
||||
def _on_button_clicked(self):
|
||||
"""Starts or stops motion depending on current situation"""
|
||||
if self._thread and self._thread.isRunning():
|
||||
logger.info(f"Clicked on button, is busy: {self.is_busy}")
|
||||
if self.is_busy:
|
||||
self._stop_motion()
|
||||
else:
|
||||
self._start_motion()
|
||||
self.start_motion()
|
||||
|
||||
def _start_motion(self):
|
||||
"""Start a motion"""
|
||||
target = self.target
|
||||
if abs(target - self.fb) <= self.deadband:
|
||||
def start_motion(self, abort: threading.Event | None = None):
|
||||
"""Start a motion. `abort` is shared by a batch (Move Selection) so that one failure
|
||||
prevents the not-yet-started motors of that batch from starting."""
|
||||
logger.info(f"start_motion on motor {self.motor}")
|
||||
if self.is_busy:
|
||||
return
|
||||
if abs(self.target - self.fb) <= self.deadband:
|
||||
logger.info("Within deadband")
|
||||
self._set_status(Status.IN_POSITION)
|
||||
return
|
||||
|
||||
self._set_status(Status.MOVING)
|
||||
self._apply_button_style("stop")
|
||||
self._cancel = threading.Event()
|
||||
|
||||
self._worker = MotionWorker(self.beamline, self.dev, self.motor, target)
|
||||
self._thread = QThread()
|
||||
self._worker.moveToThread(self._thread)
|
||||
logger.info("Prepare stuff")
|
||||
|
||||
self._thread.started.connect(self._worker.run)
|
||||
self._worker.position_changed.connect(self._on_position_changed)
|
||||
self._worker.error.connect(self._on_error)
|
||||
self._worker.error.connect(self._thread.quit)
|
||||
self._worker.finished.connect(self._on_motion_finished)
|
||||
self._worker.finished.connect(self._thread.quit)
|
||||
self._thread.finished.connect(self._cleanup_thread)
|
||||
signals = _WorkerSignals()
|
||||
signals.waiting.connect(self._on_waiting)
|
||||
signals.started.connect(self._on_started)
|
||||
signals.position_changed.connect(self._on_position_changed)
|
||||
signals.error.connect(self._on_error)
|
||||
signals.finished.connect(self._on_motion_finished)
|
||||
signals.finished.connect(self._cleanup_thread)
|
||||
self._signals = signals
|
||||
|
||||
# No on_finished here: _run emits it exactly once (MotionWorker.run never calls
|
||||
# it for motors that are "not integrated in digital twin").
|
||||
worker = MotionWorker(
|
||||
self.beamline,
|
||||
self.dev,
|
||||
self.motor,
|
||||
self.target,
|
||||
on_position_changed=signals.position_changed.emit,
|
||||
on_error=signals.error.emit,
|
||||
)
|
||||
self._worker = worker
|
||||
self._thread = threading.Thread(
|
||||
target=self._run, args=(worker, signals, self._cancel, abort), daemon=True
|
||||
)
|
||||
logger.info("Start motion now...")
|
||||
self._thread.start()
|
||||
logger.info("Motion has started")
|
||||
|
||||
def _run(self, worker, signals, cancel, abort):
|
||||
try:
|
||||
logger.info("run_exclusive")
|
||||
self.core.run_exclusive(
|
||||
worker,
|
||||
abort=abort,
|
||||
cancel=cancel,
|
||||
on_waiting=signals.waiting.emit,
|
||||
on_started=signals.started.emit,
|
||||
)
|
||||
except Exception:
|
||||
logger.info("Exception")
|
||||
signals.error.emit()
|
||||
raise
|
||||
finally:
|
||||
logger.info("finally 2")
|
||||
signals.finished.emit()
|
||||
|
||||
def _on_waiting(self):
|
||||
self._set_status(Status.QUEUED)
|
||||
|
||||
def _on_started(self):
|
||||
self._set_status(Status.MOVING)
|
||||
|
||||
def _on_error(self):
|
||||
"""Called when an error occurs"""
|
||||
@@ -523,9 +382,11 @@ class MoveWidget(QWidget):
|
||||
self._apply_button_style("start")
|
||||
|
||||
def _stop_motion(self):
|
||||
"""Attempts to stop the motion"""
|
||||
"""Stop a running motor, or remove a queued one from the queue."""
|
||||
if self._cancel:
|
||||
self._cancel.set() # releases a waiting motor within ~0.1 s
|
||||
if self._worker:
|
||||
self._worker.stop()
|
||||
self._worker.stop() # stops a running motor
|
||||
|
||||
def _on_position_changed(self, pos: float):
|
||||
"""Change the feedback value in the ui"""
|
||||
@@ -547,20 +408,16 @@ class MoveWidget(QWidget):
|
||||
|
||||
def _cleanup_thread(self):
|
||||
"""Cleaning up of the mover thread"""
|
||||
if self._thread:
|
||||
self._thread.deleteLater()
|
||||
self._thread = None
|
||||
if self._worker:
|
||||
self._worker.deleteLater()
|
||||
self._worker = None
|
||||
self._thread = None
|
||||
self._worker = None
|
||||
self._signals = None
|
||||
|
||||
def shutdown(self):
|
||||
"""Cleaning up of the mover when shutting down the application"""
|
||||
if self._worker:
|
||||
self._worker.stop()
|
||||
if self._thread:
|
||||
self._thread.quit()
|
||||
self._thread.wait(2000) # max 2 s grace period
|
||||
if self._thread and self._thread.is_alive():
|
||||
self._thread.join(2.0) # max 2 s grace period
|
||||
|
||||
|
||||
class AbsorberWidget(QWidget):
|
||||
|
||||
@@ -106,10 +106,20 @@ class InputNumberField(QWidget):
|
||||
if prefix is not None:
|
||||
self.val.setPrefix(prefix + " ")
|
||||
layout.addWidget(self.val)
|
||||
self.ll = ll
|
||||
self.hl = hl
|
||||
|
||||
def set_number(self, number):
|
||||
self.val.setValue(number)
|
||||
|
||||
def set_range(self, ll, hl):
|
||||
self.val.setRange(ll, hl)
|
||||
self.ll = ll
|
||||
self.hl = hl
|
||||
|
||||
def get_range(self):
|
||||
return (self.ll, self.hl)
|
||||
|
||||
def has_focus(self) -> bool:
|
||||
return self.val.hasFocus()
|
||||
|
||||
@@ -157,6 +167,7 @@ class ComboBox(QWidget):
|
||||
func,
|
||||
identifier=self.identifier,
|
||||
value_obj=self.value,
|
||||
index=lambda: self.value.currentIndex(),
|
||||
value=lambda: self.value.currentText(),
|
||||
)
|
||||
)
|
||||
@@ -164,9 +175,14 @@ class ComboBox(QWidget):
|
||||
def setDisabled(self, disable):
|
||||
self.value.setDisabled(disable)
|
||||
|
||||
def get_all_texts(self) -> list[str]:
|
||||
return [self.value.itemText(i) for i in range(self.value.count())]
|
||||
|
||||
|
||||
class Button(QWidget):
|
||||
def __init__(self, label=None, label_button: str = "", enabled=False):
|
||||
def __init__(
|
||||
self, label=None, label_button: str = "", enabled: bool = False, color: str = "default"
|
||||
):
|
||||
super().__init__()
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(*ROW_MARGINS)
|
||||
@@ -176,28 +192,35 @@ class Button(QWidget):
|
||||
self.label.setFixedWidth(LABEL_WIDTH)
|
||||
layout.addWidget(self.label)
|
||||
self.button = QPushButton(label_button)
|
||||
self.enable_button(enabled)
|
||||
layout.addWidget(self.button)
|
||||
self.color = color
|
||||
self.setEnabled(enabled)
|
||||
|
||||
def clicked_connect(self, func):
|
||||
"""Connect a function to the button press."""
|
||||
self.button.clicked.connect(func)
|
||||
|
||||
def enable_button(self, enable: bool = False):
|
||||
if enable:
|
||||
self.button.setStyleSheet(
|
||||
f"QPushButton {{background-color: {get_accent_colors().default.name()}; color: white;}}"
|
||||
)
|
||||
self.button.setEnabled(True)
|
||||
else: # disabled
|
||||
self.button.setStyleSheet(
|
||||
"QPushButton {{background-color: rgb(120, 120, 120); color: white;}}"
|
||||
)
|
||||
self.button.setDisabled(True)
|
||||
def setEnabled(self, enable: bool = True):
|
||||
self.button.setEnabled(enable)
|
||||
self.apply_theme()
|
||||
|
||||
def setText(self, text):
|
||||
self.button.setText(text)
|
||||
|
||||
def setColor(self, color: str):
|
||||
self.color = color
|
||||
self.apply_theme()
|
||||
|
||||
def apply_theme(self):
|
||||
if self.button.isEnabled():
|
||||
colors = get_accent_colors()
|
||||
color = getattr(colors, self.color).name()
|
||||
self.button.setStyleSheet(f"QPushButton {{ background-color: {color}; color: white; }}")
|
||||
else:
|
||||
self.button.setStyleSheet(
|
||||
"QPushButton {{background-color: rgb(120, 120, 120); color: white;}}"
|
||||
)
|
||||
|
||||
|
||||
class TextIndicator(QWidget):
|
||||
def __init__(self, label):
|
||||
|
||||
+7812
File diff suppressed because it is too large.
Load diff
+7902
File diff suppressed because it is too large.
Load diff
@@ -21,10 +21,6 @@ logger = bec_logger.logger
|
||||
class RestartServer(BECWidget, QWidget):
|
||||
"""
|
||||
Main widget of server restart widget.
|
||||
|
||||
This widget has no visible UI of its own - it only drives the confirmation/
|
||||
progress dialog. The surrounding dock panel is hidden as soon as we can find
|
||||
it, so the user only ever sees the dialog, never an empty "Restart Server" tab.
|
||||
"""
|
||||
|
||||
PLUGIN = True
|
||||
|
||||
@@ -37,6 +37,8 @@ from ..edge_selector import EdgeSelector
|
||||
logger = bec_logger.logger
|
||||
|
||||
ALLOWED_SCANS = [
|
||||
"acquire",
|
||||
"line_scan",
|
||||
"xas_simple_scan",
|
||||
"xas_simple_scan_with_xrd",
|
||||
"xas_advanced_scan",
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,519 @@
|
||||
"""
|
||||
Function registry of the Scheduler widget.
|
||||
|
||||
A schedule item never stores executable code. It stores the *name* of a registered action plus
|
||||
JSON-serialisable parameters (`ScheduleItem.action` / `ScheduleItem.params`). At execution time
|
||||
the executor looks the action up in `ACTIONS` and calls its `run` function with an
|
||||
`ExecutionContext` (BEC shortcuts and beamline helpers) and the stored parameters. This replaces
|
||||
the former `eval` of command strings: only registered, reviewed functions can ever be executed,
|
||||
and a schedule stays saveable as plain JSON.
|
||||
|
||||
Adding a new item type means:
|
||||
|
||||
1. writing a `run(ctx, **params)` function (and a `describe(params, beamline)` function for the
|
||||
"Command" column),
|
||||
2. registering both with `register_action(ActionSpec(...))`,
|
||||
3. adding a page to `item_dialog.ScheduleItemDialog` that produces the parameters.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any, Callable, Literal
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover
|
||||
from .models import ScheduleItem
|
||||
|
||||
ActionCategory = Literal["scan", "move", "device", "delay", "control"]
|
||||
|
||||
#: Registry key of the "Wait until parent has completed" control item.
|
||||
WAIT_FOR_PARENT = "wait_for_parent"
|
||||
#: Registry key of the delay item.
|
||||
DELAY = "delay"
|
||||
|
||||
|
||||
class ActionInterrupted(Exception):
|
||||
"""Raised by an action that was interrupted by an abort of the schedule."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExecutionContext:
|
||||
"""
|
||||
Everything an action may need at execution time.
|
||||
|
||||
Attributes:
|
||||
scans: BEC scan shortcut (`client.scans`).
|
||||
dev: BEC device container (`client.device_manager.devices`).
|
||||
digital_twin: `DigitalTwinCore` instance, if available at this beamline.
|
||||
auto_gain: `AutoGainCore` instance, if available at this beamline.
|
||||
beamline: Beamline name, e.g. "x01da".
|
||||
abort_event: Set when the schedule is aborted or the widget is closed; long-running local
|
||||
actions (e.g. delays) must return early when it is set.
|
||||
"""
|
||||
|
||||
scans: Any
|
||||
dev: Any
|
||||
digital_twin: Any = None
|
||||
auto_gain: Any = None
|
||||
beamline: str | None = None
|
||||
abort_event: threading.Event = field(default_factory=threading.Event)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ActionSpec:
|
||||
"""
|
||||
Description of one registered schedule action.
|
||||
|
||||
Attributes:
|
||||
name: Registry key, stored in `ScheduleItem.action` (and therefore in Redis/JSON). Never
|
||||
rename the key of an existing action, or saved schedules can no longer be loaded.
|
||||
label: Human-readable name, e.g. for the item dialog.
|
||||
category: Used for notification filtering and execution rules:
|
||||
"scan" and "move" submit requests to the BEC scan server, "device" covers other
|
||||
device actions and beamline tools, "delay" is a local wait and "control" items only
|
||||
steer the schedule itself.
|
||||
run: `run(ctx, **params) -> handle`. May block until done, or return a handle with
|
||||
`wait()` (and optionally `cancel()`), e.g. a BEC `ScanReport`. `None` for control
|
||||
actions, which are handled by the executor itself.
|
||||
describe: `describe(params, beamline) -> str`, the text of the "Command" column.
|
||||
report: Optional `report(handle, item, ctx) -> str | None`, the text of the "Report"
|
||||
column after a successful execution. Defaults to `default_report`.
|
||||
cancellable: True if the returned handle supports `cancel()` (e.g. scans/moves), so that
|
||||
the item can be interrupted when the schedule is aborted or a beamline state trips.
|
||||
"""
|
||||
|
||||
name: str
|
||||
label: str
|
||||
category: ActionCategory
|
||||
run: Callable[..., Any] | None
|
||||
describe: Callable[[dict, str | None], str]
|
||||
report: Callable[[Any, "ScheduleItem", ExecutionContext], str | None] | None = None
|
||||
cancellable: bool = False
|
||||
|
||||
|
||||
ACTIONS: dict[str, ActionSpec] = {}
|
||||
|
||||
|
||||
def register_action(spec: ActionSpec) -> ActionSpec:
|
||||
"""
|
||||
Add an action to the registry.
|
||||
|
||||
Args:
|
||||
spec: The action to register.
|
||||
|
||||
Returns:
|
||||
The registered spec (so this can be used inline).
|
||||
|
||||
Raises:
|
||||
ValueError: If an action with the same name is already registered.
|
||||
"""
|
||||
if spec.name in ACTIONS:
|
||||
raise ValueError(f"A schedule action named {spec.name!r} is already registered.")
|
||||
ACTIONS[spec.name] = spec
|
||||
return spec
|
||||
|
||||
|
||||
def get_action(name: str) -> ActionSpec:
|
||||
"""
|
||||
Look up a registered action.
|
||||
|
||||
Raises:
|
||||
KeyError: If no action with this name is registered.
|
||||
"""
|
||||
try:
|
||||
return ACTIONS[name]
|
||||
except KeyError:
|
||||
raise KeyError(f"Unknown schedule action {name!r}.") from None
|
||||
|
||||
|
||||
def run_action(ctx: ExecutionContext, action: str, params: dict) -> Any:
|
||||
"""
|
||||
Execute a registered action - the single dispatch point used by the executor.
|
||||
|
||||
Args:
|
||||
ctx: Execution context.
|
||||
action: Registry key of the action.
|
||||
params: Keyword arguments for the action's `run` function.
|
||||
|
||||
Returns:
|
||||
Whatever the action returns (e.g. a `ScanReport` to wait on), or None.
|
||||
|
||||
Raises:
|
||||
KeyError: If the action is not registered.
|
||||
ValueError: If the action is a control action that cannot be run directly.
|
||||
"""
|
||||
spec = get_action(action)
|
||||
if spec.run is None:
|
||||
raise ValueError(f"Schedule action {action!r} is handled by the executor.")
|
||||
return spec.run(ctx, **params)
|
||||
|
||||
|
||||
def describe_item(item: "ScheduleItem", beamline: str | None) -> str:
|
||||
"""
|
||||
Text for the "Command" column of an item. Never raises: an unknown action or malformed
|
||||
parameters fall back to a generic representation.
|
||||
"""
|
||||
spec = ACTIONS.get(item.action)
|
||||
if spec is None:
|
||||
return f"Unknown action '{item.action}' {item.params}"
|
||||
try:
|
||||
return spec.describe(item.params, beamline)
|
||||
except Exception: # pylint: disable=broad-except
|
||||
return f"{spec.label} {item.params}"
|
||||
|
||||
|
||||
def default_report(handle: Any, item: "ScheduleItem", _ctx: ExecutionContext) -> str | None:
|
||||
"""Fallback "Report" text: the scan number, or a short summary of a returned value."""
|
||||
if item.scan_number is not None:
|
||||
return f"Scan #{item.scan_number} done"
|
||||
if handle is None or hasattr(handle, "wait"):
|
||||
return "Done"
|
||||
text = str(handle)
|
||||
return text if len(text) <= 120 else text[:117] + "..."
|
||||
|
||||
|
||||
def format_duration(seconds: float) -> str:
|
||||
"""Format a duration as e.g. "1 h 05 min 00 s" / "2 min 30 s" / "12 s"."""
|
||||
seconds = max(0, int(round(seconds)))
|
||||
hours, rest = divmod(seconds, 3600)
|
||||
minutes, secs = divmod(rest, 60)
|
||||
if hours:
|
||||
return f"{hours} h {minutes:02d} min {secs:02d} s"
|
||||
if minutes:
|
||||
return f"{minutes} min {secs:02d} s"
|
||||
return f"{secs} s"
|
||||
|
||||
|
||||
def _format_call(name: str, args: list, kwargs: dict) -> str:
|
||||
parts = [repr(a) for a in args]
|
||||
parts += [f"{key}={value!r}" for key, value in kwargs.items()]
|
||||
return f"{name}({', '.join(parts)})"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
# Scan
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
def _run_scan(ctx: ExecutionContext, scan_name: str, args: list | None = None, kwargs=None):
|
||||
scan = getattr(ctx.scans, scan_name, None)
|
||||
if scan is None or scan_name.startswith("_"):
|
||||
raise ValueError(f"Scan {scan_name!r} is not available in this BEC session.")
|
||||
return scan(*(args or []), **(kwargs or {}))
|
||||
|
||||
|
||||
def _describe_scan(params: dict, _beamline: str | None) -> str:
|
||||
scan_name = params["scan_name"]
|
||||
kwargs = params.get("kwargs") or {}
|
||||
if scan_name == "xas_simple_scan":
|
||||
metadata = kwargs.get("metadata") or {}
|
||||
return (
|
||||
f"XAS simple scan from {kwargs.get('start')} eV to {kwargs.get('stop')} eV, "
|
||||
f"{kwargs.get('scan_time')} s per spectrum, measure {kwargs.get('scan_duration')} s"
|
||||
f"\nComment: {metadata.get('comment', '')}, "
|
||||
f"Sample Name: {metadata.get('sample_name', '')}"
|
||||
)
|
||||
return _format_call(f"scans.{scan_name}", params.get("args") or [], kwargs)
|
||||
|
||||
|
||||
register_action(
|
||||
ActionSpec(
|
||||
name="scan",
|
||||
label="Scan",
|
||||
category="scan",
|
||||
run=_run_scan,
|
||||
describe=_describe_scan,
|
||||
cancellable=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
# Move
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
def _run_move(ctx: ExecutionContext, device: str, value: float, relative: bool = False, **_):
|
||||
return ctx.dev[device].move(value, relative=relative)
|
||||
|
||||
|
||||
def _describe_move(params: dict, _beamline: str | None) -> str:
|
||||
units = params.get("units", "")
|
||||
if params.get("relative"):
|
||||
return f"Move {params['device']} by {params['value']:+g} {units}".rstrip()
|
||||
return f"Move {params['device']} to {params['value']:g} {units}".rstrip()
|
||||
|
||||
|
||||
def _report_move(_handle, item: "ScheduleItem", ctx: ExecutionContext) -> str | None:
|
||||
device = item.params["device"]
|
||||
try:
|
||||
position = ctx.dev[device].position
|
||||
return f"Moved to {position:g} {item.params.get('units', '')}".rstrip()
|
||||
except Exception: # pylint: disable=broad-except
|
||||
return "Done"
|
||||
|
||||
|
||||
register_action(
|
||||
ActionSpec(
|
||||
name="move",
|
||||
label="Move",
|
||||
category="move",
|
||||
run=_run_move,
|
||||
describe=_describe_move,
|
||||
report=_report_move,
|
||||
cancellable=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
# Digital twin (X01DA / X10DA)
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
def _run_digital_twin(ctx: ExecutionContext, config: dict):
|
||||
if ctx.digital_twin is None:
|
||||
raise RuntimeError("The digital twin is not available at this beamline.")
|
||||
result = ctx.digital_twin.move_with_config(config)
|
||||
if isinstance(result, dict) and not result.get("success", True):
|
||||
details = {key: result[key] for key in ("failures", "aborted") if result.get(key)}
|
||||
raise RuntimeError(f"Beamline alignment did not complete: {details}")
|
||||
|
||||
|
||||
def _describe_digital_twin(params: dict, beamline: str | None) -> str:
|
||||
config = params["config"]
|
||||
monochromatic = config["mo1_mode"] == "Monochromatic"
|
||||
text = (
|
||||
f"Align beamline for {config['energy']:.0f} eV"
|
||||
if monochromatic
|
||||
else "Align beamline for pink beam"
|
||||
)
|
||||
text += (
|
||||
f"\nFE: {config['h_acc'] * 1e3:.3f} mrad x {config['v_acc'] * 1e3:.3f} mrad"
|
||||
f"\nCM: {config['cm_stripe']} at {config['cm_pitch'] * 1e3:.3f} mrad"
|
||||
)
|
||||
if monochromatic:
|
||||
text += f"\nMO1: {config['mo1_xtal']}"
|
||||
text += f"\nFM: {config['fm_stripe']} at {config['fm_rotx'] * 1e3:.3f} mrad"
|
||||
if beamline == "x01da":
|
||||
text += f"\nES1: {config['ot_es1_trz']:.0f} mm"
|
||||
text += f"\nSMPL_TRZ: {config['es1man_trz']:.3f} mm"
|
||||
if beamline == "x01da":
|
||||
text += f"\nSMPL-XRD: {config['smpl_to_xrd']:.3f} mm"
|
||||
return text
|
||||
|
||||
|
||||
register_action(
|
||||
ActionSpec(
|
||||
name="digital_twin",
|
||||
label="Digital Twin",
|
||||
category="device",
|
||||
run=_run_digital_twin,
|
||||
describe=_describe_digital_twin,
|
||||
report=lambda *_: "Beamline aligned",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
# Auto-gain (X01DA / X10DA)
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
def _run_auto_gain(ctx: ExecutionContext, config: dict):
|
||||
if ctx.auto_gain is None:
|
||||
raise RuntimeError("Auto-gain is not available at this beamline.")
|
||||
return ctx.auto_gain.start(
|
||||
element=config["element"],
|
||||
edge=config["edge"],
|
||||
amplifier=config["all_amplifiers"],
|
||||
link_ic0_ic1=config["link_ic0_ic1"],
|
||||
comp_ring_current=config["compensate_ring_current"],
|
||||
prohibited_gains=config["prohibited_gains"],
|
||||
)
|
||||
|
||||
|
||||
def _describe_auto_gain(params: dict, _beamline: str | None) -> str:
|
||||
config = params["config"]
|
||||
text = f"Auto-configure gains for {config['element']}, {config['edge']}-edge"
|
||||
text += f"\nfor devices {config['all_amplifiers']}"
|
||||
if config["link_ic0_ic1"]:
|
||||
text += "\nLink IC0 and IC1 gains"
|
||||
if config["compensate_ring_current"]:
|
||||
text += "\nCalculate for 400 mA ring current"
|
||||
if config["prohibited_gains"]:
|
||||
prohibited = ", ".join(
|
||||
f"{amp}: [" + ", ".join(f"{gain:.0e}" for gain in gains) + "]"
|
||||
for amp, gains in config["prohibited_gains"].items()
|
||||
)
|
||||
text += f"\nProhibited gains: {{{prohibited}}}"
|
||||
return text
|
||||
|
||||
|
||||
def _report_auto_gain(handle, _item, _ctx) -> str | None:
|
||||
if isinstance(handle, dict) and handle:
|
||||
return "Gains: " + ", ".join(
|
||||
f"{key}={value:.0e}" if isinstance(value, (int, float)) else f"{key}={value}"
|
||||
for key, value in handle.items()
|
||||
)
|
||||
return "Done"
|
||||
|
||||
|
||||
register_action(
|
||||
ActionSpec(
|
||||
name="auto_gain",
|
||||
label="Auto Gain",
|
||||
category="device",
|
||||
run=_run_auto_gain,
|
||||
describe=_describe_auto_gain,
|
||||
report=_report_auto_gain,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
# Absorber
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
ABSORBER_ACTIONS = ("Open", "Force open", "Close")
|
||||
|
||||
|
||||
def _run_absorber(ctx: ExecutionContext, action: str):
|
||||
absorber = ctx.dev["abs"]
|
||||
if action == "Open":
|
||||
return absorber.open()
|
||||
if action == "Force open":
|
||||
return absorber.open(force=True)
|
||||
if action == "Close":
|
||||
return absorber.close()
|
||||
raise ValueError(f"Unknown absorber action {action!r}.")
|
||||
|
||||
|
||||
register_action(
|
||||
ActionSpec(
|
||||
name="absorber",
|
||||
label="Absorber",
|
||||
category="device",
|
||||
run=_run_absorber,
|
||||
describe=lambda params, _bl: f"{params['action']} absorber",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
# Ionization chamber gas filling
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
def _run_ic_fill(
|
||||
ctx: ExecutionContext,
|
||||
chamber: str,
|
||||
gas1: str,
|
||||
conc1: float,
|
||||
gas2: str,
|
||||
conc2: float,
|
||||
pressure: float,
|
||||
):
|
||||
return ctx.dev[chamber.lower()].fill(
|
||||
gas1=gas1, conc1=conc1, gas2=gas2, conc2=conc2, pressure=pressure, wait=True
|
||||
)
|
||||
|
||||
|
||||
register_action(
|
||||
ActionSpec(
|
||||
name="ic_fill",
|
||||
label="Ionization Chamber",
|
||||
category="device",
|
||||
run=_run_ic_fill,
|
||||
describe=lambda p, _bl: (
|
||||
f"Fill {p['chamber']} with {p['conc1']:g} % {p['gas1']} and {p['conc2']:g} % "
|
||||
f"{p['gas2']} to {p['pressure']:g} bar"
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
# Reference foil changer
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
def _run_reffoil(ctx: ExecutionContext, foil: str):
|
||||
return ctx.dev["reffoilchanger"].insert(ref=foil, wait=True)
|
||||
|
||||
|
||||
register_action(
|
||||
ActionSpec(
|
||||
name="reffoil",
|
||||
label="Reference foil changer",
|
||||
category="device",
|
||||
run=_run_reffoil,
|
||||
describe=lambda params, _bl: f"Insert {params['foil']} reference foil",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
# Temperature controller
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
def _run_temperature_controller(ctx: ExecutionContext, config: dict):
|
||||
# Pass plain values: the device builds its own ConfigDict from them, so no pydantic object
|
||||
# has to be stored in (or sent from) the schedule.
|
||||
return ctx.dev["univ_temp_cont"].load_config(
|
||||
power_mode=config["power_mode"],
|
||||
target_setpoint=config["target_setpoint"],
|
||||
ramp_rate=config["ramp_rate"],
|
||||
ramp_rate_unit=config["ramp_rate_unit"],
|
||||
)
|
||||
|
||||
|
||||
def _describe_temperature_controller(params: dict, _beamline: str | None) -> str:
|
||||
config = params["config"]
|
||||
match config["power_mode"]:
|
||||
case "Standby":
|
||||
return "Switch temperature controller to standby"
|
||||
case "Configuration":
|
||||
return "Switch temperature controller to configuration mode"
|
||||
case _:
|
||||
return (
|
||||
f"Set temperature controller to {config['target_setpoint']} °C"
|
||||
f"\nwith ramp rate of {config['ramp_rate']} {config['ramp_rate_unit']}"
|
||||
)
|
||||
|
||||
|
||||
register_action(
|
||||
ActionSpec(
|
||||
name="temperature_controller",
|
||||
label="Temperature Controller",
|
||||
category="device",
|
||||
run=_run_temperature_controller,
|
||||
describe=_describe_temperature_controller,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
# Delay
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
def _run_delay(ctx: ExecutionContext, seconds: float):
|
||||
# Event.wait instead of time.sleep, so that aborting the schedule interrupts the delay.
|
||||
if ctx.abort_event.wait(timeout=max(0.0, float(seconds))):
|
||||
raise ActionInterrupted("Delay interrupted.")
|
||||
|
||||
|
||||
register_action(
|
||||
ActionSpec(
|
||||
name=DELAY,
|
||||
label="Delay",
|
||||
category="delay",
|
||||
run=_run_delay,
|
||||
describe=lambda params, _bl: f"Delay for {format_duration(params['seconds'])}",
|
||||
report=lambda _h, item, _c: f"Waited {format_duration(item.params['seconds'])}",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
# Wait until parent has completed (control item, executed by the executor itself)
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
register_action(
|
||||
ActionSpec(
|
||||
name=WAIT_FOR_PARENT,
|
||||
label="Wait until parent has completed",
|
||||
category="control",
|
||||
run=None,
|
||||
describe=lambda _params, _bl: "Wait until parent has completed",
|
||||
report=lambda *_: "Parent completed",
|
||||
)
|
||||
)
|
||||
|
||||
#: Actions that always block until done; "wait for completion" cannot be switched off for them.
|
||||
ALWAYS_WAIT_ACTIONS = frozenset({DELAY, WAIT_FOR_PARENT})
|
||||
@@ -0,0 +1,61 @@
|
||||
"""
|
||||
Redis endpoint(s) for the schedule widget plugin.
|
||||
|
||||
Design notes (why this looks the way it does)
|
||||
-----------------------------------------------
|
||||
BEC never touches Redis with raw keys/commands. Every channel is described
|
||||
by an `EndpointInfo` (endpoint string + message type + allowed operations,
|
||||
see `bec_lib.endpoints`), and `RedisConnector` enforces both: calling an
|
||||
operation that isn't in the endpoint's `MessageOp` raises
|
||||
`IncompatibleRedisOperation`, and passing a message that isn't an instance
|
||||
of the endpoint's declared `message_type` raises
|
||||
`IncompatibleMessageForEndpoint`. Plain string topics still work but are
|
||||
deprecated. So a "conforming" custom endpoint means building a real
|
||||
`EndpointInfo`, exactly like `bec_lib.endpoints.MessageEndpoints` does
|
||||
internally.
|
||||
|
||||
Namespace: we use `EndpointType.USER` ("user/...”), the same prefix BEC's
|
||||
own `MessageEndpoints.scan_queue_schedule()` uses for user-writable,
|
||||
persisted data (as opposed to `internal/`, `public/`, etc.).
|
||||
|
||||
Message type: we deliberately do NOT declare our own `BECMessage`
|
||||
subclass. BEC's msgpack codec (`bec_lib.codecs.BECMessageEncoder.decode`)
|
||||
resolves an incoming message's class by name via
|
||||
`getattr(bec_lib.messages, type_name)` - i.e. only classes physically
|
||||
defined inside `bec_lib.messages` are resolvable this way. A message class
|
||||
declared in plugin code would fail to deserialize unless you monkey-patch
|
||||
it into that module, which is exactly the kind of side-door this plugin
|
||||
is meant to avoid. Instead we reuse `bec_lib.messages.VariableMessage`,
|
||||
a first-class, exported message type built for carrying an arbitrary
|
||||
(msgpack-serializable) payload under `.value`.
|
||||
`bec_lib.script_executor.upload_script` persists a script's text in Redis
|
||||
the same way, for the same reason - it's the established BEC pattern for
|
||||
"a plugin needs to stash its own structured data in Redis".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from bec_lib.endpoints import EndpointInfo, EndpointType, MessageOp
|
||||
from bec_lib.messages import VariableMessage
|
||||
|
||||
|
||||
def schedule(schedule_name: str) -> EndpointInfo:
|
||||
"""
|
||||
Endpoint for one named widget schedule (an ordered list of commands
|
||||
plus their execution status). The whole schedule is stored as a single
|
||||
`VariableMessage` document that gets overwritten and republished on
|
||||
every change (`MessageOp.SET_PUBLISH`), so any other subscriber -
|
||||
another instance of this widget, a monitoring script, ... - stays in
|
||||
sync live.
|
||||
|
||||
Args:
|
||||
schedule_name: a stable, user-chosen name for the schedule. Unlike
|
||||
a widget's `gui_id` (regenerated every time the widget is
|
||||
constructed), this name is what lets a widget that was closed
|
||||
and reopened find its own previously persisted schedule again.
|
||||
"""
|
||||
return EndpointInfo(
|
||||
endpoint=f"{EndpointType.USER.value}/schedule_widget/schedule/{schedule_name}",
|
||||
message_type=VariableMessage,
|
||||
message_op=MessageOp.SET_PUBLISH,
|
||||
)
|
||||
@@ -0,0 +1,442 @@
|
||||
"""
|
||||
Execution engine of the Scheduler widget.
|
||||
|
||||
`ScheduleExecutor.run` is executed on a worker thread (started by the widget through
|
||||
`BECWidget.submit_task`). It never touches Qt widgets: all state changes are written to the
|
||||
shared `Schedule` under the widget's lock, persisted to Redis through `persist_locked`, and the
|
||||
GUI is told to redraw through `emit_changed` (which emits a Qt signal, marshalled onto the GUI
|
||||
thread).
|
||||
|
||||
Execution rules
|
||||
---------------
|
||||
- Items run top to bottom. The next item is re-derived after every step
|
||||
(`schedule_logic.pick_next_runnable`), so PENDING items can be added, edited, moved or deleted
|
||||
while the schedule runs.
|
||||
- `wait_for_completion=True` (default): the item is run and waited for before continuing.
|
||||
- `wait_for_completion=False` ("background item"): the item is started on its own thread and the
|
||||
schedule continues with the items of its block (see `schedule_logic`). Before an item outside
|
||||
that block starts, and at a "Wait until parent has completed" item, the executor waits for the
|
||||
background item to complete. Children keep running if the parent finishes first.
|
||||
- `pause_on_state=True`: before the item starts, the executor waits until all beamline states
|
||||
are VALID or WARNING. If a state turns INVALID while such an item is a running scan, the scan
|
||||
is cancelled, the item is reset to PENDING and repeated once the states have recovered. Other
|
||||
item types are not interrupted.
|
||||
- `pause_on_failure=True`: a failure of the item pauses the schedule after the current step;
|
||||
otherwise the schedule continues with the next item.
|
||||
- "Pause after current item" lets running items finish; "Pause now" (abort) additionally cancels
|
||||
running scans/moves and interrupts delays.
|
||||
- Closing the widget stops the loop without cancelling anything server-side; the widget
|
||||
reconciles the persisted state with the BEC queue when it is opened again.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable, Literal
|
||||
|
||||
from bec_lib.logger import bec_logger
|
||||
|
||||
from .actions import (
|
||||
WAIT_FOR_PARENT,
|
||||
ActionInterrupted,
|
||||
ActionSpec,
|
||||
ExecutionContext,
|
||||
default_report,
|
||||
get_action,
|
||||
run_action,
|
||||
)
|
||||
from .models import ItemStatus, ScheduleItem
|
||||
from .schedule_logic import block_parents, index_of, pick_next_runnable
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
RunOutcome = Literal["finished", "aborted", "paused", "paused_on_failure", "widget_closed"]
|
||||
|
||||
_ACTIVE_QUEUE_STATES = ("PENDING", "RUNNING")
|
||||
_POLL_INTERVAL = 0.2
|
||||
|
||||
|
||||
def is_queue_item_active(queue_item: Any) -> bool:
|
||||
"""True if a BEC queue item is still pending or running server-side."""
|
||||
return str(getattr(queue_item, "status", "")).upper() in _ACTIVE_QUEUE_STATES
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Execution:
|
||||
"""Bookkeeping of one item that is currently being executed."""
|
||||
|
||||
item: ScheduleItem
|
||||
spec: ActionSpec
|
||||
handle: Any = None
|
||||
interrupted: bool = False # cancelled because a beamline state tripped -> repeat later
|
||||
done: threading.Event = field(default_factory=threading.Event)
|
||||
|
||||
|
||||
class ScheduleExecutor:
|
||||
"""
|
||||
Runs the items of a schedule (see the module docstring for the rules).
|
||||
|
||||
Args:
|
||||
lock: The widget's lock guarding the schedule.
|
||||
get_items: Returns the live list of schedule items. Only called while holding `lock`.
|
||||
persist_locked: Writes the schedule to Redis; only called while holding `lock`.
|
||||
emit_changed: Thread-safe "please redraw" callback.
|
||||
context: Execution context handed to the registered actions.
|
||||
state_monitor: Object with `is_ok()`, `wait_until_ok(should_abort)` and
|
||||
`blocking_states()` (normally a `BeamlineStateMonitor`).
|
||||
notify_item: Called (without lock) with an item after it COMPLETED, FAILED or ABORTED.
|
||||
get_queue_storage: Returns BEC's queue storage; used to re-attach to requests that are
|
||||
still running from a previous widget session.
|
||||
closing: Set by the widget when it is being closed.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
lock: threading.Lock,
|
||||
get_items: Callable[[], list[ScheduleItem]],
|
||||
persist_locked: Callable[[], None],
|
||||
emit_changed: Callable[[], None],
|
||||
context: ExecutionContext,
|
||||
state_monitor: Any,
|
||||
notify_item: Callable[[ScheduleItem], None],
|
||||
get_queue_storage: Callable[[], Any],
|
||||
closing: threading.Event,
|
||||
) -> None:
|
||||
self._lock = lock
|
||||
self._get_items = get_items
|
||||
self._persist_locked = persist_locked
|
||||
self._emit_changed = emit_changed
|
||||
self._ctx = context
|
||||
self._state_monitor = state_monitor
|
||||
self._notify_item = notify_item
|
||||
self._get_queue_storage = get_queue_storage
|
||||
self._closing = closing
|
||||
|
||||
self._abort = threading.Event()
|
||||
self._pause = threading.Event()
|
||||
self._paused_on_failure = False
|
||||
self._foreground: _Execution | None = None
|
||||
self._background: _Execution | None = None
|
||||
self._attempted: set[str] = set()
|
||||
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
# Control (called from the GUI thread)
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
def request_pause(self) -> None:
|
||||
"""Stop after the running item(s) have finished ("Pause after current item")."""
|
||||
self._pause.set()
|
||||
|
||||
def request_abort(self) -> None:
|
||||
"""Stop now: cancel running scans/moves and interrupt delays ("Pause now")."""
|
||||
self._abort.set()
|
||||
self._ctx.abort_event.set()
|
||||
for execution in (self._foreground, self._background):
|
||||
if execution is not None and not execution.done.is_set():
|
||||
self._cancel(execution)
|
||||
|
||||
def notify_closing(self) -> None:
|
||||
"""The widget is closing: interrupt local waits, but do not cancel server-side work."""
|
||||
self._ctx.abort_event.set()
|
||||
|
||||
def on_states_tripped(self) -> None:
|
||||
"""
|
||||
A beamline state became INVALID: cancel running scans that have `pause_on_state` set.
|
||||
They are reset to PENDING and repeated once the states have recovered.
|
||||
"""
|
||||
for execution in (self._foreground, self._background):
|
||||
if execution is None or execution.done.is_set():
|
||||
continue
|
||||
if not (execution.item.pause_on_state and execution.spec.cancellable):
|
||||
continue
|
||||
if execution.spec.category != "scan":
|
||||
continue
|
||||
logger.info(f"Beamline state tripped: interrupting scan item {execution.item.item_id}")
|
||||
execution.interrupted = True
|
||||
self._cancel(execution)
|
||||
|
||||
def active_item_ids(self) -> set[str]:
|
||||
"""Ids of the items currently executed by this executor."""
|
||||
return {
|
||||
execution.item.item_id
|
||||
for execution in (self._foreground, self._background)
|
||||
if execution is not None and not execution.done.is_set()
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
# Main loop (worker thread)
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
def run(self, first_item_id: str | None = None, retry_unfinished: bool = False) -> RunOutcome:
|
||||
"""
|
||||
Execute the schedule until it is finished, paused, aborted or the widget is closed.
|
||||
|
||||
Args:
|
||||
first_item_id: Start with this item; items above it are ignored. None starts at the
|
||||
top (already COMPLETED items are always skipped).
|
||||
retry_unfinished: Run FAILED and ABORTED items again (once each).
|
||||
|
||||
Returns:
|
||||
Why the run ended.
|
||||
"""
|
||||
self._abort.clear()
|
||||
self._pause.clear()
|
||||
self._ctx.abort_event.clear()
|
||||
self._paused_on_failure = False
|
||||
self._attempted = set()
|
||||
self._background = None
|
||||
self._foreground = None
|
||||
|
||||
outcome: RunOutcome = "finished"
|
||||
while True:
|
||||
outcome = self._stop_reason()
|
||||
if outcome != "finished":
|
||||
break
|
||||
if self._background is not None and self._background.done.is_set():
|
||||
self._background = None
|
||||
|
||||
with self._lock:
|
||||
items = self._get_items()
|
||||
first_index = index_of(items, first_item_id) or 0
|
||||
item = pick_next_runnable(
|
||||
items,
|
||||
retry_unfinished=retry_unfinished,
|
||||
first_index=first_index,
|
||||
active_ids=self.active_item_ids(),
|
||||
attempted_ids=self._attempted,
|
||||
)
|
||||
in_background_block = False
|
||||
if item is not None and self._background is not None:
|
||||
parent = block_parents(items)[index_of(items, item.item_id)]
|
||||
in_background_block = (
|
||||
parent is not None
|
||||
and items[parent].item_id == self._background.item.item_id
|
||||
)
|
||||
|
||||
if item is None:
|
||||
break
|
||||
if self._background is not None and not in_background_block:
|
||||
# Leaving the block of the running background item: wait for it first.
|
||||
self._join_background()
|
||||
continue
|
||||
if item.status == ItemStatus.RUNNING:
|
||||
self._reattach(item)
|
||||
continue
|
||||
if item.action == WAIT_FOR_PARENT:
|
||||
self._run_wait_for_parent(item)
|
||||
continue
|
||||
if item.pause_on_state and not self._wait_for_states(item):
|
||||
continue
|
||||
|
||||
execution = self._start(item)
|
||||
if item.wait_for_completion:
|
||||
self._foreground = execution
|
||||
self._execute(execution)
|
||||
self._foreground = None
|
||||
else:
|
||||
self._background = execution
|
||||
threading.Thread(
|
||||
target=self._execute,
|
||||
args=(execution,),
|
||||
name=f"scheduler-background-{item.item_id}",
|
||||
daemon=True,
|
||||
).start()
|
||||
|
||||
if outcome != "widget_closed":
|
||||
self._join_background()
|
||||
if self._closing.is_set():
|
||||
return "widget_closed"
|
||||
if outcome == "finished":
|
||||
# The loop may also have ended because a pause/abort happened while joining.
|
||||
outcome = self._stop_reason()
|
||||
return outcome
|
||||
|
||||
def _stop_reason(self) -> RunOutcome:
|
||||
if self._closing.is_set():
|
||||
return "widget_closed"
|
||||
if self._abort.is_set():
|
||||
return "aborted"
|
||||
if self._pause.is_set():
|
||||
return "paused_on_failure" if self._paused_on_failure else "paused"
|
||||
return "finished"
|
||||
|
||||
def _should_stop_waiting(self) -> bool:
|
||||
return self._closing.is_set() or self._abort.is_set() or self._pause.is_set()
|
||||
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
# Steps
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
def _start(self, item: ScheduleItem) -> _Execution:
|
||||
spec = get_action(item.action)
|
||||
with self._lock:
|
||||
item.reset_execution()
|
||||
item.status = ItemStatus.RUNNING
|
||||
item.started_at = time.time()
|
||||
self._attempted.add(item.item_id)
|
||||
self._persist_locked()
|
||||
self._emit_changed()
|
||||
return _Execution(item=item, spec=spec)
|
||||
|
||||
def _execute(self, execution: _Execution) -> None:
|
||||
"""Run one item to completion and record the outcome. Runs on a worker thread."""
|
||||
item, spec = execution.item, execution.spec
|
||||
final_status: ItemStatus | None = None
|
||||
try:
|
||||
handle = run_action(self._ctx, item.action, item.params)
|
||||
execution.handle = handle
|
||||
request_id = getattr(getattr(handle, "request", None), "requestID", None)
|
||||
if request_id is not None:
|
||||
with self._lock:
|
||||
item.request_id = request_id
|
||||
self._persist_locked()
|
||||
if execution.interrupted or self._abort.is_set():
|
||||
self._cancel(execution)
|
||||
wait = getattr(handle, "wait", None)
|
||||
if callable(wait):
|
||||
wait()
|
||||
if self._closing.is_set():
|
||||
return # leave RUNNING; reconciled when the widget is opened again
|
||||
|
||||
scan_id, scan_number = _scan_info(handle) if request_id else (None, None)
|
||||
with self._lock:
|
||||
item.scan_id, item.scan_number = scan_id, scan_number
|
||||
if execution.interrupted:
|
||||
self._requeue(item)
|
||||
elif self._abort.is_set() and spec.cancellable:
|
||||
with self._lock:
|
||||
item.status = ItemStatus.ABORTED
|
||||
item.report = "Aborted"
|
||||
else:
|
||||
report = (spec.report or default_report)(handle, item, self._ctx)
|
||||
with self._lock:
|
||||
item.status = ItemStatus.COMPLETED
|
||||
item.report = report
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
if self._closing.is_set():
|
||||
return
|
||||
if execution.interrupted:
|
||||
self._requeue(item)
|
||||
elif self._abort.is_set() or isinstance(exc, ActionInterrupted):
|
||||
with self._lock:
|
||||
item.status = ItemStatus.ABORTED
|
||||
item.report = "Aborted"
|
||||
else:
|
||||
error = traceback.format_exc()
|
||||
logger.error(f"Schedule item {item.action} {item.params} failed:\n{error}")
|
||||
with self._lock:
|
||||
item.status = ItemStatus.FAILED
|
||||
item.error = error
|
||||
item.report = _last_line(error)
|
||||
if item.pause_on_failure:
|
||||
self._paused_on_failure = True
|
||||
self._pause.set()
|
||||
finally:
|
||||
if not self._closing.is_set():
|
||||
with self._lock:
|
||||
if item.status != ItemStatus.PENDING:
|
||||
item.finished_at = time.time()
|
||||
final_status = item.status
|
||||
self._persist_locked()
|
||||
execution.done.set()
|
||||
self._emit_changed()
|
||||
|
||||
if final_status in (ItemStatus.COMPLETED, ItemStatus.FAILED, ItemStatus.ABORTED):
|
||||
self._notify_item(item)
|
||||
|
||||
def _requeue(self, item: ScheduleItem) -> None:
|
||||
with self._lock:
|
||||
item.reset_execution()
|
||||
item.report = "Interrupted by beamline state, will be repeated"
|
||||
logger.info(f"Schedule item {item.item_id} re-queued after beamline state trip")
|
||||
|
||||
def _run_wait_for_parent(self, item: ScheduleItem) -> None:
|
||||
self._start(item)
|
||||
self._join_background()
|
||||
if self._closing.is_set():
|
||||
return
|
||||
with self._lock:
|
||||
if self._abort.is_set():
|
||||
item.status = ItemStatus.ABORTED
|
||||
item.report = "Aborted"
|
||||
else:
|
||||
item.status = ItemStatus.COMPLETED
|
||||
item.report = get_action(WAIT_FOR_PARENT).report(None, item, self._ctx)
|
||||
item.finished_at = time.time()
|
||||
self._persist_locked()
|
||||
self._emit_changed()
|
||||
|
||||
def _join_background(self) -> None:
|
||||
"""Wait until the running background item (if any) has finished."""
|
||||
execution = self._background
|
||||
if execution is None:
|
||||
return
|
||||
while not execution.done.wait(timeout=_POLL_INTERVAL):
|
||||
if self._closing.is_set():
|
||||
return
|
||||
self._background = None
|
||||
|
||||
def _wait_for_states(self, item: ScheduleItem) -> bool:
|
||||
"""Wait until all beamline states are OK. False if paused/aborted/closed meanwhile."""
|
||||
if self._state_monitor.is_ok():
|
||||
return True
|
||||
with self._lock:
|
||||
blocking = ", ".join(self._state_monitor.blocking_states())
|
||||
item.report = f"Waiting for beamline states: {blocking}"
|
||||
self._persist_locked()
|
||||
self._emit_changed()
|
||||
ok = self._state_monitor.wait_until_ok(should_abort=self._should_stop_waiting)
|
||||
with self._lock:
|
||||
item.report = None
|
||||
self._persist_locked()
|
||||
self._emit_changed()
|
||||
return ok
|
||||
|
||||
def _reattach(self, item: ScheduleItem) -> None:
|
||||
"""Follow a request that is still RUNNING from a previous widget session."""
|
||||
if not item.request_id:
|
||||
with self._lock:
|
||||
item.status = ItemStatus.ABORTED
|
||||
item.report = "Interrupted (widget was closed)"
|
||||
item.finished_at = time.time()
|
||||
self._persist_locked()
|
||||
self._emit_changed()
|
||||
return
|
||||
queue_storage = self._get_queue_storage()
|
||||
while not self._should_stop_waiting():
|
||||
queue_item = queue_storage.find_queue_item_by_requestID(item.request_id)
|
||||
if queue_item is None or not is_queue_item_active(queue_item):
|
||||
with self._lock:
|
||||
item.status = ItemStatus.COMPLETED
|
||||
item.report = item.report or "Done"
|
||||
item.finished_at = time.time()
|
||||
self._persist_locked()
|
||||
self._emit_changed()
|
||||
return
|
||||
time.sleep(0.5)
|
||||
|
||||
@staticmethod
|
||||
def _cancel(execution: _Execution) -> None:
|
||||
cancel = getattr(execution.handle, "cancel", None)
|
||||
if not callable(cancel):
|
||||
return
|
||||
try:
|
||||
cancel()
|
||||
except Exception: # pylint: disable=broad-except
|
||||
logger.exception(f"Failed to cancel schedule item {execution.item.item_id}")
|
||||
|
||||
|
||||
def _scan_info(handle: Any) -> tuple[str | None, int | None]:
|
||||
try:
|
||||
scan = handle.scan
|
||||
except Exception: # pylint: disable=broad-except
|
||||
return None, None
|
||||
if scan is None:
|
||||
return None, None
|
||||
return getattr(scan, "scan_id", None), getattr(scan, "scan_number", None)
|
||||
|
||||
|
||||
def _last_line(text: str) -> str:
|
||||
lines = text.strip().splitlines()
|
||||
return lines[-1] if lines else text
|
||||
@@ -0,0 +1,102 @@
|
||||
"""
|
||||
Hide the scan-interlock controls of BEC's stock `BeamlineStateManager`.
|
||||
|
||||
The Scheduler embeds `bec_widgets`' own `BeamlineStateManager` unchanged, so that beamline states
|
||||
are created, edited and removed exactly as everywhere else in BEC. The Scheduler, however, pauses
|
||||
its items based on the states itself ("pause on state") and does not use the BEC scan interlock.
|
||||
To avoid confusion, the interlock-related controls are hidden:
|
||||
|
||||
- the "Scan interlock" toggle in the manager's toolbar, and
|
||||
- the per-state "watched by scan interlock" lock button (and the interlock-only "Trigger
|
||||
ScanInterlock on WARNING state" checkbox in the state's settings panel).
|
||||
|
||||
There is no public API for this, so this module touches private attributes of
|
||||
`BeamlineStateManager` / `BeamlineStatePill`. It is deliberately kept in one place and fails
|
||||
soft: if `bec_widgets` renames those attributes, the controls simply stay visible and a warning
|
||||
is logged.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from bec_lib.logger import bec_logger
|
||||
from bec_widgets.widgets.services.beamline_states.beamline_state_manager import BeamlineStateManager
|
||||
|
||||
# pylint: disable=no-name-in-module # qtpy re-exports are not visible to pylint
|
||||
from qtpy.QtCore import QTimer
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
_TOOLBAR_ACTIONS = ("scan_interlock", "scan_interlock_spacer")
|
||||
_PILL_WIDGETS = ("_interlock_button", "_interlock_warning_checkbox")
|
||||
|
||||
|
||||
def hide_scan_interlock_controls(manager: BeamlineStateManager) -> None:
|
||||
"""
|
||||
Hide the scan-interlock controls of `manager` once.
|
||||
|
||||
Pills are created lazily, so use `install_scan_interlock_hiding` to keep them hidden.
|
||||
"""
|
||||
toolbar = getattr(manager, "_toolbar", None)
|
||||
for name in _TOOLBAR_ACTIONS:
|
||||
try:
|
||||
action = toolbar.components.get_action(name).action
|
||||
action.setVisible(False)
|
||||
_hide_toolbar_entry_of(toolbar, action)
|
||||
except Exception: # pylint: disable=broad-except
|
||||
logger.warning(
|
||||
f"Scheduler: could not hide BeamlineStateManager toolbar action {name!r}"
|
||||
)
|
||||
try:
|
||||
toolbar.update_separators() # drop the separator left in front of the hidden button
|
||||
except Exception: # pylint: disable=broad-except
|
||||
pass
|
||||
|
||||
for pill in list(getattr(manager, "_state_pills", {}).values()):
|
||||
for attr in _PILL_WIDGETS:
|
||||
widget = getattr(pill, attr, None)
|
||||
if widget is None:
|
||||
logger.warning(f"Scheduler: BeamlineStatePill has no attribute {attr!r} to hide")
|
||||
continue
|
||||
widget.setVisible(False)
|
||||
|
||||
|
||||
def _hide_toolbar_entry_of(toolbar, action) -> None:
|
||||
"""
|
||||
Hide the toolbar entry that displays `action`.
|
||||
|
||||
Actions with a text label are not added to the toolbar directly: the toolbar holds a
|
||||
`QToolButton` (with `action` as its default action, or the widget itself for widget actions)
|
||||
wrapped in its own `QWidgetAction`. That wrapper must be hidden for the button to disappear.
|
||||
"""
|
||||
for entry in toolbar.actions():
|
||||
widget = toolbar.widgetForAction(entry)
|
||||
if widget is None:
|
||||
continue
|
||||
default_action = getattr(widget, "defaultAction", lambda: None)()
|
||||
if widget is action or default_action is action:
|
||||
entry.setVisible(False)
|
||||
|
||||
|
||||
def install_scan_interlock_hiding(manager: BeamlineStateManager) -> None:
|
||||
"""
|
||||
Hide the scan-interlock controls now and every time the manager (re)creates state pills.
|
||||
|
||||
Pills are persistent editors of the manager's list model, created when rows are inserted;
|
||||
hiding is therefore deferred to the next event-loop iteration, after the editors exist.
|
||||
"""
|
||||
|
||||
def _schedule_hide(*_):
|
||||
QTimer.singleShot(0, manager, lambda: hide_scan_interlock_controls(manager))
|
||||
|
||||
model = getattr(manager, "_model", None)
|
||||
if model is None:
|
||||
logger.warning(
|
||||
"Scheduler: BeamlineStateManager has no '_model'; interlock hiding is partial"
|
||||
)
|
||||
else:
|
||||
model.rowsInserted.connect(_schedule_hide)
|
||||
model.modelReset.connect(_schedule_hide)
|
||||
model.layoutChanged.connect(_schedule_hide)
|
||||
model.dataChanged.connect(_schedule_hide)
|
||||
hide_scan_interlock_controls(manager)
|
||||
_schedule_hide()
|
||||
@@ -0,0 +1,597 @@
|
||||
"""
|
||||
Dialog behind the Scheduler's "Add" and "Edit" buttons.
|
||||
|
||||
Each item type has one page. A page collects the *parameters* of a registered action (see
|
||||
`actions.py`) - it never builds executable code. The dialog's result is a dict
|
||||
|
||||
{"action": str, "params": dict, "wait_for_completion": bool,
|
||||
"pause_on_failure": bool, "pause_on_state": bool}
|
||||
|
||||
which maps 1:1 onto `ScheduleItem` fields.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from types import SimpleNamespace
|
||||
from typing import Callable
|
||||
|
||||
from bec_lib.logger import bec_logger
|
||||
from bec_widgets.widgets.control.device_input.device_combobox.device_combobox import (
|
||||
BECDeviceFilter,
|
||||
DeviceComboBox,
|
||||
)
|
||||
from bec_widgets.widgets.control.scan_control.scan_control import ScanControl, ScanParameterConfig
|
||||
|
||||
# pylint: disable=no-name-in-module # qtpy re-exports are not visible to pylint
|
||||
from qtpy.QtWidgets import (
|
||||
QCheckBox,
|
||||
QComboBox,
|
||||
QDialog,
|
||||
QDialogButtonBox,
|
||||
QDoubleSpinBox,
|
||||
QFormLayout,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QMessageBox,
|
||||
QScrollArea,
|
||||
QSpinBox,
|
||||
QStackedWidget,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from .actions import ABSORBER_ACTIONS, ALWAYS_WAIT_ACTIONS, DELAY, WAIT_FOR_PARENT
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
# UI widgets are created in the _build_* helpers called from __init__.
|
||||
# pylint: disable=attribute-defined-outside-init
|
||||
|
||||
#: Beamlines with the XAS scan control and the beamline-specific items (Digital Twin, Absorber,
|
||||
#: Ionization Chamber, Reference foil changer, Auto Gain, Temperature Controller).
|
||||
XAS_BEAMLINES = ("x01da", "x10da")
|
||||
|
||||
|
||||
def _hint(text: str) -> QLabel:
|
||||
label = QLabel(text)
|
||||
label.setWordWrap(True)
|
||||
label.setStyleSheet("color: gray;")
|
||||
return label
|
||||
|
||||
|
||||
class ScheduleItemDialog(QDialog):
|
||||
"""
|
||||
Add or edit one schedule item.
|
||||
|
||||
Args:
|
||||
scans: BEC scans shortcut.
|
||||
dev: BEC device container.
|
||||
parent: Parent widget.
|
||||
initial: An existing item's `ScheduleItem.definition()` to edit; None to add a new item.
|
||||
client: BEC client (passed to embedded BEC widgets).
|
||||
beamline: Beamline name; enables the beamline-specific pages at X01DA/X10DA.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
scans,
|
||||
dev,
|
||||
parent=None,
|
||||
initial: dict | None = None,
|
||||
client=None,
|
||||
beamline: str | None = None,
|
||||
):
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("Edit schedule item" if initial else "Add schedule item")
|
||||
self.setMinimumSize(520, 480)
|
||||
|
||||
self._scans = scans
|
||||
self._dev = dev
|
||||
self._client = client
|
||||
self._result: dict | None = None
|
||||
self.beamline = beamline
|
||||
self._is_xas_beamline = beamline in XAS_BEAMLINES
|
||||
|
||||
# action key -> collect() returning params / prefill(params)
|
||||
self._collectors: dict[str, Callable[[], dict]] = {}
|
||||
self._prefillers: dict[str, Callable[[dict], None]] = {}
|
||||
|
||||
if self._is_xas_beamline:
|
||||
self._import_beamline_widgets()
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
self.item_combo = QComboBox()
|
||||
layout.addWidget(self.item_combo)
|
||||
self.stack = QStackedWidget()
|
||||
layout.addWidget(self.stack, 1)
|
||||
|
||||
self._build_scan_page()
|
||||
self._build_move_page()
|
||||
if self._is_xas_beamline:
|
||||
self._build_digital_twin_page()
|
||||
self._build_absorber_page()
|
||||
self._build_ic_page()
|
||||
self._build_reffoil_page()
|
||||
self._build_auto_gain_page()
|
||||
self._build_temperature_controller_page()
|
||||
self._build_delay_page()
|
||||
self._build_wait_for_parent_page()
|
||||
|
||||
# Item options, shared by all pages.
|
||||
self.wait_for_completion_check = QCheckBox("Wait for completion")
|
||||
self.wait_for_completion_check.setToolTip(
|
||||
"Uncheck to run the following items while this one is still running. They are shown "
|
||||
"indented until a 'Wait until parent has completed' item."
|
||||
)
|
||||
self.wait_for_completion_check.setChecked(True)
|
||||
self.pause_on_failure_check = QCheckBox("Pause schedule if this item fails")
|
||||
self.pause_on_state_check = QCheckBox("Pause on beamline state")
|
||||
self.pause_on_state_check.setToolTip(
|
||||
"Wait for all beamline states to be valid (or warning) before starting this item. "
|
||||
"A running scan is interrupted and repeated if a state becomes invalid."
|
||||
)
|
||||
options = QHBoxLayout()
|
||||
for check in (
|
||||
self.wait_for_completion_check,
|
||||
self.pause_on_failure_check,
|
||||
self.pause_on_state_check,
|
||||
):
|
||||
options.addWidget(check)
|
||||
options.addStretch()
|
||||
layout.addLayout(options)
|
||||
|
||||
self.item_combo.currentIndexChanged.connect(self._on_page_changed)
|
||||
|
||||
buttons = QDialogButtonBox(
|
||||
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
|
||||
)
|
||||
buttons.button(QDialogButtonBox.StandardButton.Ok).setText("Save" if initial else "Add")
|
||||
buttons.setStyleSheet("QPushButton {qproperty-icon: none;}")
|
||||
buttons.accepted.connect(self._on_accept)
|
||||
buttons.rejected.connect(self.reject)
|
||||
layout.addWidget(buttons)
|
||||
|
||||
# The embedded DigitalTwin runs a polling timer and dispatcher subscriptions; stop them
|
||||
# however the dialog is closed.
|
||||
self.finished.connect(self._cleanup_digital_twin)
|
||||
|
||||
self._apply_initial(initial or {})
|
||||
self._on_page_changed()
|
||||
|
||||
def _import_beamline_widgets(self) -> None:
|
||||
logger.info(f"Loading beamline-specific item pages for {self.beamline}")
|
||||
# pylint: disable=import-outside-toplevel
|
||||
from ..auto_gain.auto_gain import AutoGain
|
||||
from ..digital_twin.digital_twin import DigitalTwin
|
||||
from ..scan_control_xas.scan_control_xas import ScanControlXAS
|
||||
from ..temperature_controller.temperature_controller import TemperatureControllerControl
|
||||
|
||||
self._digital_twin_cls = DigitalTwin
|
||||
self._auto_gain_cls = AutoGain
|
||||
self._scan_control_xas_cls = ScanControlXAS
|
||||
self._temperature_controller_cls = TemperatureControllerControl
|
||||
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
# Page plumbing
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
def _add_page(
|
||||
self,
|
||||
action: str,
|
||||
label: str,
|
||||
widget: QWidget,
|
||||
collect: Callable[[], dict],
|
||||
prefill: Callable[[dict], None] | None = None,
|
||||
) -> None:
|
||||
# Combo and stack are always appended together, so a combo index is a stack index.
|
||||
self.item_combo.addItem(label, action)
|
||||
self.stack.addWidget(widget)
|
||||
self._collectors[action] = collect
|
||||
if prefill is not None:
|
||||
self._prefillers[action] = prefill
|
||||
|
||||
def _select_page(self, action: str) -> bool:
|
||||
"""Switch to the page of `action`; False if that page is not available."""
|
||||
idx = self.item_combo.findData(action)
|
||||
if idx < 0:
|
||||
return False
|
||||
self.item_combo.setCurrentIndex(idx)
|
||||
return True
|
||||
|
||||
def _on_page_changed(self, *_) -> None:
|
||||
self.stack.setCurrentIndex(self.item_combo.currentIndex())
|
||||
action = self.item_combo.currentData()
|
||||
always_wait = action in ALWAYS_WAIT_ACTIONS
|
||||
if always_wait:
|
||||
self.wait_for_completion_check.setChecked(True)
|
||||
self.wait_for_completion_check.setEnabled(not always_wait)
|
||||
is_control = action == WAIT_FOR_PARENT
|
||||
self.pause_on_failure_check.setEnabled(not is_control)
|
||||
self.pause_on_state_check.setEnabled(not is_control)
|
||||
if is_control:
|
||||
self.pause_on_failure_check.setChecked(False)
|
||||
self.pause_on_state_check.setChecked(False)
|
||||
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
# Scan (embeds BEC's ScanControl, or the XAS variant)
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
def _build_scan_page(self) -> None:
|
||||
page = QWidget()
|
||||
layout = QVBoxLayout(page)
|
||||
scan_control_cls = self._scan_control_xas_cls if self._is_xas_beamline else ScanControl
|
||||
self.scan_control = scan_control_cls(parent=page, client=self._client)
|
||||
self.scan_control.button_run_scan.hide()
|
||||
layout.addWidget(self.scan_control)
|
||||
self._add_page("scan", "Scan", page, self._collect_scan, self._prefill_scan)
|
||||
|
||||
def _collect_scan(self) -> dict:
|
||||
# Same call ScanControl.run_scan() makes to resolve a typed-but-unconfirmed scan name.
|
||||
self.scan_control.validate_scan_selection()
|
||||
scan_name = self.scan_control.current_scan
|
||||
if not scan_name:
|
||||
raise ValueError("No scan selected.")
|
||||
# bec_object=False: plain values (device names instead of device objects), so the
|
||||
# parameters are JSON-serialisable.
|
||||
args, kwargs = self.scan_control.get_scan_parameters(bec_object=False)
|
||||
return {"scan_name": scan_name, "args": list(args), "kwargs": dict(kwargs)}
|
||||
|
||||
def _prefill_scan(self, params: dict) -> None:
|
||||
# Pre-load ScanControl's own parameter cache and let it restore the form.
|
||||
scan_name = params["scan_name"]
|
||||
self.scan_control.config.scans[scan_name] = ScanParameterConfig(
|
||||
name=scan_name, args=params.get("args") or [], kwargs=params.get("kwargs") or {}
|
||||
)
|
||||
self.scan_control.current_scan = scan_name
|
||||
self.scan_control.restore_scan_parameters(scan_name)
|
||||
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
# Move
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
def _build_move_page(self) -> None:
|
||||
page = QWidget()
|
||||
form = QFormLayout(page)
|
||||
form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint)
|
||||
self.move_device_combo = DeviceComboBox(self, device_filter=[BECDeviceFilter.POSITIONER])
|
||||
self.move_value_spin = QDoubleSpinBox()
|
||||
self.move_relative_check = QCheckBox("")
|
||||
form.addRow("Device", self.move_device_combo)
|
||||
form.addRow("Value", self.move_value_spin)
|
||||
form.addRow("Relative move", self.move_relative_check)
|
||||
self.move_device_combo.currentTextChanged.connect(self._adjust_move_spinbox)
|
||||
self._adjust_move_spinbox(self.move_device_combo.currentText())
|
||||
self._add_page("move", "Move", page, self._collect_move, self._prefill_move)
|
||||
|
||||
def _adjust_move_spinbox(self, device_name: str) -> None:
|
||||
"""Adapt precision, units and limits of the value spin box to the selected device."""
|
||||
if not device_name or device_name not in self._dev:
|
||||
return
|
||||
device = self._dev[device_name]
|
||||
try:
|
||||
precision, units = device.precision, device.egu()
|
||||
low, high = device.low_limit, device.high_limit
|
||||
except Exception: # pylint: disable=broad-except
|
||||
logger.exception(f"Could not read limits/units of {device_name}")
|
||||
return
|
||||
self.move_value_spin.setDecimals(precision)
|
||||
self.move_value_spin.setSuffix(f" {units}" if units else "")
|
||||
if high - low > 0:
|
||||
self.move_value_spin.setRange(low, high)
|
||||
self.move_value_spin.setSingleStep(10 ** round(math.log10((high - low) / 100)))
|
||||
else: # no limits configured
|
||||
self.move_value_spin.setRange(-1e6, 1e6)
|
||||
self.move_value_spin.setSingleStep(1)
|
||||
|
||||
def _collect_move(self) -> dict:
|
||||
device = self.move_device_combo.currentText()
|
||||
if not device:
|
||||
raise ValueError("No movable device available/selected.")
|
||||
return {
|
||||
"device": device,
|
||||
"value": self.move_value_spin.value(),
|
||||
"relative": self.move_relative_check.isChecked(),
|
||||
"units": self.move_value_spin.suffix().strip(),
|
||||
}
|
||||
|
||||
def _prefill_move(self, params: dict) -> None:
|
||||
idx = self.move_device_combo.findText(params.get("device", ""))
|
||||
if idx >= 0:
|
||||
self.move_device_combo.setCurrentIndex(idx)
|
||||
self.move_value_spin.setValue(float(params.get("value", 0.0)))
|
||||
self.move_relative_check.setChecked(bool(params.get("relative", False)))
|
||||
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
# Digital Twin
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
def _build_digital_twin_page(self) -> None:
|
||||
page = QWidget()
|
||||
outer = QVBoxLayout(page)
|
||||
# DigitalTwin is normally a large top-level window; wrap it in a scroll area.
|
||||
scroll = QScrollArea()
|
||||
scroll.setWidgetResizable(True)
|
||||
self.digital_twin = self._digital_twin_cls(parent=scroll, client=self._client)
|
||||
for mover in self.digital_twin.mover.mover_widgets:
|
||||
mover.btn_action.hide()
|
||||
self.digital_twin.mover.abs.btn_action.hide()
|
||||
scroll.setWidget(self.digital_twin)
|
||||
outer.addWidget(scroll)
|
||||
outer.addWidget(
|
||||
_hint(
|
||||
"Configure the beamline alignment above. The motor targets are computed and moved "
|
||||
"when this schedule item runs, not now."
|
||||
)
|
||||
)
|
||||
self._add_page(
|
||||
"digital_twin",
|
||||
"Digital Twin",
|
||||
page,
|
||||
lambda: {"config": self.digital_twin.get_assistant_config()},
|
||||
lambda params: self.digital_twin.set_assistant_config(params["config"]),
|
||||
)
|
||||
|
||||
def _cleanup_digital_twin(self, *_) -> None:
|
||||
digital_twin = getattr(self, "digital_twin", None)
|
||||
if digital_twin is None:
|
||||
return
|
||||
try:
|
||||
digital_twin._timer.stop() # pylint: disable=protected-access
|
||||
digital_twin.cleanup()
|
||||
except Exception: # pylint: disable=broad-except
|
||||
logger.exception("Failed to clean up the embedded Digital Twin widget.")
|
||||
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
# Absorber
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
def _build_absorber_page(self) -> None:
|
||||
if "abs" not in self._dev:
|
||||
return
|
||||
page = QWidget()
|
||||
form = QFormLayout(page)
|
||||
form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint)
|
||||
self.abs_selector = QComboBox()
|
||||
self.abs_selector.addItems(list(ABSORBER_ACTIONS))
|
||||
form.addRow("Action", self.abs_selector)
|
||||
self._add_page(
|
||||
"absorber",
|
||||
"Absorber",
|
||||
page,
|
||||
lambda: {"action": self.abs_selector.currentText()},
|
||||
lambda params: self._set_combo(self.abs_selector, params.get("action")),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
# Ionization chamber
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
def _build_ic_page(self) -> None:
|
||||
if not all(key in self._dev for key in ("ic0", "ic1", "ic2")):
|
||||
return
|
||||
page = QWidget()
|
||||
form = QFormLayout(page)
|
||||
form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint)
|
||||
|
||||
self.ic_selector = QComboBox()
|
||||
self.ic_selector.addItems(["IC0", "IC1", "IC2"])
|
||||
gases = ["He", "N2", "Ar", "Kr"]
|
||||
self.gas1, self.gas2 = QComboBox(), QComboBox()
|
||||
self.gas1.addItems(gases)
|
||||
self.gas2.addItems(gases)
|
||||
self.conc1, self.conc2 = QDoubleSpinBox(), QDoubleSpinBox()
|
||||
for conc in (self.conc1, self.conc2):
|
||||
conc.setDecimals(0)
|
||||
conc.setSuffix(" %")
|
||||
conc.setRange(0, 100)
|
||||
self.pressure = QDoubleSpinBox()
|
||||
self.pressure.setDecimals(3)
|
||||
self.pressure.setSuffix(" bar abs")
|
||||
self.pressure.setRange(1, 3)
|
||||
self.pressure.setSingleStep(0.1)
|
||||
|
||||
form.addRow("Ionization chamber", self.ic_selector)
|
||||
form.addRow("Gas 1", self.gas1)
|
||||
form.addRow("Concentration 1", self.conc1)
|
||||
form.addRow("Gas 2", self.gas2)
|
||||
form.addRow("Concentration 2", self.conc2)
|
||||
form.addRow("Pressure", self.pressure)
|
||||
|
||||
self.conc1.valueChanged.connect(lambda value: self.conc2.setValue(100 - value))
|
||||
self.conc2.valueChanged.connect(lambda value: self.conc1.setValue(100 - value))
|
||||
self._add_page("ic_fill", "Ionization Chamber", page, self._collect_ic, self._prefill_ic)
|
||||
|
||||
def _collect_ic(self) -> dict:
|
||||
total = self.conc1.value() + self.conc2.value()
|
||||
if total != 100:
|
||||
raise ValueError(f"Gas concentrations must add up to 100% (currently {total:.0f}%).")
|
||||
return {
|
||||
"chamber": self.ic_selector.currentText(),
|
||||
"gas1": self.gas1.currentText(),
|
||||
"conc1": self.conc1.value(),
|
||||
"gas2": self.gas2.currentText(),
|
||||
"conc2": self.conc2.value(),
|
||||
"pressure": self.pressure.value(),
|
||||
}
|
||||
|
||||
def _prefill_ic(self, params: dict) -> None:
|
||||
self._set_combo(self.ic_selector, params.get("chamber"))
|
||||
self._set_combo(self.gas1, params.get("gas1"))
|
||||
self._set_combo(self.gas2, params.get("gas2"))
|
||||
self.conc1.setValue(float(params.get("conc1", 0))) # also sets conc2 = 100 - conc1
|
||||
self.pressure.setValue(float(params.get("pressure", self.pressure.minimum())))
|
||||
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
# Reference foil changer
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
def _build_reffoil_page(self) -> None:
|
||||
if "reffoilchanger" not in self._dev:
|
||||
return
|
||||
page = QWidget()
|
||||
form = QFormLayout(page)
|
||||
form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint)
|
||||
self.reffoil_selector = QComboBox()
|
||||
self.reffoil_selector.addItems(self._dev["reffoilchanger"].get_all_foils())
|
||||
form.addRow("Reference foil", self.reffoil_selector)
|
||||
self._add_page(
|
||||
"reffoil",
|
||||
"Reference foil changer",
|
||||
page,
|
||||
self._collect_reffoil,
|
||||
lambda params: self._set_combo(self.reffoil_selector, params.get("foil")),
|
||||
)
|
||||
|
||||
def _collect_reffoil(self) -> dict:
|
||||
foil = self.reffoil_selector.currentText()
|
||||
if not foil:
|
||||
raise ValueError("Select a reference foil.")
|
||||
return {"foil": foil}
|
||||
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
# Auto Gain
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
def _build_auto_gain_page(self) -> None:
|
||||
page = QWidget()
|
||||
outer = QVBoxLayout(page)
|
||||
scroll = QScrollArea()
|
||||
scroll.setWidgetResizable(True)
|
||||
self.auto_gain = self._auto_gain_cls(show_control=False, parent=scroll, client=self._client)
|
||||
scroll.setWidget(self.auto_gain)
|
||||
outer.addWidget(scroll)
|
||||
outer.addWidget(
|
||||
_hint("Configure the auto-gain above. It is executed when this schedule item runs.")
|
||||
)
|
||||
self._add_page(
|
||||
"auto_gain",
|
||||
"Auto Gain",
|
||||
page,
|
||||
lambda: {"config": self.auto_gain.get_config()},
|
||||
lambda params: self.auto_gain.load_config(params["config"]),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
# Temperature Controller
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
def _build_temperature_controller_page(self) -> None:
|
||||
page = QWidget()
|
||||
outer = QVBoxLayout(page)
|
||||
scroll = QScrollArea()
|
||||
scroll.setWidgetResizable(True)
|
||||
self.temperature_controller = self._temperature_controller_cls(
|
||||
config_only=True, parent=scroll
|
||||
)
|
||||
scroll.setWidget(self.temperature_controller)
|
||||
outer.addWidget(scroll)
|
||||
outer.addStretch()
|
||||
self._add_page(
|
||||
"temperature_controller",
|
||||
"Temperature Controller",
|
||||
page,
|
||||
# get_config() returns a pydantic ConfigDict; store it as a plain (JSON) dict.
|
||||
lambda: {"config": self.temperature_controller.get_config().model_dump(mode="json")},
|
||||
# load_config() only reads attributes, so a namespace over the stored dict suffices.
|
||||
lambda params: self.temperature_controller.load_config(
|
||||
SimpleNamespace(**params["config"])
|
||||
),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
# Delay
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
def _build_delay_page(self) -> None:
|
||||
page = QWidget()
|
||||
form = QFormLayout(page)
|
||||
form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.FieldsStayAtSizeHint)
|
||||
self.delay_hours = QSpinBox(suffix=" h", maximum=999)
|
||||
self.delay_minutes = QSpinBox(suffix=" min", maximum=59)
|
||||
self.delay_seconds = QSpinBox(suffix=" s", maximum=59)
|
||||
row = QHBoxLayout()
|
||||
for spin in (self.delay_hours, self.delay_minutes, self.delay_seconds):
|
||||
row.addWidget(spin)
|
||||
form.addRow("Wait for", row)
|
||||
form.addRow(_hint("The schedule waits for the given time before continuing."))
|
||||
self._add_page(DELAY, "Delay", page, self._collect_delay, self._prefill_delay)
|
||||
|
||||
def _collect_delay(self) -> dict:
|
||||
seconds = (
|
||||
self.delay_hours.value() * 3600
|
||||
+ self.delay_minutes.value() * 60
|
||||
+ self.delay_seconds.value()
|
||||
)
|
||||
if seconds <= 0:
|
||||
raise ValueError("The delay must be longer than 0 s.")
|
||||
return {"seconds": seconds}
|
||||
|
||||
def _prefill_delay(self, params: dict) -> None:
|
||||
hours, rest = divmod(int(params.get("seconds", 0)), 3600)
|
||||
minutes, seconds = divmod(rest, 60)
|
||||
self.delay_hours.setValue(hours)
|
||||
self.delay_minutes.setValue(minutes)
|
||||
self.delay_seconds.setValue(seconds)
|
||||
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
# Wait until parent has completed
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
def _build_wait_for_parent_page(self) -> None:
|
||||
page = QWidget()
|
||||
layout = QVBoxLayout(page)
|
||||
layout.addWidget(
|
||||
_hint(
|
||||
"Waits until the item above that runs without 'Wait for completion' (the parent) "
|
||||
"has completed. Ends the indented block of items that run while the parent is "
|
||||
"busy; the following items start only after the parent has finished."
|
||||
)
|
||||
)
|
||||
layout.addStretch()
|
||||
self._add_page(WAIT_FOR_PARENT, "Wait until parent has completed", page, dict)
|
||||
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
# Prefill / result
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
@staticmethod
|
||||
def _set_combo(combo: QComboBox, text: str | None) -> None:
|
||||
idx = combo.findText(text or "")
|
||||
if idx >= 0:
|
||||
combo.setCurrentIndex(idx)
|
||||
|
||||
def _apply_initial(self, initial: dict) -> None:
|
||||
self.wait_for_completion_check.setChecked(bool(initial.get("wait_for_completion", True)))
|
||||
self.pause_on_failure_check.setChecked(bool(initial.get("pause_on_failure", False)))
|
||||
self.pause_on_state_check.setChecked(bool(initial.get("pause_on_state", False)))
|
||||
action = initial.get("action")
|
||||
if action is None:
|
||||
return
|
||||
if not self._select_page(action):
|
||||
logger.warning(f"Item type {action!r} is not available at this beamline.")
|
||||
return
|
||||
prefill = self._prefillers.get(action)
|
||||
if prefill is not None:
|
||||
try:
|
||||
prefill(initial.get("params") or {})
|
||||
except Exception: # pylint: disable=broad-except
|
||||
logger.exception(f"Could not restore the parameters of a {action!r} item")
|
||||
|
||||
def _on_accept(self) -> None:
|
||||
action = self.item_combo.currentData()
|
||||
try:
|
||||
params = self._collectors[action]()
|
||||
except ValueError as exc:
|
||||
QMessageBox.warning(self, "Invalid item", str(exc))
|
||||
return
|
||||
try:
|
||||
json.dumps(params)
|
||||
except TypeError as exc:
|
||||
# A page returned a non-JSON value (e.g. a pydantic model) - a programming error.
|
||||
logger.error(f"Parameters of {action!r} are not JSON-serialisable: {params!r}")
|
||||
QMessageBox.critical(
|
||||
self, "Invalid item", f"The item parameters cannot be saved (not JSON): {exc}"
|
||||
)
|
||||
return
|
||||
self._result = {
|
||||
"action": action,
|
||||
"params": params,
|
||||
"wait_for_completion": self.wait_for_completion_check.isChecked(),
|
||||
"pause_on_failure": self.pause_on_failure_check.isChecked(),
|
||||
"pause_on_state": self.pause_on_state_check.isChecked(),
|
||||
}
|
||||
self.accept()
|
||||
|
||||
def result(self) -> dict: # pylint: disable=invalid-overridden-method
|
||||
"""The item definition; valid after `exec_()` returned `QDialog.Accepted`."""
|
||||
return self._result
|
||||
@@ -0,0 +1,170 @@
|
||||
"""
|
||||
Persisted data model of the Scheduler widget.
|
||||
|
||||
Everything in here is a plain pydantic model. The whole `Schedule` document is stored in Redis as
|
||||
the `.value` payload of a `bec_lib.messages.VariableMessage` (see `endpoints.schedule`) and can be
|
||||
saved to / loaded from a JSON file. All fields must therefore stay JSON-serialisable; in
|
||||
particular, a `ScheduleItem` describes *what* to run as a registry key (`action`) plus plain
|
||||
parameters (`params`) - never as executable code (see `actions.py`).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
|
||||
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, ValidationError, field_validator
|
||||
|
||||
|
||||
class ItemStatus(str, Enum):
|
||||
"""Execution status of one schedule item."""
|
||||
|
||||
PENDING = "pending"
|
||||
RUNNING = "running"
|
||||
COMPLETED = "completed"
|
||||
FAILED = "failed"
|
||||
ABORTED = "aborted"
|
||||
|
||||
|
||||
class NotificationTarget(str, Enum):
|
||||
"""BEC messaging service used to send schedule notifications."""
|
||||
|
||||
SCILOG = "scilog"
|
||||
SIGNAL = "signal"
|
||||
|
||||
|
||||
class NotificationSettings(BaseModel):
|
||||
"""Per-schedule notification preferences (see `notifications.py` for the send logic)."""
|
||||
|
||||
model_config = ConfigDict(extra="ignore", populate_by_name=True)
|
||||
|
||||
enabled: bool = False
|
||||
notify_scan: bool = True
|
||||
notify_move: bool = True
|
||||
# Device actions and beamline tools (digital twin, auto-gain, ...). Older schedules stored
|
||||
# this flag as "notify_rpc".
|
||||
notify_device: bool = Field(
|
||||
default=True, validation_alias=AliasChoices("notify_device", "notify_rpc")
|
||||
)
|
||||
|
||||
target: NotificationTarget = NotificationTarget.SCILOG
|
||||
events: list[ItemStatus] = Field(default_factory=list)
|
||||
signal_number: str | None = None # a phone number, or a pre-registered Signal scope
|
||||
|
||||
@field_validator("target", mode="before")
|
||||
@classmethod
|
||||
def _map_legacy_target(cls, value: Any) -> Any:
|
||||
"""Map targets that are no longer supported (e.g. the removed "teams") to SciLog."""
|
||||
valid = {target.value for target in NotificationTarget}
|
||||
if isinstance(value, NotificationTarget):
|
||||
return value
|
||||
if not isinstance(value, str) or value not in valid:
|
||||
return NotificationTarget.SCILOG
|
||||
return value
|
||||
|
||||
|
||||
class ScheduleItem(BaseModel):
|
||||
"""
|
||||
One entry of the schedule: what to run, how to run it, and its execution bookkeeping.
|
||||
|
||||
Attributes:
|
||||
item_id: Stable unique id, used to address the item from the UI and over RPC.
|
||||
action: Key of the action in the function registry (`actions.ACTIONS`).
|
||||
params: JSON-serialisable keyword arguments passed to the action.
|
||||
status: Current execution status.
|
||||
wait_for_completion: If False, the item is started and the schedule immediately
|
||||
continues with the following items ("background item"). The following items are
|
||||
shown indented until a "Wait until parent has completed" item, the next background
|
||||
item or the end of the schedule.
|
||||
pause_on_failure: Pause the schedule if this item fails.
|
||||
pause_on_state: Only start this item while all beamline states are VALID or WARNING.
|
||||
A gated scan that is running when a state becomes INVALID is cancelled and repeated
|
||||
once the states have recovered.
|
||||
report: Short human-readable result, shown in the "Report" column.
|
||||
request_id / scan_id / scan_number: Set for items that submit a request to the BEC
|
||||
scan server; used to re-attach to a still-running request after a widget restart.
|
||||
error: Full traceback of the last failure.
|
||||
started_at / finished_at: Unix timestamps of the last execution.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
item_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
|
||||
action: str
|
||||
params: dict[str, Any] = Field(default_factory=dict)
|
||||
status: ItemStatus = ItemStatus.PENDING
|
||||
|
||||
wait_for_completion: bool = True
|
||||
pause_on_failure: bool = False
|
||||
pause_on_state: bool = False
|
||||
|
||||
report: str | None = None
|
||||
request_id: str | None = None
|
||||
scan_id: str | None = None
|
||||
scan_number: int | None = None
|
||||
error: str | None = None
|
||||
started_at: float | None = None
|
||||
finished_at: float | None = None
|
||||
|
||||
def reset_execution(self) -> None:
|
||||
"""Clear all execution bookkeeping and mark the item PENDING again."""
|
||||
self.status = ItemStatus.PENDING
|
||||
self.report = None
|
||||
self.request_id = None
|
||||
self.scan_id = None
|
||||
self.scan_number = None
|
||||
self.error = None
|
||||
self.started_at = None
|
||||
self.finished_at = None
|
||||
|
||||
def definition(self) -> dict[str, Any]:
|
||||
"""The user-defined part of the item (no id, no execution state), e.g. for copy/paste."""
|
||||
return {
|
||||
"action": self.action,
|
||||
"params": dict(self.params),
|
||||
"wait_for_completion": self.wait_for_completion,
|
||||
"pause_on_failure": self.pause_on_failure,
|
||||
"pause_on_state": self.pause_on_state,
|
||||
}
|
||||
|
||||
|
||||
class Schedule(BaseModel):
|
||||
"""The full persisted state of one named schedule."""
|
||||
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
schedule_name: str
|
||||
items: list[ScheduleItem] = Field(default_factory=list)
|
||||
is_running: bool = False
|
||||
notes: str = ""
|
||||
notifications: NotificationSettings = Field(default_factory=NotificationSettings)
|
||||
|
||||
|
||||
def is_legacy_schedule(data: Any) -> bool:
|
||||
"""
|
||||
True if `data` looks like a schedule written by the old, eval-based Scheduler widget
|
||||
(items described by a `command` string instead of an `action` registry key).
|
||||
"""
|
||||
if not isinstance(data, dict):
|
||||
return False
|
||||
items = data.get("items") or []
|
||||
return any(
|
||||
isinstance(item, dict) and "command" in item and "action" not in item for item in items
|
||||
)
|
||||
|
||||
|
||||
def schedule_from_document(data: Any) -> tuple[Schedule | None, str | None]:
|
||||
"""
|
||||
Validate a persisted schedule document (from Redis or a JSON file) without raising.
|
||||
|
||||
Returns:
|
||||
`(schedule, None)` if the document is valid, otherwise `(None, problem)` where `problem`
|
||||
is a short human-readable description, e.g. "an old schedule format".
|
||||
"""
|
||||
if is_legacy_schedule(data):
|
||||
return None, "an old schedule format"
|
||||
try:
|
||||
return Schedule.model_validate(data), None
|
||||
except (ValidationError, TypeError, KeyError, AttributeError) as exc:
|
||||
return None, f"an invalid schedule ({exc.__class__.__name__})"
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Settings dialog for the schedule notifications (`models.NotificationSettings`)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# pylint: disable=no-name-in-module # qtpy re-exports are not visible to pylint
|
||||
from qtpy.QtWidgets import (
|
||||
QButtonGroup,
|
||||
QCheckBox,
|
||||
QComboBox,
|
||||
QDialog,
|
||||
QDialogButtonBox,
|
||||
QGroupBox,
|
||||
QLabel,
|
||||
QMessageBox,
|
||||
QPushButton,
|
||||
QRadioButton,
|
||||
QVBoxLayout,
|
||||
)
|
||||
|
||||
from .models import ItemStatus, NotificationSettings, NotificationTarget
|
||||
from .notifications import send_notification
|
||||
|
||||
|
||||
def _service_state(client, name: str) -> tuple[bool, list[str]]:
|
||||
"""
|
||||
Best-effort read of a messaging service's enabled flag and registered scopes. BEC offers no
|
||||
public accessor for this, hence the private attributes. Never raises.
|
||||
"""
|
||||
messaging = getattr(client, "messaging", None)
|
||||
service = getattr(messaging, name, None) if messaging is not None else None
|
||||
if service is None:
|
||||
return False, []
|
||||
return bool(getattr(service, "_enabled", False)), sorted(getattr(service, "_scopes", set()))
|
||||
|
||||
|
||||
def _dim_label(text: str) -> QLabel:
|
||||
label = QLabel(text)
|
||||
label.setStyleSheet("color: gray;")
|
||||
label.setWordWrap(True)
|
||||
return label
|
||||
|
||||
|
||||
class NotificationSettingsDialog(QDialog):
|
||||
"""Choose whether, where and for which items/events notifications are sent."""
|
||||
|
||||
_EVENTS = (
|
||||
(ItemStatus.COMPLETED, "Completed"),
|
||||
(ItemStatus.ABORTED, "Aborted"),
|
||||
(ItemStatus.FAILED, "Failed"),
|
||||
)
|
||||
|
||||
def __init__(self, settings: NotificationSettings, client, parent=None):
|
||||
super().__init__(parent)
|
||||
self._client = client
|
||||
self.setWindowTitle("Notifications")
|
||||
self.setMinimumWidth(380)
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
info = QLabel(
|
||||
"Sends a message through the selected BEC messaging service when the schedule "
|
||||
"starts or stops, and when an item finishes."
|
||||
)
|
||||
info.setWordWrap(True)
|
||||
layout.addWidget(info)
|
||||
|
||||
self.enabled_check = QCheckBox("Send notifications")
|
||||
self.enabled_check.setChecked(settings.enabled)
|
||||
layout.addWidget(self.enabled_check)
|
||||
|
||||
kind_box = QGroupBox("Notify for")
|
||||
kind_layout = QVBoxLayout(kind_box)
|
||||
self.scan_check = QCheckBox("Scans")
|
||||
self.scan_check.setChecked(settings.notify_scan)
|
||||
self.move_check = QCheckBox("Movements")
|
||||
self.move_check.setChecked(settings.notify_move)
|
||||
self.device_check = QCheckBox("Device actions and beamline tools")
|
||||
self.device_check.setChecked(settings.notify_device)
|
||||
for check in (self.scan_check, self.move_check, self.device_check):
|
||||
kind_layout.addWidget(check)
|
||||
layout.addWidget(kind_box)
|
||||
|
||||
event_box = QGroupBox("Send when an item is")
|
||||
event_layout = QVBoxLayout(event_box)
|
||||
self._event_checks: dict[ItemStatus, QCheckBox] = {}
|
||||
for status, label in self._EVENTS:
|
||||
check = QCheckBox(label)
|
||||
check.setChecked(status in settings.events)
|
||||
event_layout.addWidget(check)
|
||||
self._event_checks[status] = check
|
||||
layout.addWidget(event_box)
|
||||
|
||||
target_box = QGroupBox("Send via")
|
||||
target_layout = QVBoxLayout(target_box)
|
||||
self.scilog_radio = QRadioButton("SciLog")
|
||||
self.signal_radio = QRadioButton("Signal Messenger")
|
||||
self._target_group = QButtonGroup(self)
|
||||
for radio in (self.scilog_radio, self.signal_radio):
|
||||
self._target_group.addButton(radio)
|
||||
target_layout.addWidget(radio)
|
||||
layout.addWidget(target_box)
|
||||
|
||||
# Signal: a raw phone number works directly, so this is an editable combo box offering
|
||||
# any pre-registered scopes as suggestions.
|
||||
self.signal_box = QGroupBox("Signal settings")
|
||||
signal_layout = QVBoxLayout(self.signal_box)
|
||||
signal_enabled, signal_scopes = _service_state(client, "signal")
|
||||
self.signal_combo = QComboBox()
|
||||
self.signal_combo.setEditable(True)
|
||||
self.signal_combo.addItems(signal_scopes)
|
||||
self.signal_combo.setEnabled(signal_enabled)
|
||||
self.signal_combo.setEditText(settings.signal_number or "")
|
||||
self.signal_combo.lineEdit().setPlaceholderText("e.g. +41791234567")
|
||||
signal_layout.addWidget(QLabel("Phone number or contact"))
|
||||
signal_layout.addWidget(self.signal_combo)
|
||||
if not signal_enabled:
|
||||
signal_layout.addWidget(_dim_label("Signal messaging is not enabled for this session."))
|
||||
layout.addWidget(self.signal_box)
|
||||
|
||||
if settings.target == NotificationTarget.SIGNAL:
|
||||
self.signal_radio.setChecked(True)
|
||||
else:
|
||||
self.scilog_radio.setChecked(True)
|
||||
self.signal_radio.toggled.connect(self._sync_target_widgets)
|
||||
|
||||
self.test_btn = QPushButton("Send test message")
|
||||
self.test_btn.clicked.connect(self._on_test_clicked)
|
||||
layout.addWidget(self.test_btn)
|
||||
|
||||
buttons = QDialogButtonBox(
|
||||
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
|
||||
)
|
||||
buttons.accepted.connect(self.accept)
|
||||
buttons.rejected.connect(self.reject)
|
||||
layout.addWidget(buttons)
|
||||
|
||||
self._sync_target_widgets()
|
||||
|
||||
def _sync_target_widgets(self, *_) -> None:
|
||||
self.signal_box.setVisible(self.signal_radio.isChecked())
|
||||
self.layout().activate()
|
||||
self.adjustSize()
|
||||
|
||||
def _current_settings(self) -> NotificationSettings:
|
||||
target = (
|
||||
NotificationTarget.SIGNAL
|
||||
if self.signal_radio.isChecked()
|
||||
else NotificationTarget.SCILOG
|
||||
)
|
||||
return NotificationSettings(
|
||||
enabled=self.enabled_check.isChecked(),
|
||||
notify_scan=self.scan_check.isChecked(),
|
||||
notify_move=self.move_check.isChecked(),
|
||||
notify_device=self.device_check.isChecked(),
|
||||
target=target,
|
||||
events=[status for status, check in self._event_checks.items() if check.isChecked()],
|
||||
signal_number=self.signal_combo.currentText().strip() or None,
|
||||
)
|
||||
|
||||
def _on_test_clicked(self) -> None:
|
||||
try:
|
||||
send_notification(
|
||||
self._client, self._current_settings(), "Test message from the BEC Scheduler."
|
||||
)
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
QMessageBox.critical(self, "Test message failed", str(exc))
|
||||
return
|
||||
QMessageBox.information(self, "Test message sent", "The test message was sent.")
|
||||
|
||||
def result_settings(self) -> NotificationSettings:
|
||||
"""The edited settings; valid after `exec_()` returned `QDialog.Accepted`."""
|
||||
return self._current_settings()
|
||||
@@ -0,0 +1,114 @@
|
||||
"""
|
||||
"Tell the user when something finished/failed" - independent of the scheduling logic.
|
||||
|
||||
Messages are sent through BEC's own messaging services (`client.messaging`), see
|
||||
https://bec.readthedocs.io/latest/how-to/general/send-messages-to-signal.html and
|
||||
https://bec.readthedocs.io/latest/how-to/general/send-messages-to-scilog.html:
|
||||
|
||||
bec.messaging.scilog.new("Beamline checks completed.").send()
|
||||
bec.messaging.signal.new("Beamline checks completed.").send(scope="+41791234567")
|
||||
|
||||
- **SciLog** needs no scope: it posts to the logbook of the currently active pgroup.
|
||||
- **Signal** accepts a raw phone number as scope (BEC normalises it, defaulting to the Swiss
|
||||
country code) or the name of a pre-registered scope.
|
||||
|
||||
The settings model (`NotificationSettings`) lives in `models.py`, as it is persisted with the
|
||||
schedule.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from bec_lib.logger import bec_logger
|
||||
|
||||
from .actions import ACTIONS
|
||||
from .models import NotificationSettings, NotificationTarget, ScheduleItem
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
ScheduleState = Literal[
|
||||
"started", "finished", "aborted", "paused", "paused_on_failure", "widget_closed"
|
||||
]
|
||||
|
||||
_STATE_TEXT: dict[str, str] = {
|
||||
"started": "has started",
|
||||
"finished": "has finished",
|
||||
"aborted": "was aborted",
|
||||
"paused": "was paused",
|
||||
"paused_on_failure": "was paused because an item failed",
|
||||
"widget_closed": "has stopped prematurely because the widget was closed",
|
||||
}
|
||||
|
||||
|
||||
def _enabled_for_category(settings: NotificationSettings, category: str) -> bool:
|
||||
return {
|
||||
"scan": settings.notify_scan,
|
||||
"move": settings.notify_move,
|
||||
"device": settings.notify_device,
|
||||
}.get(category, False)
|
||||
|
||||
|
||||
def send_notification(client, settings: NotificationSettings, text: str) -> None:
|
||||
"""
|
||||
Send `text` through the service selected by `settings.target`.
|
||||
|
||||
Raises:
|
||||
ValueError: If the target is not configured (e.g. no Signal number).
|
||||
Exception: Whatever the BEC messaging service raises. Callers that want a
|
||||
fire-and-forget send must catch it; the dialog's "Send test message" button
|
||||
deliberately does not, so the operator sees what went wrong.
|
||||
"""
|
||||
if settings.target == NotificationTarget.SCILOG:
|
||||
client.messaging.scilog.new(text).send()
|
||||
elif settings.target == NotificationTarget.SIGNAL:
|
||||
if not settings.signal_number:
|
||||
raise ValueError("No Signal phone number/contact set.")
|
||||
client.messaging.signal.new(text).send(scope=settings.signal_number)
|
||||
else:
|
||||
raise ValueError(f"Unsupported notification target {settings.target!r}.")
|
||||
|
||||
|
||||
def notify_item_finished(
|
||||
client, settings: NotificationSettings, item: ScheduleItem, description: str
|
||||
) -> None:
|
||||
"""
|
||||
Send a message about a finished schedule item, if notifications are enabled for the item's
|
||||
category and final status. Never raises.
|
||||
|
||||
Args:
|
||||
client: BEC client.
|
||||
settings: Notification settings of the schedule.
|
||||
item: The finished item (COMPLETED, FAILED or ABORTED).
|
||||
description: Human-readable description of the item (the "Command" column text).
|
||||
"""
|
||||
spec = ACTIONS.get(item.action)
|
||||
if not settings.enabled or spec is None or not _enabled_for_category(settings, spec.category):
|
||||
return
|
||||
if item.status not in settings.events:
|
||||
return
|
||||
|
||||
text = f"**BEC Scheduler**\n{spec.label} {item.status.name.lower()}"
|
||||
if item.scan_number is not None:
|
||||
text += f"\nScan number: {item.scan_number}"
|
||||
text += f"\n\n{description}"
|
||||
if item.report:
|
||||
text += f"\n\n{item.report}"
|
||||
_send_safe(client, settings, text)
|
||||
|
||||
|
||||
def notify_schedule_state(
|
||||
client, settings: NotificationSettings, schedule_name: str, state: ScheduleState
|
||||
) -> None:
|
||||
"""Send a message when the schedule starts or stops (if notifications are on). Never raises."""
|
||||
if not settings.enabled:
|
||||
return
|
||||
text = f'**BEC Scheduler**\nSchedule "{schedule_name}" {_STATE_TEXT.get(state, state)}'
|
||||
_send_safe(client, settings, text)
|
||||
|
||||
|
||||
def _send_safe(client, settings: NotificationSettings, text: str) -> None:
|
||||
try:
|
||||
send_notification(client, settings, text)
|
||||
except Exception: # pylint: disable=broad-except
|
||||
logger.exception(f"Failed to send schedule notification via {settings.target.value}")
|
||||
@@ -0,0 +1,15 @@
|
||||
def main(): # pragma: no cover
|
||||
from qtpy import PYSIDE6
|
||||
|
||||
if not PYSIDE6:
|
||||
print("PYSIDE6 is not available in the environment. Cannot patch designer.")
|
||||
return
|
||||
from PySide6.QtDesigner import QPyDesignerCustomWidgetCollection
|
||||
|
||||
from .scheduler_plugin import SchedulerPlugin
|
||||
|
||||
QPyDesignerCustomWidgetCollection.addCustomWidget(SchedulerPlugin())
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
main()
|
||||
@@ -0,0 +1,153 @@
|
||||
"""
|
||||
Pure bookkeeping over a list of `ScheduleItem`s - no Qt, no locking, no I/O - so that it can be
|
||||
unit-tested on its own. Callers (the widget and the executor) hold their own lock while calling
|
||||
these functions.
|
||||
|
||||
Two concepts are handled here:
|
||||
|
||||
**Protected prefix.** Items are executed from top to bottom. Everything before the first PENDING
|
||||
item has already started or finished (RUNNING, COMPLETED, FAILED, ABORTED) and must not be
|
||||
moved, edited or deleted; new items can never be inserted before it. Because of background items
|
||||
(see below), several items of that prefix may be RUNNING at the same time.
|
||||
|
||||
**Blocks.** An item with `wait_for_completion=False` ("background item") is started and the
|
||||
schedule immediately continues with the following items, which form its *block* and are shown
|
||||
indented. A block ends
|
||||
|
||||
- with a "Wait until parent has completed" item (which belongs to the block, as its last child),
|
||||
- implicitly right before the next background item (no nesting), or
|
||||
- at the end of the schedule.
|
||||
|
||||
The block structure is derived from the item order every time it is needed and never stored, so
|
||||
moving, adding or deleting items automatically updates which block an item belongs to.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum
|
||||
|
||||
from .actions import WAIT_FOR_PARENT
|
||||
from .models import ItemStatus, ScheduleItem
|
||||
|
||||
|
||||
class BlockRole(str, Enum):
|
||||
"""Position of an item relative to the block structure (used for drawing guide lines)."""
|
||||
|
||||
NONE = "none" # not part of a block
|
||||
PARENT = "parent" # background item that opens a block
|
||||
PARENT_EMPTY = "parent_empty" # background item without any children
|
||||
CHILD = "child" # inside a block
|
||||
LAST_CHILD = "last_child" # last item of a block
|
||||
|
||||
|
||||
def opens_block(item: ScheduleItem) -> bool:
|
||||
"""True if the item is a background item, i.e. starts a block of following items."""
|
||||
return not item.wait_for_completion and item.action != WAIT_FOR_PARENT
|
||||
|
||||
|
||||
def block_parents(items: list[ScheduleItem]) -> list[int | None]:
|
||||
"""
|
||||
For every item, the index of the background item whose block it belongs to.
|
||||
|
||||
Returns:
|
||||
A list with one entry per item: the index of its parent, or None if the item is not
|
||||
inside a block. Background items themselves are never inside a block.
|
||||
"""
|
||||
parents: list[int | None] = []
|
||||
current: int | None = None
|
||||
for idx, item in enumerate(items):
|
||||
if opens_block(item):
|
||||
current = idx
|
||||
parents.append(None)
|
||||
elif current is not None:
|
||||
parents.append(current)
|
||||
if item.action == WAIT_FOR_PARENT:
|
||||
current = None
|
||||
else:
|
||||
parents.append(None)
|
||||
return parents
|
||||
|
||||
|
||||
def item_depths(items: list[ScheduleItem]) -> list[int]:
|
||||
"""Indentation level of every item: 1 inside a block, 0 otherwise."""
|
||||
return [0 if parent is None else 1 for parent in block_parents(items)]
|
||||
|
||||
|
||||
def block_roles(items: list[ScheduleItem]) -> list[BlockRole]:
|
||||
"""The `BlockRole` of every item, e.g. for drawing the block guide lines in the table."""
|
||||
parents = block_parents(items)
|
||||
roles: list[BlockRole] = []
|
||||
for idx, item in enumerate(items):
|
||||
next_parent = parents[idx + 1] if idx + 1 < len(items) else None
|
||||
if opens_block(item):
|
||||
roles.append(BlockRole.PARENT if next_parent == idx else BlockRole.PARENT_EMPTY)
|
||||
elif parents[idx] is not None:
|
||||
last = next_parent != parents[idx]
|
||||
roles.append(BlockRole.LAST_CHILD if last else BlockRole.CHILD)
|
||||
else:
|
||||
roles.append(BlockRole.NONE)
|
||||
return roles
|
||||
|
||||
|
||||
def protected_prefix_length(items: list[ScheduleItem]) -> int:
|
||||
"""Number of leading items that are no longer PENDING (see module docstring)."""
|
||||
count = 0
|
||||
for item in items:
|
||||
if item.status != ItemStatus.PENDING:
|
||||
count += 1
|
||||
else:
|
||||
break
|
||||
return count
|
||||
|
||||
|
||||
def index_of(items: list[ScheduleItem], item_id: str | None) -> int | None:
|
||||
"""Index of the item with `item_id`, or None if there is no such item."""
|
||||
if item_id is None:
|
||||
return None
|
||||
for idx, item in enumerate(items):
|
||||
if item.item_id == item_id:
|
||||
return idx
|
||||
return None
|
||||
|
||||
|
||||
def pick_next_runnable(
|
||||
items: list[ScheduleItem],
|
||||
retry_unfinished: bool = False,
|
||||
first_index: int = 0,
|
||||
active_ids: frozenset[str] | set[str] = frozenset(),
|
||||
attempted_ids: frozenset[str] | set[str] = frozenset(),
|
||||
) -> ScheduleItem | None:
|
||||
"""
|
||||
Decide which item the execution loop should handle next.
|
||||
|
||||
This is always re-derived from the current list (never a remembered index), so edits to the
|
||||
PENDING part of the schedule between two calls are picked up.
|
||||
|
||||
Args:
|
||||
items: The schedule items.
|
||||
retry_unfinished: If True, FAILED and ABORTED items are run again (once per run, see
|
||||
`attempted_ids`); otherwise they are skipped.
|
||||
first_index: Items before this index are ignored ("run from selection").
|
||||
active_ids: Ids of items that are currently being executed by this executor (e.g. a
|
||||
running background item); they are skipped.
|
||||
attempted_ids: Ids of items already started during the current run. A FAILED/ABORTED
|
||||
item is only retried if it has not been attempted in this run yet, so a failing
|
||||
item cannot be retried in an endless loop.
|
||||
|
||||
Returns:
|
||||
The next PENDING item, a RUNNING item that is not owned by this executor (left over
|
||||
from a previous widget session; the caller should re-attach to it), a FAILED/ABORTED
|
||||
item if `retry_unfinished` is set, or None if nothing is left to do.
|
||||
"""
|
||||
for idx, item in enumerate(items):
|
||||
if idx < first_index or item.item_id in active_ids:
|
||||
continue
|
||||
if item.status in (ItemStatus.PENDING, ItemStatus.RUNNING):
|
||||
return item
|
||||
if (
|
||||
retry_unfinished
|
||||
and item.status in (ItemStatus.FAILED, ItemStatus.ABORTED)
|
||||
and item.item_id not in attempted_ids
|
||||
):
|
||||
return item
|
||||
return None
|
||||
@@ -0,0 +1,424 @@
|
||||
"""
|
||||
Table model and view showing a schedule.
|
||||
|
||||
Columns: line number | status | command | report | pause on failure | pause on state |
|
||||
wait for completion. All columns except "Command" and "Report" have a fixed width; those two
|
||||
share the remaining width 50/50.
|
||||
|
||||
Items inside the block of a background item (`wait_for_completion=False`) are indented in the
|
||||
"Command" column, and a vertical guide line connects them with their parent, so it is visible
|
||||
which items run while the parent is still busy (see `schedule_logic` for the block rules).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from bec_qthemes import material_icon
|
||||
from bec_widgets.utils.colors import get_accent_colors
|
||||
|
||||
# pylint: disable=no-name-in-module # qtpy re-exports are not visible to pylint
|
||||
from qtpy.QtCore import QAbstractTableModel, QModelIndex, QRect, QSize, Qt, QTimer, Signal
|
||||
from qtpy.QtGui import QKeySequence, QPen
|
||||
from qtpy.QtWidgets import QHeaderView, QStyle, QStyledItemDelegate, QTableView
|
||||
|
||||
from .actions import ACTIONS, DELAY, describe_item, format_duration
|
||||
from .models import ItemStatus, ScheduleItem
|
||||
from .schedule_logic import BlockRole, block_roles, item_depths
|
||||
|
||||
# Qt virtual overrides (rowCount, data, paint, sizeHint, ...) keep Qt's names and docs.
|
||||
# pylint: disable=invalid-name,missing-function-docstring,too-many-return-statements
|
||||
|
||||
|
||||
ICON_SIZE = 20
|
||||
INDENT_WIDTH = 24 # px per indentation level in the "Command" column
|
||||
_ROW_MARGIN = 6 # total vertical padding (top + bottom) of a text cell
|
||||
|
||||
_STATUS_ICONS = {
|
||||
ItemStatus.PENDING: ("hourglass", "#919090"),
|
||||
ItemStatus.RUNNING: ("cycle", "#2980b9"),
|
||||
ItemStatus.COMPLETED: ("check", "#27ae60"),
|
||||
ItemStatus.FAILED: ("warning", "#e74c3c"),
|
||||
ItemStatus.ABORTED: ("cancel", "#e6d922"),
|
||||
}
|
||||
|
||||
#: Custom data roles
|
||||
DepthRole = Qt.ItemDataRole.UserRole + 1
|
||||
BlockRoleRole = Qt.ItemDataRole.UserRole + 2
|
||||
|
||||
|
||||
class ScheduleTableModel(QAbstractTableModel):
|
||||
"""
|
||||
Read-only table model over a snapshot of `Schedule.items`.
|
||||
|
||||
The widget calls `set_items()` with a fresh copy whenever the schedule changes (a full model
|
||||
reset - schedules are short, and this keeps the model free of locking). Display text comes
|
||||
from the action registry (`actions.describe_item`), block indentation from
|
||||
`schedule_logic.item_depths`.
|
||||
"""
|
||||
|
||||
COL_LINE = 0
|
||||
COL_STATUS = 1
|
||||
COL_COMMAND = 2
|
||||
COL_REPORT = 3
|
||||
COL_PAUSE_ON_FAILURE = 4
|
||||
COL_PAUSE_ON_STATE = 5
|
||||
COL_WAIT = 6
|
||||
HEADERS = (
|
||||
"Line",
|
||||
"Status",
|
||||
"Command",
|
||||
"Report",
|
||||
"Pause on failure",
|
||||
"Pause on state",
|
||||
"Wait for completion",
|
||||
)
|
||||
ICON_COLUMNS = (COL_STATUS, COL_PAUSE_ON_FAILURE, COL_PAUSE_ON_STATE, COL_WAIT)
|
||||
|
||||
def __init__(self, parent=None, beamline: str | None = None):
|
||||
super().__init__(parent)
|
||||
self._items: list[ScheduleItem] = []
|
||||
self._depths: list[int] = []
|
||||
self._roles: list[BlockRole] = []
|
||||
self._beamline = beamline
|
||||
# The status icon of the selected row is drawn white (on the selection colour). Kept
|
||||
# here rather than read from the view so it survives a model reset.
|
||||
self._selected_item_id: str | None = None
|
||||
|
||||
# ---- Qt model API ---- #
|
||||
def rowCount(self, parent: QModelIndex = QModelIndex()) -> int: # noqa: N802
|
||||
return 0 if parent.isValid() else len(self._items)
|
||||
|
||||
def columnCount(self, parent: QModelIndex = QModelIndex()) -> int: # noqa: N802
|
||||
return 0 if parent.isValid() else len(self.HEADERS)
|
||||
|
||||
def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole): # noqa: N802
|
||||
if orientation != Qt.Orientation.Horizontal:
|
||||
return None
|
||||
if role == Qt.ItemDataRole.DisplayRole:
|
||||
return self.HEADERS[section]
|
||||
if role == Qt.ItemDataRole.TextAlignmentRole:
|
||||
if section in (self.COL_COMMAND, self.COL_REPORT):
|
||||
return int(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
|
||||
return int(Qt.AlignmentFlag.AlignCenter)
|
||||
return None
|
||||
|
||||
def data(self, index: QModelIndex, role=Qt.ItemDataRole.DisplayRole):
|
||||
if not index.isValid():
|
||||
return None
|
||||
row, col = index.row(), index.column()
|
||||
item = self._items[row]
|
||||
|
||||
if role == Qt.ItemDataRole.DisplayRole:
|
||||
if col == self.COL_LINE:
|
||||
return str(row + 1)
|
||||
if col == self.COL_COMMAND:
|
||||
return describe_item(item, self._beamline)
|
||||
if col == self.COL_REPORT:
|
||||
return self._report_text(item)
|
||||
return None
|
||||
if role == Qt.ItemDataRole.DecorationRole:
|
||||
return self._icon(item, col)
|
||||
if role == Qt.ItemDataRole.ToolTipRole:
|
||||
return self._tooltip(item, col)
|
||||
if role == Qt.ItemDataRole.TextAlignmentRole and col == self.COL_LINE:
|
||||
return int(Qt.AlignmentFlag.AlignCenter)
|
||||
if role == DepthRole:
|
||||
return self._depths[row]
|
||||
if role == BlockRoleRole:
|
||||
return self._roles[row]
|
||||
return None
|
||||
|
||||
# ---- content ---- #
|
||||
def set_items(self, items: list[ScheduleItem], selected_item_id: str | None = None) -> None:
|
||||
"""
|
||||
Replace the displayed items (full model reset).
|
||||
|
||||
Args:
|
||||
items: Snapshot of the schedule items.
|
||||
selected_item_id: Item whose status icon is drawn for the selected row.
|
||||
"""
|
||||
self.beginResetModel()
|
||||
self._selected_item_id = selected_item_id
|
||||
self._items = list(items)
|
||||
self._depths = item_depths(self._items)
|
||||
self._roles = block_roles(self._items)
|
||||
self.endResetModel()
|
||||
|
||||
def set_selected_item_id(self, item_id: str | None) -> None:
|
||||
"""Remember the selected item and repaint the status icons (no full reset)."""
|
||||
self._selected_item_id = item_id
|
||||
self._emit_column_changed(self.COL_STATUS, [Qt.ItemDataRole.DecorationRole])
|
||||
|
||||
def refresh_live_cells(self) -> None:
|
||||
"""Repaint the report of running delays (remaining time). Called once per second."""
|
||||
if any(item.status == ItemStatus.RUNNING and item.action == DELAY for item in self._items):
|
||||
self._emit_column_changed(self.COL_REPORT, [Qt.ItemDataRole.DisplayRole])
|
||||
|
||||
def item_id(self, row: int) -> str | None:
|
||||
"""Id of the item in `row`, or None."""
|
||||
return self._items[row].item_id if 0 <= row < len(self._items) else None
|
||||
|
||||
def row_of(self, item_id: str | None) -> int | None:
|
||||
"""Row of the item with `item_id`, or None."""
|
||||
for row, item in enumerate(self._items):
|
||||
if item.item_id == item_id:
|
||||
return row
|
||||
return None
|
||||
|
||||
def _emit_column_changed(self, column: int, roles: list) -> None:
|
||||
if self._items:
|
||||
self.dataChanged.emit(
|
||||
self.index(0, column), self.index(len(self._items) - 1, column), roles
|
||||
)
|
||||
|
||||
# ---- cell content helpers ---- #
|
||||
@staticmethod
|
||||
def _report_text(item: ScheduleItem) -> str:
|
||||
if item.status == ItemStatus.RUNNING and item.action == DELAY and item.started_at:
|
||||
remaining = item.params.get("seconds", 0) - (time.time() - item.started_at)
|
||||
return f"{format_duration(remaining)} remaining"
|
||||
if item.status == ItemStatus.RUNNING and not item.report:
|
||||
return "Running..."
|
||||
return item.report or ""
|
||||
|
||||
def _icon(self, item: ScheduleItem, col: int):
|
||||
if col == self.COL_STATUS:
|
||||
name, color = _STATUS_ICONS[item.status]
|
||||
if item.item_id == self._selected_item_id:
|
||||
color = "#FFFFFF"
|
||||
return _pixmap(name, color)
|
||||
if col == self.COL_PAUSE_ON_FAILURE and item.pause_on_failure:
|
||||
return _pixmap("pause_circle", "#e6d922")
|
||||
if col == self.COL_PAUSE_ON_STATE and item.pause_on_state:
|
||||
return _pixmap("shield", "#2980b9")
|
||||
if col == self.COL_WAIT and ACTIONS.get(item.action) is not None:
|
||||
if ACTIONS[item.action].category == "control":
|
||||
return None
|
||||
if item.wait_for_completion:
|
||||
return _pixmap("hourglass_bottom", "#919090")
|
||||
return _pixmap("call_split", get_accent_colors().highlight.name())
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _tooltip(item: ScheduleItem, col: int) -> str | None:
|
||||
if col == ScheduleTableModel.COL_STATUS:
|
||||
return item.status.name.capitalize()
|
||||
if col == ScheduleTableModel.COL_REPORT and item.error:
|
||||
return item.error
|
||||
if col == ScheduleTableModel.COL_PAUSE_ON_FAILURE:
|
||||
return "Pauses the schedule if this item fails" if item.pause_on_failure else None
|
||||
if col == ScheduleTableModel.COL_PAUSE_ON_STATE:
|
||||
if item.pause_on_state:
|
||||
return (
|
||||
"Waits for all beamline states to be valid before starting;\n"
|
||||
"running scans are interrupted and repeated if a state becomes invalid"
|
||||
)
|
||||
return None
|
||||
if col == ScheduleTableModel.COL_WAIT:
|
||||
if not item.wait_for_completion:
|
||||
return "Runs in the background: the following (indented) items start right away"
|
||||
return "The schedule waits for this item to complete"
|
||||
return None
|
||||
|
||||
|
||||
def _pixmap(name: str, color: str):
|
||||
return material_icon(name, size=(ICON_SIZE, ICON_SIZE), color=color, convert_to_pixmap=True)
|
||||
|
||||
|
||||
def _paint_background(painter, option) -> None:
|
||||
if option.state & QStyle.StateFlag.State_Selected:
|
||||
painter.fillRect(option.rect, option.palette.highlight())
|
||||
painter.setPen(option.palette.highlightedText().color())
|
||||
else:
|
||||
painter.setPen(option.palette.text().color())
|
||||
|
||||
|
||||
class _TextDelegate(QStyledItemDelegate):
|
||||
"""
|
||||
Paints word-wrapped, multi-line text and reports the height the wrapped text needs at the
|
||||
current column width, so the view's ResizeToContents row mode shows the full text. If
|
||||
`indent` is True, the text is indented by the item's block depth and the block guide line
|
||||
is drawn.
|
||||
|
||||
Selection is painted with the palette highlight colour, like `BecLogTableView`.
|
||||
"""
|
||||
|
||||
_FLAGS = Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter
|
||||
_H_MARGIN = 6
|
||||
|
||||
def __init__(self, parent=None, indent: bool = False):
|
||||
super().__init__(parent)
|
||||
self._indent = indent
|
||||
|
||||
def _text_rect(self, cell: QRect, index: QModelIndex) -> QRect:
|
||||
"""Area of the cell the text is drawn in (margins and block indentation removed)."""
|
||||
rect = cell.adjusted(self._H_MARGIN, _ROW_MARGIN // 2, -self._H_MARGIN, -(_ROW_MARGIN // 2))
|
||||
if self._indent:
|
||||
rect.setLeft(rect.left() + (index.data(DepthRole) or 0) * INDENT_WIDTH)
|
||||
return rect
|
||||
|
||||
def paint(self, painter, option, index):
|
||||
painter.save()
|
||||
_paint_background(painter, option)
|
||||
painter.setFont(option.font)
|
||||
text_pen = painter.pen()
|
||||
if self._indent:
|
||||
self._paint_guide(painter, option.rect, index.data(BlockRoleRole))
|
||||
painter.setPen(text_pen)
|
||||
text = index.data(Qt.ItemDataRole.DisplayRole) or ""
|
||||
painter.drawText(self._text_rect(option.rect, index), int(self._FLAGS), text)
|
||||
painter.restore()
|
||||
|
||||
@staticmethod
|
||||
def _paint_guide(painter, rect: QRect, role: BlockRole | None) -> None:
|
||||
"""
|
||||
Draw the block guide line of a child row: a vertical line from the top edge of the row
|
||||
(i.e. the bottom edge of the row above, ending there so it never crosses the parent's
|
||||
text) down to the next child, plus a short tick towards the indented text.
|
||||
"""
|
||||
if role not in (BlockRole.CHILD, BlockRole.LAST_CHILD):
|
||||
return
|
||||
pen = QPen(get_accent_colors().highlight)
|
||||
pen.setWidth(2)
|
||||
painter.setPen(pen)
|
||||
x = rect.left() + 10
|
||||
mid = rect.center().y()
|
||||
bottom = mid if role == BlockRole.LAST_CHILD else rect.bottom()
|
||||
painter.drawLine(x, rect.top(), x, bottom)
|
||||
painter.drawLine(x, mid, x + INDENT_WIDTH - 8, mid)
|
||||
|
||||
def sizeHint(self, option, index): # noqa: N802
|
||||
text = index.data(Qt.ItemDataRole.DisplayRole) or ""
|
||||
view = self.parent()
|
||||
column_width = (
|
||||
view.columnWidth(index.column())
|
||||
if isinstance(view, QTableView)
|
||||
else option.rect.width()
|
||||
)
|
||||
cell = QRect(0, 0, max(column_width, 1), 100000)
|
||||
width = max(self._text_rect(cell, index).width(), 20)
|
||||
text_height = option.fontMetrics.boundingRect(
|
||||
QRect(0, 0, width, 100000), int(self._FLAGS), text
|
||||
).height()
|
||||
height = max(text_height + _ROW_MARGIN, ICON_SIZE + _ROW_MARGIN)
|
||||
return QSize(column_width, height)
|
||||
|
||||
|
||||
class _CenteredIconDelegate(QStyledItemDelegate):
|
||||
"""Paints the DecorationRole pixmap centred in the cell."""
|
||||
|
||||
def paint(self, painter, option, index):
|
||||
painter.save()
|
||||
_paint_background(painter, option)
|
||||
pixmap = index.data(Qt.ItemDataRole.DecorationRole)
|
||||
if pixmap is not None:
|
||||
x = option.rect.center().x() - ICON_SIZE // 2
|
||||
y = option.rect.center().y() - ICON_SIZE // 2
|
||||
painter.drawPixmap(x, y, pixmap)
|
||||
painter.restore()
|
||||
|
||||
|
||||
class _CenteredTextDelegate(QStyledItemDelegate):
|
||||
"""Paints short single-line text centred in the cell (line numbers)."""
|
||||
|
||||
def paint(self, painter, option, index):
|
||||
painter.save()
|
||||
_paint_background(painter, option)
|
||||
painter.drawText(
|
||||
option.rect, int(Qt.AlignmentFlag.AlignCenter), index.data(Qt.ItemDataRole.DisplayRole)
|
||||
)
|
||||
painter.restore()
|
||||
|
||||
|
||||
class ScheduleTableView(QTableView):
|
||||
"""
|
||||
Table view for a `ScheduleTableModel`: single row selection, fixed-width icon columns,
|
||||
"Command" and "Report" sharing the remaining width, plus keyboard shortcuts.
|
||||
|
||||
Signals:
|
||||
deletePressed: The Delete key was pressed on a selected row.
|
||||
copyPressed / pastePressed: The standard copy/paste shortcut was pressed.
|
||||
emptySpaceClicked: The user clicked below the last row (clears the selection).
|
||||
"""
|
||||
|
||||
deletePressed = Signal()
|
||||
emptySpaceClicked = Signal()
|
||||
copyPressed = Signal()
|
||||
pastePressed = Signal()
|
||||
|
||||
FIXED_WIDTHS = {
|
||||
ScheduleTableModel.COL_LINE: 50,
|
||||
ScheduleTableModel.COL_STATUS: 60,
|
||||
ScheduleTableModel.COL_PAUSE_ON_FAILURE: 120,
|
||||
ScheduleTableModel.COL_PAUSE_ON_STATE: 110,
|
||||
ScheduleTableModel.COL_WAIT: 145,
|
||||
}
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows)
|
||||
self.setSelectionMode(QTableView.SelectionMode.SingleSelection)
|
||||
self.setEditTriggers(QTableView.EditTrigger.NoEditTriggers)
|
||||
self.setShowGrid(False)
|
||||
self.setWordWrap(True)
|
||||
self.verticalHeader().hide()
|
||||
# ResizeToContents so that a row grows with the number of text lines of its cells.
|
||||
self.verticalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)
|
||||
|
||||
self.setItemDelegateForColumn(ScheduleTableModel.COL_LINE, _CenteredTextDelegate(self))
|
||||
self.setItemDelegateForColumn(
|
||||
ScheduleTableModel.COL_COMMAND, _TextDelegate(self, indent=True)
|
||||
)
|
||||
self.setItemDelegateForColumn(ScheduleTableModel.COL_REPORT, _TextDelegate(self))
|
||||
icon_delegate = _CenteredIconDelegate(self)
|
||||
for col in ScheduleTableModel.ICON_COLUMNS:
|
||||
self.setItemDelegateForColumn(col, icon_delegate)
|
||||
|
||||
# Wrapped text needs more or fewer lines when the stretching columns change width, so
|
||||
# the row heights are recomputed (once per event-loop pass) after any column resize.
|
||||
self._row_resize_timer = QTimer(self)
|
||||
self._row_resize_timer.setSingleShot(True)
|
||||
self._row_resize_timer.setInterval(0)
|
||||
self._row_resize_timer.timeout.connect(self._resize_rows)
|
||||
self.horizontalHeader().sectionResized.connect(self._row_resize_timer.start)
|
||||
|
||||
def _resize_rows(self) -> None:
|
||||
self.verticalHeader().resizeSections(QHeaderView.ResizeMode.ResizeToContents)
|
||||
|
||||
def configure_columns(self) -> None:
|
||||
"""Apply the column sizing; call after `setModel()`."""
|
||||
header = self.horizontalHeader()
|
||||
header.setStretchLastSection(False)
|
||||
for col, width in self.FIXED_WIDTHS.items():
|
||||
header.setSectionResizeMode(col, QHeaderView.ResizeMode.Fixed)
|
||||
header.resizeSection(col, width)
|
||||
# Both stretch columns get the same stretch factor -> the leftover width is shared 50/50.
|
||||
header.setSectionResizeMode(ScheduleTableModel.COL_COMMAND, QHeaderView.ResizeMode.Stretch)
|
||||
header.setSectionResizeMode(ScheduleTableModel.COL_REPORT, QHeaderView.ResizeMode.Stretch)
|
||||
|
||||
def keyPressEvent(self, event): # noqa: N802
|
||||
if event.key() == Qt.Key.Key_Delete and self.currentIndex().isValid():
|
||||
self.deletePressed.emit()
|
||||
event.accept()
|
||||
return
|
||||
if event.matches(QKeySequence.StandardKey.Copy) and self.currentIndex().isValid():
|
||||
self.copyPressed.emit()
|
||||
event.accept()
|
||||
return
|
||||
if event.matches(QKeySequence.StandardKey.Paste):
|
||||
self.pastePressed.emit()
|
||||
event.accept()
|
||||
return
|
||||
super().keyPressEvent(event)
|
||||
|
||||
def mousePressEvent(self, event): # noqa: N802
|
||||
if (
|
||||
event.button() == Qt.MouseButton.LeftButton
|
||||
and not self.indexAt(event.position().toPoint()).isValid()
|
||||
):
|
||||
self.clearSelection()
|
||||
self.setCurrentIndex(QModelIndex())
|
||||
self.emptySpaceClicked.emit()
|
||||
return
|
||||
super().mousePressEvent(event)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
||||
{'files': ['scheduler.py']}
|
||||
@@ -0,0 +1,57 @@
|
||||
# Copyright (C) 2022 The Qt Company Ltd.
|
||||
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
|
||||
|
||||
from bec_widgets.utils.bec_designer import designer_material_icon
|
||||
from qtpy.QtDesigner import QDesignerCustomWidgetInterface
|
||||
from qtpy.QtWidgets import QWidget
|
||||
|
||||
from .scheduler import Scheduler
|
||||
|
||||
DOM_XML = """
|
||||
<ui language='c++'>
|
||||
<widget class='Scheduler' name='scheduler'>
|
||||
</widget>
|
||||
</ui>
|
||||
"""
|
||||
|
||||
|
||||
class SchedulerPlugin(QDesignerCustomWidgetInterface): # pragma: no cover
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._form_editor = None
|
||||
|
||||
def createWidget(self, parent):
|
||||
if parent is None:
|
||||
return QWidget()
|
||||
t = Scheduler(parent)
|
||||
return t
|
||||
|
||||
def domXml(self):
|
||||
return DOM_XML
|
||||
|
||||
def group(self):
|
||||
return ""
|
||||
|
||||
def icon(self):
|
||||
return designer_material_icon(Scheduler.ICON_NAME)
|
||||
|
||||
def includeFile(self):
|
||||
return "scheduler"
|
||||
|
||||
def initialize(self, form_editor):
|
||||
self._form_editor = form_editor
|
||||
|
||||
def isContainer(self):
|
||||
return False
|
||||
|
||||
def isInitialized(self):
|
||||
return self._form_editor is not None
|
||||
|
||||
def name(self):
|
||||
return "Scheduler"
|
||||
|
||||
def toolTip(self):
|
||||
return "Scheduler"
|
||||
|
||||
def whatsThis(self):
|
||||
return self.toolTip()
|
||||
@@ -0,0 +1,190 @@
|
||||
"""
|
||||
Watch all BEC beamline states on behalf of the Scheduler ("pause on state").
|
||||
|
||||
Beamline states are created, edited and deleted with BEC's own `BeamlineStateManager` widget,
|
||||
which the Scheduler embeds. This module only *reads* them: it follows
|
||||
`MessageEndpoints.available_beamline_states()` to learn which states exist, subscribes to
|
||||
`MessageEndpoints.beamline_state(name)` of each of them through the `BECDispatcher`, and keeps
|
||||
track of whether all of them are acceptable (VALID or WARNING).
|
||||
|
||||
Dispatcher callbacks run on the Qt GUI thread. The schedule executor runs on a worker thread and
|
||||
only uses the thread-safe `is_ok()` / `wait_until_ok()` methods, backed by a `threading.Event`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from typing import Any, Callable
|
||||
|
||||
from bec_lib.endpoints import MessageEndpoints
|
||||
from bec_lib.logger import bec_logger
|
||||
from bec_widgets.utils.error_popups import SafeSlot
|
||||
|
||||
# pylint: disable=no-name-in-module # qtpy re-exports are not visible to pylint
|
||||
from qtpy.QtCore import QObject, Signal
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
#: Beamline state statuses that do not pause gated schedule items.
|
||||
OK_STATUSES = frozenset({"valid", "warning"})
|
||||
|
||||
|
||||
def _state_name(state: Any) -> str | None:
|
||||
"""Name of a `BeamlineStateConfig` (object or plain dict)."""
|
||||
if isinstance(state, dict):
|
||||
return state.get("name")
|
||||
return getattr(state, "name", None)
|
||||
|
||||
|
||||
class BeamlineStateMonitor(QObject):
|
||||
"""
|
||||
Aggregates the status of all beamline states.
|
||||
|
||||
Signals:
|
||||
tripped(): At least one state left VALID/WARNING (was OK before).
|
||||
recovered(): All states are VALID/WARNING again (was not OK before).
|
||||
statuses_changed(): Any status changed, or a state was added/removed.
|
||||
|
||||
A state whose status is still unknown (e.g. right after creation, or if its device is not
|
||||
reachable) counts as not OK, so that gated items never start on unverified conditions.
|
||||
Without any beamline states, the monitor is always OK.
|
||||
"""
|
||||
|
||||
tripped = Signal()
|
||||
recovered = Signal()
|
||||
statuses_changed = Signal()
|
||||
|
||||
def __init__(self, client, bec_dispatcher, parent: QObject | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self._client = client
|
||||
self._dispatcher = bec_dispatcher
|
||||
self._lock = threading.Lock()
|
||||
self._statuses: dict[str, str] = {}
|
||||
self._ok_event = threading.Event()
|
||||
self._ok_event.set()
|
||||
|
||||
self._dispatcher.connect_slot(
|
||||
self._on_available_states, MessageEndpoints.available_beamline_states()
|
||||
)
|
||||
msg = self._client.connector.get_last(
|
||||
MessageEndpoints.available_beamline_states(), key="data"
|
||||
)
|
||||
if msg is not None:
|
||||
self._on_available_states(msg.content, msg.metadata)
|
||||
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
# Thread-safe queries (used by the executor's worker thread)
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
def is_ok(self) -> bool:
|
||||
"""True if every beamline state is VALID or WARNING (or no states exist)."""
|
||||
return self._ok_event.is_set()
|
||||
|
||||
def wait_until_ok(self, should_abort: Callable[[], bool], poll_interval: float = 0.5) -> bool:
|
||||
"""
|
||||
Block the calling (non-GUI) thread until `is_ok()` is True.
|
||||
|
||||
Args:
|
||||
should_abort: Polled between waits; the wait ends early if it returns True.
|
||||
poll_interval: Seconds between two `should_abort` checks.
|
||||
|
||||
Returns:
|
||||
True if the states became OK, False if `should_abort()` returned True first.
|
||||
"""
|
||||
while not should_abort():
|
||||
if self._ok_event.wait(timeout=poll_interval):
|
||||
return True
|
||||
return False
|
||||
|
||||
def statuses(self) -> dict[str, str]:
|
||||
"""A copy of the current `{state name: status}` mapping."""
|
||||
with self._lock:
|
||||
return dict(self._statuses)
|
||||
|
||||
def blocking_states(self) -> list[str]:
|
||||
"""Names of the states that currently prevent gated items from running."""
|
||||
with self._lock:
|
||||
return sorted(
|
||||
name for name, status in self._statuses.items() if status not in OK_STATUSES
|
||||
)
|
||||
|
||||
def summary(self) -> str:
|
||||
"""One-line, human-readable summary, e.g. for a status label."""
|
||||
statuses = self.statuses()
|
||||
if not statuses:
|
||||
return "No beamline states defined"
|
||||
blocking = self.blocking_states()
|
||||
if not blocking:
|
||||
return f"All {len(statuses)} beamline state(s) OK"
|
||||
return f"Not OK: {', '.join(blocking)} - items with 'pause on state' will wait"
|
||||
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
# Dispatcher callbacks (GUI thread)
|
||||
# ------------------------------------------------------------------------------------------ #
|
||||
@SafeSlot(dict, dict)
|
||||
def _on_available_states(self, content: dict, _metadata: dict | None = None) -> None:
|
||||
names = {name for state in content.get("states", []) if (name := _state_name(state))}
|
||||
with self._lock:
|
||||
known = set(self._statuses)
|
||||
for name in known - names:
|
||||
self._dispatcher.disconnect_slot(
|
||||
self._on_state_update, MessageEndpoints.beamline_state(name)
|
||||
)
|
||||
with self._lock:
|
||||
self._statuses.pop(name, None)
|
||||
for name in names - known:
|
||||
with self._lock:
|
||||
self._statuses[name] = "unknown"
|
||||
self._dispatcher.connect_slot(
|
||||
self._on_state_update, MessageEndpoints.beamline_state(name)
|
||||
)
|
||||
last = self._client.connector.get_last(
|
||||
MessageEndpoints.beamline_state(name), key="data"
|
||||
)
|
||||
if last is not None:
|
||||
self._set_status(name, last.content.get("status"))
|
||||
self._evaluate()
|
||||
|
||||
@SafeSlot(dict, dict)
|
||||
def _on_state_update(self, content: dict, _metadata: dict | None = None) -> None:
|
||||
name = content.get("name")
|
||||
if not name:
|
||||
return
|
||||
with self._lock:
|
||||
if name not in self._statuses:
|
||||
return # update of a state that was just removed
|
||||
self._set_status(name, content.get("status"))
|
||||
self._evaluate()
|
||||
|
||||
def _set_status(self, name: str, status: Any) -> None:
|
||||
with self._lock:
|
||||
self._statuses[name] = str(status or "unknown").lower()
|
||||
|
||||
def _evaluate(self) -> None:
|
||||
with self._lock:
|
||||
ok = all(status in OK_STATUSES for status in self._statuses.values())
|
||||
was_ok = self._ok_event.is_set()
|
||||
if ok:
|
||||
self._ok_event.set()
|
||||
else:
|
||||
self._ok_event.clear()
|
||||
self.statuses_changed.emit()
|
||||
if was_ok and not ok:
|
||||
logger.info(f"Scheduler: beamline state(s) not OK: {self.blocking_states()}")
|
||||
self.tripped.emit()
|
||||
elif ok and not was_ok:
|
||||
logger.info("Scheduler: all beamline states OK again.")
|
||||
self.recovered.emit()
|
||||
|
||||
def cleanup(self) -> None:
|
||||
"""Disconnect all dispatcher subscriptions and release waiting threads."""
|
||||
self._dispatcher.disconnect_slot(
|
||||
self._on_available_states, MessageEndpoints.available_beamline_states()
|
||||
)
|
||||
with self._lock:
|
||||
names = list(self._statuses)
|
||||
self._statuses.clear()
|
||||
for name in names:
|
||||
self._dispatcher.disconnect_slot(
|
||||
self._on_state_update, MessageEndpoints.beamline_state(name)
|
||||
)
|
||||
self._ok_event.set()
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Small reusable Qt widgets of the Scheduler."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from bec_widgets.utils.colors import get_accent_colors
|
||||
|
||||
# pylint: disable=no-name-in-module # qtpy re-exports are not visible to pylint
|
||||
from qtpy.QtWidgets import QPushButton
|
||||
|
||||
|
||||
class AccentButton(QPushButton):
|
||||
"""
|
||||
Push button filled with one of BEC's accent colours ("default", "success", "warning",
|
||||
"emergency", ...), greyed out while disabled.
|
||||
"""
|
||||
|
||||
def __init__(self, text: str = "", color: str = "default", parent=None):
|
||||
self.color = color
|
||||
super().__init__(text, parent)
|
||||
self.apply_theme()
|
||||
|
||||
def apply_theme(self) -> None:
|
||||
"""Re-apply the colours, e.g. after a theme change."""
|
||||
if self.isEnabled():
|
||||
color = getattr(get_accent_colors(), self.color).name()
|
||||
self.setStyleSheet(f"QPushButton {{ background-color: {color}; color: white; }}")
|
||||
else:
|
||||
self.setStyleSheet(
|
||||
"QPushButton { background-color: rgb(120, 120, 120); color: white; }"
|
||||
)
|
||||
|
||||
def setEnabled(self, enable: bool = True) -> None: # noqa: N802 pylint: disable=invalid-name
|
||||
"""Enable/disable the button and update its colours."""
|
||||
super().setEnabled(enable)
|
||||
self.apply_theme()
|
||||
Whitespace-only changes.
@@ -0,0 +1,273 @@
|
||||
"""
|
||||
Universal Qt widgets
|
||||
"""
|
||||
|
||||
from functools import partial
|
||||
|
||||
from bec_widgets.utils.colors import get_accent_colors
|
||||
from qtpy.QtCore import Qt
|
||||
|
||||
# pylint: disable=E0611
|
||||
from qtpy.QtGui import QFont
|
||||
from qtpy.QtWidgets import (
|
||||
QApplication,
|
||||
QComboBox,
|
||||
QDoubleSpinBox,
|
||||
QGroupBox,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QPushButton,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
LABEL_WIDTH = 118
|
||||
ROW_MARGINS = (4, 0, 4, 0)
|
||||
ROW_SPACING = 6
|
||||
|
||||
|
||||
class Group(QGroupBox):
|
||||
def __init__(self, label, widgets):
|
||||
super().__init__(label)
|
||||
self.layout = QVBoxLayout(self) # type: ignore
|
||||
self.layout.setContentsMargins(6, 6, 6, 6)
|
||||
self.layout.setSpacing(4)
|
||||
for widget in widgets:
|
||||
self.layout.addWidget(widget) # type: ignore
|
||||
|
||||
|
||||
class NumberIndicator(QWidget):
|
||||
def __init__(self, label="", unit=None, highlight=False, decimals=3):
|
||||
super().__init__()
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(*ROW_MARGINS)
|
||||
layout.setSpacing(ROW_SPACING)
|
||||
self.label = QLabel(label)
|
||||
self.label.setFixedWidth(LABEL_WIDTH)
|
||||
self.label.setWordWrap(True)
|
||||
layout.addWidget(self.label)
|
||||
self.val = QLabel("-")
|
||||
self.val.setAlignment(Qt.AlignTop) # type: ignore
|
||||
layout.addWidget(self.val)
|
||||
self.unit = unit
|
||||
self.highlight = highlight
|
||||
self.decimals = decimals
|
||||
self.number = 0
|
||||
if highlight:
|
||||
font = QFont()
|
||||
font.setBold(True)
|
||||
font.setPointSize(14)
|
||||
self.label.setFont(font)
|
||||
self.val.setFont(font)
|
||||
|
||||
def value(self) -> float:
|
||||
return self.number
|
||||
|
||||
def setLabel(self, label) -> None:
|
||||
self.label.setText(label)
|
||||
|
||||
def setValue(self, number):
|
||||
self.number = number
|
||||
text = f"{number:.{int(self.decimals)}f}"
|
||||
if self.unit is not None:
|
||||
text = text + " " + self.unit
|
||||
self.val.setText(text)
|
||||
|
||||
|
||||
class InputNumberField(QWidget):
|
||||
def __init__(
|
||||
self,
|
||||
identifier="",
|
||||
label="",
|
||||
unit=None,
|
||||
prefix=None,
|
||||
init=0.0,
|
||||
decimals=1,
|
||||
single_step=0.1,
|
||||
ll=-1e6,
|
||||
hl=1e6,
|
||||
):
|
||||
super().__init__()
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(*ROW_MARGINS)
|
||||
layout.setSpacing(ROW_SPACING)
|
||||
self.identifier = identifier
|
||||
self.label = QLabel(label)
|
||||
self.label.setFixedWidth(LABEL_WIDTH)
|
||||
self.label.setWordWrap(True)
|
||||
layout.addWidget(self.label)
|
||||
self.val = QDoubleSpinBox()
|
||||
self.val.setRange(ll, hl)
|
||||
self.val.setDecimals(decimals)
|
||||
self.val.setSingleStep(single_step)
|
||||
self.val.setValue(init)
|
||||
if unit is not None:
|
||||
self.val.setSuffix(" " + unit)
|
||||
if prefix is not None:
|
||||
self.val.setPrefix(prefix + " ")
|
||||
layout.addWidget(self.val)
|
||||
self.ll = ll
|
||||
self.hl = hl
|
||||
|
||||
def set_number(self, number):
|
||||
if not self.val.hasFocus():
|
||||
self.val.setValue(number)
|
||||
|
||||
def set_range(self, ll, hl):
|
||||
self.val.setRange(ll, hl)
|
||||
self.ll = ll
|
||||
self.hl = hl
|
||||
|
||||
def setUnit(self, unit: str):
|
||||
self.val.setSuffix(" " + unit)
|
||||
|
||||
def get_range(self):
|
||||
return (self.ll, self.hl)
|
||||
|
||||
def has_focus(self) -> bool:
|
||||
return self.val.hasFocus()
|
||||
|
||||
def value(self) -> float:
|
||||
return self.val.value()
|
||||
|
||||
def value_changed_connect(self, func):
|
||||
"""Connect a function to a change in value."""
|
||||
self.val.valueChanged.connect(
|
||||
partial(
|
||||
func, identifier=self.identifier, value_obj=self.val, value=lambda: self.val.value()
|
||||
)
|
||||
)
|
||||
|
||||
def editing_finished_connect(self, func):
|
||||
"""Connect a function to the Enter/Return press."""
|
||||
self.val.editingFinished.connect(
|
||||
partial(
|
||||
func, identifier=self.identifier, value_obj=self.val, value=lambda: self.val.value()
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class ComboBox(QWidget):
|
||||
def __init__(self, identifier="", label="", enums=None):
|
||||
super().__init__()
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(*ROW_MARGINS)
|
||||
layout.setSpacing(ROW_SPACING)
|
||||
self.identifier = identifier
|
||||
self.label = QLabel(label)
|
||||
self.label.setFixedWidth(LABEL_WIDTH)
|
||||
self.label.setWordWrap(True)
|
||||
layout.addWidget(self.label)
|
||||
self.value = QComboBox()
|
||||
for entry in enums or []:
|
||||
self.value.addItem(entry)
|
||||
layout.addWidget(self.value)
|
||||
|
||||
def set_current_text(self, text):
|
||||
if not QApplication.focusWidget() is self.value.view():
|
||||
self.value.setCurrentText(text)
|
||||
|
||||
def setCurrentIndex(self, index):
|
||||
if not QApplication.focusWidget() is self.value.view():
|
||||
self.value.setCurrentIndex(index)
|
||||
|
||||
def currentIndex(self):
|
||||
return self.value.currentIndex()
|
||||
|
||||
def currentText(self) -> str:
|
||||
return self.value.currentText()
|
||||
|
||||
def has_focus(self) -> bool:
|
||||
return QApplication.focusWidget() is self.value.view()
|
||||
|
||||
def activated_connect(self, func):
|
||||
"""Connect a function to the Enter/Return key press."""
|
||||
self.value.activated.connect(
|
||||
partial(
|
||||
func,
|
||||
identifier=self.identifier,
|
||||
value_obj=self.value,
|
||||
index=lambda: self.value.currentIndex(),
|
||||
value=lambda: self.value.currentText(),
|
||||
)
|
||||
)
|
||||
|
||||
def setDisabled(self, disable):
|
||||
self.value.setDisabled(disable)
|
||||
|
||||
def get_all_texts(self) -> list[str]:
|
||||
return [self.value.itemText(i) for i in range(self.value.count())]
|
||||
|
||||
|
||||
class Button(QWidget):
|
||||
def __init__(
|
||||
self, label=None, label_button: str = "", enabled: bool = False, color: str = "default"
|
||||
):
|
||||
super().__init__()
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(*ROW_MARGINS)
|
||||
layout.setSpacing(ROW_SPACING)
|
||||
if label is not None:
|
||||
self.label = QLabel(label)
|
||||
self.label.setFixedWidth(LABEL_WIDTH)
|
||||
layout.addWidget(self.label)
|
||||
self.button = QPushButton(label_button)
|
||||
self.color = color
|
||||
self.setEnabled(enabled)
|
||||
layout.addWidget(self.button)
|
||||
|
||||
def clicked_connect(self, func):
|
||||
"""Connect a function to the button press."""
|
||||
self.button.clicked.connect(func)
|
||||
|
||||
def setEnabled(self, enable: bool = True):
|
||||
self.button.setEnabled(enable)
|
||||
self.apply_theme()
|
||||
|
||||
def setText(self, text):
|
||||
self.button.setText(text)
|
||||
|
||||
def setColor(self, color: str):
|
||||
self.color = color
|
||||
self.apply_theme()
|
||||
|
||||
def apply_theme(self):
|
||||
if self.button.isEnabled():
|
||||
colors = get_accent_colors()
|
||||
color = getattr(colors, self.color).name()
|
||||
self.button.setStyleSheet(f"QPushButton {{ background-color: {color}; color: white; }}")
|
||||
else:
|
||||
self.button.setStyleSheet(
|
||||
"QPushButton {{background-color: rgb(120, 120, 120); color: white;}}"
|
||||
)
|
||||
|
||||
|
||||
class TextIndicator(QWidget):
|
||||
def __init__(self, label):
|
||||
super().__init__()
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(*ROW_MARGINS)
|
||||
layout.setSpacing(ROW_SPACING)
|
||||
self.label = QLabel(label)
|
||||
self.label.setFixedWidth(LABEL_WIDTH)
|
||||
self.label.setWordWrap(True)
|
||||
layout.addWidget(self.label)
|
||||
self.text = QLabel("-")
|
||||
self.text.setAlignment(Qt.AlignTop) # type: ignore
|
||||
layout.addWidget(self.text)
|
||||
self.color = "default"
|
||||
|
||||
def setLabel(self, label) -> None:
|
||||
self.label.setText(label)
|
||||
|
||||
def setText(self, text):
|
||||
self.text.setText(text)
|
||||
|
||||
def setColor(self, color: str):
|
||||
self.color = color
|
||||
self.apply_theme()
|
||||
|
||||
def apply_theme(self):
|
||||
colors = get_accent_colors()
|
||||
color = getattr(colors, self.color).name()
|
||||
self.text.setStyleSheet(f"QLabel {{color:{color}}}")
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
def main(): # pragma: no cover
|
||||
from qtpy import PYSIDE6
|
||||
|
||||
if not PYSIDE6:
|
||||
print("PYSIDE6 is not available in the environment. Cannot patch designer.")
|
||||
return
|
||||
from PySide6.QtDesigner import QPyDesignerCustomWidgetCollection
|
||||
|
||||
from .temperature_controller_plugin import TemperatureControllerPlugin
|
||||
|
||||
QPyDesignerCustomWidgetCollection.addCustomWidget(TemperatureControllerPlugin())
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
main()
|
||||
@@ -0,0 +1,421 @@
|
||||
"""Temperature controller widget"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
from collections import deque
|
||||
from typing import Literal
|
||||
|
||||
import numpy as np
|
||||
import pyqtgraph as pg
|
||||
from bec_lib import bec_logger
|
||||
from bec_lib.endpoints import MessageEndpoints
|
||||
from bec_widgets.utils.bec_dispatcher import BECDispatcher
|
||||
from bec_widgets.utils.bec_widget import BECWidget
|
||||
from bec_widgets.utils.colors import apply_theme
|
||||
from bec_widgets.utils.error_popups import SafeSlot
|
||||
from bec_widgets.widgets.plots.waveform.waveform import Waveform
|
||||
from pydantic import BaseModel
|
||||
from PySide6.QtCore import QLocale, QPoint, QRect, QSize, Qt
|
||||
from PySide6.QtGui import QCursor, QFont, QIcon, QPalette, QRegion
|
||||
from PySide6.QtWidgets import QSizePolicy
|
||||
|
||||
# pylint: disable=E0611
|
||||
from qtpy.QtCore import QTimer
|
||||
from qtpy.QtWidgets import QApplication, QHBoxLayout, QLabel, QVBoxLayout, QWidget
|
||||
|
||||
from ....devices.univ_temp_cont.univ_temp_cont import ConfigDict
|
||||
from ....devices.univ_temp_cont.univ_temp_cont_enums import (
|
||||
POWER_MAP,
|
||||
RAMP_RATE_MAP,
|
||||
THERMOCOUPLE_MAP,
|
||||
UnivTempContAutoTune,
|
||||
UnivTempContHeaterTcFault,
|
||||
UnivTempContOpMode,
|
||||
UnivTempContPower,
|
||||
UnivTempContRampRateUnit,
|
||||
UnivTempContSensorBreak,
|
||||
)
|
||||
from .qt_widgets import Button, ComboBox, Group, InputNumberField, NumberIndicator, TextIndicator
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
DEVICE_NAME = "univ_temp_cont"
|
||||
|
||||
DEFAULT_WINDOW_S = 600
|
||||
MAX_WINDOW_S = 36000
|
||||
REFRESH_MS = 500
|
||||
PLOT_SIGNALS = ["temperature", "setpoint", "output_power"]
|
||||
READ_CONFIG_SIGNAL_MS = 1000
|
||||
|
||||
|
||||
class TemperatureControllerError(Exception):
|
||||
"""Temperature Controller specific error"""
|
||||
|
||||
|
||||
class TemperatureControllerControl(QWidget):
|
||||
def __init__(self, config_only: bool = False, *arg, parent=None, **kwargs) -> None:
|
||||
super().__init__(*arg, parent=parent, **kwargs)
|
||||
|
||||
self._layout = QVBoxLayout(self)
|
||||
|
||||
self.power_mode = ComboBox("power", "Power mode", POWER_MAP.keys())
|
||||
self.target_setpoint = InputNumberField(
|
||||
"target_setpoint", "Target setpoint", "°C", decimals=0, single_step=1, ll=0, hl=850
|
||||
)
|
||||
self.ramp_rate = InputNumberField(
|
||||
"ramp_rate", "Ramp rate", decimals=0, single_step=1, ll=0, hl=1e5
|
||||
)
|
||||
self.ramp_rate_unit = ComboBox("ramp_rate_unit", "Ramp rate unit", RAMP_RATE_MAP.keys())
|
||||
|
||||
if not config_only:
|
||||
self.setpoint = NumberIndicator("Setpoint", "°C", highlight=True, decimals=0)
|
||||
widgets = [
|
||||
self.power_mode,
|
||||
self.target_setpoint,
|
||||
self.setpoint,
|
||||
self.ramp_rate,
|
||||
self.ramp_rate_unit,
|
||||
]
|
||||
else:
|
||||
widgets = [self.power_mode, self.target_setpoint, self.ramp_rate, self.ramp_rate_unit]
|
||||
|
||||
control_group = Group("Control", widgets)
|
||||
self.ramp_rate_unit.activated_connect(self._on_ramp_rate_unit_change)
|
||||
self._on_ramp_rate_unit_change()
|
||||
|
||||
self._layout.addWidget(control_group)
|
||||
|
||||
@SafeSlot()
|
||||
def _on_ramp_rate_unit_change(self, *_, **__):
|
||||
index = self.ramp_rate_unit.currentIndex()
|
||||
self.ramp_rate.setUnit(
|
||||
list(RAMP_RATE_MAP.keys())[list(RAMP_RATE_MAP.values()).index(index)]
|
||||
)
|
||||
|
||||
def get_config(self) -> ConfigDict:
|
||||
return ConfigDict(
|
||||
power_mode=self.power_mode.currentText(),
|
||||
target_setpoint=self.target_setpoint.value(),
|
||||
ramp_rate=self.ramp_rate.value(),
|
||||
ramp_rate_unit=self.ramp_rate_unit.currentText(),
|
||||
)
|
||||
|
||||
def load_config(self, config: ConfigDict) -> None:
|
||||
self.power_mode.setCurrentIndex(POWER_MAP[config.power_mode])
|
||||
self.ramp_rate_unit.setCurrentIndex(RAMP_RATE_MAP[config.ramp_rate_unit])
|
||||
self.ramp_rate.set_number(config.ramp_rate)
|
||||
self.target_setpoint.set_number(config.target_setpoint)
|
||||
|
||||
|
||||
class TemperatureController(BECWidget, QWidget):
|
||||
"""Waveform with predefined curves and one status label."""
|
||||
|
||||
PLUGIN = True
|
||||
ICON_NAME = "mode_heat"
|
||||
|
||||
def __init__(self, *arg, parent=None, **kwargs):
|
||||
super().__init__(parent=parent, *arg, **kwargs)
|
||||
self.get_bec_shortcuts()
|
||||
|
||||
if DEVICE_NAME not in self.dev:
|
||||
raise TemperatureControllerError(
|
||||
"Universal Temperature Controller is not in the config, abort."
|
||||
)
|
||||
|
||||
self._window_s = DEFAULT_WINDOW_S
|
||||
|
||||
self.init_ui()
|
||||
|
||||
self._buffers: dict[str, deque] = {}
|
||||
self._curves = {}
|
||||
for signal in PLOT_SIGNALS:
|
||||
self._buffers[signal] = deque() # (timestamp, value), trimmed by time
|
||||
self._curves[signal] = self.waveform.plot(
|
||||
x=[], y=[], label=getattr(self.dev.univ_temp_cont, signal).full_name
|
||||
)
|
||||
self._curves[signal].set_symbol(None)
|
||||
|
||||
self.bec_dispatcher.connect_slot(
|
||||
self._on_readback, MessageEndpoints.device_readback(DEVICE_NAME)
|
||||
)
|
||||
self._refresh_timer = QTimer(self)
|
||||
self._refresh_timer.timeout.connect(self._redraw)
|
||||
self._refresh_timer.start(REFRESH_MS)
|
||||
|
||||
self._config_signal_timer = QTimer(self)
|
||||
self._config_signal_timer.timeout.connect(self._config_signal_read)
|
||||
self._config_signal_timer.start(READ_CONFIG_SIGNAL_MS)
|
||||
|
||||
self.control.power_mode.activated_connect(self._on_value_changed)
|
||||
self.control.target_setpoint.editing_finished_connect(self._on_value_changed)
|
||||
self.control.ramp_rate.editing_finished_connect(self._on_value_changed)
|
||||
self.control.ramp_rate_unit.activated_connect(self._on_value_changed)
|
||||
self.pid_pb.editing_finished_connect(self._on_value_changed)
|
||||
self.pid_ti.editing_finished_connect(self._on_value_changed)
|
||||
self.pid_td.editing_finished_connect(self._on_value_changed)
|
||||
self.autotune.clicked_connect(self._start_stop_autotune)
|
||||
self.thermocouple.activated_connect(self._on_value_changed)
|
||||
|
||||
self.plot_init = True
|
||||
|
||||
def init_ui(self) -> None:
|
||||
"""Init the UI for the temperature controller widget, should only take place once."""
|
||||
root_layout = QHBoxLayout(self)
|
||||
|
||||
control_layout = QVBoxLayout()
|
||||
control_layout.setContentsMargins(4, 4, 4, 4)
|
||||
control_layout.setSpacing(4)
|
||||
|
||||
self.sensor_break = TextIndicator("Thermocouple")
|
||||
self.operating_mode = TextIndicator("Operating mode")
|
||||
self.output_power = NumberIndicator("Output Power", "%", decimals=0)
|
||||
self.temperature = NumberIndicator("Temperature", "°C", highlight=True, decimals=0)
|
||||
self.heater_temperature = NumberIndicator("Heater temperature", "°C", decimals=0)
|
||||
self.heater_sensor_break = TextIndicator("Heater Thermocouple")
|
||||
|
||||
status_group = Group(
|
||||
"Status",
|
||||
[
|
||||
self.sensor_break,
|
||||
self.operating_mode,
|
||||
self.output_power,
|
||||
self.temperature,
|
||||
self.heater_temperature,
|
||||
self.heater_sensor_break,
|
||||
],
|
||||
)
|
||||
|
||||
self.control = TemperatureControllerControl()
|
||||
|
||||
self.pid_pb = InputNumberField("pb", "PB", decimals=0, single_step=1, ll=1, hl=9999)
|
||||
self.pid_ti = InputNumberField(
|
||||
"ti", "TI", decimals=0, single_step=1, ll=0, hl=9999, unit="s"
|
||||
)
|
||||
self.pid_td = InputNumberField(
|
||||
"td", "TD", decimals=0, single_step=1, ll=0, hl=9999, unit="s"
|
||||
)
|
||||
|
||||
self.autotune = Button("Autotune", "Start", enabled=True, color="success")
|
||||
self.autotune_status = TextIndicator("Autotune Status")
|
||||
|
||||
pid_loop_group = Group(
|
||||
"PID loop", [self.pid_pb, self.pid_ti, self.pid_td, self.autotune, self.autotune_status]
|
||||
)
|
||||
|
||||
self.tc_info = QLabel("Controller will restart when changing value")
|
||||
self.thermocouple = ComboBox("thermocouple", "Thermocouple", THERMOCOUPLE_MAP.keys())
|
||||
|
||||
configuration_group = Group("Configuration", [self.tc_info, self.thermocouple])
|
||||
|
||||
control_layout.addWidget(status_group)
|
||||
control_layout.addWidget(self.control)
|
||||
control_layout.addWidget(pid_loop_group)
|
||||
control_layout.addWidget(configuration_group)
|
||||
control_layout.addStretch()
|
||||
|
||||
root_layout.addLayout(control_layout)
|
||||
|
||||
waveform_layout = QVBoxLayout()
|
||||
|
||||
waveform_settings_layout = QHBoxLayout()
|
||||
self.user_window_s = InputNumberField(
|
||||
"",
|
||||
"Plot range",
|
||||
"s",
|
||||
init=DEFAULT_WINDOW_S,
|
||||
decimals=0,
|
||||
single_step=60,
|
||||
ll=1,
|
||||
hl=MAX_WINDOW_S,
|
||||
)
|
||||
waveform_settings_layout.addWidget(self.user_window_s)
|
||||
waveform_settings_layout.addStretch()
|
||||
|
||||
waveform_layout.addLayout(waveform_settings_layout)
|
||||
|
||||
self.waveform = Waveform(parent=self, client=self.client, popups=True)
|
||||
|
||||
waveform_layout.addWidget(self.waveform, stretch=1)
|
||||
|
||||
root_layout.addLayout(waveform_layout, stretch=1)
|
||||
|
||||
self.waveform.set(title="", x_label="Time")
|
||||
self.waveform.enable_toolbar = True
|
||||
self.waveform.enable_side_panel = False
|
||||
self.waveform.plot_item.setAxisItems({"bottom": pg.DateAxisItem(orientation="bottom")})
|
||||
|
||||
@SafeSlot()
|
||||
def apply_theme(self, theme):
|
||||
self.sensor_break.apply_theme()
|
||||
self.operating_mode.apply_theme()
|
||||
self.heater_sensor_break.apply_theme()
|
||||
self.autotune_status.apply_theme()
|
||||
self.autotune.apply_theme()
|
||||
return super().apply_theme(theme)
|
||||
|
||||
def load_config(self, config: ConfigDict) -> None:
|
||||
# Power mode
|
||||
signal = getattr(self.dev.univ_temp_cont, "power")
|
||||
signal.put(POWER_MAP[config.power_mode])
|
||||
# Ramp rate unit
|
||||
signal = getattr(self.dev.univ_temp_cont, "ramp_rate_unit")
|
||||
signal.put(RAMP_RATE_MAP[config.ramp_rate_unit])
|
||||
# Ramp rate
|
||||
signal = getattr(self.dev.univ_temp_cont, "ramp_rate")
|
||||
signal.put(config.ramp_rate)
|
||||
# Target setpoint
|
||||
signal = getattr(self.dev.univ_temp_cont, "target_setpoint")
|
||||
signal.put(config.target_setpoint)
|
||||
|
||||
@SafeSlot()
|
||||
def _on_value_changed(self, *_, **kwargs):
|
||||
if "index" in kwargs.keys():
|
||||
value = kwargs["index"]()
|
||||
else:
|
||||
value = kwargs["value"]()
|
||||
signal = getattr(self.dev.univ_temp_cont, kwargs["identifier"])
|
||||
signal.put(value)
|
||||
|
||||
@SafeSlot()
|
||||
def _start_stop_autotune(self, *_):
|
||||
signal = getattr(self.dev.univ_temp_cont, "autotune")
|
||||
val = signal.read()["autotune"]["value"]
|
||||
signal.put(not val)
|
||||
|
||||
@SafeSlot(dict, dict)
|
||||
def _on_readback(self, msg: dict, *_):
|
||||
signals = msg.get("signals", {})
|
||||
now = time.time()
|
||||
for signal, buf in self._buffers.items():
|
||||
entry = signals.get(DEVICE_NAME + "_" + signal)
|
||||
if entry is None or entry.get("value") is None:
|
||||
continue
|
||||
buf.append((now, entry["value"]))
|
||||
value = signals[DEVICE_NAME + "_" + "temperature"]["value"]
|
||||
self.temperature.setValue(value)
|
||||
value = signals[DEVICE_NAME + "_" + "heater_temperature"]["value"]
|
||||
self.heater_temperature.setValue(value)
|
||||
value = signals[DEVICE_NAME + "_" + "output_power"]["value"]
|
||||
self.output_power.setValue(value)
|
||||
value = signals[DEVICE_NAME + "_" + "sensor_break"]["value"]
|
||||
match value:
|
||||
case UnivTempContSensorBreak.GOOD:
|
||||
self.sensor_break.setText("OK")
|
||||
self.sensor_break.setColor("success")
|
||||
case UnivTempContSensorBreak.SENSOR_BREAK:
|
||||
self.sensor_break.setText("FAULT")
|
||||
self.sensor_break.setColor("emergency")
|
||||
case _:
|
||||
raise TemperatureControllerError(f"Not implemented sensor_break value {value}")
|
||||
value = signals[DEVICE_NAME + "_" + "heater_tc_fault"]["value"]
|
||||
match value:
|
||||
case UnivTempContHeaterTcFault.NO_FAULT:
|
||||
self.heater_sensor_break.setText("OK")
|
||||
self.heater_sensor_break.setColor("success")
|
||||
case UnivTempContHeaterTcFault.TC_OPEN_FAULT:
|
||||
self.heater_sensor_break.setText("OPEN")
|
||||
self.heater_sensor_break.setColor("warning")
|
||||
case (
|
||||
UnivTempContHeaterTcFault.OVER_UNDERVOLTAGE_FAULT
|
||||
| UnivTempContHeaterTcFault.TC_LOW_FAULT
|
||||
| UnivTempContHeaterTcFault.TC_HIGH_FAULT
|
||||
| UnivTempContHeaterTcFault.COLD_JUNC_LOW_FAULT
|
||||
| UnivTempContHeaterTcFault.COLD_JUNC_HIGH_FAULT
|
||||
| UnivTempContHeaterTcFault.TC_RANGE_FAULT
|
||||
| UnivTempContHeaterTcFault.COLD_JUNC_RNG_FAULT
|
||||
):
|
||||
self.heater_sensor_break.setText("FAULT")
|
||||
self.heater_sensor_break.setColor("emergency")
|
||||
case _:
|
||||
raise TemperatureControllerError(
|
||||
f"Not implemented heater_sensor_break value {value}"
|
||||
)
|
||||
value = signals[DEVICE_NAME + "_" + "op_mode"]["value"]
|
||||
match value:
|
||||
case UnivTempContOpMode.AUTO:
|
||||
self.operating_mode.setText("AUTO")
|
||||
self.operating_mode.setColor("success")
|
||||
case UnivTempContOpMode.MANUAL:
|
||||
self.operating_mode.setText("MANUAL")
|
||||
self.operating_mode.setColor("warning")
|
||||
case UnivTempContOpMode.STANDBY:
|
||||
self.operating_mode.setText("STANDBY")
|
||||
self.operating_mode.setColor("default")
|
||||
case _:
|
||||
raise TemperatureControllerError(f"Not implemented op_mode value {value}")
|
||||
index = signals[DEVICE_NAME + "_" + "power"]["value"]
|
||||
self.control.power_mode.setCurrentIndex(index)
|
||||
value = signals[DEVICE_NAME + "_" + "target_setpoint"]["value"]
|
||||
self.control.target_setpoint.set_number(value)
|
||||
value = signals[DEVICE_NAME + "_" + "setpoint"]["value"]
|
||||
self.control.setpoint.setValue(value)
|
||||
value = signals[DEVICE_NAME + "_" + "ramp_rate"]["value"]
|
||||
self.control.ramp_rate.set_number(value)
|
||||
|
||||
def _config_signal_read(self):
|
||||
# Ramp rate unit
|
||||
value = self.dev.univ_temp_cont.ramp_rate_unit.read()
|
||||
index = value[DEVICE_NAME + "_ramp_rate_unit"]["value"]
|
||||
self.control.ramp_rate_unit.setCurrentIndex(index)
|
||||
# PB
|
||||
value = self.dev.univ_temp_cont.pb.read()[DEVICE_NAME + "_pb"]["value"]
|
||||
self.pid_pb.set_number(value)
|
||||
# TI
|
||||
value = self.dev.univ_temp_cont.ti.read()[DEVICE_NAME + "_ti"]["value"]
|
||||
self.pid_ti.set_number(value)
|
||||
# TD
|
||||
value = self.dev.univ_temp_cont.td.read()[DEVICE_NAME + "_td"]["value"]
|
||||
self.pid_td.set_number(value)
|
||||
# Autotune
|
||||
value = self.dev.univ_temp_cont.autotune.read()
|
||||
index = value[DEVICE_NAME + "_autotune"]["value"]
|
||||
match index:
|
||||
case UnivTempContAutoTune.NOTUNE:
|
||||
self.autotune.setText("Start")
|
||||
self.autotune.setColor("success")
|
||||
self.autotune_status.setText("Not active")
|
||||
self.autotune_status.setColor("default")
|
||||
case UnivTempContAutoTune.TUNE:
|
||||
self.autotune.setText("Stop")
|
||||
self.autotune.setColor("emergency")
|
||||
self.autotune_status.setText("Active")
|
||||
self.autotune_status.setColor("warning")
|
||||
case _:
|
||||
raise TemperatureControllerError(f"Not implemented autotune value {index}")
|
||||
# Thermocouple
|
||||
value = self.dev.univ_temp_cont.thermocouple.read()
|
||||
index = value[DEVICE_NAME + "_thermocouple"]["value"]
|
||||
self.thermocouple.setCurrentIndex(index)
|
||||
|
||||
def _redraw(self):
|
||||
now = time.time()
|
||||
cutoff = now - MAX_WINDOW_S
|
||||
view_cutoff = now - min(self.user_window_s.value(), MAX_WINDOW_S)
|
||||
|
||||
for key, buf in self._buffers.items():
|
||||
while buf and buf[0][0] < cutoff:
|
||||
buf.popleft()
|
||||
if not buf:
|
||||
continue
|
||||
|
||||
t, v = map(np.asarray, zip(*buf))
|
||||
i = np.searchsorted(t, view_cutoff, side="left")
|
||||
self._curves[key].set_data(t[i:], v[i:])
|
||||
if len(self._buffers[PLOT_SIGNALS[0]]) > 0 and self.plot_init:
|
||||
self.plot_init = False
|
||||
self.waveform.plot_item.enableAutoRange(axis=pg.ViewBox.XYAxes, enable=True)
|
||||
|
||||
def cleanup(self):
|
||||
self._refresh_timer.stop()
|
||||
super().cleanup()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app = QApplication(sys.argv)
|
||||
apply_theme("light")
|
||||
dispatcher = BECDispatcher(gui_id="restart_server")
|
||||
win = TemperatureControllerControl(config_only=True)
|
||||
win.show()
|
||||
sys.exit(app.exec_())
|
||||
@@ -0,0 +1 @@
|
||||
{'files': ['temperature_controller.py']}
|
||||
@@ -0,0 +1,57 @@
|
||||
# Copyright (C) 2022 The Qt Company Ltd.
|
||||
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
|
||||
|
||||
from bec_widgets.utils.bec_designer import designer_material_icon
|
||||
from qtpy.QtDesigner import QDesignerCustomWidgetInterface
|
||||
from qtpy.QtWidgets import QWidget
|
||||
|
||||
from .temperature_controller import TemperatureController
|
||||
|
||||
DOM_XML = """
|
||||
<ui language='c++'>
|
||||
<widget class='TemperatureController' name='temperature_controller'>
|
||||
</widget>
|
||||
</ui>
|
||||
"""
|
||||
|
||||
|
||||
class TemperatureControllerPlugin(QDesignerCustomWidgetInterface): # pragma: no cover
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self._form_editor = None
|
||||
|
||||
def createWidget(self, parent):
|
||||
if parent is None:
|
||||
return QWidget()
|
||||
t = TemperatureController(parent)
|
||||
return t
|
||||
|
||||
def domXml(self):
|
||||
return DOM_XML
|
||||
|
||||
def group(self):
|
||||
return ""
|
||||
|
||||
def icon(self):
|
||||
return designer_material_icon(TemperatureController.ICON_NAME)
|
||||
|
||||
def includeFile(self):
|
||||
return "temperature_controller"
|
||||
|
||||
def initialize(self, form_editor):
|
||||
self._form_editor = form_editor
|
||||
|
||||
def isContainer(self):
|
||||
return False
|
||||
|
||||
def isInitialized(self):
|
||||
return self._form_editor is not None
|
||||
|
||||
def name(self):
|
||||
return "TemperatureController"
|
||||
|
||||
def toolTip(self):
|
||||
return "TemperatureController"
|
||||
|
||||
def whatsThis(self):
|
||||
return self.toolTip()
|
||||
@@ -1,26 +1,41 @@
|
||||
|
||||
#######################################
|
||||
## Experimental Hutch Photon Shutter ##
|
||||
#######################################
|
||||
|
||||
eh_sh:
|
||||
readoutPriority: baseline
|
||||
description: Experimental Hutch Photon Shutter
|
||||
deviceClass: debye_bec.devices.eh_shutter.EHPhotonShutter
|
||||
deviceConfig:
|
||||
prefix: "X01DA-"
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
|
||||
###################################
|
||||
## Optical Table ##
|
||||
###################################
|
||||
|
||||
ot_tryu:
|
||||
readoutPriority: baseline
|
||||
description: Optical Table Y-Translation Upstream
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-ES-OT:TRYU
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# ot_tryu:
|
||||
# readoutPriority: baseline
|
||||
# description: Optical Table Y-Translation Upstream
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-ES-OT:TRYU
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
ot_tryd:
|
||||
readoutPriority: baseline
|
||||
description: Optical Table Y-Translation Downstream
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-ES-OT:TRYD
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# ot_tryd:
|
||||
# readoutPriority: baseline
|
||||
# description: Optical Table Y-Translation Downstream
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-ES-OT:TRYD
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
ot_es1_trz:
|
||||
readoutPriority: baseline
|
||||
@@ -94,45 +109,45 @@ es0filter:
|
||||
## Slits ES0 ##
|
||||
###################################
|
||||
|
||||
es0sl_trxr:
|
||||
readoutPriority: baseline
|
||||
description: End Station slits X-translation Ring-edge
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-ES0-SL:TRXR
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# es0sl_trxr:
|
||||
# readoutPriority: baseline
|
||||
# description: End Station slits X-translation Ring-edge
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-ES0-SL:TRXR
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
es0sl_trxw:
|
||||
readoutPriority: baseline
|
||||
description: End Station slits X-translation Wall-edge
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-ES0-SL:TRXW
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# es0sl_trxw:
|
||||
# readoutPriority: baseline
|
||||
# description: End Station slits X-translation Wall-edge
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-ES0-SL:TRXW
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
es0sl_tryb:
|
||||
readoutPriority: baseline
|
||||
description: End Station slits Y-translation Bottom-edge
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-ES0-SL:TRYB
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# es0sl_tryb:
|
||||
# readoutPriority: baseline
|
||||
# description: End Station slits Y-translation Bottom-edge
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-ES0-SL:TRYB
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
es0sl_tryt:
|
||||
readoutPriority: baseline
|
||||
description: End Station slits X-translation Top-edge
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-ES0-SL:TRYT
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# es0sl_tryt:
|
||||
# readoutPriority: baseline
|
||||
# description: End Station slits X-translation Top-edge
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-ES0-SL:TRYT
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
es0sl_center:
|
||||
readoutPriority: baseline
|
||||
@@ -266,15 +281,15 @@ es1bm1_trx:
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
|
||||
es1det2_trx:
|
||||
readoutPriority: baseline
|
||||
description: End Station SDD 2 X-translation
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-ES1-DET2:TRX
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# es1det2_trx:
|
||||
# readoutPriority: baseline
|
||||
# description: End Station SDD 2 X-translation
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-ES1-DET2:TRX
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
###################################
|
||||
## IC1 + IC2 Manipulator ##
|
||||
|
||||
@@ -17,45 +17,45 @@ abs:
|
||||
## Frontend Slits ##
|
||||
###################################
|
||||
|
||||
sldi_trxr:
|
||||
readoutPriority: baseline
|
||||
description: Front-end slit diaphragm X-translation Ring-edge
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-FE-SLDI:TRXR
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# sldi_trxr:
|
||||
# readoutPriority: baseline
|
||||
# description: Front-end slit diaphragm X-translation Ring-edge
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-FE-SLDI:TRXR
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
sldi_trxw:
|
||||
readoutPriority: baseline
|
||||
description: Front-end slit diaphragm X-translation Wall-edge
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-FE-SLDI:TRXW
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# sldi_trxw:
|
||||
# readoutPriority: baseline
|
||||
# description: Front-end slit diaphragm X-translation Wall-edge
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-FE-SLDI:TRXW
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
sldi_tryb:
|
||||
readoutPriority: baseline
|
||||
description: Front-end slit diaphragm Y-translation Bottom-edge
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-FE-SLDI:TRYB
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# sldi_tryb:
|
||||
# readoutPriority: baseline
|
||||
# description: Front-end slit diaphragm Y-translation Bottom-edge
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-FE-SLDI:TRYB
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
sldi_tryt:
|
||||
readoutPriority: baseline
|
||||
description: Front-end slit diaphragm X-translation Top-edge
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-FE-SLDI:TRYT
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# sldi_tryt:
|
||||
# readoutPriority: baseline
|
||||
# description: Front-end slit diaphragm X-translation Top-edge
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-FE-SLDI:TRYT
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
sldi_centerx:
|
||||
readoutPriority: baseline
|
||||
@@ -101,55 +101,55 @@ sldi_gapy:
|
||||
## Collimating Mirror ##
|
||||
###################################
|
||||
|
||||
cm_trxu:
|
||||
readoutPriority: baseline
|
||||
description: Collimating Mirror X-translation upstream
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-FE-CM:TRXU
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# cm_trxu:
|
||||
# readoutPriority: baseline
|
||||
# description: Collimating Mirror X-translation upstream
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-FE-CM:TRXU
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
cm_trxd:
|
||||
readoutPriority: baseline
|
||||
description: Collimating Mirror X-translation downstream
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-FE-CM:TRXD
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# cm_trxd:
|
||||
# readoutPriority: baseline
|
||||
# description: Collimating Mirror X-translation downstream
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-FE-CM:TRXD
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
cm_tryu:
|
||||
readoutPriority: baseline
|
||||
description: Collimating Mirror Y-translation upstream
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-FE-CM:TRYU
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# cm_tryu:
|
||||
# readoutPriority: baseline
|
||||
# description: Collimating Mirror Y-translation upstream
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-FE-CM:TRYU
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
cm_trydr:
|
||||
readoutPriority: baseline
|
||||
description: Collimating Mirror Y-translation downstream ring
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-FE-CM:TRYDR
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# cm_trydr:
|
||||
# readoutPriority: baseline
|
||||
# description: Collimating Mirror Y-translation downstream ring
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-FE-CM:TRYDR
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
cm_trydw:
|
||||
readoutPriority: baseline
|
||||
description: Collimating Mirror Y-translation downstream wall
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-FE-CM:TRYDW
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# cm_trydw:
|
||||
# readoutPriority: baseline
|
||||
# description: Collimating Mirror Y-translation downstream wall
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-FE-CM:TRYDW
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
cm_bnd:
|
||||
readoutPriority: baseline
|
||||
@@ -240,4 +240,4 @@ cm_xstripe:
|
||||
prefix: X01DA-FE-CM:XSTRIPE
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
softwareTrigger: false
|
||||
@@ -15,4 +15,18 @@ curr:
|
||||
onFailure: buffer
|
||||
enabled: true
|
||||
readOnly: true
|
||||
softwareTrigger: false
|
||||
|
||||
bl_status:
|
||||
readoutPriority: baseline
|
||||
description: BL status for machine
|
||||
deviceClass: ophyd.EpicsSignal
|
||||
deviceConfig:
|
||||
auto_monitor: false
|
||||
read_pv: AGEOP-BL:STATUS-X01DA
|
||||
deviceTags:
|
||||
- machine
|
||||
onFailure: buffer
|
||||
enabled: true
|
||||
readOnly: false
|
||||
softwareTrigger: false
|
||||
@@ -0,0 +1,13 @@
|
||||
######################################
|
||||
## Universal Temperature Controller ##
|
||||
######################################
|
||||
|
||||
univ_temp_cont:
|
||||
readoutPriority: monitored
|
||||
description: Universal Temperature Controller
|
||||
deviceClass: debye_bec.devices.univ_temp_cont.univ_temp_cont.UnivTempCont
|
||||
deviceConfig:
|
||||
prefix: "X01DA-ES-CRS:"
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
@@ -1,4 +1,18 @@
|
||||
|
||||
###################################
|
||||
## Optics Photon Shutter ##
|
||||
###################################
|
||||
|
||||
op_sh:
|
||||
readoutPriority: baseline
|
||||
description: Optics Hutch Photon Shutter
|
||||
deviceClass: debye_bec.devices.op_shutter.OPPhotonShutter
|
||||
deviceConfig:
|
||||
prefix: "X01DA-"
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
|
||||
###################################
|
||||
## Monochromator ##
|
||||
###################################
|
||||
@@ -37,57 +51,57 @@ mo1_roty:
|
||||
## Optics Slits + Beam Monitor 1 ##
|
||||
###################################
|
||||
|
||||
sl1_trxr:
|
||||
readoutPriority: baseline
|
||||
description: Optics slits 1 X-translation Ring-edge
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-OP-SL1:TRXR
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
deviceTags:
|
||||
- optics
|
||||
- slits
|
||||
# sl1_trxr:
|
||||
# readoutPriority: baseline
|
||||
# description: Optics slits 1 X-translation Ring-edge
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-OP-SL1:TRXR
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
# deviceTags:
|
||||
# - optics
|
||||
# - slits
|
||||
|
||||
sl1_trxw:
|
||||
readoutPriority: baseline
|
||||
description: Optics slits 1 X-translation Wall-edge
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-OP-SL1:TRXW
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
deviceTags:
|
||||
- optics
|
||||
- slits
|
||||
# sl1_trxw:
|
||||
# readoutPriority: baseline
|
||||
# description: Optics slits 1 X-translation Wall-edge
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-OP-SL1:TRXW
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
# deviceTags:
|
||||
# - optics
|
||||
# - slits
|
||||
|
||||
sl1_tryb:
|
||||
readoutPriority: baseline
|
||||
description: Optics slits 1 Y-translation Bottom-edge
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-OP-SL1:TRYB
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
deviceTags:
|
||||
- optics
|
||||
- slits
|
||||
# sl1_tryb:
|
||||
# readoutPriority: baseline
|
||||
# description: Optics slits 1 Y-translation Bottom-edge
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-OP-SL1:TRYB
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
# deviceTags:
|
||||
# - optics
|
||||
# - slits
|
||||
|
||||
sl1_tryt:
|
||||
readoutPriority: baseline
|
||||
description: Optics slits 1 X-translation Top-edge
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-OP-SL1:TRYT
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
deviceTags:
|
||||
- optics
|
||||
- slits
|
||||
# sl1_tryt:
|
||||
# readoutPriority: baseline
|
||||
# description: Optics slits 1 X-translation Top-edge
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-OP-SL1:TRYT
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
# deviceTags:
|
||||
# - optics
|
||||
# - slits
|
||||
|
||||
bm1_try:
|
||||
readoutPriority: baseline
|
||||
@@ -158,55 +172,55 @@ sl1_gapy:
|
||||
## Focusing Mirror ##
|
||||
###################################
|
||||
|
||||
fm_trxu:
|
||||
readoutPriority: baseline
|
||||
description: Focusing Mirror X-translation upstream
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-OP-FM:TRXU
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# fm_trxu:
|
||||
# readoutPriority: baseline
|
||||
# description: Focusing Mirror X-translation upstream
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-OP-FM:TRXU
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
fm_trxd:
|
||||
readoutPriority: baseline
|
||||
description: Focusing Mirror X-translation downstream
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-OP-FM:TRXD
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# fm_trxd:
|
||||
# readoutPriority: baseline
|
||||
# description: Focusing Mirror X-translation downstream
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-OP-FM:TRXD
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
fm_tryd:
|
||||
readoutPriority: baseline
|
||||
description: Focusing Mirror Y-translation downstream
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-OP-FM:TRYD
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# fm_tryd:
|
||||
# readoutPriority: baseline
|
||||
# description: Focusing Mirror Y-translation downstream
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-OP-FM:TRYD
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
fm_tryur:
|
||||
readoutPriority: baseline
|
||||
description: Focusing Mirror Y-translation upstream ring
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-OP-FM:TRYUR
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# fm_tryur:
|
||||
# readoutPriority: baseline
|
||||
# description: Focusing Mirror Y-translation upstream ring
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-OP-FM:TRYUR
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
fm_tryuw:
|
||||
readoutPriority: baseline
|
||||
description: Focusing Mirror Y-translation upstream wall
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-OP-FM:TRYUW
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
# fm_tryuw:
|
||||
# readoutPriority: baseline
|
||||
# description: Focusing Mirror Y-translation upstream wall
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-OP-FM:TRYUW
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
|
||||
fm_bnd:
|
||||
readoutPriority: baseline
|
||||
@@ -293,57 +307,57 @@ fm_ztcp:
|
||||
## Optics Slits + Beam Monitor 2 ##
|
||||
###################################
|
||||
|
||||
sl2_trxr:
|
||||
readoutPriority: baseline
|
||||
description: Optics slits 2 X-translation Ring-edge
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-OP-SL2:TRXR
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
deviceTags:
|
||||
- optics
|
||||
- slits
|
||||
# sl2_trxr:
|
||||
# readoutPriority: baseline
|
||||
# description: Optics slits 2 X-translation Ring-edge
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-OP-SL2:TRXR
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
# deviceTags:
|
||||
# - optics
|
||||
# - slits
|
||||
|
||||
sl2_trxw:
|
||||
readoutPriority: baseline
|
||||
description: Optics slits 2 X-translation Wall-edge
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-OP-SL2:TRXW
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
deviceTags:
|
||||
- optics
|
||||
- slits
|
||||
# sl2_trxw:
|
||||
# readoutPriority: baseline
|
||||
# description: Optics slits 2 X-translation Wall-edge
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-OP-SL2:TRXW
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
# deviceTags:
|
||||
# - optics
|
||||
# - slits
|
||||
|
||||
sl2_tryb:
|
||||
readoutPriority: baseline
|
||||
description: Optics slits 2 Y-translation Bottom-edge
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-OP-SL2:TRYB
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
deviceTags:
|
||||
- optics
|
||||
- slits
|
||||
# sl2_tryb:
|
||||
# readoutPriority: baseline
|
||||
# description: Optics slits 2 Y-translation Bottom-edge
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-OP-SL2:TRYB
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
# deviceTags:
|
||||
# - optics
|
||||
# - slits
|
||||
|
||||
sl2_tryt:
|
||||
readoutPriority: baseline
|
||||
description: Optics slits 2 X-translation Top-edge
|
||||
deviceClass: ophyd_devices.EpicsMotorEC
|
||||
deviceConfig:
|
||||
prefix: X01DA-OP-SL2:TRYT
|
||||
onFailure: retry
|
||||
enabled: true
|
||||
softwareTrigger: false
|
||||
deviceTags:
|
||||
- optics
|
||||
- slits
|
||||
# sl2_tryt:
|
||||
# readoutPriority: baseline
|
||||
# description: Optics slits 2 X-translation Top-edge
|
||||
# deviceClass: ophyd_devices.EpicsMotorEC
|
||||
# deviceConfig:
|
||||
# prefix: X01DA-OP-SL2:TRYT
|
||||
# onFailure: retry
|
||||
# enabled: true
|
||||
# softwareTrigger: false
|
||||
# deviceTags:
|
||||
# - optics
|
||||
# - slits
|
||||
|
||||
bm2_try:
|
||||
readoutPriority: baseline
|
||||
@@ -408,4 +422,4 @@ sl2_gapy:
|
||||
softwareTrigger: false
|
||||
deviceTags:
|
||||
- optics
|
||||
- slits
|
||||
- slits
|
||||
@@ -7,11 +7,16 @@ from typing import TYPE_CHECKING
|
||||
|
||||
from ophyd import Component as Cpt
|
||||
from ophyd import EpicsSignal, EpicsSignalRO
|
||||
from ophyd_devices import CompareStatus, DeviceStatus
|
||||
from ophyd_devices import CompareStatus
|
||||
from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase
|
||||
|
||||
from .utils.bl_status_enum import BlStatus
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from bec_lib.devicemanager import ScanInfo
|
||||
from bec_server.device_server.device_server import DeviceManagerDS
|
||||
|
||||
TIMEOUT_FOR_PV = 5
|
||||
|
||||
|
||||
class AbsorberError(Exception):
|
||||
@@ -38,6 +43,13 @@ class STATUS(int, enum.Enum):
|
||||
UNDEFINED = 14
|
||||
|
||||
|
||||
class BL_ENABLE(int, enum.Enum):
|
||||
"""Beamline enable"""
|
||||
|
||||
DISABLE = 0
|
||||
ENABLE = 1
|
||||
|
||||
|
||||
class Absorber(PSIDeviceBase):
|
||||
"""Class for the Frontend Absorber"""
|
||||
|
||||
@@ -55,30 +67,56 @@ class Absorber(PSIDeviceBase):
|
||||
string=True,
|
||||
doc="Absorber Status",
|
||||
)
|
||||
close4bl = Cpt(EpicsSignal, suffix="CLOSE4BL", kind="config", doc="Beamline enable")
|
||||
|
||||
def __init__(self, *, name: str, prefix: str = "", scan_info: ScanInfo | None = None, **kwargs):
|
||||
super().__init__(name=name, prefix=prefix, scan_info=scan_info, **kwargs)
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
name: str,
|
||||
prefix: str = "",
|
||||
scan_info: ScanInfo | None = None,
|
||||
device_manager: DeviceManagerDS | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(
|
||||
name=name, prefix=prefix, scan_info=scan_info, device_manager=device_manager, **kwargs
|
||||
)
|
||||
self.device_manager = device_manager
|
||||
|
||||
self.timeout_for_move = 10
|
||||
# Wait for connection on all components, ensure IOC is connected
|
||||
self.wait_for_connection(all_signals=True, timeout=5)
|
||||
|
||||
def open(self) -> DeviceStatus | None:
|
||||
"""Open the Absorber"""
|
||||
if self.status.get() == STATUS.CLOSED:
|
||||
self.request.put(1)
|
||||
status_open = CompareStatus(self.status, STATUS.OPEN, timeout=self.timeout_for_move)
|
||||
status = status_open
|
||||
return status
|
||||
else:
|
||||
return None
|
||||
def open(self, force: bool = False, wait: bool = True) -> CompareStatus | None:
|
||||
"""Open the Absorber
|
||||
|
||||
def close(self) -> DeviceStatus | None:
|
||||
Args:
|
||||
force(bool): If needed, set bl status to enable and bl enable to ENABLE, defaults to False
|
||||
|
||||
"""
|
||||
if self.status.get() == STATUS.CLOSED:
|
||||
if force:
|
||||
if self.device_manager.devices.bl_status.get() == BlStatus.OFFLINE:
|
||||
status = self.device_manager.devices.bl_status.put(BlStatus.ATTENDED)
|
||||
status.wait(timeout=TIMEOUT_FOR_PV)
|
||||
if self.close4bl.get() == BL_ENABLE.DISABLE:
|
||||
status = self.close4bl.set(BL_ENABLE.ENABLE)
|
||||
status.wait(timeout=TIMEOUT_FOR_PV)
|
||||
self.request.put(1)
|
||||
status = CompareStatus(self.status, STATUS.OPEN, timeout=self.timeout_for_move)
|
||||
if wait:
|
||||
status.wait(timeout=self.timeout_for_move)
|
||||
return None
|
||||
return status
|
||||
return None
|
||||
|
||||
def close(self, wait: bool = True) -> CompareStatus | None:
|
||||
"""Close the Absorber"""
|
||||
if self.status.get() == STATUS.OPEN:
|
||||
self.request.put(1)
|
||||
status_close = CompareStatus(self.status, STATUS.CLOSED, timeout=self.timeout_for_move)
|
||||
status = status_close
|
||||
status = CompareStatus(self.status, STATUS.CLOSED, timeout=self.timeout_for_move)
|
||||
if wait:
|
||||
status.wait(timeout=self.timeout_for_move)
|
||||
return None
|
||||
return status
|
||||
else:
|
||||
return None
|
||||
return None
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Experimental Hutch Photon Shutter"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from ophyd import Component as Cpt
|
||||
from ophyd import EpicsSignal, EpicsSignalRO
|
||||
from ophyd_devices import CompareStatus
|
||||
from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from bec_lib.devicemanager import ScanInfo
|
||||
|
||||
TIMEOUT_FOR_PV = 5
|
||||
|
||||
|
||||
class STATUS(int, enum.Enum):
|
||||
"""Shutter States"""
|
||||
|
||||
NOT_CLOSED = 0
|
||||
CLOSED = 1
|
||||
|
||||
|
||||
class BL_ENABLE(int, enum.Enum):
|
||||
"""Beamline enable"""
|
||||
|
||||
DISABLE = 0
|
||||
ENABLE = 1
|
||||
|
||||
|
||||
class EHPhotonShutter(PSIDeviceBase):
|
||||
"""Class for the Experimental Hutch Photon Shutter"""
|
||||
|
||||
USER_ACCESS = ["open", "close"]
|
||||
|
||||
request_open = Cpt(
|
||||
EpicsSignal, suffix="EH1-PSYS:SH-A-OPEN-SET", kind="config", doc="Open Shutter"
|
||||
)
|
||||
request_close = Cpt(
|
||||
EpicsSignal, suffix="EH1-PSYS:SH-A-CLOSE-SET", kind="config", doc="Close Shutter"
|
||||
)
|
||||
status = Cpt(
|
||||
EpicsSignalRO,
|
||||
suffix="EH1-PSYS:SH-A-CLOSE",
|
||||
kind="normal",
|
||||
auto_monitor=True,
|
||||
doc="Shutter Status",
|
||||
)
|
||||
status_string = Cpt(
|
||||
EpicsSignalRO,
|
||||
suffix="EH1-PSYS:SH-A-CLOSE",
|
||||
kind="normal",
|
||||
auto_monitor=True,
|
||||
string=True,
|
||||
doc="Shutter Status",
|
||||
)
|
||||
|
||||
def __init__(self, *, name: str, prefix: str = "", scan_info: ScanInfo | None = None, **kwargs):
|
||||
super().__init__(name=name, prefix=prefix, scan_info=scan_info, **kwargs)
|
||||
|
||||
self.timeout_for_move = 10
|
||||
# Wait for connection on all components, ensure IOC is connected
|
||||
self.wait_for_connection(all_signals=True, timeout=5)
|
||||
|
||||
def open(self, wait: bool = True) -> CompareStatus | None:
|
||||
"""Open the Shutter"""
|
||||
if self.status.get() == STATUS.CLOSED:
|
||||
self.request_open.put(1)
|
||||
status = CompareStatus(self.status, STATUS.NOT_CLOSED, timeout=self.timeout_for_move)
|
||||
if wait:
|
||||
status.wait(timeout=self.timeout_for_move)
|
||||
return None
|
||||
return status
|
||||
return None
|
||||
|
||||
def close(self, wait: bool = True) -> CompareStatus | None:
|
||||
"""Close the Shutter"""
|
||||
if self.status.get() == STATUS.NOT_CLOSED:
|
||||
self.request_close.put(1)
|
||||
status = CompareStatus(self.status, STATUS.CLOSED, timeout=self.timeout_for_move)
|
||||
if wait:
|
||||
status.wait(timeout=self.timeout_for_move)
|
||||
return None
|
||||
return status
|
||||
return None
|
||||
@@ -14,6 +14,7 @@ from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase
|
||||
from typeguard import typechecked
|
||||
|
||||
from debye_bec.devices.ionization_chambers.ionization_chamber_enums import (
|
||||
GAIN_MAP,
|
||||
AmplifierEnable,
|
||||
AmplifierFilter,
|
||||
AmplifierGain,
|
||||
@@ -120,12 +121,16 @@ class IonizationChamber0(PSIDeviceBase):
|
||||
self.timeout_for_pvwait = 2.5
|
||||
super().__init__(name=name, prefix=prefix, scan_info=scan_info, **kwargs)
|
||||
|
||||
@typechecked
|
||||
def set_gain(self, gain: Literal["1e6", "1e7", "5e7", "1e8", "1e9"]) -> None:
|
||||
def set_gain(self, gain: float) -> None:
|
||||
"""Configure the gain setting of the specified channel
|
||||
|
||||
Args:
|
||||
gain (Literal['1e6', '1e7', '5e7', '1e8', '1e9']) : Desired gain
|
||||
gain(float): Amplifier gain to set. Accepts either a float/int or a string,
|
||||
e.g. 1e6 or "1e6". Must be one of: 1e6, 1e7, 5e7, 1e8, 1e9.
|
||||
|
||||
Raises:
|
||||
ValueError: If `gain` cannot be converted to a float, or does not
|
||||
match one of the supported gain values.
|
||||
"""
|
||||
|
||||
if self.amp.cOnOff.get() == AmplifierEnable.OFF:
|
||||
@@ -134,17 +139,21 @@ class IonizationChamber0(PSIDeviceBase):
|
||||
self.amp.cOnOff.put(AmplifierEnable.ON)
|
||||
status.wait(self.timeout_for_pvwait)
|
||||
|
||||
match gain:
|
||||
case "1e6":
|
||||
self.amp.cGain_ENUM.put(AmplifierGain.G1E6)
|
||||
case "1e7":
|
||||
self.amp.cGain_ENUM.put(AmplifierGain.G1E7)
|
||||
case "5e7":
|
||||
self.amp.cGain_ENUM.put(AmplifierGain.G5E7)
|
||||
case "1e8":
|
||||
self.amp.cGain_ENUM.put(AmplifierGain.G1E8)
|
||||
case "1e9":
|
||||
self.amp.cGain_ENUM.put(AmplifierGain.G1E9)
|
||||
try:
|
||||
key = float(gain)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError(f"Invalid gain: {gain!r}") from exc
|
||||
|
||||
try:
|
||||
enum_val = GAIN_MAP[key]
|
||||
except KeyError as exc:
|
||||
raise ValueError(
|
||||
f"Unsupported gain: {gain!r}. Must be one of {sorted(GAIN_MAP)}"
|
||||
) from exc
|
||||
|
||||
self.amp.cGain_ENUM.put(enum_val)
|
||||
status = CompareStatus(self.amp.cGain_ENUM, enum_val)
|
||||
status.wait(self.timeout_for_pvwait)
|
||||
|
||||
def set_filter(
|
||||
self, value: Literal["1us", "3us", "10us", "30us", "100us", "300us", "1ms", "3ms"]
|
||||
@@ -263,7 +272,7 @@ class IonizationChamber0(PSIDeviceBase):
|
||||
self.gmes.gas2_req.set(gas2).wait(timeout=3)
|
||||
self.gmes.conc2_req.set(conc2).wait(timeout=3)
|
||||
|
||||
status = TransitionStatus(self.gmes.status.get(), [0, 1])
|
||||
status = TransitionStatus(self.gmes.status, [0, 1])
|
||||
self.cancel_on_stop(status)
|
||||
self.gmes.fill.put(1)
|
||||
if wait:
|
||||
@@ -373,6 +382,7 @@ class IonizationChamber2(IonizationChamber0):
|
||||
}
|
||||
hv_en = Dcpt(hv_en_signals)
|
||||
|
||||
|
||||
class Pips(IonizationChamber0):
|
||||
"""Pips, prefix should be 'X01DA-'."""
|
||||
|
||||
|
||||
@@ -19,6 +19,15 @@ class AmplifierGain(int, enum.Enum):
|
||||
G1E9 = 4
|
||||
|
||||
|
||||
GAIN_MAP = {
|
||||
1e6: AmplifierGain.G1E6,
|
||||
1e7: AmplifierGain.G1E7,
|
||||
5e7: AmplifierGain.G5E7,
|
||||
1e8: AmplifierGain.G1E8,
|
||||
1e9: AmplifierGain.G1E9,
|
||||
}
|
||||
|
||||
|
||||
class AmplifierFilter(int, enum.Enum):
|
||||
"""Enum class for the filter of the channel"""
|
||||
|
||||
|
||||
@@ -178,6 +178,9 @@ class NidaqControl(Device):
|
||||
heartbeat = Cpt(EpicsSignal, suffix="NIDAQ-Heartbeat", kind=Kind.config, auto_monitor=True)
|
||||
time_left = Cpt(EpicsSignalRO, suffix="NIDAQ-TimeLeft", kind=Kind.config, auto_monitor=True)
|
||||
|
||||
epics_mode = Cpt(EpicsSignal, suffix="NIDAQ-EpicsMode", kind=Kind.config, auto_monitor=True)
|
||||
epics_max_reset = Cpt(EpicsSignal, suffix="NIDAQ-EpicsMaxReset", kind=Kind.config, auto_monitor=True)
|
||||
|
||||
ai_chans = Cpt(EpicsSignal, suffix="NIDAQ-AIChans", kind=Kind.config, auto_monitor=True)
|
||||
ci_chans = Cpt(EpicsSignal, suffix="NIDAQ-CIChans", kind=Kind.config, auto_monitor=True)
|
||||
di_chans = Cpt(EpicsSignal, suffix="NIDAQ-DIChans", kind=Kind.config, auto_monitor=True)
|
||||
|
||||
@@ -58,3 +58,10 @@ class EncoderFactors(int, enum.Enum):
|
||||
X1 = 4
|
||||
X2 = 5
|
||||
X4 = 6
|
||||
|
||||
|
||||
class EpicsMode(int, enum.Enum):
|
||||
"""Mode when sending through EPICS"""
|
||||
|
||||
MEAN = 0
|
||||
MAX = 1
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Optics Photon Shutter"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from ophyd import Component as Cpt
|
||||
from ophyd import EpicsSignal, EpicsSignalRO
|
||||
from ophyd_devices import CompareStatus
|
||||
from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase
|
||||
|
||||
from .utils.bl_status_enum import BlStatus
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from bec_lib.devicemanager import ScanInfo
|
||||
from bec_server.device_server.device_server import DeviceManagerDS
|
||||
|
||||
TIMEOUT_FOR_PV = 5
|
||||
|
||||
|
||||
class OPPhotonShutterError(Exception):
|
||||
"""Shutter specific exception"""
|
||||
|
||||
|
||||
class STATUS(int, enum.Enum):
|
||||
"""Shutter States"""
|
||||
|
||||
NOT_CLOSED = 0
|
||||
CLOSED = 1
|
||||
|
||||
|
||||
class BL_ENABLE(int, enum.Enum):
|
||||
"""Beamline enable"""
|
||||
|
||||
DISABLE = 0
|
||||
ENABLE = 1
|
||||
|
||||
|
||||
class OPPhotonShutter(PSIDeviceBase):
|
||||
"""Class for the Optics Photon Shutter"""
|
||||
|
||||
USER_ACCESS = ["open", "close"]
|
||||
|
||||
request_open = Cpt(
|
||||
EpicsSignal, suffix="OP-PSYS:SH-A-OPEN-SET", kind="config", doc="Open Shutter"
|
||||
)
|
||||
request_close = Cpt(
|
||||
EpicsSignal, suffix="OP-PSYS:SH-A-CLOSE-SET", kind="config", doc="Close Shutter"
|
||||
)
|
||||
status = Cpt(
|
||||
EpicsSignalRO,
|
||||
suffix="OP-PSYS:SH-A-CLOSE",
|
||||
kind="normal",
|
||||
auto_monitor=True,
|
||||
doc="Shutter Status",
|
||||
)
|
||||
status_string = Cpt(
|
||||
EpicsSignalRO,
|
||||
suffix="OP-PSYS:SH-A-CLOSE",
|
||||
kind="normal",
|
||||
auto_monitor=True,
|
||||
string=True,
|
||||
doc="Shutter Status",
|
||||
)
|
||||
close4bl = Cpt(EpicsSignal, suffix="FE-BST1:CLOSE4BL", kind="config", doc="Beamline enable")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
name: str,
|
||||
prefix: str = "",
|
||||
scan_info: ScanInfo | None = None,
|
||||
device_manager: DeviceManagerDS | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(
|
||||
name=name, prefix=prefix, scan_info=scan_info, device_manager=device_manager, **kwargs
|
||||
)
|
||||
self.device_manager = device_manager
|
||||
|
||||
self.timeout_for_move = 10
|
||||
# Wait for connection on all components, ensure IOC is connected
|
||||
self.wait_for_connection(all_signals=True, timeout=5)
|
||||
|
||||
def open(self, force: bool = False, wait: bool = True) -> CompareStatus | None:
|
||||
"""Open the Shutter
|
||||
|
||||
Args:
|
||||
force(bool): If needed, set bl status to enable and bl enable to ENABLE, defaults to False
|
||||
|
||||
"""
|
||||
if self.status.get() == STATUS.CLOSED:
|
||||
if force:
|
||||
if self.device_manager.devices.bl_status.get() == BlStatus.OFFLINE:
|
||||
status = self.device_manager.devices.bl_status.put(BlStatus.ATTENDED)
|
||||
status.wait(timeout=TIMEOUT_FOR_PV)
|
||||
if self.close4bl.get() == BL_ENABLE.DISABLE:
|
||||
status = self.close4bl.set(BL_ENABLE.ENABLE)
|
||||
status.wait(timeout=TIMEOUT_FOR_PV)
|
||||
self.request_open.put(1)
|
||||
status = CompareStatus(self.status, STATUS.NOT_CLOSED, timeout=self.timeout_for_move)
|
||||
if wait:
|
||||
status.wait(timeout=self.timeout_for_move)
|
||||
return None
|
||||
return status
|
||||
return None
|
||||
|
||||
def close(self, wait: bool = True) -> CompareStatus | None:
|
||||
"""Close the Shutter"""
|
||||
if self.status.get() == STATUS.NOT_CLOSED:
|
||||
self.request_close.put(1)
|
||||
status = CompareStatus(self.status, STATUS.CLOSED, timeout=self.timeout_for_move)
|
||||
if wait:
|
||||
status.wait(timeout=self.timeout_for_move)
|
||||
return None
|
||||
return status
|
||||
return None
|
||||
@@ -5,8 +5,9 @@ from __future__ import annotations
|
||||
import enum
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from bec_lib.logger import bec_logger
|
||||
from ophyd import Component as Cpt
|
||||
from ophyd import EpicsSignal, EpicsSignalRO, EpicsSignalWithRBV
|
||||
from ophyd import EpicsSignal, EpicsSignalRO, EpicsSignalWithRBV, Signal
|
||||
from ophyd.status import DeviceStatus
|
||||
from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase
|
||||
from ophyd_devices.utils.errors import DeviceStopError
|
||||
@@ -14,6 +15,8 @@ from ophyd_devices.utils.errors import DeviceStopError
|
||||
if TYPE_CHECKING:
|
||||
from bec_lib.devicemanager import ScanInfo
|
||||
|
||||
logger = bec_logger.logger
|
||||
|
||||
|
||||
class Status(int, enum.Enum):
|
||||
"""Enum class for the status field"""
|
||||
@@ -34,10 +37,67 @@ class OpMode(int, enum.Enum):
|
||||
ERRORMODE = 3
|
||||
|
||||
|
||||
N_FOILS = 38
|
||||
|
||||
|
||||
class CurrentFoilSignal(Signal):
|
||||
"""
|
||||
Soft signal reflecting the description of the foil currently
|
||||
inserted. Recomputed whenever 'ref_rb', 'status' or any of the
|
||||
`foilNN` signals on the parent device change.
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._subscribed = False
|
||||
|
||||
def _foil_signal(self):
|
||||
if self.parent.status.get() != Status.INSERTED:
|
||||
return None
|
||||
idx = self.parent.ref_rb.get()
|
||||
try:
|
||||
idx = int(round(idx))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return getattr(self.parent, f"foil{idx:02d}", None)
|
||||
|
||||
def _compute(self):
|
||||
sig = self._foil_signal()
|
||||
if sig is None:
|
||||
return ""
|
||||
try:
|
||||
return sig.get()
|
||||
except Exception:
|
||||
logger.exception("current_foil: failed to read %s", sig.name)
|
||||
return ""
|
||||
|
||||
def get(self, **kwargs):
|
||||
self._readback = self._compute()
|
||||
return self._readback
|
||||
|
||||
def _on_upstream_change(self, value=None, timestamp=None, **kwargs):
|
||||
old_value = self._readback
|
||||
new_value = self._compute()
|
||||
self._readback = new_value
|
||||
self._run_subs(
|
||||
sub_type=self.SUB_VALUE, old_value=old_value, value=new_value, timestamp=timestamp
|
||||
)
|
||||
|
||||
def subscribe_to_parent_signals(self):
|
||||
if self._subscribed:
|
||||
return
|
||||
self.parent.ref_rb.subscribe(self._on_upstream_change, run=False)
|
||||
self.parent.status.subscribe(self._on_upstream_change, run=False)
|
||||
for i in range(1, N_FOILS + 1):
|
||||
getattr(self.parent, f"foil{i:02d}").subscribe(self._on_upstream_change, run=False)
|
||||
self._subscribed = True
|
||||
self._readback = self._compute()
|
||||
|
||||
|
||||
class Reffoilchanger(PSIDeviceBase):
|
||||
"""Class for the ES2 Reference Foil Changer"""
|
||||
|
||||
USER_ACCESS = ["insert"]
|
||||
USER_ACCESS = ["get_all_foils", "insert"]
|
||||
|
||||
inserted = Cpt(
|
||||
EpicsSignalRO, suffix="ES2-REF:TRY-FilterInserted", kind="config", doc="Inserted indicator"
|
||||
@@ -53,18 +113,30 @@ class Reffoilchanger(PSIDeviceBase):
|
||||
EpicsSignal, suffix="ES2-REF:SELN-FilterState-ENUM_RBV", kind="config", doc="Status"
|
||||
)
|
||||
status_string = Cpt(
|
||||
EpicsSignal, suffix="ES2-REF:SELN-FilterState-ENUM_RBV", kind="config", doc="Status", string=True
|
||||
EpicsSignal,
|
||||
suffix="ES2-REF:SELN-FilterState-ENUM_RBV",
|
||||
kind="config",
|
||||
doc="Status",
|
||||
string=True,
|
||||
)
|
||||
op_mode = Cpt(
|
||||
EpicsSignalWithRBV, suffix="ES2-REF:SELN-OpMode-ENUM", kind="config", doc="Status"
|
||||
)
|
||||
op_mode_string = Cpt(
|
||||
EpicsSignalWithRBV, suffix="ES2-REF:SELN-OpMode-ENUM", kind="config", doc="Status", string=True
|
||||
EpicsSignalWithRBV,
|
||||
suffix="ES2-REF:SELN-OpMode-ENUM",
|
||||
kind="config",
|
||||
doc="Status",
|
||||
string=True,
|
||||
)
|
||||
ref_set = Cpt(EpicsSignal, suffix="ES2-REF:SELN-SET", kind="config", doc="Requested reference")
|
||||
ref_rb = Cpt(
|
||||
EpicsSignalRO, suffix="ES2-REF:SELN-RB", kind="config", doc="Currently set reference"
|
||||
EpicsSignalRO,
|
||||
suffix="ES2-REF:SELN-RB",
|
||||
kind="config",
|
||||
doc="Currently set reference (angle)",
|
||||
)
|
||||
current_foil = Cpt(CurrentFoilSignal, value="", kind="normal", doc="Inserted reference")
|
||||
|
||||
foil01 = Cpt(EpicsSignalRO, suffix="ES-REFFOIL:FOIL01.DESC", kind="config", doc="Foil 01")
|
||||
foil02 = Cpt(EpicsSignalRO, suffix="ES-REFFOIL:FOIL02.DESC", kind="config", doc="Foil 02")
|
||||
@@ -107,6 +179,7 @@ class Reffoilchanger(PSIDeviceBase):
|
||||
|
||||
def __init__(self, *, name: str, prefix: str = "", scan_info: ScanInfo | None = None, **kwargs):
|
||||
super().__init__(name=name, prefix=prefix, scan_info=scan_info, **kwargs)
|
||||
self.current_foil.subscribe_to_parent_signals()
|
||||
|
||||
self.foils = [
|
||||
self.foil01,
|
||||
@@ -149,6 +222,13 @@ class Reffoilchanger(PSIDeviceBase):
|
||||
self.foil38,
|
||||
]
|
||||
|
||||
def get_all_foils(self) -> list[str]:
|
||||
"""Returns a list of strings of all available foils"""
|
||||
foils_list = []
|
||||
for foil in self.foils:
|
||||
foils_list.append(foil.get())
|
||||
return foils_list
|
||||
|
||||
def insert(self, ref: str, wait: bool = False) -> DeviceStatus:
|
||||
"""Insert a reference
|
||||
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Universal Temperature Controller"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Literal
|
||||
|
||||
from ophyd import Component as Cpt
|
||||
from ophyd import EpicsSignal, EpicsSignalRO
|
||||
from ophyd_devices.interfaces.base_classes.psi_device_base import PSIDeviceBase
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .univ_temp_cont_enums import POWER_MAP, RAMP_RATE_MAP, UnivTempContSetpointSelect
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from bec_lib.devicemanager import ScanInfo
|
||||
|
||||
TIMEOUT_FOR_PV = 5
|
||||
|
||||
|
||||
class ConfigDict(BaseModel):
|
||||
"""A configuration dictionary."""
|
||||
|
||||
power_mode: Literal[tuple(POWER_MAP)] # type: ignore[valid-type]
|
||||
target_setpoint: float
|
||||
ramp_rate: float
|
||||
ramp_rate_unit: Literal[tuple(RAMP_RATE_MAP)] # type: ignore[valid-type]
|
||||
|
||||
|
||||
class UnivTempCont(PSIDeviceBase):
|
||||
"""Class for the Universal Temperature Controller"""
|
||||
|
||||
USER_ACCESS = ["load_config"]
|
||||
|
||||
temperature = Cpt(
|
||||
EpicsSignalRO, suffix="TEMPERATURE", kind="normal", auto_monitor=True, doc="Temperature"
|
||||
)
|
||||
timestamp = Cpt(EpicsSignalRO, suffix="TIMESTAMP", kind="omitted", doc="Current timestamp")
|
||||
setpoint = Cpt(EpicsSignalRO, suffix="SETPOINT", kind="normal", doc="Setpoint on Controller")
|
||||
target_setpoint = Cpt(
|
||||
EpicsSignal, suffix="TARGET-SETPOINT", kind="normal", doc="Target Setpoint"
|
||||
)
|
||||
output_power = Cpt(EpicsSignalRO, suffix="OUTPUT-POWER", kind="normal", doc="Output Power %")
|
||||
ramp_rate = Cpt(EpicsSignal, suffix="RAMP-RATE", kind="normal", doc="Ramp rate")
|
||||
pb = Cpt(EpicsSignal, suffix="PB", kind="config", doc="Controller PB value")
|
||||
ti = Cpt(EpicsSignal, suffix="TI", kind="config", doc="Controller TI value")
|
||||
td = Cpt(EpicsSignal, suffix="TD", kind="config", doc="Controller TD value")
|
||||
op_mode = Cpt(EpicsSignal, suffix="OP-MODE", kind="normal", doc="Operation mode")
|
||||
setpoint_select = Cpt(
|
||||
EpicsSignal, suffix="SETPOINT-SELECT", kind="config", doc="Local or remote setpoint"
|
||||
)
|
||||
ramp_rate_unit = Cpt(
|
||||
EpicsSignal, suffix="RAMP-RATE-UNIT", kind="config", auto_monitor=True, doc="Ramp rate unit"
|
||||
)
|
||||
autotune = Cpt(EpicsSignal, suffix="AUTOTUNE", kind="config", doc="Autotune function")
|
||||
sensor_break = Cpt(
|
||||
EpicsSignalRO, suffix="SENSOR-BREAK", kind="normal", doc="Thermocouple Status"
|
||||
)
|
||||
thermocouple = Cpt(EpicsSignal, suffix="THERMOCOUPLE", kind="config", doc="Thermocouple type")
|
||||
power = Cpt(EpicsSignal, suffix="POWER", kind="normal", doc="Power status")
|
||||
controller_type = Cpt(EpicsSignalRO, suffix="TYPE", kind="config", doc="Controller type")
|
||||
heartbeat = Cpt(
|
||||
EpicsSignalRO, suffix="HEARTBEAT", kind="normal", auto_monitor=True, doc="Heartbeat"
|
||||
)
|
||||
connection = Cpt(
|
||||
EpicsSignalRO, suffix="CONNECTION", kind="normal", doc="Connection to Eurotherm Controller"
|
||||
)
|
||||
heater_temperature = Cpt(
|
||||
EpicsSignalRO,
|
||||
suffix="HEATER-TEMPERATURE",
|
||||
kind="normal",
|
||||
doc="Temperature of heating element",
|
||||
)
|
||||
heater_tc_fault = Cpt(
|
||||
EpicsSignalRO,
|
||||
suffix="HEATER-TC-FAULT",
|
||||
kind="normal",
|
||||
doc="TC Fault inside heating element",
|
||||
)
|
||||
|
||||
def __init__(self, *, name: str, prefix: str = "", scan_info: ScanInfo | None = None, **kwargs):
|
||||
super().__init__(name=name, prefix=prefix, scan_info=scan_info, **kwargs)
|
||||
|
||||
self.timeout_for_pvwait = 5
|
||||
# Wait for connection on all components, ensure IOC is connected
|
||||
self.wait_for_connection(all_signals=True, timeout=5)
|
||||
|
||||
def on_connected(self) -> None:
|
||||
"""
|
||||
Called after the device is connected and its signals are connected.
|
||||
Default values for signals should be set here.
|
||||
"""
|
||||
if self.setpoint_select != UnivTempContSetpointSelect.REMOTE:
|
||||
self.setpoint_select.set(UnivTempContSetpointSelect.REMOTE).wait(
|
||||
timeout=self.timeout_for_pvwait
|
||||
)
|
||||
|
||||
def load_config(
|
||||
self,
|
||||
config: ConfigDict | None = None,
|
||||
power_mode: str = "",
|
||||
ramp_rate_unit: str = "",
|
||||
ramp_rate: float = 0,
|
||||
target_setpoint: float = 0,
|
||||
) -> None:
|
||||
if config is None:
|
||||
config = ConfigDict(
|
||||
power_mode=power_mode,
|
||||
ramp_rate_unit=ramp_rate_unit,
|
||||
ramp_rate=ramp_rate,
|
||||
target_setpoint=target_setpoint,
|
||||
)
|
||||
# Load a config to the controller (power, setpoint and ramp rate)
|
||||
self.power.set(POWER_MAP[config.power_mode]).wait(timeout=self.timeout_for_pvwait)
|
||||
self.ramp_rate_unit.set(RAMP_RATE_MAP[config.ramp_rate_unit]).wait(
|
||||
timeout=self.timeout_for_pvwait
|
||||
)
|
||||
self.ramp_rate.set(config.ramp_rate).wait(timeout=self.timeout_for_pvwait)
|
||||
self.target_setpoint.set(config.target_setpoint).wait(timeout=self.timeout_for_pvwait)
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Enums for the universal temperature controller"""
|
||||
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class UnivTempContOpMode(int, Enum):
|
||||
"""Class for operating mode"""
|
||||
|
||||
AUTO = 0
|
||||
MANUAL = 1
|
||||
STANDBY = 2
|
||||
|
||||
|
||||
class UnivTempContSetpointSelect(int, Enum):
|
||||
"""Class for setpoint selection"""
|
||||
|
||||
LOCAL = 0
|
||||
REMOTE = 1
|
||||
|
||||
|
||||
class UnivTempContRampRateUnit(int, Enum):
|
||||
"""Class for ramp rate unit selection"""
|
||||
|
||||
DEG_C_MIN = 0
|
||||
DEG_C_H = 1
|
||||
DEG_C_S = 2
|
||||
|
||||
|
||||
RAMP_RATE_MAP = {
|
||||
"°C/min": UnivTempContRampRateUnit.DEG_C_MIN,
|
||||
"°C/h": UnivTempContRampRateUnit.DEG_C_H,
|
||||
"°C/s": UnivTempContRampRateUnit.DEG_C_S,
|
||||
}
|
||||
|
||||
|
||||
class UnivTempContAutoTune(int, Enum):
|
||||
"""Class for autotune function"""
|
||||
|
||||
NOTUNE = 0
|
||||
TUNE = 1
|
||||
|
||||
|
||||
class UnivTempContSensorBreak(int, Enum):
|
||||
"Class for sensor break status"
|
||||
|
||||
GOOD = 0
|
||||
SENSOR_BREAK = 1
|
||||
|
||||
|
||||
class UnivTempContThermocouple(int, Enum):
|
||||
"""Class for thermocouple type"""
|
||||
|
||||
TYPE_J = 0
|
||||
Type_K = 1
|
||||
|
||||
|
||||
THERMOCOUPLE_MAP = {
|
||||
"Type J": UnivTempContThermocouple.TYPE_J,
|
||||
"Type K": UnivTempContThermocouple.Type_K,
|
||||
}
|
||||
|
||||
|
||||
class UnivTempContPower(int, Enum):
|
||||
"""Class for power mode"""
|
||||
|
||||
AUTO = 0
|
||||
STANDBY = 1
|
||||
CONFIGURATION = 2
|
||||
|
||||
|
||||
POWER_MAP = {
|
||||
"Auto": UnivTempContPower.AUTO,
|
||||
"Standby": UnivTempContPower.STANDBY,
|
||||
"Configuration": UnivTempContPower.CONFIGURATION,
|
||||
}
|
||||
|
||||
|
||||
class UnivTempContConnection(int, Enum):
|
||||
"""Class for connection status"""
|
||||
|
||||
DISCONNECTED = 0
|
||||
CONNECTED = 1
|
||||
|
||||
|
||||
class UnivTempContHeaterTcFault(int, Enum):
|
||||
"""Class for the heater thermocouple fault"""
|
||||
|
||||
NO_FAULT = 0
|
||||
TC_OPEN_FAULT = 1
|
||||
OVER_UNDERVOLTAGE_FAULT = 2
|
||||
TC_LOW_FAULT = 3
|
||||
TC_HIGH_FAULT = 4
|
||||
COLD_JUNC_LOW_FAULT = 5
|
||||
COLD_JUNC_HIGH_FAULT = 6
|
||||
TC_RANGE_FAULT = 7
|
||||
COLD_JUNC_RNG_FAULT = 8
|
||||
@@ -0,0 +1,8 @@
|
||||
import enum
|
||||
|
||||
class BlStatus(str, enum.Enum):
|
||||
"""Beamline status enum"""
|
||||
|
||||
OFFLINE = 0
|
||||
ATTENDED = 1
|
||||
REMOTE = 2
|
||||
@@ -1,6 +1,6 @@
|
||||
from bec_server.file_writer.default_writer import DefaultFormat
|
||||
|
||||
import debye_bec.bec_widgets.widgets.digital_twin.x01da_parameters as bl
|
||||
import debye_bec.bec_ipython_client.plugins.digital_twin_core.x01da_parameters as bl
|
||||
|
||||
|
||||
class DebyeNexusStructure(DefaultFormat):
|
||||
@@ -236,7 +236,9 @@ class DebyeNexusStructure(DefaultFormat):
|
||||
self.configuration.get("nidaq", {}).get("nidaq_add_chans", {}).get("value")
|
||||
)
|
||||
|
||||
rle = self.configuration.get("nidaq", {}).get("nidaq_enable_compression", {}).get("value")
|
||||
rle = (
|
||||
self.configuration.get("nidaq", {}).get("nidaq_enable_compression", {}).get("value")
|
||||
)
|
||||
|
||||
measurement_mode = entry.create_group(name="mode")
|
||||
measurement_mode.attrs["NX_class"] = "NX_CHAR"
|
||||
@@ -288,6 +290,14 @@ class DebyeNexusStructure(DefaultFormat):
|
||||
)
|
||||
ref_trans.attrs["NX_class"] = "NX_CHAR"
|
||||
|
||||
foil = (
|
||||
self.device_manager.devices.reffoilchanger.read(cached=True)
|
||||
.get("reffoilchanger_current_foil")
|
||||
.get("value")
|
||||
)
|
||||
ref_foil = ai2ai4_active.create_dataset(name="Reference", data=foil)
|
||||
ref_foil.attrs["NX_class"] = "NX_CHAR"
|
||||
|
||||
main_data = entry.create_group(name="data")
|
||||
main_data.attrs["NX_class"] = "NXdata"
|
||||
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
"""Tests for the Scheduler's execution loop (`ScheduleExecutor`) with fake BEC handles."""
|
||||
|
||||
# pylint: disable=missing-function-docstring,missing-class-docstring
|
||||
import threading
|
||||
import time
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
from debye_bec.bec_widgets.widgets.scheduler.actions import ExecutionContext
|
||||
from debye_bec.bec_widgets.widgets.scheduler.executor import ScheduleExecutor
|
||||
from debye_bec.bec_widgets.widgets.scheduler.models import ItemStatus, ScheduleItem
|
||||
|
||||
TIMEOUT = 5
|
||||
|
||||
|
||||
class FakeHandle:
|
||||
"""Mimics a BEC ScanReport: `wait()` blocks until released, `cancel()` makes it raise."""
|
||||
|
||||
def __init__(self, release: threading.Event | None = None):
|
||||
self.release = release or threading.Event()
|
||||
if release is None:
|
||||
self.release.set()
|
||||
self.cancelled = threading.Event()
|
||||
self.request = None
|
||||
|
||||
def wait(self):
|
||||
while not self.release.wait(0.01):
|
||||
if self.cancelled.is_set():
|
||||
raise RuntimeError("cancelled")
|
||||
if self.cancelled.is_set():
|
||||
raise RuntimeError("cancelled")
|
||||
|
||||
def cancel(self):
|
||||
self.cancelled.set()
|
||||
|
||||
|
||||
class FakeStateMonitor:
|
||||
def __init__(self):
|
||||
self.ok = threading.Event()
|
||||
self.ok.set()
|
||||
|
||||
def is_ok(self):
|
||||
return self.ok.is_set()
|
||||
|
||||
def wait_until_ok(self, should_abort, poll_interval=0.01):
|
||||
while not should_abort():
|
||||
if self.ok.wait(poll_interval):
|
||||
return True
|
||||
return False
|
||||
|
||||
def blocking_states(self):
|
||||
return [] if self.ok.is_set() else ["beam"]
|
||||
|
||||
|
||||
class Harness:
|
||||
def __init__(self, items: list[ScheduleItem]):
|
||||
self.items = items
|
||||
self.scans = mock.MagicMock()
|
||||
self.dev = {"samx": mock.MagicMock()}
|
||||
self.dev["samx"].move.return_value = FakeHandle()
|
||||
self.monitor = FakeStateMonitor()
|
||||
self.notified: list[str] = []
|
||||
self.closing = threading.Event()
|
||||
self.executor = ScheduleExecutor(
|
||||
lock=threading.Lock(),
|
||||
get_items=lambda: self.items,
|
||||
persist_locked=lambda: None,
|
||||
emit_changed=lambda: None,
|
||||
context=ExecutionContext(scans=self.scans, dev=self.dev),
|
||||
state_monitor=self.monitor,
|
||||
notify_item=lambda item: self.notified.append(item.item_id),
|
||||
get_queue_storage=mock.MagicMock,
|
||||
closing=self.closing,
|
||||
)
|
||||
self.outcome = None
|
||||
self.thread = None
|
||||
|
||||
def start(self, **kwargs):
|
||||
def _run():
|
||||
self.outcome = self.executor.run(**kwargs)
|
||||
|
||||
self.thread = threading.Thread(target=_run, daemon=True)
|
||||
self.thread.start()
|
||||
|
||||
def join(self):
|
||||
self.thread.join(TIMEOUT)
|
||||
assert not self.thread.is_alive(), "executor did not finish"
|
||||
return self.outcome
|
||||
|
||||
|
||||
def _wait_until(predicate, timeout=TIMEOUT):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
if predicate():
|
||||
return
|
||||
time.sleep(0.01)
|
||||
pytest.fail("condition not reached")
|
||||
|
||||
|
||||
def _scan(item_id, wait=True, pause_on_state=False):
|
||||
return ScheduleItem(
|
||||
item_id=item_id,
|
||||
action="scan",
|
||||
params={"scan_name": "line_scan", "args": [], "kwargs": {}},
|
||||
wait_for_completion=wait,
|
||||
pause_on_state=pause_on_state,
|
||||
)
|
||||
|
||||
|
||||
def _delay(item_id, seconds=0.05):
|
||||
return ScheduleItem(item_id=item_id, action="delay", params={"seconds": seconds})
|
||||
|
||||
|
||||
def _move(item_id, pause_on_failure=False):
|
||||
return ScheduleItem(
|
||||
item_id=item_id,
|
||||
action="move",
|
||||
params={"device": "samx", "value": 1.0, "relative": False, "units": "mm"},
|
||||
pause_on_failure=pause_on_failure,
|
||||
)
|
||||
|
||||
|
||||
def _by_id(harness, item_id):
|
||||
return next(item for item in harness.items if item.item_id == item_id)
|
||||
|
||||
|
||||
def test_sequential_items_complete():
|
||||
harness = Harness([_move("m1"), _delay("d1"), _move("m2")])
|
||||
harness.start()
|
||||
assert harness.join() == "finished"
|
||||
assert all(item.status == ItemStatus.COMPLETED for item in harness.items)
|
||||
assert harness.notified == ["m1", "d1", "m2"]
|
||||
assert _by_id(harness, "d1").report.startswith("Waited")
|
||||
|
||||
|
||||
def test_background_item_runs_concurrently_with_its_block():
|
||||
release = threading.Event()
|
||||
parent_handle = FakeHandle(release)
|
||||
harness = Harness(
|
||||
[
|
||||
_scan("parent", wait=False),
|
||||
_delay("child1"),
|
||||
_delay("child2"),
|
||||
ScheduleItem(item_id="join", action="wait_for_parent"),
|
||||
_move("after"),
|
||||
]
|
||||
)
|
||||
harness.scans.line_scan.return_value = parent_handle
|
||||
harness.start()
|
||||
|
||||
_wait_until(lambda: _by_id(harness, "child2").status == ItemStatus.COMPLETED)
|
||||
assert _by_id(harness, "parent").status == ItemStatus.RUNNING
|
||||
_wait_until(lambda: _by_id(harness, "join").status == ItemStatus.RUNNING)
|
||||
time.sleep(0.1)
|
||||
assert _by_id(harness, "after").status == ItemStatus.PENDING # still waiting for parent
|
||||
|
||||
release.set()
|
||||
assert harness.join() == "finished"
|
||||
assert all(item.status == ItemStatus.COMPLETED for item in harness.items)
|
||||
assert _by_id(harness, "after").started_at >= _by_id(harness, "parent").finished_at
|
||||
|
||||
|
||||
def test_next_background_item_implicitly_waits_for_previous():
|
||||
release = threading.Event()
|
||||
first, second = FakeHandle(release), FakeHandle()
|
||||
harness = Harness([_scan("bg1", wait=False), _delay("child"), _scan("bg2", wait=False)])
|
||||
harness.scans.line_scan.side_effect = [first, second]
|
||||
harness.start()
|
||||
_wait_until(lambda: _by_id(harness, "child").status == ItemStatus.COMPLETED)
|
||||
time.sleep(0.1)
|
||||
assert _by_id(harness, "bg2").status == ItemStatus.PENDING
|
||||
release.set()
|
||||
assert harness.join() == "finished"
|
||||
assert _by_id(harness, "bg2").started_at >= _by_id(harness, "bg1").finished_at
|
||||
|
||||
|
||||
def test_failure_without_pause_continues():
|
||||
harness = Harness([_move("bad"), _move("good")])
|
||||
harness.dev["samx"].move.side_effect = [RuntimeError("motor error"), FakeHandle()]
|
||||
harness.start()
|
||||
assert harness.join() == "finished"
|
||||
assert _by_id(harness, "bad").status == ItemStatus.FAILED
|
||||
assert "motor error" in _by_id(harness, "bad").report
|
||||
assert _by_id(harness, "good").status == ItemStatus.COMPLETED
|
||||
|
||||
|
||||
def test_pause_on_failure_pauses():
|
||||
harness = Harness([_move("bad", pause_on_failure=True), _move("next")])
|
||||
harness.dev["samx"].move.side_effect = RuntimeError("motor error")
|
||||
harness.start()
|
||||
assert harness.join() == "paused_on_failure"
|
||||
assert _by_id(harness, "bad").status == ItemStatus.FAILED
|
||||
assert _by_id(harness, "next").status == ItemStatus.PENDING
|
||||
|
||||
|
||||
def test_retry_unfinished_runs_failed_item_once():
|
||||
harness = Harness([_move("bad"), _move("next")])
|
||||
harness.items[0].status = ItemStatus.FAILED
|
||||
harness.dev["samx"].move.side_effect = [RuntimeError("again"), FakeHandle()]
|
||||
harness.start(retry_unfinished=True)
|
||||
assert harness.join() == "finished"
|
||||
assert _by_id(harness, "bad").status == ItemStatus.FAILED
|
||||
assert _by_id(harness, "next").status == ItemStatus.COMPLETED
|
||||
assert harness.dev["samx"].move.call_count == 2
|
||||
|
||||
|
||||
def test_abort_interrupts_delay():
|
||||
harness = Harness([_delay("long", seconds=100), _move("next")])
|
||||
harness.start()
|
||||
_wait_until(lambda: _by_id(harness, "long").status == ItemStatus.RUNNING)
|
||||
harness.executor.request_abort()
|
||||
assert harness.join() == "aborted"
|
||||
assert _by_id(harness, "long").status == ItemStatus.ABORTED
|
||||
assert _by_id(harness, "next").status == ItemStatus.PENDING
|
||||
|
||||
|
||||
def test_pause_after_current_item():
|
||||
harness = Harness([_delay("d1", seconds=0.2), _move("next")])
|
||||
harness.start()
|
||||
_wait_until(lambda: _by_id(harness, "d1").status == ItemStatus.RUNNING)
|
||||
harness.executor.request_pause()
|
||||
assert harness.join() == "paused"
|
||||
assert _by_id(harness, "d1").status == ItemStatus.COMPLETED
|
||||
assert _by_id(harness, "next").status == ItemStatus.PENDING
|
||||
|
||||
|
||||
def test_pause_on_state_waits_for_states():
|
||||
harness = Harness([_move("gated")])
|
||||
harness.items[0].pause_on_state = True
|
||||
harness.monitor.ok.clear()
|
||||
harness.start()
|
||||
_wait_until(lambda: (_by_id(harness, "gated").report or "").startswith("Waiting"))
|
||||
assert _by_id(harness, "gated").status == ItemStatus.PENDING
|
||||
harness.monitor.ok.set()
|
||||
assert harness.join() == "finished"
|
||||
assert _by_id(harness, "gated").status == ItemStatus.COMPLETED
|
||||
|
||||
|
||||
def test_state_trip_cancels_and_repeats_gated_scan():
|
||||
first = FakeHandle(threading.Event()) # blocks until cancelled
|
||||
second = FakeHandle()
|
||||
harness = Harness([_scan("scan", pause_on_state=True)])
|
||||
harness.scans.line_scan.side_effect = [first, second]
|
||||
harness.start()
|
||||
_wait_until(lambda: _by_id(harness, "scan").status == ItemStatus.RUNNING)
|
||||
|
||||
harness.monitor.ok.clear()
|
||||
harness.executor.on_states_tripped()
|
||||
_wait_until(lambda: first.cancelled.is_set())
|
||||
_wait_until(lambda: (_by_id(harness, "scan").report or "").startswith("Waiting"))
|
||||
harness.monitor.ok.set()
|
||||
|
||||
assert harness.join() == "finished"
|
||||
assert _by_id(harness, "scan").status == ItemStatus.COMPLETED
|
||||
assert harness.scans.line_scan.call_count == 2
|
||||
|
||||
|
||||
def test_state_trip_does_not_interrupt_ungated_scan():
|
||||
release = threading.Event()
|
||||
handle = FakeHandle(release)
|
||||
harness = Harness([_scan("scan", pause_on_state=False)])
|
||||
harness.scans.line_scan.return_value = handle
|
||||
harness.start()
|
||||
_wait_until(lambda: _by_id(harness, "scan").status == ItemStatus.RUNNING)
|
||||
harness.executor.on_states_tripped()
|
||||
assert not handle.cancelled.is_set()
|
||||
release.set()
|
||||
assert harness.join() == "finished"
|
||||
|
||||
|
||||
def test_closing_leaves_running_item_untouched():
|
||||
harness = Harness([_scan("scan")])
|
||||
harness.scans.line_scan.return_value = FakeHandle(threading.Event())
|
||||
harness.start()
|
||||
_wait_until(lambda: _by_id(harness, "scan").status == ItemStatus.RUNNING)
|
||||
harness.closing.set()
|
||||
harness.executor.notify_closing()
|
||||
# The fake scan only ends when cancelled; closing must not cancel it server-side.
|
||||
time.sleep(0.1)
|
||||
assert _by_id(harness, "scan").status == ItemStatus.RUNNING
|
||||
harness.scans.line_scan.return_value.cancel()
|
||||
assert harness.join() == "widget_closed"
|
||||
assert _by_id(harness, "scan").status == ItemStatus.RUNNING
|
||||
@@ -0,0 +1,320 @@
|
||||
"""Tests for the Scheduler's data model, action registry and pure scheduling logic."""
|
||||
|
||||
# pylint: disable=missing-function-docstring
|
||||
import json
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
from debye_bec.bec_widgets.widgets.scheduler.actions import (
|
||||
ACTIONS,
|
||||
ExecutionContext,
|
||||
describe_item,
|
||||
format_duration,
|
||||
run_action,
|
||||
)
|
||||
from debye_bec.bec_widgets.widgets.scheduler.models import (
|
||||
ItemStatus,
|
||||
NotificationTarget,
|
||||
Schedule,
|
||||
ScheduleItem,
|
||||
is_legacy_schedule,
|
||||
schedule_from_document,
|
||||
)
|
||||
from debye_bec.bec_widgets.widgets.scheduler.schedule_logic import (
|
||||
BlockRole,
|
||||
block_parents,
|
||||
block_roles,
|
||||
item_depths,
|
||||
pick_next_runnable,
|
||||
protected_prefix_length,
|
||||
)
|
||||
|
||||
# A schedule document as written to Redis by the previous (eval-based) Scheduler version.
|
||||
LEGACY_SCHEDULE = {
|
||||
"schedule_name": "default_schedule",
|
||||
"items": [
|
||||
{
|
||||
"item_id": "a",
|
||||
"command": "dev.samx.move(1.0, relative=False)",
|
||||
"status": "completed",
|
||||
"kind": "move",
|
||||
"form_state": {"device_name": "samx", "value": 1.0, "units": "mm", "relative": False},
|
||||
"pause_on_failure": False,
|
||||
}
|
||||
],
|
||||
"is_running": False,
|
||||
"notes": "",
|
||||
"notifications": {"enabled": True, "target": "teams", "teams_scope": "x", "events": []},
|
||||
"guard": {"enabled": False, "device_name": None, "pause_below": None, "resume_above": None},
|
||||
}
|
||||
|
||||
# Sample parameters for every registered action (the "describe" text must work with them).
|
||||
SAMPLE_PARAMS = {
|
||||
"scan": {"scan_name": "line_scan", "args": ["samx", -1, 1], "kwargs": {"steps": 10}},
|
||||
"move": {"device": "samx", "value": 1.5, "relative": True, "units": "mm"},
|
||||
"digital_twin": {
|
||||
"config": {
|
||||
"mo1_mode": "Monochromatic",
|
||||
"energy": 9000,
|
||||
"h_acc": 1e-3,
|
||||
"v_acc": 1e-4,
|
||||
"cm_stripe": "Rh",
|
||||
"cm_pitch": 2e-3,
|
||||
"mo1_xtal": "Si111",
|
||||
"fm_stripe": "Pt",
|
||||
"fm_rotx": 3e-3,
|
||||
"ot_es1_trz": 100,
|
||||
"es1man_trz": 1.0,
|
||||
"smpl_to_xrd": 200.0,
|
||||
}
|
||||
},
|
||||
"auto_gain": {
|
||||
"config": {
|
||||
"element": "Cu",
|
||||
"edge": "K",
|
||||
"all_amplifiers": ["ic0", "ic1"],
|
||||
"link_ic0_ic1": True,
|
||||
"compensate_ring_current": True,
|
||||
"prohibited_gains": {"ic0": [1e6]},
|
||||
}
|
||||
},
|
||||
"absorber": {"action": "Open"},
|
||||
"ic_fill": {
|
||||
"chamber": "IC1",
|
||||
"gas1": "N2",
|
||||
"conc1": 80.0,
|
||||
"gas2": "Ar",
|
||||
"conc2": 20.0,
|
||||
"pressure": 1.5,
|
||||
},
|
||||
"reffoil": {"foil": "Cu"},
|
||||
"temperature_controller": {
|
||||
"config": {
|
||||
"power_mode": "On",
|
||||
"target_setpoint": 120,
|
||||
"ramp_rate": 10,
|
||||
"ramp_rate_unit": "K/min",
|
||||
}
|
||||
},
|
||||
"delay": {"seconds": 3725},
|
||||
"wait_for_parent": {},
|
||||
}
|
||||
|
||||
|
||||
def _item(action="delay", wait=True, status=ItemStatus.PENDING, item_id=None, **params):
|
||||
kwargs = {"item_id": item_id} if item_id else {}
|
||||
return ScheduleItem(
|
||||
action=action,
|
||||
params=params or SAMPLE_PARAMS[action],
|
||||
wait_for_completion=wait,
|
||||
status=status,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
# models
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
def test_legacy_schedule_is_detected_and_rejected():
|
||||
assert is_legacy_schedule(LEGACY_SCHEDULE)
|
||||
with pytest.raises(Exception):
|
||||
Schedule.model_validate(LEGACY_SCHEDULE)
|
||||
|
||||
|
||||
def test_legacy_teams_target_maps_to_scilog():
|
||||
schedule = Schedule.model_validate({**LEGACY_SCHEDULE, "items": []})
|
||||
assert schedule.notifications.target == NotificationTarget.SCILOG
|
||||
assert schedule.notifications.enabled
|
||||
|
||||
|
||||
def test_legacy_notify_rpc_alias():
|
||||
schedule = Schedule.model_validate(
|
||||
{"schedule_name": "s", "notifications": {"notify_rpc": False}}
|
||||
)
|
||||
assert schedule.notifications.notify_device is False
|
||||
|
||||
|
||||
def test_schedule_json_round_trip():
|
||||
schedule = Schedule(
|
||||
schedule_name="s", items=[_item(action) for action in SAMPLE_PARAMS], notes="hello"
|
||||
)
|
||||
data = json.loads(json.dumps(schedule.model_dump(mode="json")))
|
||||
assert Schedule.model_validate(data) == schedule
|
||||
|
||||
|
||||
def test_reset_execution_and_definition():
|
||||
item = _item("move", status=ItemStatus.FAILED)
|
||||
item.error, item.report, item.scan_number = "boom", "boom", 3
|
||||
item.reset_execution()
|
||||
assert item.status == ItemStatus.PENDING
|
||||
assert (item.error, item.report, item.scan_number) == (None, None, None)
|
||||
assert set(item.definition()) == {
|
||||
"action",
|
||||
"params",
|
||||
"wait_for_completion",
|
||||
"pause_on_failure",
|
||||
"pause_on_state",
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
# actions
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
def test_every_action_has_sample_params_and_description():
|
||||
assert set(ACTIONS) == set(SAMPLE_PARAMS)
|
||||
for action, params in SAMPLE_PARAMS.items():
|
||||
json.dumps(params)
|
||||
text = describe_item(_item(action), "x01da")
|
||||
assert text and "Unknown action" not in text
|
||||
|
||||
|
||||
def test_describe_unknown_action_does_not_raise():
|
||||
item = ScheduleItem(action="does_not_exist", params={"a": 1})
|
||||
assert "does_not_exist" in describe_item(item, None)
|
||||
|
||||
|
||||
def test_run_action_unknown_raises():
|
||||
with pytest.raises(KeyError):
|
||||
run_action(ExecutionContext(scans=None, dev=None), "does_not_exist", {})
|
||||
|
||||
|
||||
def test_run_scan_dispatches_to_scans():
|
||||
scans = mock.MagicMock()
|
||||
ctx = ExecutionContext(scans=scans, dev=None)
|
||||
run_action(ctx, "scan", SAMPLE_PARAMS["scan"])
|
||||
scans.line_scan.assert_called_once_with("samx", -1, 1, steps=10)
|
||||
|
||||
|
||||
def test_run_scan_rejects_private_names():
|
||||
ctx = ExecutionContext(scans=mock.MagicMock(), dev=None)
|
||||
with pytest.raises(ValueError):
|
||||
run_action(ctx, "scan", {"scan_name": "_run", "args": [], "kwargs": {}})
|
||||
|
||||
|
||||
def test_run_move_dispatches_to_device():
|
||||
dev = {"samx": mock.MagicMock()}
|
||||
run_action(ExecutionContext(scans=None, dev=dev), "move", SAMPLE_PARAMS["move"])
|
||||
dev["samx"].move.assert_called_once_with(1.5, relative=True)
|
||||
|
||||
|
||||
def test_run_digital_twin_failure_raises():
|
||||
twin = mock.MagicMock()
|
||||
twin.move_with_config.return_value = {"success": False, "failures": {"m": "x"}}
|
||||
ctx = ExecutionContext(scans=None, dev=None, digital_twin=twin)
|
||||
with pytest.raises(RuntimeError):
|
||||
run_action(ctx, "digital_twin", SAMPLE_PARAMS["digital_twin"])
|
||||
|
||||
|
||||
def test_run_delay_is_interrupted_by_abort():
|
||||
ctx = ExecutionContext(scans=None, dev=None)
|
||||
ctx.abort_event.set()
|
||||
with pytest.raises(Exception):
|
||||
run_action(ctx, "delay", {"seconds": 100})
|
||||
|
||||
|
||||
def test_control_action_cannot_be_run_directly():
|
||||
with pytest.raises(ValueError):
|
||||
run_action(ExecutionContext(scans=None, dev=None), "wait_for_parent", {})
|
||||
|
||||
|
||||
def test_format_duration():
|
||||
assert format_duration(3725) == "1 h 02 min 05 s"
|
||||
assert format_duration(150) == "2 min 30 s"
|
||||
assert format_duration(5) == "5 s"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
# block structure
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
def test_blocks_explicit_close():
|
||||
items = [
|
||||
_item("move"),
|
||||
_item("scan", wait=False),
|
||||
_item("temperature_controller"),
|
||||
_item("delay"),
|
||||
_item("wait_for_parent"),
|
||||
_item("move"),
|
||||
]
|
||||
assert block_parents(items) == [None, None, 1, 1, 1, None]
|
||||
assert item_depths(items) == [0, 0, 1, 1, 1, 0]
|
||||
assert block_roles(items) == [
|
||||
BlockRole.NONE,
|
||||
BlockRole.PARENT,
|
||||
BlockRole.CHILD,
|
||||
BlockRole.CHILD,
|
||||
BlockRole.LAST_CHILD,
|
||||
BlockRole.NONE,
|
||||
]
|
||||
|
||||
|
||||
def test_blocks_implicit_close_by_next_background_item_and_end():
|
||||
items = [_item("scan", wait=False), _item("delay"), _item("scan", wait=False), _item("delay")]
|
||||
assert block_parents(items) == [None, 0, None, 2]
|
||||
assert block_roles(items)[1] == BlockRole.LAST_CHILD
|
||||
assert block_roles(items)[3] == BlockRole.LAST_CHILD
|
||||
|
||||
|
||||
def test_background_item_without_children():
|
||||
items = [_item("scan", wait=False), _item("scan", wait=False)]
|
||||
assert block_roles(items) == [BlockRole.PARENT_EMPTY, BlockRole.PARENT_EMPTY]
|
||||
|
||||
|
||||
def test_wait_for_parent_outside_block_is_top_level():
|
||||
items = [_item("wait_for_parent"), _item("move")]
|
||||
assert item_depths(items) == [0, 0]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
# next item / protected prefix
|
||||
# ---------------------------------------------------------------------------------------------- #
|
||||
def test_protected_prefix_with_several_running_items():
|
||||
items = [
|
||||
_item(status=ItemStatus.COMPLETED),
|
||||
_item(status=ItemStatus.RUNNING),
|
||||
_item(status=ItemStatus.RUNNING),
|
||||
_item(),
|
||||
]
|
||||
assert protected_prefix_length(items) == 3
|
||||
|
||||
|
||||
def test_pick_next_skips_completed_failed_and_active():
|
||||
items = [
|
||||
_item(status=ItemStatus.COMPLETED),
|
||||
_item(status=ItemStatus.FAILED),
|
||||
_item(status=ItemStatus.RUNNING, item_id="bg"),
|
||||
_item(item_id="next"),
|
||||
]
|
||||
assert pick_next_runnable(items, active_ids={"bg"}).item_id == "next"
|
||||
|
||||
|
||||
def test_pick_next_retries_unfinished_once():
|
||||
items = [_item(status=ItemStatus.FAILED, item_id="f"), _item(item_id="p")]
|
||||
assert pick_next_runnable(items, retry_unfinished=True).item_id == "f"
|
||||
assert pick_next_runnable(items, retry_unfinished=True, attempted_ids={"f"}).item_id == "p"
|
||||
|
||||
|
||||
def test_pick_next_respects_first_index_and_end():
|
||||
items = [_item(item_id="a"), _item(item_id="b")]
|
||||
assert pick_next_runnable(items, first_index=1).item_id == "b"
|
||||
assert pick_next_runnable([_item(status=ItemStatus.COMPLETED)]) is None
|
||||
|
||||
|
||||
def test_schedule_from_document_never_raises():
|
||||
schedule, problem = schedule_from_document(LEGACY_SCHEDULE)
|
||||
assert schedule is None and "old" in problem
|
||||
schedule, problem = schedule_from_document({"items": "garbage"})
|
||||
assert schedule is None and problem
|
||||
schedule, problem = schedule_from_document(None)
|
||||
assert schedule is None and problem
|
||||
schedule, problem = schedule_from_document({"schedule_name": "s", "items": []})
|
||||
assert problem is None and schedule.schedule_name == "s"
|
||||
|
||||
|
||||
def test_run_temperature_controller_passes_plain_values():
|
||||
dev = {"univ_temp_cont": mock.MagicMock()}
|
||||
params = SAMPLE_PARAMS["temperature_controller"]
|
||||
run_action(ExecutionContext(scans=None, dev=dev), "temperature_controller", params)
|
||||
dev["univ_temp_cont"].load_config.assert_called_once_with(
|
||||
power_mode="On", target_setpoint=120, ramp_rate=10, ramp_rate_unit="K/min"
|
||||
)
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Tests for the Scheduler's beamline-state monitor and the interlock hiding helper."""
|
||||
|
||||
# pylint: disable=missing-function-docstring,redefined-outer-name
|
||||
from types import SimpleNamespace
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
from bec_lib.endpoints import MessageEndpoints
|
||||
from qtpy.QtWidgets import QApplication
|
||||
|
||||
from debye_bec.bec_widgets.widgets.scheduler.interlock_hiding import hide_scan_interlock_controls
|
||||
from debye_bec.bec_widgets.widgets.scheduler.state_monitor import BeamlineStateMonitor
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def qapp():
|
||||
return QApplication.instance() or QApplication([])
|
||||
|
||||
|
||||
class FakeDispatcher:
|
||||
def __init__(self):
|
||||
self.slots: dict[str, object] = {}
|
||||
|
||||
def connect_slot(self, slot, topic):
|
||||
self.slots[topic.endpoint] = slot
|
||||
|
||||
def disconnect_slot(self, slot, topic):
|
||||
self.slots.pop(topic.endpoint, None)
|
||||
|
||||
def publish_state(self, name, status):
|
||||
self.slots[MessageEndpoints.beamline_state(name).endpoint](
|
||||
{"name": name, "status": status, "label": ""}, {}
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def monitor(qapp): # pylint: disable=unused-argument
|
||||
client = mock.MagicMock()
|
||||
client.connector.get_last.return_value = None
|
||||
dispatcher = FakeDispatcher()
|
||||
mon = BeamlineStateMonitor(client, dispatcher)
|
||||
yield mon, dispatcher
|
||||
mon.cleanup()
|
||||
|
||||
|
||||
def _set_available(dispatcher, *names):
|
||||
dispatcher.slots[MessageEndpoints.available_beamline_states().endpoint](
|
||||
{"states": [SimpleNamespace(name=name) for name in names]}, {}
|
||||
)
|
||||
|
||||
|
||||
def test_no_states_is_ok(monitor):
|
||||
mon, _ = monitor
|
||||
assert mon.is_ok()
|
||||
assert mon.summary() == "No beamline states defined"
|
||||
|
||||
|
||||
def test_new_state_is_unknown_until_reported(monitor):
|
||||
mon, dispatcher = monitor
|
||||
_set_available(dispatcher, "beam")
|
||||
assert not mon.is_ok()
|
||||
dispatcher.publish_state("beam", "valid")
|
||||
assert mon.is_ok()
|
||||
|
||||
|
||||
def test_warning_is_ok_invalid_trips_and_recovers(monitor):
|
||||
mon, dispatcher = monitor
|
||||
tripped, recovered = mock.MagicMock(), mock.MagicMock()
|
||||
mon.tripped.connect(tripped)
|
||||
mon.recovered.connect(recovered)
|
||||
_set_available(dispatcher, "beam", "shutter")
|
||||
tripped.assert_called_once() # new states are "unknown" until they report
|
||||
dispatcher.publish_state("beam", "valid")
|
||||
dispatcher.publish_state("shutter", "warning")
|
||||
assert mon.is_ok()
|
||||
recovered.assert_called_once()
|
||||
|
||||
dispatcher.publish_state("shutter", "invalid")
|
||||
assert not mon.is_ok()
|
||||
assert mon.blocking_states() == ["shutter"]
|
||||
assert tripped.call_count == 2
|
||||
|
||||
dispatcher.publish_state("shutter", "valid")
|
||||
assert mon.is_ok()
|
||||
assert recovered.call_count == 2
|
||||
|
||||
|
||||
def test_removed_state_is_unsubscribed(monitor):
|
||||
mon, dispatcher = monitor
|
||||
_set_available(dispatcher, "beam")
|
||||
dispatcher.publish_state("beam", "invalid")
|
||||
assert not mon.is_ok()
|
||||
_set_available(dispatcher)
|
||||
assert mon.is_ok()
|
||||
assert MessageEndpoints.beamline_state("beam").endpoint not in dispatcher.slots
|
||||
|
||||
|
||||
def test_wait_until_ok_aborts(monitor):
|
||||
mon, dispatcher = monitor
|
||||
_set_available(dispatcher, "beam")
|
||||
assert mon.wait_until_ok(should_abort=lambda: True) is False
|
||||
|
||||
|
||||
def test_hide_scan_interlock_controls():
|
||||
action = mock.MagicMock()
|
||||
pill = SimpleNamespace(_interlock_button=mock.MagicMock(), _interlock_warning_checkbox=None)
|
||||
manager = SimpleNamespace(
|
||||
_toolbar=SimpleNamespace(
|
||||
components=SimpleNamespace(get_action=lambda name: SimpleNamespace(action=action))
|
||||
),
|
||||
_state_pills={"beam": pill},
|
||||
)
|
||||
hide_scan_interlock_controls(manager) # must not raise on the missing checkbox
|
||||
action.setVisible.assert_called_with(False)
|
||||
pill._interlock_button.setVisible.assert_called_once_with(
|
||||
False
|
||||
) # pylint: disable=protected-access
|
||||
Reference in new issue
Block a user