diff --git a/debye_bec/bec_ipython_client/plugins/auto_gain_core.py b/debye_bec/bec_ipython_client/plugins/auto_gain_core.py new file mode 100644 index 0000000..6152d99 --- /dev/null +++ b/debye_bec/bec_ipython_client/plugins/auto_gain_core.py @@ -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 diff --git a/debye_bec/bec_widgets/widgets/digital_twin/beamline.py b/debye_bec/bec_ipython_client/plugins/beamline.py similarity index 79% rename from debye_bec/bec_widgets/widgets/digital_twin/beamline.py rename to debye_bec/bec_ipython_client/plugins/beamline.py index 3653284..9604799 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/beamline.py +++ b/debye_bec/bec_ipython_client/plugins/beamline.py @@ -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 diff --git a/debye_bec/bec_widgets/widgets/digital_twin/calculations/__init__.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/__init__.py similarity index 100% rename from debye_bec/bec_widgets/widgets/digital_twin/calculations/__init__.py rename to debye_bec/bec_ipython_client/plugins/digital_twin_core/__init__.py diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py new file mode 100644 index 0000000..7bb9280 --- /dev/null +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/digital_twin_core.py @@ -0,0 +1,1338 @@ +import builtins +import re +import threading +from pathlib import Path +from typing import Literal, cast + +import numpy as np +import yaml +from bec_lib import bec_logger +from scipy.interpolate import UnivariateSpline +from xrt.backends.raycing.physconsts import AVOGADRO, CHeVcm + +from ..beamline import get_beamline_id +from .motion_worker import MotionOutcome, MotionWorker +from .types import BeamlineId, ConfigDict, DataDict, SurfaceDict + +H = 6.62606957e-34 +E = 1.602176634e-19 +C = 299792458 +RE = 2.8179e-15 + +OFFSET_FILE_X01DA = Path(__file__).with_name("x01da_offsets.yaml") +OFFSET_FILE_X10DA = Path(__file__).with_name("x10da_offsets.yaml") + +logger = bec_logger.logger + + +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 + + +bl = get_parameters() + + +class _ExclusiveGroupManager: + def __init__(self): + self._cond = threading.Condition() + self._active_subgroup = None + self._active_count = 0 + + def acquire(self, subgroup_id, cancelled=None, on_wait=None) -> bool: + """Block until the subgroup may run. Returns False if cancelled while waiting.""" + with self._cond: + notified = False + while self._active_subgroup is not None and self._active_subgroup != subgroup_id: + if cancelled and cancelled(): + return False + if on_wait and not notified: + on_wait() + notified = True + self._cond.wait(0.1) # timeout so cancellation is noticed + if cancelled and cancelled(): + return False + self._active_subgroup = subgroup_id + self._active_count += 1 + return True + + def release(self): + with self._cond: + self._active_count -= 1 + if self._active_count == 0: + self._active_subgroup = None + self._cond.notify_all() + + +# Each entry is one exclusive group, made of subgroups. Motors in the same +# subgroup may move concurrently; motors in different subgroups of the +# same group may not. Motors not listed here move completely freely. +# Example from below: Each listed cm_* motor needs to move alone, but +# sldi_gapx and sldi_gapy can move together. sldi_gapx can move together +# with ot_try +EXCLUSIVE_GROUPS: list[list[list[str]]] = [ + [["sldi_gapx", "sldi_gapy"], ["sldi_centerx", "sldi_centery"]], + [["cm_trx"], ["cm_roty"], ["cm_try"], ["cm_rotx"], ["cm_rotz"]], + [["fm_trx"], ["fm_roty"], ["fm_try"], ["fm_rotx"], ["fm_rotz"]], + [["sl1_gapx", "sl1_gapy"], ["sl1_centerx", "sl1_centery"]], + [["sl2_gapx", "sl2_gapy"], ["sl2_centerx", "sl2_centery"]], + [["ot_try"], ["ot_rotx"]], +] + + +class DigitalTwinCoreError(Exception): + """DigitalTwinCore specific error""" + + +class DigitalTwinCore: + + def __init__(self, load_offsets: bool = True): + logger.info("This is the digital twin from the ipython client!") + dev = builtins.__dict__.get("dev") + bec = builtins.__dict__.get("bec") + if dev is None: + raise DigitalTwinCoreError("Did not get dev") + if bec is None: + raise DigitalTwinCoreError("Did not get bec") + self.dev = dev + self.bec = bec + + self.beamline = get_beamline_id() + self.offset_file = Path() + match self.beamline: + case BeamlineId.X01DA: + self.offset_file = OFFSET_FILE_X01DA + case "x10da": + self.offset_file = OFFSET_FILE_X10DA + self.offsets = {} + if load_offsets: + self.load_offsets() + + self._group_managers = {gi: _ExclusiveGroupManager() for gi in range(len(EXCLUSIVE_GROUPS))} + + def _exclusive_group_key(self, motor: str): + """Return (group_index, subgroup_index) for `motor`, or (None, None) + if it isn't part of any exclusive group and can move freely.""" + for gi, group in enumerate(EXCLUSIVE_GROUPS): + for si, subgroup in enumerate(group): + if motor in subgroup: + return gi, si + return None, None + + def run_exclusive( + self, worker, abort=None, cancel=None, on_waiting=None, on_started=None + ) -> str: + """ + Run `worker` once its exclusive group allows it. Blocks the calling thread. + + abort: shared by a batch of motors; set on the first failure so that + motors of the batch that have not started yet are not started. + cancel: per-motor event (user pressed Stop while waiting). + """ + events = [e for e in (abort, cancel) if e is not None] + cancelled = lambda: any(e.is_set() for e in events) + + gi, si = self._exclusive_group_key( + worker.motor + ) # before run(): aliases change worker.motor + manager = self._group_managers[gi] if gi is not None else None + + if manager is not None and not manager.acquire(si, cancelled, on_waiting): + return MotionOutcome.CANCELLED + try: + if cancelled(): + return MotionOutcome.CANCELLED + if on_started: + on_started() + try: + worker.run() + except Exception as e: # raised outside motion()'s own try/except + logger.error(f"Error preparing movement of {worker.motor}: {e}") + worker.last_exception = e + if worker.last_exception is not None: + if abort is not None: + abort.set() + return MotionOutcome.FAILED + return MotionOutcome.DONE + finally: + if manager is not None: + manager.release() + + def move_with_config(self, config, motors: list | None = None): + """ + Move all motors according to the "config" to their target positions, all starting at + once. Motors are free to move concurrently unless they belong to the + same exclusive group (see `EXCLUSIVE_GROUPS`) but different subgroups, + in which case one subgroup must fully finish before another starts. + If "motors" is provided, only these motors will be moved + + Returns: + dict: {"success": True, "moved": [...]} if every motor completed + without error, else {"success": False, "moved": [...], + "failures": {motor: error}} or "aborted": {motor} + """ + positions = self.calc_positions(config) + positions = self.apply_offsets(positions, nested_config=True) + + if motors is not None: + positions = {m: p for m, p in positions.items() if m in motors} + + abort = threading.Event() + moved, aborted = [], [] + failures: dict[str, Exception | str] = {} + results_lock = threading.Lock() + + def run_motor(motor: str, target: float): + worker = MotionWorker(self.beamline, self.dev, motor, target) + outcome = self.run_exclusive(worker, abort=abort) + with results_lock: + if outcome == MotionOutcome.DONE: + moved.append(motor) + elif outcome == MotionOutcome.FAILED: + failures[motor] = worker.last_exception + else: + aborted.append(motor) + + threads = [ + threading.Thread(target=run_motor, args=(m, p["value"]), daemon=True) + for m, p in positions.items() + ] + for t in threads: + t.start() + for t in threads: + t.join() + + result = {"success": not failures, "moved": moved} + if failures: + result["failures"] = failures + result["aborted"] = aborted # never started because of the failure + return result + + def load_offsets(self): + if self.offsets == {}: + logger.info("Load beamline offsets") + if not self.offset_file.exists(): + raise FileNotFoundError(f"Offset file not found: {self.offset_file}") + + with self.offset_file.open("r", encoding="utf-8") as f: + data = yaml.safe_load(f) + + if not isinstance(data, dict): + raise ValueError(f"Expected a YAML mapping, got {type(data).__name__}") + + self.offsets = data + else: + logger.info("Unload beamline offsets") + self.offsets = {} + + def apply_offsets(self, config, nested_config=False): + for axis, axis_data in config.items(): + if axis in self.offsets: + axis_offsets = self.offsets[axis] + if "modifier" in axis_offsets and "offset" in axis_offsets: + for idx, rng in enumerate(axis_offsets["modifier"]["range"]): + modifier_axis = axis_offsets["modifier"]["axis"] + modifier_value = ( + config[modifier_axis]["value"] + if nested_config + else config[modifier_axis] + ) + if rng[0] < modifier_value < rng[1]: + if nested_config: + axis_data["value"] += axis_offsets["offset"][idx] + else: + config[axis] += axis_offsets["offset"][idx] + break + elif "offset" in axis_offsets: + if nested_config: + axis_data["value"] += axis_offsets["offset"] + else: + config[axis] += axis_offsets["offset"] + return config + + def remove_offsets(self, config): + for axis, _ in config.items(): + if axis in self.offsets: + axis_offsets = self.offsets[axis] + if "modifier" in axis_offsets and "offset" in axis_offsets: + for idx, rng in enumerate(axis_offsets["modifier"]["range"]): + if rng[0] < config[axis_offsets["modifier"]["axis"]] < rng[1]: + config[axis] -= axis_offsets["offset"][idx] + break + elif "offset" in axis_offsets: + config[axis] -= axis_offsets["offset"] + return config + + def calc_positions(self, 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": + pos["mo1_trx"] = {"value": self.mo1_xtal_to_trx(cfg["mo1_xtal"])} + 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"])) + + # roty, Azimuthal angle + pos["mo1_roty"] = {"value": cfg["mo1_roty"]} + + ## 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 + radius = self.calc_fm_bnd_radius( + cfg["ot_es1_trz"] + cfg["es1man_trz"], cfg["fm_qy"], cfg["fm_rotx"] + ) + 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 self.beamline == BeamlineId.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["ot_es1_trz"] + pos["ot_es1_trz"] = {"value": ot_es1_trz} + + # Sample manipulator TRZ + es1man_trz = cfg["es1man_trz"] + if es1man_trz is None: + raise ValueError("es1man_trz is None") + pos["es1man_trz"] = {"value": es1man_trz} + + # TRZ ES2 + smpl_to_xrd = cfg["smpl_to_xrd"] + if smpl_to_xrd is None: + raise ValueError("smpl_to_xrd is None") + ot_es2_trz = smpl_to_xrd + ot_es1_trz + es1man_trz - 32 + pos["ot_es2_trz"] = {"value": ot_es2_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 + + @staticmethod + 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 + + @staticmethod + 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 + + @staticmethod + 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 + + @staticmethod + 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 + + @staticmethod + 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 + + @staticmethod + def calc_fm_bnd_radius(smpl: float, fm_qy: None | float, fm_rotx: float): + """ + Calculate the fm bender radius + + Args: + smpl(float): Sample position in mm + fm_qy(None|float): FM qy value + fm_rotx(float: FM rotx position in rad + + Returns: + float: bending radius in m + """ + # p = bl.fm.center[1] + q = smpl - bl.fm.center[1] + # f = (p * q) / (p + q) # focal length + + # Bender radius + if fm_qy is None: + radius = 2 * q / np.sin(fm_rotx) # ideal bending radius for focused beam + else: + radius = 2 * fm_qy / np.sin(fm_rotx) # ideal bending radius for unfocused beam + return radius + + @staticmethod + 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 + + @staticmethod + def mo1_xtal_to_trx(xtal: str) -> float: + """ + Returns the trx position for a given xtal. + + Args: + xtal(str): Xtal, e.g. "Si(111)" + + Returns: + float: Position of trx + """ + xtal = 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!") + return bl.mo1.xtalOffsetX[index] + + @staticmethod + 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 + + @staticmethod + 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 + + @staticmethod + 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 + + @staticmethod + 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 + + @staticmethod + 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 + + @staticmethod + 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 + + @staticmethod + 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 + + @staticmethod + 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 + + @staticmethod + 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 + + @staticmethod + 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 + + @staticmethod + 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") + + @staticmethod + def smpl_pos_to_table(smpl_pos: float) -> str: + """Return the table name based on the sample position.""" + if np.isclose(smpl_pos, bl.es1.center[1]): + return bl.es1.name + if np.isclose(smpl_pos, bl.es2.center[1]): + return bl.es2.name + raise ValueError(f"Sample position {smpl_pos} not found in beamline parameter file") + + @staticmethod + 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) + smpl = cfg["ot_es1_trz"] + cfg["es1man_trz"] + 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(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"])) * (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(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"])) * (smpl - bl.fm.center[1]) + ) + + return beam + + @staticmethod + 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 diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py new file mode 100644 index 0000000..192eb20 --- /dev/null +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/motion_worker.py @@ -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() diff --git a/debye_bec/bec_widgets/widgets/digital_twin/types.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/types.py similarity index 85% rename from debye_bec/bec_widgets/widgets/digital_twin/types.py rename to debye_bec/bec_ipython_client/plugins/digital_twin_core/types.py index d5c0393..913c951 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/types.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/types.py @@ -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): diff --git a/debye_bec/bec_widgets/widgets/digital_twin/x01da_offsets.yaml b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_offsets.yaml similarity index 86% rename from debye_bec/bec_widgets/widgets/digital_twin/x01da_offsets.yaml rename to debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_offsets.yaml index f475d96..2fe5196 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/x01da_offsets.yaml +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_offsets.yaml @@ -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 diff --git a/debye_bec/bec_widgets/widgets/digital_twin/x01da_parameters.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_parameters.py similarity index 99% rename from debye_bec/bec_widgets/widgets/digital_twin/x01da_parameters.py rename to debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_parameters.py index 214cb7d..66fa86c 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/x01da_parameters.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_parameters.py @@ -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 diff --git a/debye_bec/bec_widgets/widgets/digital_twin/x10da_offsets.yaml b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_offsets.yaml similarity index 85% rename from debye_bec/bec_widgets/widgets/digital_twin/x10da_offsets.yaml rename to debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_offsets.yaml index f0fe9a8..947e9b5 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/x10da_offsets.yaml +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_offsets.yaml @@ -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 diff --git a/debye_bec/bec_widgets/widgets/digital_twin/x10da_parameters.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_parameters.py similarity index 96% rename from debye_bec/bec_widgets/widgets/digital_twin/x10da_parameters.py rename to debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_parameters.py index b7b40a5..bcb5b46 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/x10da_parameters.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x10da_parameters.py @@ -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 diff --git a/debye_bec/bec_ipython_client/plugins/move_to_label.py b/debye_bec/bec_ipython_client/plugins/move_to_label.py deleted file mode 100644 index dd14970..0000000 --- a/debye_bec/bec_ipython_client/plugins/move_to_label.py +++ /dev/null @@ -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()})" - ) diff --git a/debye_bec/bec_ipython_client/startup/post_startup.py b/debye_bec/bec_ipython_client/startup/post_startup.py index 07d6da4..a5dc63c 100644 --- a/debye_bec/bec_ipython_client/startup/post_startup.py +++ b/debye_bec/bec_ipython_client/startup/post_startup.py @@ -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.") diff --git a/debye_bec/bec_widgets/widgets/auto_gain/__init__,py b/debye_bec/bec_widgets/widgets/auto_gain/__init__,py new file mode 100644 index 0000000..e69de29 diff --git a/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.py b/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.py new file mode 100644 index 0000000..194d02d --- /dev/null +++ b/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.py @@ -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_()) diff --git a/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.pyproject b/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.pyproject new file mode 100644 index 0000000..56f7f23 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/auto_gain/auto_gain.pyproject @@ -0,0 +1 @@ +{'files': ['auto_gain.py']} \ No newline at end of file diff --git a/debye_bec/bec_widgets/widgets/auto_gain/auto_gain_plugin.py b/debye_bec/bec_widgets/widgets/auto_gain/auto_gain_plugin.py new file mode 100644 index 0000000..0c2bb03 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/auto_gain/auto_gain_plugin.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 = """ + + + + +""" + + +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() diff --git a/debye_bec/bec_widgets/widgets/auto_gain/qt_widgets.py b/debye_bec/bec_widgets/widgets/auto_gain/qt_widgets.py new file mode 100644 index 0000000..54f0ed8 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/auto_gain/qt_widgets.py @@ -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}}}") diff --git a/debye_bec/bec_widgets/widgets/auto_gain/register_auto_gain.py b/debye_bec/bec_widgets/widgets/auto_gain/register_auto_gain.py new file mode 100644 index 0000000..2ee7a62 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/auto_gain/register_auto_gain.py @@ -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() diff --git a/debye_bec/bec_widgets/widgets/client.py b/debye_bec/bec_widgets/widgets/client.py index c974339..af1dff4 100644 --- a/debye_bec/bec_widgets/widgets/client.py +++ b/debye_bec/bec_widgets/widgets/client.py @@ -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. + """ diff --git a/debye_bec/bec_widgets/widgets/data_viewer/data_viewer.py b/debye_bec/bec_widgets/widgets/data_viewer/data_viewer.py index d8addb3..f4ab865 100644 --- a/debye_bec/bec_widgets/widgets/data_viewer/data_viewer.py +++ b/debye_bec/bec_widgets/widgets/data_viewer/data_viewer.py @@ -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""" diff --git a/debye_bec/bec_widgets/widgets/data_viewer/panels/data_view.py b/debye_bec/bec_widgets/widgets/data_viewer/panels/data_view.py index e9b368c..4dff090 100644 --- a/debye_bec/bec_widgets/widgets/data_viewer/panels/data_view.py +++ b/debye_bec/bec_widgets/widgets/data_viewer/panels/data_view.py @@ -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) ) diff --git a/debye_bec/bec_widgets/widgets/data_viewer/widgets/qt_widgets.py b/debye_bec/bec_widgets/widgets/data_viewer/widgets/qt_widgets.py index 7242c1e..4f9add1 100644 --- a/debye_bec/bec_widgets/widgets/data_viewer/widgets/qt_widgets.py +++ b/debye_bec/bec_widgets/widgets/data_viewer/widgets/qt_widgets.py @@ -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) diff --git a/debye_bec/bec_widgets/widgets/designer_plugins.py b/debye_bec/bec_widgets/widgets/designer_plugins.py index 77ddd10..e4e1893 100644 --- a/debye_bec/bec_widgets/widgets/designer_plugins.py +++ b/debye_bec/bec_widgets/widgets/designer_plugins.py @@ -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", } diff --git a/debye_bec/bec_widgets/widgets/digital_twin/__init__.py b/debye_bec/bec_widgets/widgets/digital_twin/__init__.py index a42cb09..e69de29 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/__init__.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/__init__.py @@ -1,3 +0,0 @@ -from .beamline import get_parameters - -parameters = get_parameters() diff --git a/debye_bec/bec_widgets/widgets/digital_twin/azimuth_calculator.py b/debye_bec/bec_widgets/widgets/digital_twin/azimuth_calculator.py new file mode 100644 index 0000000..a32c3cd --- /dev/null +++ b/debye_bec/bec_widgets/widgets/digital_twin/azimuth_calculator.py @@ -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}" + ) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_positions.py b/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_positions.py deleted file mode 100644 index 3047bdf..0000000 --- a/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_positions.py +++ /dev/null @@ -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 diff --git a/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_sideview.py b/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_sideview.py deleted file mode 100644 index 135c76d..0000000 --- a/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_sideview.py +++ /dev/null @@ -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 diff --git a/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_surfaces.py b/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_surfaces.py deleted file mode 100644 index 2ef4a59..0000000 --- a/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_surfaces.py +++ /dev/null @@ -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 diff --git a/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_varia.py b/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_varia.py deleted file mode 100644 index 5c80afb..0000000 --- a/debye_bec/bec_widgets/widgets/digital_twin/calculations/calc_varia.py +++ /dev/null @@ -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") diff --git a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py index 15304bd..715e670 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py @@ -2,10 +2,14 @@ Digital Twin: Custom BEC widget to support the beamline alignment. """ +import json import sys +import threading +import time from pathlib import Path from typing import Literal, cast +import h5py import numpy as np import yaml from bec_lib import bec_logger @@ -23,9 +27,11 @@ from qtpy.QtWidgets import ( QComboBox, QDialog, QDialogButtonBox, + QFileDialog, QFrame, QHBoxLayout, QLabel, + QMessageBox, QPlainTextEdit, QPushButton, QScrollArea, @@ -35,38 +41,17 @@ from qtpy.QtWidgets import ( QWidget, ) +from ....bec_ipython_client.plugins.digital_twin_core.digital_twin_core import DigitalTwinCore +from ....bec_ipython_client.plugins.digital_twin_core.types import BeamlineId, ConfigDict from ..edge_selector import EdgeSelector -from .beamline import get_beamline_id -from .calculations.calc_positions import calc_positions -from .calculations.calc_sideview import calc_sideview -from .calculations.calc_surfaces import calc_surfaces -from .calculations.calc_varia import ( - calc_beamsize, - cm_critical_angle, - cm_reflectivity, - cm_stripe_to_trx, - cm_trx_to_stripe, - fm_ideal_pitch, - fm_reflectivity, - fm_stripe_to_trx, - fm_trx_to_stripe, - mo1_bragg_angle, - mo1_energy_resolution, - sldi_gap_to_acc, - table_to_smpl_pos, -) +from .glitches_preview import GlitchesPreview from .panels.input_panel import InputPanel from .panels.mover_panel import MoverPanel from .panels.plots import SideviewPlot, SurfacePlots from .panels.settings_panel import SettingsPanel -from .types import ConfigDict -from .widgets.qt_widgets import ComboBox, InputNumberField logger = bec_logger.logger -OFFSET_FILE_X01DA = Path(__file__).with_name("x01da_offsets.yaml") -OFFSET_FILE_X10DA = Path(__file__).with_name("x10da_offsets.yaml") - X01DA_E_MIN = 4500 X01DA_E_MAX = 60000 X10DA_E_MIN = 4500 @@ -85,17 +70,12 @@ class DigitalTwin(BECWidget, QWidget): super().__init__(parent=parent, *arg, **kwargs) self.get_bec_shortcuts() - self.beamline = get_beamline_id() + self.core = DigitalTwinCore(load_offsets=False) # Offsets are loaded through GUI later + + self.beamline = self.core.beamline # Debugging, override beamline! # self.beamline = BeamlineId.X10DA - self.offset_file = Path() - match self.beamline: - case "x01da": - self.offset_file = OFFSET_FILE_X01DA - case "x10da": - self.offset_file = OFFSET_FILE_X10DA - # Check if devices are all in config self.check_bec_config() self.bec_dispatcher.connect_slot( @@ -123,13 +103,13 @@ class DigitalTwin(BECWidget, QWidget): self.plot_layout = QVBoxLayout(self.plot_widget) self.plot_layout.setContentsMargins(4, 4, 4, 4) self.plot_layout.setSpacing(6) - self.sideview_plot = SideviewPlot() - self.surface_plots = SurfacePlots(self.beamline) + self.sideview_plot = SideviewPlot(self.core) + self.surface_plots = SurfacePlots(self.beamline, self.core) self.plot_layout.addWidget(self.sideview_plot, stretch=1) self.plot_layout.addWidget(self.surface_plots, stretch=1) self.plot_widget.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) - self.mover = MoverPanel(self.beamline, self.dev) + self.mover = MoverPanel(self.core, self.beamline, self.dev) self.input_scroll = self._scroll_area(self.input_widget, min_width=320, max_width=360) self.mover_scroll = self._scroll_area(self.mover, min_width=380, max_width=460) @@ -154,25 +134,37 @@ class DigitalTwin(BECWidget, QWidget): self.input.cm_pitch.value_changed_connect(self.calc_assistant) self.input.mo1_mode.activated_connect(self.calc_assistant) self.input.mo1_xtal.activated_connect(self.calc_assistant) + if self.beamline == BeamlineId.X01DA: + self.input.mo1_azm_angle.value_changed_connect(self.calc_assistant) + self.input.mo1_glitch_preview.clicked_connect(self.open_glitches_preview) self.input.fm_stripe.activated_connect(self.calc_assistant) self.input.fm_focus.activated_connect(self.calc_assistant) self.input.fm_rotx.value_changed_connect(self.calc_assistant) self.input.fm_focx.value_changed_connect(self.calc_assistant) self.input.fm_focy.value_changed_connect(self.calc_assistant) - match self.input.smpl: - case InputNumberField(): - self.input.smpl.value_changed_connect(self.calc_assistant) - case ComboBox(): - self.input.smpl.activated_connect(self.calc_assistant) + if self.beamline == BeamlineId.X01DA: + self.input.ot_es1_trz.value_changed_connect(self.calc_assistant) + self.input.smpl_to_xrd.value_changed_connect(self.calc_assistant) + else: + self.input.table.activated_connect(self.calc_assistant) + self.input.es1man_trz.value_changed_connect(self.calc_assistant) self.input.adapt_reality.clicked_connect(self.adapt_reality) self.settings.load_offsets.clicked_connect(self.load_offsets) self.settings.show_offsets.clicked_connect(self.show_offsets) + self.settings.save_config.clicked_connect(self.save_config) + self.settings.load_from_config.clicked_connect(self.load_from_config) + self.settings.load_from_scan.clicked_connect(self.load_from_scan) + + self.mover.multi_move.clicked_connect(self._multi_move) self.edge_selector_energy = 0.0 + self.edge_selector_element = "" + self.edge_selector_edge = "" self.bragg_angle = 0.0 + self.old_xtal = self.input.mo1_xtal.currentText() + self.azm_ranges = {} self.qy = 0.0 - self.offsets = {} # Initialize all values self.load_offsets(recalculate=False) @@ -243,16 +235,19 @@ class DigitalTwin(BECWidget, QWidget): "fm_rotz", "bm2_try", "es0wi_try", + "es1man_trz", ] - if self.beamline == "x01da": # X01DA specific devices + if self.beamline == BeamlineId.X01DA: # X01DA specific devices devices.extend( [ "cm_bnd_radius", + "mo1_roty", "fm_bnd_radius", "sl2_centery", "sl2_gapy", "ot_try", "ot_es1_trz", + "ot_es2_trz", ] ) if self.beamline == "x10da": # X10DA specific devices @@ -329,10 +324,11 @@ class DigitalTwin(BECWidget, QWidget): self.calc_cm_crit_pitch() self.calc_cm_reflectivity() self.update_fm_mode() + self.calc_fm_ideal_pitch() self.calc_fm_reflectivity() self.calc_cm_fm_harm_suppr() - self.calc_fm_ideal_pitch() self.calc_mo1_energy_resolution() + self.update_mo1_azm_angle() case "energy": self.update_edge_selected() self.calc_mo1_bragg_angle() @@ -357,6 +353,9 @@ class DigitalTwin(BECWidget, QWidget): case "mo1_xtal": self.calc_mo1_bragg_angle() self.calc_mo1_energy_resolution() + self.update_mo1_azm_angle() + case "mo1_azm_angle": + self.update_mo1_azm_angle() case "fm_focus": self.update_fm_mode() self.calc_fm_ideal_pitch() @@ -368,10 +367,14 @@ class DigitalTwin(BECWidget, QWidget): self.calc_fm_reflectivity() self.calc_cm_fm_harm_suppr() case "fm_stripe": + self.calc_fm_ideal_pitch() self.calc_fm_reflectivity() self.calc_cm_fm_harm_suppr() + case "ot_es1_trz": self.calc_fm_ideal_pitch() - case "smpl": + case "es1man_trz": + self.calc_fm_ideal_pitch() + case "smpl_to_xrd": self.calc_fm_ideal_pitch() self.calc_positions() self.calc_assistant_sideview() @@ -395,55 +398,54 @@ class DigitalTwin(BECWidget, QWidget): elif fm_focus == "Focused": fm_rotx = self.input.fm_rotx_ideal.value() fm_qy = None - else: # Focused + else: # Defocused fm_rotx = self.input.fm_rotx_ideal.value() fm_qy = self.qy cm_stripe = self.input.cm_stripe.currentText() - cm_trx = cm_stripe_to_trx(cm_stripe) + cm_trx = self.core.cm_stripe_to_trx(cm_stripe) fm_stripe = self.input.fm_stripe.currentText() - fm_trx = fm_stripe_to_trx(fm_stripe) + fm_trx = self.core.fm_stripe_to_trx(fm_stripe) assert cm_trx is not None, f"No cm_trx found for given stripe {cm_stripe}!" assert fm_trx is not None, f"No fm_trx found for given stripe {fm_stripe}!" - match self.input.smpl: - case InputNumberField(): - smpl = self.input.smpl.value() - case ComboBox(): - table = self.input.smpl.currentText() - smpl = table_to_smpl_pos(table) + if self.beamline == BeamlineId.X01DA: + ot_es1_trz = self.input.ot_es1_trz.value() + smpl_to_xrd = self.input.smpl_to_xrd.value() + else: + table = self.input.table.currentText() + ot_es1_trz = self.core.table_to_smpl_pos(table) + smpl_to_xrd = None + + es1man_trz = self.input.es1man_trz.value() config: ConfigDict = { "energy": self.input.energy.value(), "h_acc": self.input.sldi_hacc.value(), "v_acc": self.input.sldi_vacc.value(), - "cm_pitch": -self.input.cm_pitch.value(), + "cm_pitch": -np.float64(self.input.cm_pitch.value()), "cm_stripe": cm_stripe, "cm_trx": cm_trx, "mo1_mode": self.input.mo1_mode.currentText(), "mo1_xtal": self.input.mo1_xtal.currentText(), "mo1_bragg": self.bragg_angle, + "mo1_roty": self.input.mo1_azm_angle.value(), "fm_rotx": -fm_rotx, "fm_stripe": fm_stripe, "fm_trx": fm_trx, "fm_qy": fm_qy, "fm_gain_height": 1, - "smpl": smpl, + "ot_es1_trz": ot_es1_trz, + "es1man_trz": es1man_trz, + "smpl_to_xrd": smpl_to_xrd, } + config["mo1_trx"] = self.core.mo1_xtal_to_trx(self.input.mo1_xtal.currentText()) + # Apply offsets if apply_offset: - for axis, _ in config.items(): - if axis in self.offsets: - axis_offsets = self.offsets[axis] - if "modifier" in axis_offsets and "offset" in axis_offsets: - for idx, rng in enumerate(axis_offsets["modifier"]["range"]): - if rng[0] < config[axis_offsets["modifier"]["axis"]] < rng[1]: - config[axis] += axis_offsets["offset"][idx] - break - elif "offset" in axis_offsets: - config[axis] += axis_offsets["offset"] + config = self.core.apply_offsets(config, nested_config=False) # Convert to SI units! config["h_acc"] *= 1e-3 @@ -454,6 +456,74 @@ class DigitalTwin(BECWidget, QWidget): # logger.info(f'Config created: {config}') return config + def set_assistant_config(self, config: ConfigDict) -> None: + """ + Applies an assistant config to the input Qt widgets. + Config must be without offsets! + + Args: + config: Assistant configuration, as returned by + ``get_assistant_config``. The acceleration and angular + values are expected to be in SI units. + """ + + config = ConfigDict(config) # Important: Copy dict to not change the original + + # Convert to mrad units! + config["h_acc"] *= 1e3 + config["v_acc"] *= 1e3 + config["cm_pitch"] *= -1e3 + config["fm_rotx"] *= 1e3 + + self.input.energy.set_number(config["energy"]) + self.input.sldi_hacc.set_number(config["h_acc"]) + self.input.sldi_vacc.set_number(config["v_acc"]) + self.input.cm_pitch.set_number(config["cm_pitch"]) + self.input.cm_stripe.set_current_text(config["cm_stripe"]) + self.input.fm_stripe.set_current_text(config["fm_stripe"]) + self.input.mo1_mode.set_current_text(config["mo1_mode"]) + self.input.mo1_xtal.set_current_text(config["mo1_xtal"]) + if self.beamline == BeamlineId.X01DA: + self.input.mo1_azm_angle.set_number(config["mo1_roty"]) + + self.bragg_angle = config["mo1_bragg"] + + fm_rotx = -config["fm_rotx"] + + self.qy = config["fm_qy"] + + smpl = config["ot_es1_trz"] + config["es1man_trz"] + radius = self.core.calc_fm_bnd_radius(smpl, config["fm_qy"], config["fm_rotx"] * 1e-3) + fm_focx, fm_focy = self.core.calc_beamsize( + config["h_acc"] * 1e-3, + config["v_acc"] * 1e-3, + config["fm_stripe"], + -fm_rotx * 1e-3, + radius, + smpl, + ) + if config["fm_qy"] is not None: + self.input.fm_focus.set_current_text("Defocused") + self.input.fm_focx.set_number(fm_focx) + self.input.fm_focy.set_number(fm_focy) + elif fm_focx < 0.08 and fm_focy < 0.08: + self.input.fm_focus.set_current_text("Focused") + else: + self.input.fm_focus.set_current_text("Manual") + self.input.fm_rotx_ideal.setValue(fm_rotx * 1e-3) + + if self.beamline == BeamlineId.X01DA: + self.input.ot_es1_trz.set_number(config["ot_es1_trz"]) + if config["smpl_to_xrd"] is not None: + self.input.smpl_to_xrd.set_number(config["smpl_to_xrd"]) + else: + table = self.core.smpl_pos_to_table(config["ot_es1_trz"]) + self.input.table.set_current_text(table) + + self.input.es1man_trz.set_number(config["es1man_trz"]) + + self.calc_assistant(identifier="init") + def get_reality_config(self) -> ConfigDict: """ Assembles the digital twin config based on the real axis positions. @@ -466,24 +536,29 @@ class DigitalTwin(BECWidget, QWidget): mo1_mode = "Monochromatic" else: mo1_mode = "Pinkbeam" - mo1_bragg = self.dev.mo1_bragg.read(cached=True) + mo1_bragg = self.dev.mo1_bragg.read(cached=False) sldi_gapx = self.dev.sldi_gapx.read(cached=True)["sldi_gapx"]["value"] sldi_gapy = self.dev.sldi_gapy.read(cached=True)["sldi_gapy"]["value"] - h_acc, v_acc = sldi_gap_to_acc(sldi_gapx, sldi_gapy) + h_acc, v_acc = self.core.sldi_gap_to_acc(sldi_gapx, sldi_gapy) cm_trx = self.dev.cm_trx.read(cached=True)["cm_trx"]["value"] - cm_stripe = cm_trx_to_stripe(-cm_trx) + cm_stripe = self.core.cm_trx_to_stripe(-cm_trx) cm_pitch = self.dev.cm_rotx.read(cached=True)["cm_rotx"]["value"] fm_trx = self.dev.fm_trx.read(cached=True)["fm_trx"]["value"] - fm_stripe = fm_trx_to_stripe(-fm_trx) + fm_stripe = self.core.fm_trx_to_stripe(-fm_trx) fm_rotx = self.dev.fm_rotx.read(cached=True)["fm_rotx"]["value"] fm_rotx_real = 2 * cm_pitch - fm_rotx + es1man_trz = self.dev.es1man_trz.read(cached=True)["es1man_trz"]["value"] - match self.input.smpl: - case InputNumberField(): - smpl = self.dev.ot_es1_trz.read(cached=True)["ot_es1_trz"]["value"] - case ComboBox(): - table = self.input.smpl.currentText() - smpl = table_to_smpl_pos(table) + if self.beamline == BeamlineId.X01DA: + mo1_roty = self.dev.mo1_roty.read(cached=True)["mo1_roty"]["value"] + ot_es1_trz = self.dev.ot_es1_trz.read(cached=True)["ot_es1_trz"]["value"] + ot_es2_trz = self.dev.ot_es2_trz.read(cached=True)["ot_es2_trz"]["value"] + smpl_to_xrd = ot_es2_trz - ot_es1_trz - es1man_trz + 32 + else: + mo1_roty = 0 # No axis for roty available at SuperXAS + table = self.input.table.currentText() + ot_es1_trz = self.core.table_to_smpl_pos(table) + smpl_to_xrd = None raw = { # Config in SI units! "energy": mo1_bragg["mo1_bragg"]["value"], @@ -495,12 +570,15 @@ class DigitalTwin(BECWidget, QWidget): "mo1_mode": mo1_mode, "mo1_xtal": mo1_bragg["mo1_bragg_crystal_current_xtal_string"]["value"], "mo1_bragg": mo1_bragg["mo1_bragg_angle"]["value"] / 180 * np.pi, + "mo1_roty": mo1_roty, "fm_rotx": -fm_rotx_real * 1e-3, "fm_stripe": fm_stripe, "fm_trx": fm_trx, "fm_qy": None, "fm_gain_height": 1, - "smpl": smpl, + "ot_es1_trz": ot_es1_trz, + "es1man_trz": es1man_trz, + "smpl_to_xrd": smpl_to_xrd, } config = cast(ConfigDict, raw) # logger.info(f'Config created: {config}') @@ -529,6 +607,10 @@ class DigitalTwin(BECWidget, QWidget): self.mover.mo1_bragg_angle.set_feedback(mo1_bragg["mo1_bragg_angle"]["value"]) self.mover.mo1_trx.set_feedback(mo1_trx) self.mover.mo1_try.set_feedback(self.dev.mo1_try.read(cached=True)["mo1_try"]["value"]) + if self.beamline == BeamlineId.X01DA: + self.mover.mo1_roty.set_feedback( + self.dev.mo1_roty.read(cached=True)["mo1_roty"]["value"] + ) self.mover.sl1_centery.set_feedback( self.dev.sl1_centery.read(cached=True)["sl1_centery"]["value"] ) @@ -542,7 +624,7 @@ class DigitalTwin(BECWidget, QWidget): self.mover.fm_rotx.set_feedback(fm_rotx) self.mover.fm_roty.set_feedback(self.dev.fm_roty.read(cached=True)["fm_roty"]["value"]) self.mover.fm_rotz.set_feedback(self.dev.fm_rotz.read(cached=True)["fm_rotz"]["value"]) - if self.beamline == "x01da": + if self.beamline == BeamlineId.X01DA: self.mover.sl2_centery.set_feedback( self.dev.sl2_centery.read(cached=True)["sl2_centery"]["value"] ) @@ -550,10 +632,12 @@ class DigitalTwin(BECWidget, QWidget): self.dev.sl2_gapy.read(cached=True)["sl2_gapy"]["value"] ) self.mover.bm2_try.set_feedback(self.dev.bm2_try.read(cached=True)["bm2_try"]["value"]) - if self.beamline == "x01da": + if self.beamline == BeamlineId.X01DA: self.mover.ot_try.set_feedback(self.dev.ot_try.read(cached=True)["ot_try"]["value"]) self.mover.ot_rotx.set_feedback(self.dev.ot_rotx.read(cached=True)["ot_rotx"]["value"]) - self.mover.ot_es1_trz.set_feedback(smpl) + self.mover.ot_es1_trz.set_feedback(ot_es1_trz) + self.mover.ot_es2_trz.set_feedback(ot_es2_trz) + self.mover.es1man_trz.set_feedback(es1man_trz) self.mover.es0wi_try.set_feedback( self.dev.es0wi_try.read(cached=True)["es0wi_try"]["value"] ) @@ -585,53 +669,76 @@ class DigitalTwin(BECWidget, QWidget): pos["cm_trx"] = self.dev.cm_trx.read(cached=True)["cm_trx"]["value"] pos["cm_rotx"] = self.dev.cm_rotx.read(cached=True)["cm_rotx"]["value"] pos["mo1_trx"] = self.dev.mo1_trx.read(cached=True)["mo1_trx"]["value"] + if self.beamline == BeamlineId.X01DA: + pos["mo1_roty"] = self.dev.mo1_roty.read(cached=True)["mo1_roty"]["value"] + else: + pos["mo1_roty"] = 0 pos["fm_trx"] = self.dev.fm_trx.read(cached=True)["fm_trx"]["value"] pos["fm_rotx"] = self.dev.fm_rotx.read(cached=True)["fm_rotx"]["value"] pos["fm_bnd_radius"] = self.dev.fm_bnd_radius.read(cached=True)["fm_bnd_radius"]["value"] - if self.beamline == "x01da": + pos["es1man_trz"] = self.dev.es1man_trz.read(cached=True)["es1man_trz"]["value"] + if self.beamline == BeamlineId.X01DA: pos["ot_es1_trz"] = self.dev.ot_es1_trz.read(cached=True)["ot_es1_trz"]["value"] + pos["ot_es2_trz"] = self.dev.ot_es2_trz.read(cached=True)["ot_es2_trz"]["value"] + pos["smpl_to_xrd"] = pos["ot_es2_trz"] - pos["ot_es1_trz"] - pos["es1man_trz"] + 32 + else: + table = self.ask_table_selection(self.input.table.currentText()) + pos["ot_es1_trz"] = self.core.table_to_smpl_pos(table) # Removing offsets - for axis, _ in pos.items(): - if axis in self.offsets: - axis_offsets = self.offsets[axis] - if "modifier" in axis_offsets and "offset" in axis_offsets: - for idx, rng in enumerate(axis_offsets["modifier"]["range"]): - if rng[0] < pos[axis_offsets["modifier"]["axis"]] < rng[1]: - pos[axis] -= axis_offsets["offset"][idx] - break - elif "offset" in axis_offsets: - pos[axis] -= axis_offsets["offset"] + pos = self.core.remove_offsets(pos) - self.input.energy.set_number(self.dev.mo1_bragg.read(cached=True)["mo1_bragg"]["value"]) - h_acc, v_acc = sldi_gap_to_acc(pos["sldi_gapx"], pos["sldi_gapy"]) + self.input.energy.set_number(self.dev.mo1_bragg.read(cached=False)["mo1_bragg"]["value"]) + h_acc, v_acc = self.core.sldi_gap_to_acc(pos["sldi_gapx"], pos["sldi_gapy"]) self.input.sldi_hacc.set_number(h_acc * 1e3) self.input.sldi_vacc.set_number(v_acc * 1e3) - self.input.cm_stripe.set_current_text(cm_trx_to_stripe(-pos["cm_trx"])) + self.input.cm_stripe.set_current_text(self.core.cm_trx_to_stripe(-pos["cm_trx"])) self.input.cm_pitch.set_number(pos["cm_rotx"]) if abs(pos["mo1_trx"]) > 5: mo1_mode = "Monochromatic" else: mo1_mode = "Pinkbeam" self.input.mo1_mode.set_current_text(mo1_mode) - self.input.mo1_xtal.set_current_text( - self.dev.mo1_bragg.read(cached=True)["mo1_bragg_crystal_current_xtal_string"]["value"] - ) - fm_stripe = fm_trx_to_stripe(-pos["fm_trx"]) + current_xtal = self.dev.mo1_bragg.read(cached=False)[ + "mo1_bragg_crystal_current_xtal_string" + ]["value"] + self.input.mo1_xtal.set_current_text(current_xtal) + if self.beamline == BeamlineId.X01DA: + mo1_roty_desc = self.dev.mo1_roty.describe()["mo1_roty"] + + for item in self.input.mo1_xtal.get_all_texts(): + mo1_trx = self.core.mo1_xtal_to_trx(item) + ll = self.core.remove_offsets( + {"mo1_roty": mo1_roty_desc["lower_ctrl_limit"], "mo1_trx": mo1_trx} + )["mo1_roty"] + hl = self.core.remove_offsets( + {"mo1_roty": mo1_roty_desc["upper_ctrl_limit"], "mo1_trx": mo1_trx} + )["mo1_roty"] + self.azm_ranges[item] = {} + self.azm_ranges[item]["ll"] = ll + self.azm_ranges[item]["hl"] = hl + + self.input.mo1_azm_angle.set_range( + self.azm_ranges[current_xtal]["ll"], self.azm_ranges[current_xtal]["hl"] + ) + self.input.mo1_azm_angle.set_number(pos["mo1_roty"]) + else: + self.input.mo1_azm_angle.setValue(pos["mo1_roty"]) + fm_stripe = self.core.fm_trx_to_stripe(-pos["fm_trx"]) self.input.fm_stripe.set_current_text(fm_stripe) fm_rotx_real = 2 * pos["cm_rotx"] - pos["fm_rotx"] self.input.fm_rotx.set_number(fm_rotx_real) - match self.input.smpl: - case InputNumberField(): - smpl = pos["ot_es1_trz"] - self.input.smpl.set_number(pos["ot_es1_trz"]) - case ComboBox(): - table = self.ask_table_selection(self.input.smpl.currentText()) - smpl = table_to_smpl_pos(table) - self.input.smpl.set_current_text(table) + if self.beamline == BeamlineId.X01DA: + self.input.ot_es1_trz.set_number(pos["ot_es1_trz"]) + self.input.smpl_to_xrd.set_number(pos["smpl_to_xrd"]) + else: + table = self.ask_table_selection(self.input.table.currentText()) + self.input.table.set_current_text(table) - fm_focx, fm_focy = calc_beamsize( + smpl = pos["ot_es1_trz"] + pos["es1man_trz"] + + fm_focx, fm_focy = self.core.calc_beamsize( h_acc, v_acc, fm_stripe, -fm_rotx_real * 1e-3, pos["fm_bnd_radius"] * 1e6, smpl ) if fm_focx < 0.08 and fm_focy < 0.08: @@ -690,35 +797,24 @@ class DigitalTwin(BECWidget, QWidget): Defaults to True """ - if self.offsets == {}: - # Load offsets - if not self.offset_file.exists(): - raise FileNotFoundError(f"Offset file not found: {self.offset_file}") - - with self.offset_file.open("r", encoding="utf-8") as f: - data = yaml.safe_load(f) - - if not isinstance(data, dict): - raise ValueError(f"Expected a YAML mapping, got {type(data).__name__}") - - self.offsets = data - + self.core.load_offsets() + if self.core.offsets != {}: + # Offsets were loaded if recalculate: self.calc_assistant(identifier="init") self.settings.load_offsets.setText("Unload") self.settings.offsets_status.setText("Loaded and applied") self.settings.offsets_status.setColor(get_accent_colors().success.name()) - self.settings.show_offsets.enable_button(True) + self.settings.show_offsets.setEnabled(True) else: - # Unload offsets - self.offsets = {} + # Offsets were unloaded self.calc_assistant(identifier="init") self.settings.load_offsets.setText("Load") self.settings.offsets_status.setText("No offsets") self.settings.offsets_status.setColor(get_accent_colors().default.name()) - self.settings.show_offsets.enable_button(False) + self.settings.show_offsets.setEnabled(False) @SafeSlot() def show_offsets(self, *_): @@ -736,7 +832,7 @@ class DigitalTwin(BECWidget, QWidget): intro_label.setWordWrap(True) layout.addWidget(intro_label) - file = QLabel(str(self.offset_file)) + file = QLabel(str(self.core.offset_file)) file.setWordWrap(True) font = QFont() font.setItalic(True) @@ -753,7 +849,9 @@ class DigitalTwin(BECWidget, QWidget): def represent_sequence(self, tag, sequence, *_): return super().represent_sequence(tag, sequence, flow_style=True) - text_edit.setPlainText(yaml.dump(self.offsets, Dumper=InlineListDumper, sort_keys=False)) + text_edit.setPlainText( + yaml.dump(self.core.offsets, Dumper=InlineListDumper, sort_keys=False) + ) layout.addWidget(text_edit) buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) @@ -762,6 +860,228 @@ class DigitalTwin(BECWidget, QWidget): dialog.exec() + @SafeSlot() + def save_config(self, *_): + config = self.get_assistant_config() + + hostname = self.client._hostname + start = hostname.find("x") + if start != -1: + beamline = hostname[start : start + 5] + active_account = self.client.active_account + folder = f"/sls/{beamline}/data/{active_account}/raw/widgets/digital_twin/configs" + else: + folder = "/sls" + + folder = Path(folder) + folder.mkdir(parents=True, exist_ok=True) + + t = time.localtime() + fmt_time = time.strftime("%Y%m%d_%H%M%S", t) + default_filename = "config_" + fmt_time + ".json" + + filename, _ = QFileDialog.getSaveFileName( + self, + "Save dictionary", + str(folder / default_filename), + "JSON files (*.json);;All files (*)", + ) + + if not filename: + return None + + path = Path(filename) + + if path.suffix.lower() != ".json": + path = path.with_suffix(".json") + + with path.open("w", encoding="utf-8") as f: + json.dump(config, f, indent=4, ensure_ascii=False) + + return path + + @SafeSlot() + def load_from_config(self, *_): + hostname = self.client._hostname + start = hostname.find("x") + if start != -1: + beamline = hostname[start : start + 5] + active_account = self.client.active_account + folder = f"/sls/{beamline}/data/{active_account}/raw/widgets/digital_twin/configs" + else: + folder = "/sls" + + path, _ = QFileDialog.getOpenFileName( + self, "Load config from file", folder, "JSON files (*.json);;All files (*)" + ) + if not path: + return + + try: + with open(path, encoding="utf-8") as f: + config = json.load(f) + except (OSError, json.JSONDecodeError) as exc: + QMessageBox.critical( + self, "Load failed", f"Could not load a config from {path}:\n{exc}" + ) + return + + self.set_assistant_config(config) + + @SafeSlot() + def load_from_scan(self, *_): + hostname = self.client._hostname + start = hostname.find("x") + if start != -1: + beamline = hostname[start : start + 5] + active_account = self.client.active_account + start_folder = f"/sls/{beamline}/data/{active_account}/raw" + else: + start_folder = "/sls" + + filename, _ = QFileDialog.getOpenFileName( + self, "Open scan", start_folder, "h5 files (*.h5);;All files (*)" + ) + + if not filename: + return None, None + + path = Path(filename) + + with h5py.File(path, "r") as f: + devices = cast(h5py.Group, f["entry/collection/devices"]) + + pos = {} + # fmt:off + pos["sldi_gapx"] = cast(h5py.Dataset, devices["sldi_gapx/sldi_gapx/value"])[()] + pos["sldi_gapy"] = cast(h5py.Dataset, devices["sldi_gapy/sldi_gapy/value"])[()] + pos["cm_trx"] = cast(h5py.Dataset, devices["cm_trx/cm_trx/value"])[()] + pos["cm_rotx"] = cast(h5py.Dataset, devices["cm_rotx/cm_rotx/value"])[()] + pos["mo1_trx"] = cast(h5py.Dataset, devices["mo1_trx/mo1_trx/value"])[()] + if self.beamline == BeamlineId.X01DA: + pos["mo1_roty"] = cast(h5py.Dataset, devices["mo1_roty/mo1_roty/value"])[()] + else: + pos["mo1_roty"] = 0 + pos["fm_trx"] = cast(h5py.Dataset, devices["fm_trx/fm_trx/value"])[()] + pos["fm_rotx"] = cast(h5py.Dataset, devices["fm_rotx/fm_rotx/value"])[()] + pos["fm_bnd_radius"] = cast(h5py.Dataset, devices["fm_bnd_radius/fm_bnd_radius/value"])[()] + pos["es1man_trz"] = cast(h5py.Dataset, devices["es1man_trz/es1man_trz/value"])[()] + if self.beamline == BeamlineId.X01DA: + pos["ot_es1_trz"] = cast(h5py.Dataset, devices["ot_es1_trz/ot_es1_trz/value"])[()] + pos["ot_es2_trz"] = cast(h5py.Dataset, devices["ot_es2_trz/ot_es2_trz/value"])[()] + pos["smpl_to_xrd"] = pos["ot_es2_trz"] - pos["ot_es1_trz"] - pos["es1man_trz"] + 32 + else: + table = self.ask_table_selection(self.input.table.currentText()) + pos["ot_es1_trz"] = self.core.table_to_smpl_pos(table) + # fmt:on + + # Removing offsets + pos = self.core.remove_offsets(pos) + + self.input.energy.set_number( + cast(h5py.Dataset, devices["mo1_bragg/mo1_bragg/value"])[()] + ) + h_acc, v_acc = self.core.sldi_gap_to_acc(pos["sldi_gapx"], pos["sldi_gapy"]) + self.input.sldi_hacc.set_number(h_acc * 1e3) + self.input.sldi_vacc.set_number(v_acc * 1e3) + self.input.cm_stripe.set_current_text(self.core.cm_trx_to_stripe(-pos["cm_trx"])) + self.input.cm_pitch.set_number(pos["cm_rotx"]) + if abs(pos["mo1_trx"]) > 5: + mo1_mode = "Monochromatic" + else: + mo1_mode = "Pinkbeam" + self.input.mo1_mode.set_current_text(mo1_mode) + self.input.mo1_xtal.set_current_text( + str( + cast( + h5py.Dataset, + devices["mo1_bragg/mo1_bragg_crystal_current_xtal_string/value"], + )[()] + ) + ) + + if self.beamline == BeamlineId.X01DA: + self.input.mo1_azm_angle.set_number(pos["mo1_roty"]) + else: + self.input.mo1_azm_angle.setValue(pos["mo1_roty"]) + fm_stripe = self.core.fm_trx_to_stripe(-pos["fm_trx"]) + self.input.fm_stripe.set_current_text(fm_stripe) + fm_rotx_real = 2 * pos["cm_rotx"] - pos["fm_rotx"] + self.input.fm_rotx.set_number(fm_rotx_real) + + if self.beamline == BeamlineId.X01DA: + self.input.ot_es1_trz.set_number(pos["ot_es1_trz"]) + self.input.smpl_to_xrd.set_number(pos["smpl_to_xrd"]) + else: + table = self.ask_table_selection(self.input.table.currentText()) + self.input.table.set_current_text(table) + + smpl = pos["ot_es1_trz"] + pos["es1man_trz"] + + fm_focx, fm_focy = self.core.calc_beamsize( + h_acc, v_acc, fm_stripe, -fm_rotx_real * 1e-3, pos["fm_bnd_radius"] * 1e6, smpl + ) + if fm_focx < 0.08 and fm_focy < 0.08: + self.input.fm_focus.set_current_text("Focused") + else: + self.input.fm_focus.set_current_text("Defocused") + self.input.fm_focx.set_number(fm_focx) + self.input.fm_focy.set_number(fm_focy) + + self.calc_assistant(identifier="init") + + def update_mo1_azm_angle(self, desired_azm_angle: float | None = None): + new_xtal = self.input.mo1_xtal.currentText() + old_mo1_trx = self.core.mo1_xtal_to_trx(self.old_xtal) + new_mo1_trx = self.core.mo1_xtal_to_trx(new_xtal) + old_mo1_roty = self.core.apply_offsets( + {"mo1_roty": self.input.mo1_azm_angle.value(), "mo1_trx": old_mo1_trx} + )["mo1_roty"] + new_azm_angle = self.core.remove_offsets( + {"mo1_roty": old_mo1_roty, "mo1_trx": new_mo1_trx} + )["mo1_roty"] + # Apply new range + if self.beamline == BeamlineId.X01DA: + self.input.mo1_azm_angle.set_range( + self.azm_ranges[new_xtal]["ll"], self.azm_ranges[new_xtal]["hl"] + ) + if desired_azm_angle is not None: + self.input.mo1_azm_angle.set_number(desired_azm_angle) + else: + self.input.mo1_azm_angle.set_number(new_azm_angle) + else: + self.input.mo1_azm_angle.setValue(new_azm_angle) + self.old_xtal = new_xtal + + def open_glitches_preview(self): + + if self.azm_ranges == {}: + logger.info( + "No azimuthal ranges found, can't open glitches preview. First adapt to reality once" + ) + return + + current_xtal = self.input.mo1_xtal.currentText() + current_azm = self.input.mo1_azm_angle.value() + + if self.edge_selector_energy != 0: + dlg = GlitchesPreview( + self, + current_xtal, + current_azm, + self.azm_ranges, + self.edge_selector_element, + self.edge_selector_edge, + ) + else: + dlg = GlitchesPreview( + self, current_xtal, current_azm, self.azm_ranges, energy=self.input.energy.value() + ) + if dlg.exec_(): + self.input.mo1_xtal.set_current_text(dlg.xtal_selector.currentText()) + if self.beamline == BeamlineId.X01DA: + self.update_mo1_azm_angle(dlg.azm_angle) + def update_fm_mode(self): """ Updates the focusing mirror input group based on the @@ -793,15 +1113,15 @@ class DigitalTwin(BECWidget, QWidget): Updates the plots for the reality scene """ config = self.get_reality_config() - data = calc_sideview(config) + data = self.core.calc_sideview(config) self.sideview_plot.update_curves("reality", data=data) - surfaces = calc_surfaces(config) + surfaces = self.core.calc_surfaces(config) self.surface_plots.update_surfaces(scene="reality", data=surfaces) @SafeSlot() def open_edge_selector(self, *_): match self.beamline: - case "x01da": + case BeamlineId.X01DA: dlg = EdgeSelector(self, llim=X01DA_E_MIN, hlim=X01DA_E_MAX) case "x10da": dlg = EdgeSelector(self, llim=X10DA_E_MIN, hlim=X10DA_E_MAX) @@ -810,6 +1130,8 @@ class DigitalTwin(BECWidget, QWidget): if dlg.exec_(): self.input.edge_selected.setText(f"{dlg.selected_element}, {dlg.selected_edge}-edge") self.edge_selector_energy = dlg.selected_energy + self.edge_selector_element = dlg.selected_element + self.edge_selector_edge = dlg.selected_edge self.input.energy.set_number(dlg.selected_energy) def update_edge_selected(self): @@ -825,7 +1147,7 @@ class DigitalTwin(BECWidget, QWidget): ) # Remove brackets from xtal name to conform with parameters xtal = cast(Literal["Si111", "Si311"], xtal) energy = self.input.energy.value() - self.input.mo1_eres.setValue(mo1_energy_resolution(xtal, energy)) + self.input.mo1_eres.setValue(self.core.mo1_energy_resolution(xtal, energy)) def calc_cm_reflectivity(self): """ @@ -834,9 +1156,11 @@ class DigitalTwin(BECWidget, QWidget): cm_stripe = self.input.cm_stripe.currentText() cm_pitch = -self.input.cm_pitch.value() * 1e-3 energy = self.input.energy.value() - self.input.cm_refl.setValue(100 * cm_reflectivity(cm_stripe, cm_pitch, energy)) + self.input.cm_refl.setValue(100 * self.core.cm_reflectivity(cm_stripe, cm_pitch, energy)) self.input.cm_refl.setLabel(f"Reflectivity at \n{energy:.0f} eV") - self.input.cm_refl_harm.setValue(100 * cm_reflectivity(cm_stripe, cm_pitch, 3 * energy)) + self.input.cm_refl_harm.setValue( + 100 * self.core.cm_reflectivity(cm_stripe, cm_pitch, 3 * energy) + ) self.input.cm_refl_harm.setLabel(f"Reflectivity at \n{3*energy:.0f} eV") def calc_fm_reflectivity(self): @@ -850,9 +1174,11 @@ class DigitalTwin(BECWidget, QWidget): else: fm_rotx = -self.input.fm_rotx_ideal.value() * 1e-3 energy = self.input.energy.value() - self.input.fm_refl.setValue(100 * fm_reflectivity(fm_stripe, fm_rotx, energy)) + self.input.fm_refl.setValue(100 * self.core.fm_reflectivity(fm_stripe, fm_rotx, energy)) self.input.fm_refl.setLabel(f"Reflectivity at \n{energy:.0f} eV") - self.input.fm_refl_harm.setValue(100 * fm_reflectivity(fm_stripe, fm_rotx, 3 * energy)) + self.input.fm_refl_harm.setValue( + 100 * self.core.fm_reflectivity(fm_stripe, fm_rotx, 3 * energy) + ) self.input.fm_refl_harm.setLabel(f"Reflectivity at \n{3*energy:.0f} eV") def calc_cm_fm_harm_suppr(self): @@ -872,33 +1198,23 @@ class DigitalTwin(BECWidget, QWidget): Updates the sideview plot based on the assistant values """ config = self.get_assistant_config(apply_offset=True) - data = calc_sideview(config) + data = self.core.calc_sideview(config) self.sideview_plot.update_curves("assistant", data) def calc_assistant_surfaces(self): """ Updates the surface plot based on the assistant values """ - surfaces = calc_surfaces(self.get_assistant_config()) + surfaces = self.core.calc_surfaces(self.get_assistant_config()) self.surface_plots.update_surfaces(scene="assistant", data=surfaces) def calc_positions(self): """ Calculates the positions for the axes based on the assistant values """ - out = calc_positions(self.beamline, self.get_assistant_config()) - - # Apply offsets - for axis, axis_data in out.items(): - if axis in self.offsets: - axis_offsets = self.offsets[axis] - if "modifier" in axis_offsets and "offset" in axis_offsets: - for idx, rng in enumerate(axis_offsets["modifier"]["range"]): - if rng[0] < out[axis_offsets["modifier"]["axis"]]["value"] < rng[1]: - axis_data["value"] += axis_offsets["offset"][idx] - break - elif "offset" in axis_offsets: - axis_data["value"] += axis_offsets["offset"] + config = self.get_assistant_config() + out = self.core.calc_positions(config) + out = self.core.apply_offsets(out, nested_config=True) self.mover.sldi_gapx.set_target(out["sldi_gapx"]["value"]) self.mover.sldi_gapy.set_target(out["sldi_gapy"]["value"]) @@ -909,6 +1225,8 @@ class DigitalTwin(BECWidget, QWidget): self.mover.mo1_bragg_angle.set_target(out["mo1_bragg_angle"]["value"]) self.mover.mo1_trx.set_target(out["mo1_trx"]["value"]) self.mover.mo1_try.set_target(out["mo1_try"]["value"]) + if self.beamline == BeamlineId.X01DA: + self.mover.mo1_roty.set_target(out["mo1_roty"]["value"]) self.mover.sl1_centery.set_target(out["sl1_centery"]["value"]) self.mover.sl1_gapy.set_target(out["sl1_gapy"]["value"]) self.mover.bm1_try.set_target(out["bm1_try"]["value"]) @@ -918,16 +1236,18 @@ class DigitalTwin(BECWidget, QWidget): self.mover.fm_rotx.set_target(out["fm_rotx"]["value"]) self.mover.fm_roty.set_target(out["fm_roty"]["value"]) self.mover.fm_rotz.set_target(out["fm_rotz"]["value"]) - if self.beamline == "x01da": + if self.beamline == BeamlineId.X01DA: self.mover.sl2_centery.set_target(out["sl2_centery"]["value"]) self.mover.sl2_gapy.set_target(out["sl2_gapy"]["value"]) self.mover.bm2_try.set_target(out["bm2_try"]["value"]) - if self.beamline == "x01da": + if self.beamline == BeamlineId.X01DA: self.mover.ot_try.set_target(out["ot_try"]["value"]) self.mover.ot_rotx.set_target(out["ot_rotx"]["value"]) self.mover.ot_es1_trz.set_target(out["ot_es1_trz"]["value"]) + self.mover.ot_es2_trz.set_target(out["ot_es2_trz"]["value"]) self.mover.es0wi_try.set_target(out["es0wi_try"]["value"]) - if self.beamline == "x10da": + self.mover.es1man_trz.set_target(out["es1man_trz"]["value"]) + if self.beamline == BeamlineId.X10DA: self.mover.es1_try.set_target(out["es1_try"]["value"]) self.mover.es1ic0_try.set_target(out["es1ic0_try"]["value"]) self.mover.es1ic1_try.set_target(out["es1ic1_try"]["value"]) @@ -952,7 +1272,7 @@ class DigitalTwin(BECWidget, QWidget): cm_pitch = -self.dev.cm_rotx.read(cached=True)["cm_rotx"]["value"] * 1e-3 mo1_mode = cast(Literal["Monochromatic", "Pinkbeam"], self.input.mo1_mode.currentText()) energy = self.input.energy.value() - theta, _ = mo1_bragg_angle(mo1_mode, d_spacing, energy, cm_pitch) + theta, _ = self.core.mo1_bragg_angle(mo1_mode, d_spacing, energy, cm_pitch) self.bragg_angle = theta self.input.mo1_bragg_angle.setValue(theta / np.pi * 180) @@ -965,10 +1285,14 @@ class DigitalTwin(BECWidget, QWidget): self.input.mo1_xtal.setVisible(True) self.input.mo1_bragg_angle.setVisible(True) self.input.mo1_eres.setVisible(True) + self.input.mo1_azm_angle.setVisible(True) + self.input.mo1_glitch_preview.setVisible(True) else: self.input.mo1_xtal.setVisible(False) self.input.mo1_bragg_angle.setVisible(False) self.input.mo1_eres.setVisible(False) + self.input.mo1_azm_angle.setVisible(False) + self.input.mo1_glitch_preview.setVisible(False) def calc_fm_ideal_pitch(self): """ @@ -978,17 +1302,19 @@ class DigitalTwin(BECWidget, QWidget): Literal["Defocused", "Focused", "Manual"], self.input.fm_focus.currentText() ) fm_stripe = self.input.fm_stripe.currentText() - match self.input.smpl: - case InputNumberField(): - smpl = self.input.smpl.value() - case ComboBox(): - table = self.input.smpl.currentText() - smpl = table_to_smpl_pos(table) + es1man_trz = self.input.es1man_trz.value() + if self.beamline == BeamlineId.X01DA: + ot_es1_trz = self.input.ot_es1_trz.value() + else: + table = self.input.table.currentText() + ot_es1_trz = self.core.table_to_smpl_pos(table) + smpl = ot_es1_trz + es1man_trz + sldi_hacc = self.input.sldi_hacc.value() * 1e-3 sldi_vacc = self.input.sldi_vacc.value() * 1e-3 fm_focx = self.input.fm_focx.value() fm_focy = self.input.fm_focy.value() - fm_rotx, qy = fm_ideal_pitch( + fm_rotx, qy = self.core.fm_ideal_pitch( fm_focus, fm_stripe, smpl, sldi_hacc, sldi_vacc, fm_focx, fm_focy ) self.qy = qy @@ -1000,7 +1326,16 @@ class DigitalTwin(BECWidget, QWidget): """ cm_stripe = cast(Literal["Si", "Pt", "Rh"], self.input.cm_stripe.currentText()) energy = self.input.energy.value() - self.input.cm_pitch_critical.setValue(-cm_critical_angle(cm_stripe, energy) * 1e3) + self.input.cm_pitch_critical.setValue(-self.core.cm_critical_angle(cm_stripe, energy) * 1e3) + + def _multi_move(self): + """ + Move the selected motors at the same time (if permitted).""" + logger.info("Multi move button pressed") + abort = threading.Event() # one failure aborts the not-yet-started motors of this batch + for w in self.mover.mover_widgets: + if w.checkbox.isChecked(): + w.start_motion(abort=abort) if __name__ == "__main__": diff --git a/debye_bec/bec_widgets/widgets/digital_twin/glitches_preview.py b/debye_bec/bec_widgets/widgets/digital_twin/glitches_preview.py new file mode 100644 index 0000000..cc1a7c6 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/digital_twin/glitches_preview.py @@ -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) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py b/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py index b332f98..e0d11ed 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/panels/input_panel.py @@ -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"]) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py b/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py index 4b43a3d..099931e 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/panels/mover_panel.py @@ -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, ], ) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/panels/plots.py b/debye_bec/bec_widgets/widgets/digital_twin/panels/plots.py index b7d7131..0d8f383 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/panels/plots.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/panels/plots.py @@ -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))) diff --git a/debye_bec/bec_widgets/widgets/digital_twin/panels/settings_panel.py b/debye_bec/bec_widgets/widgets/digital_twin/panels/settings_panel.py index 2bf74d2..c621bbc 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/panels/settings_panel.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/panels/settings_panel.py @@ -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() diff --git a/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py b/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py index aa57582..3db7b1e 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/widgets/move_widget.py @@ -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): diff --git a/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py b/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py index b127418..6067b90 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/widgets/qt_widgets.py @@ -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): diff --git a/debye_bec/bec_widgets/widgets/digital_twin/xop_si111_Si-LN2_8-8-8_4500-60000eV_-180-180deg.pro b/debye_bec/bec_widgets/widgets/digital_twin/xop_si111_Si-LN2_8-8-8_4500-60000eV_-180-180deg.pro new file mode 100644 index 0000000..b61fa07 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/digital_twin/xop_si111_Si-LN2_8-8-8_4500-60000eV_-180-180deg.pro @@ -0,0 +1,7812 @@ +; (xop/mare spaghetti macro) +; +; XOP/IDL macro created by MARE +; (Do not change this macro. Use Edit Parameters for user customization.) +; xop/mare multiple diffraction +; +; inputs: +; crystal index: 2 +; crystal name: Si_LN2 +; Main reflection: [1,1,1] +; Max reflections: [8,8,8] +; Wavelength [A] 1.5400000 +; Delta Wavelength [A] 0.0100000 +; Phi [deg] -20.000000 +; Delta Phi [deg] 0.10000000 +; Display: 0 +; Using reflections with fh > 1.0000000e-008 +; +; Computed parameters: +; Number of good reflections: 864 +; M vector (corresponding to phi=0) [1,-1,0] +; Intensity of main reflection: 6821.5499 +; Structure Factor fh of main reflection: 60.536598 +; Reflection with maximum intensity: +; number: 66 +; miller indices: -2 -2 0 +; fh value: 70.708675 +; +;parms = {n:500L, xmin:-90.,xmax:90.,eV:['0','A','eV'],ymin:0.,ymax:3.5} +alpha = makearray1(parms.n,parms.xmin,parms.xmax,/double) +IF Fix(parms.eV[0]) EQ 1 THEN ytitle='Photon energy [eV]' ELSE ytitle='Wavelength [A]' +plot,alpha,alpha*0,xrange=[parms.xmin,parms.xmax],yrange=[parms.ymin,parms.ymax],/nodata,/xstyle,/ystyle,title='MARE-spaghetti, Main diffraction: [1,1,1] Si_LN2',xtitle='Azimuthal angle [deg]',ytitle=ytitle +lambdas=[1.5300000,1.5400000,1.5500000] +phis=[-20.100000,-20.000000,-19.900000] +IF Fix(parms.eV[0]) EQ 1 THEN yy=physical_constants('hc')/lambdas ELSE yy=lambdas +labelflg = Fix(parms.labels[0]) +; -------------------------------- +; Reflection nr: 1 +; h k l alpha0 k p2/4 th2 th2 th2 th3 th3 th3 lambda lambda lambda BrgAngU BrgAngG fh +; -1 -1 -3 90.0000 0.902425 0.0254491 -1000.00 -1000.00 -1000.00 -1000.00 -1000.00 -1000.00 0.380117 0.378310 0.376502 28.0620 6.63612 46.7334 +ilabel=randomu(seed)*(parms.n-1) +y3 = 1D/sqrt((0.90242477/cos((alpha-90.000000)*!dpi/180))^2+0.025449077) +IF Fix(parms.eV[0]) EQ 1 THEN y3=physical_constants('hc',/Double)/y3 +oplot,alpha,y3,color= 1 +IF labelflg THEN XYouts,CharS=0.95,alpha[iLabel],y3[iLabel]+.02 1.0000000e-008 +; +; Computed parameters: +; Number of good reflections: 874 +; M vector (corresponding to phi=0) [1,-3,0] +; Intensity of main reflection: 1723.9218 +; Structure Factor fh of main reflection: 46.733379 +; Reflection with maximum intensity: +; number: 67 +; miller indices: -2 -2 0 +; fh value: 70.708675 +; +;parms = {n:500L, xmin:-90.,xmax:90.,eV:['0','A','eV'],ymin:0.,ymax:3.5} +alpha = makearray1(parms.n,parms.xmin,parms.xmax,/double) +IF Fix(parms.eV[0]) EQ 1 THEN ytitle='Photon energy [eV]' ELSE ytitle='Wavelength [A]' +plot,alpha,alpha*0,xrange=[parms.xmin,parms.xmax],yrange=[parms.ymin,parms.ymax],/nodata,/xstyle,/ystyle,title='MARE-spaghetti, Main diffraction: [3,1,1] Si_LN2',xtitle='Azimuthal angle [deg]',ytitle=ytitle +lambdas=[1.5300000,1.5400000,1.5500000] +phis=[-20.100000,-20.000000,-19.900000] +IF Fix(parms.eV[0]) EQ 1 THEN yy=physical_constants('hc')/lambdas ELSE yy=lambdas +labelflg = Fix(parms.labels[0]) +; -------------------------------- +; Reflection nr: 1 +; h k l alpha0 k p2/4 th2 th2 th2 th3 th3 th3 lambda lambda lambda BrgAngU BrgAngG fh +; -1 -1 -1 42.1304 0.864006 0.0933133 -1000.00 -1000.00 -1000.00 -1000.00 -1000.00 -1000.00 0.532081 0.533797 0.535511 14.2216 4.88496 60.5366 +ilabel=randomu(seed)*(parms.n-1) +y3 = 1D/sqrt((0.86400594/cos((alpha-42.130415)*!dpi/180))^2+0.093313283) +IF Fix(parms.eV[0]) EQ 1 THEN y3=physical_constants('hc',/Double)/y3 +oplot,alpha,y3,color= 1 +IF labelflg THEN XYouts,CharS=0.95,alpha[iLabel],y3[iLabel]+.02