From b4d2ac190675846523a304b950aad133524e7c33 Mon Sep 17 00:00:00 2001 From: hitz_s Date: Wed, 23 Sep 2026 14:10:07 +0200 Subject: [PATCH] wip digital twin --- .../digital_twin_core/digital_twin_core.py | 3 + .../plugins/digital_twin_core/types.py | 2 + .../digital_twin_core/x01da_offsets.yaml | 6 + .../digital_twin/azimuth_calculator.py | 339 + .../widgets/digital_twin/digital_twin.py | 76 +- .../widgets/digital_twin/glitches_preview.py | 148 + .../digital_twin/panels/input_panel.py | 26 +- .../digital_twin/panels/mover_panel.py | 22 +- .../digital_twin/widgets/qt_widgets.py | 10 + ..._Si-LN2_8-8-8_4500-60000eV_-180-180deg.pro | 7812 ++++++++++++++++ ...311_Si-LN2_8-8-8_4500-60000eV_0-360deg.pro | 7902 +++++++++++++++++ 11 files changed, 16341 insertions(+), 5 deletions(-) create mode 100644 debye_bec/bec_widgets/widgets/digital_twin/azimuth_calculator.py create mode 100644 debye_bec/bec_widgets/widgets/digital_twin/glitches_preview.py create mode 100644 debye_bec/bec_widgets/widgets/digital_twin/xop_si111_Si-LN2_8-8-8_4500-60000eV_-180-180deg.pro create mode 100644 debye_bec/bec_widgets/widgets/digital_twin/xop_si311_Si-LN2_8-8-8_4500-60000eV_0-360deg.pro 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 index 6e7a772..f9876d9 100644 --- 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 @@ -351,6 +351,9 @@ class DigitalTwinCore: 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 diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/types.py b/debye_bec/bec_ipython_client/plugins/digital_twin_core/types.py index 7c66f50..913c951 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/types.py +++ b/debye_bec/bec_ipython_client/plugins/digital_twin_core/types.py @@ -27,6 +27,7 @@ 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. @@ -46,6 +47,7 @@ class ConfigDict(TypedDict): mo1_mode: str mo1_xtal: str mo1_bragg: float + mo1_roty: float fm_rotx: float fm_stripe: str fm_trx: float diff --git a/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_offsets.yaml b/debye_bec/bec_ipython_client/plugins/digital_twin_core/x01da_offsets.yaml index f475d96..83f9ff0 100644 --- a/debye_bec/bec_ipython_client/plugins/digital_twin_core/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/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/digital_twin.py b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py index ce052fb..304dc0f 100644 --- a/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py +++ b/debye_bec/bec_widgets/widgets/digital_twin/digital_twin.py @@ -43,6 +43,7 @@ from qtpy.QtWidgets import ( 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 .glitches_preview import GlitchesPreview from .panels.input_panel import InputPanel from .panels.mover_panel import MoverPanel from .panels.plots import SideviewPlot, SurfacePlots @@ -132,6 +133,7 @@ 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) + 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) @@ -152,6 +154,8 @@ class DigitalTwin(BECWidget, QWidget): self.settings.load_from_scan.clicked_connect(self.load_from_scan) self.edge_selector_energy = 0.0 + self.edge_selector_element = "" + self.edge_selector_edge = "" self.bragg_angle = 0.0 self.qy = 0.0 @@ -230,6 +234,7 @@ class DigitalTwin(BECWidget, QWidget): devices.extend( [ "cm_bnd_radius", + "mo1_roty", "fm_bnd_radius", "sl2_centery", "sl2_gapy", @@ -316,6 +321,7 @@ class DigitalTwin(BECWidget, QWidget): 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() @@ -340,6 +346,7 @@ class DigitalTwin(BECWidget, QWidget): case "mo1_xtal": self.calc_mo1_bragg_angle() self.calc_mo1_energy_resolution() + self.update_mo1_azm_angle() case "fm_focus": self.update_fm_mode() self.calc_fm_ideal_pitch() @@ -414,6 +421,7 @@ class DigitalTwin(BECWidget, QWidget): "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, @@ -464,6 +472,8 @@ class DigitalTwin(BECWidget, QWidget): 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"] @@ -529,10 +539,12 @@ class DigitalTwin(BECWidget, QWidget): es1man_trz = self.dev.es1man_trz.read(cached=True)["es1man_trz"]["value"] 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 @@ -547,6 +559,7 @@ 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, @@ -583,6 +596,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"] ) @@ -641,6 +658,10 @@ 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"] @@ -670,6 +691,10 @@ class DigitalTwin(BECWidget, QWidget): self.input.mo1_xtal.set_current_text( self.dev.mo1_bragg.read(cached=False)["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"] @@ -905,6 +930,10 @@ class DigitalTwin(BECWidget, QWidget): 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"])[()] @@ -940,6 +969,10 @@ class DigitalTwin(BECWidget, QWidget): )[()] ) + 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"] @@ -967,6 +1000,39 @@ class DigitalTwin(BECWidget, QWidget): self.calc_assistant(identifier="init") + def update_mo1_azm_angle(self): + if self.beamline == BeamlineId.X01DA: + mo1_roty = self.dev.mo1_roty.describe(cached=True)["mo1_roty"] + ll = mo1_roty["lower_ctrl_limit"] + hl = mo1_roty["upper_ctrl_limit"] + + # Apply offsets + ll = self.core.apply_offsets({"mo1_roty": ll}, nested_config=False) + hl = self.core.apply_offsets({"mo1_roty": hl}, nested_config=False) + + self.input.mo1_azm_angle.set_range(ll, hl) + else: + azm_angle = self.core.apply_offsets({"mo1_roty": 0}, nested_config=False) + self.input.mo1_azm_angle.setValue(azm_angle) + + def open_glitches_preview(self): + xtal = self.input.mo1_xtal.currentText() + azm_angle = self.input.mo1_azm_angle.value() + if self.beamline == BeamlineId.X01DA: + ll, hl = self.input.mo1_azm_angle.get_range() + else: + ll, hl = None, None + if self.edge_selector_energy != 0: + dlg = GlitchesPreview( + self, xtal, azm_angle, ll, hl, self.edge_selector_element, self.edge_selector_edge + ) + else: + dlg = GlitchesPreview(self, xtal, azm_angle, self.input.energy.value()) + if dlg.exec_(): + self.input.mo1_xtal.set_current_text(dlg.xtal_selector.currentText()) + if self.beamline == BeamlineId.X01DA: + self.input.mo1_azm_angle.set_number(dlg.azm_angle) + def update_fm_mode(self): """ Updates the focusing mirror input group based on the @@ -1015,6 +1081,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): @@ -1108,6 +1176,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"]) @@ -1128,7 +1198,7 @@ class DigitalTwin(BECWidget, QWidget): self.mover.ot_es2_trz.set_target(out["ot_es2_trz"]["value"]) self.mover.es0wi_try.set_target(out["es0wi_try"]["value"]) self.mover.es1man_trz.set_target(out["es1man_trz"]["value"]) - if self.beamline == "x10da": + 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"]) @@ -1166,10 +1236,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): """ 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..4707e69 --- /dev/null +++ b/debye_bec/bec_widgets/widgets/digital_twin/glitches_preview.py @@ -0,0 +1,148 @@ +""" +GlitchesPreview: QDialog to preview monochromator glitches +""" + +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, + xtal: str, + azm_angle: float, + azm_ll: float | None = None, + azm_hl: float | None = None, + 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(energy - EV_BELOW, energy + EV_ABOVE, 1000) + self.mu = edge_step(self.energies, self.energy) + else: + self.energy = energy + self.energies = np.linspace(energy - EV_BELOW, 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(xtal) + self.xtal_selector.activated_connect(self.update_plot) + layout.addWidget(self.xtal_selector) + + self.azm_angle = azm_angle + self.azm_input = None + if azm_hl is not None and azm_ll is not None: + azm_input = InputNumberField( + "azm_angle", + "Azm. Angle", + unit="deg", + init=azm_angle, + decimals=3, + single_step=0.01, + ll=azm_ll, + hl=azm_hl, + ) + azm_input.value_changed_connect(self.update_plot) + layout.addWidget(azm_input) + accept_text = "Select xtal and azm. angle" + else: + accept_text = "Select xtal" + + 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") + 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.setEnabled(False) + self._select_button.clicked.connect(self.accept) + self._select_button.setStyleSheet( + f"QPushButton {{background-color: {get_accent_colors().default.name()}; color: white;}}" + ) + + 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( + "xop_si111_Si-LN2_8-8-8_4500-60000eV_-180-180deg.pro" + ) + self.reflections_si311 = parse_xop_macro("xop_si311_Si-LN2_8-8-8_4500-60000eV_0-360deg.pro") + + @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) + ) + + for e, wn in zip(e_pred, wnorm): + depth = 0.02 + 0.08 * wn + mu = self.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 3616160..4599a54 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 @@ -113,8 +113,32 @@ class InputPanel(QWidget): self.mo1_xtal = ComboBox("mo1_xtal", "Crystal", ["Si(111)", "Si(311)"]) 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 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 bd43e05..2c98af5 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 @@ -136,9 +136,25 @@ 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( + 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( 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..9b984a1 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() 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