wip
CI for debye_bec / test (pull_request) Successful in 57s
CI for debye_bec / test (push) Successful in 1m11s

This commit is contained in:
hitzst committed 2026-09-07 15:52:37 +02:00
1 parent a95b586256
commit d0eb5d9c94
4 files changed
+104 -51

No files matched your search

@@ -1,9 +1,10 @@
""" Module to automatically set the gains for the selected amplifiers"""
import xraydb
from bisect import bisect_right
import time
import builtins
import numpy as np
import xraydb
from bec_lib import bec_logger
from ...devices.nidaq.nidaq_enums import NidaqState
@@ -12,22 +13,17 @@ from ...devices.op_shutter import STATUS as OP_PH_STATUS
from ...devices.eh_shutter import STATUS as EH_PH_STATUS
from ...devices.ionization_chambers.ionization_chamber_enums import AmplifierEnable
if builtins.__dict__.get("bec") is not None:
bec = builtins.__dict__.get("bec")
dev = builtins.__dict__.get("dev")
scans = builtins.__dict__.get("scans")
logger = bec_logger.logger
EMIN = -100
EMAX = 200
MIN_RING_CURRENT = 5
NOMINAL_RING_CURRENT = 400
MIN_RING_CURRENT = 5 # Minimum ring current to use auto-gain
NOMINAL_RING_CURRENT = 400 # Nominal ring current of SLS2
MONO_VELOCITY = 20
TIMEOUT_MONO_PV = 5
TIMEOUT_MONO_MOVE = 60
MONO_VELOCITY = 20 # Move velocity in deg/s
TIMEOUT_MONO_PV = 5 # Timeout to set a PV on the mono
TIMEOUT_MONO_MOVE = 30 # Timeout to finish a movement on the mono
AVAILABLE_GAINS = [1e6, 1e7, 5e7, 1e8, 1e9] # ascending order
MIN_SIGNAL = 0.05 # Minimum signal to count as valid signal
@@ -38,30 +34,67 @@ class AutoGainError(Exception):
"""AutoGain specific error"""
class AutoGain():
""" Module to automatically set the gains for the selected amplifiers"""
def __init__(self):
pass
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
def start(self, element:str, edge:str, amplifier:list[str] | None=None, comp_ring_current:bool=True):
def start(
self,
element:str,
edge:str,
amplifier:list[str] | None=None,
comp_ring_current:bool=True
) -> None:
""" Start the auto-gain sequence. Measure the signals of the specified
amplifiers and set the gains accordingly. Makes sure there is actually beam available.
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 -> ['ic0', 'ic1', 'ic2', 'pips']
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
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 amplifier is None:
amplifier = ['ic0', 'ic1', 'ic2', 'pips']
# Make sure NIDAQ is in standby mode
if dev.nidaq.state.get() is not NidaqState.STANDBY:
if self.dev.nidaq.state.get() is not 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 dev.abs.status.get() != ABS_STATUS.OPEN:
if self.dev.abs.status.get() != ABS_STATUS.OPEN:
raise AutoGainError('Absorber is closed, no beam')
if dev.op_shutter.status.get() != OP_PH_STATUS.NOT_CLOSED:
if self.dev.op_shutter.status.get() != OP_PH_STATUS.NOT_CLOSED:
raise AutoGainError('OP Photon Shutter is closed, no beam')
if dev.eh_shutter.status.get() != EH_PH_STATUS.NOT_CLOSED:
if self.dev.eh_shutter.status.get() != EH_PH_STATUS.NOT_CLOSED:
raise AutoGainError('EH Photon Shutter is closed, no beam')
# Check if no scan is running
scan_id = bec.queue.scan_storage.current_scan_id
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")
@@ -73,7 +106,7 @@ class AutoGain():
emax = energy + EMAX
# Check range of mono
low_limit, high_limit = dev.mo1_bragg.limits()
low_limit, high_limit = self.dev.mo1_bragg.limits()
if emin < low_limit or emax > high_limit:
raise ValueError(
f'Chosen element/edge {element}/{edge} with edge energy of {energy}' +
@@ -83,42 +116,42 @@ class AutoGain():
# Map amplifier names to their NIDAQ channels
channel_map = {
'ic0': {'signal': dev.nidaq.ai0, 'dev': dev.ic0},
'ic1': {'signal': dev.nidaq.ai2, 'dev': dev.ic1},
'ic2': {'signal': dev.nidaq.ai4, 'dev': dev.ic2},
'pips': {'signal': dev.nidaq.ai6, 'dev': dev.pips},
'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}
# Check if amplifieres are switched on
for name, ch in active_channels.items():
if ch['dev'].amp.cOnOff.get() != AmplifierEnable.ON:
raise AutoGainError(f"Amplifier of device {name} is not enabled")
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
for name, ch in active_channels.items():
if name != 'pips':
if ch['dev'].hv_en.ena.get() is not True:
if ch['self.dev'].hv_en.ena.get() is not True:
raise AutoGainError(f"High voltage of ionization chamber {name} is not enabled")
if ch['dev'].hv.v.get() < 1000:
if ch['self.dev'].hv.v.get() < 1000:
raise AutoGainError(f"HV voltage of ionization chamber {name} is < 1000")
if ch['dev'].hv.grid_v.get() < 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
for name, ch in active_channels.items():
if name != 'pips':
if ch['dev'].gmes.status.get() != True:
if ch['self.dev'].gmes.status.get() is not True:
raise AutoGainError(f'Gas filling of ionization chamber {name} is not OK')
logger.info('All checks done, start preparing for measurement')
# Get initial monochromator position and velocity
init_pos = dev.mo1_bragg.position.get()
init_vel = dev.mo1_bragg.velocity.get()
init_pos = self.dev.mo1_bragg.position.get()
init_vel = self.dev.mo1_bragg.velocity.get()
logger.info(f'Move mono to start of {emin} eV')
status = dev.mo1_bragg.move(emin)
status = self.dev.mo1_bragg.move(emin)
status.wait(TIMEOUT_MONO_MOVE)
# Set NIDAQ to max mode
@@ -127,12 +160,12 @@ class AutoGain():
# Set gains to lowest gain
for name, ch in active_channels.items():
lowest_gain = AVAILABLE_GAINS[0]
ch['dev'].set_gain(lowest_gain)
ch['self.dev'].set_gain(lowest_gain)
ch['gain'] = lowest_gain
remeasure = True
logger.info(f'Start measurement from {emin} eV to {emax} eV')
while(remeasure):
while remeasure:
# Create temporary storage for max signal per channel
data = {name: 0 for name in active_channels}
@@ -143,9 +176,9 @@ class AutoGain():
raise AutoGainError('Ring current dropped to 0 mA right before measurement')
# Scan range, recording the peak NIDAQ signal per channel
status = dev.mo1_bragg.velocity.put(MONO_VELOCITY)
status = self.dev.mo1_bragg.velocity.put(MONO_VELOCITY)
status.wait(TIMEOUT_MONO_PV)
dev.mo1_bragg.move(emax).wait(timeout=TIMEOUT_MONO_MOVE)
self.dev.mo1_bragg.move(emax).wait(timeout=TIMEOUT_MONO_MOVE)
status.wait(TIMEOUT_MONO_MOVE)
for name, ch in active_channels.items():
data[name] = max(data[name], ch['signal'].get())
@@ -161,32 +194,40 @@ class AutoGain():
ring_current = (ring_current_1 + ring_current_2) / 2
# Move back to first monochromator position
status = dev.mo1_bragg.move(emin)
status = self.dev.mo1_bragg.move(emin)
# Choose gain per channel based on the max signal recorded during the scan
remeasure = False
for name, ch in active_channels.items():
raw_signal = data[name]
logger.info(f'Raw signal for device {name} is {raw_signal} V')
logger.info(f'Raw signal for self.device {name} is {raw_signal} V')
if comp_ring_current:
raw_signal = raw_signal * NOMINAL_RING_CURRENT / ring_current
logger.info(f'Compensate for ring current, new raw signal is {raw_signal} V')
if raw_signal < MIN_SIGNAL:
logger.info(f'Raw signal for device {name} is below {MIN_SIGNAL}')
# Choose next gain to be 100x the current gain, or if this gain does not exist, choose the next smaller one
logger.info(f'Raw signal for self.device {name} is below {MIN_SIGNAL}')
# Choose next gain to be 100x the current gain, or if this gain does not exist,
# choose the next smaller one
if ch['gain'] == AVAILABLE_GAINS[-1]:
logger.warning(f"Amplifier of {name} at highest gain {ch['gain']} and still not measured signal above {MIN_SIGNAL}")
logger.warning(
f"Amplifier of {name} at highest gain {ch['gain']} and still not" +
f" measured signal above {MIN_SIGNAL}"
)
else:
next_gain = AVAILABLE_GAINS[bisect_right(AVAILABLE_GAINS, ch['gain'] * 100) - 1]
ch['dev'].set_gain(next_gain)
logger.info(f'Setting gain of device {name} to {next_gain:.0e} and remeasure')
next_gain = AVAILABLE_GAINS[
bisect_right(AVAILABLE_GAINS, ch['gain'] * 100) - 1
]
ch['self.dev'].set_gain(next_gain)
logger.info(
f'Setting gain of self.device {name} to {next_gain:.0e} and remeasure'
)
remeasure = True
else:
gain = max(
(g for g in AVAILABLE_GAINS if raw_signal / ch['gain'] * g <= FULL_SCALE_V * SAFETY_MARGIN),
default=min(AVAILABLE_GAINS),
)
ch['dev'].set_gain(gain)
ch['self.dev'].set_gain(gain)
logger.info(f'Calculated final gain for {name} of {gain:.0e}')
# Wait for mono to return to start position
@@ -196,16 +237,15 @@ class AutoGain():
# TODO implement
# Wait for mono to move to initial position and reset velocity
status = dev.mo1_bragg.move(init_pos)
status = self.dev.mo1_bragg.move(init_pos)
status.wait(TIMEOUT_MONO_MOVE)
dev.mo1_bragg.velocity.put(init_vel)
self.dev.mo1_bragg.velocity.put(init_vel)
@staticmethod
def _get_ring_current() -> float:
def _get_ring_current(self) -> float:
ring_current = 0
retries = 0
while ring_current == 0 and retries < 10:
ring_current = dev.curr.get()
ring_current = self.dev.curr.get()
retries += 1
time.sleep(0.01)
return ring_current
@@ -42,6 +42,10 @@ logger = bec_logger.logger
logger.info("Using the Debye startup script.")
from debye_bec.bec_ipython_client.plugins.digital_twin.digital_twin import DigitalTwinCore
from debye_bec.bec_ipython_client.plugins.auto_gain import AutoGain
digital_twin = DigitalTwinCore()
logger.success("Digital Twin Core loaded. Use 'digital_twin' to access it.")
auto_gain = AutoGain()
logger.success("Auto-Gain module loaded. Use 'auto_gain' to access it.")
+3
View File
@@ -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)
+6
View File
@@ -58,3 +58,9 @@ class EncoderFactors(int, enum.Enum):
X1 = 4
X2 = 5
X4 = 6
class EpicsMode(int, enum.Enum):
"""Mode when sending through EPICS"""
MEAN = 0
MAX = 0