start deleting stuff
CI / lint (push) Skipped
CI / test (3.12) (push) Skipped
CI / test (3.13) (push) Skipped
CI / test-with-beamline-plugins (pxi_bec) (push) Skipped
CI / test-with-beamline-plugins (pxii_bec) (push) Skipped
CI / test-with-beamline-plugins (pxiii_bec) (push) Skipped

This commit is contained in:
perl_d committed 2026-11-30 21:10:25 +01:00
1 parent 7316181519
commit a24f89c885
261 files changed
+1 -53979

No files matched your search

-63
View File
@@ -1,63 +0,0 @@
# GUI Controls Cheat Sheet
## Sample Camera
| Control | Applies to | Action |
| --------------------- | ------------------ | --------------------------------------------- |
| `Left click` | | move sample to clicked position |
| `Shift + Left click` | | Z-alignment click behaviour |
| `Ctrl + Left click` | active raster grid | move to clicked position under the grid |
| `Left drag` | active raster grid | move active raster grid |
| `Right click` | | open sample camera context menu |
| `Right drag` | empty area | draw raster grid |
| `Right drag` | active raster grid | resize raster grid |
| `Mouse wheel` | | rotate omega by 90° |
| `Shift + Mouse wheel` | | rotate omega by 10° |
| `Ctrl + Mouse wheel` | | change sample camera exposure by a large step |
| `Alt + Mouse wheel` | | change sample camera exposure by a small step |
| `Shift + Mouse move` | | inspect/load raster image under cursor |
## Video Views
| Control | Action |
| -------------------- | ----------- |
| `Ctrl + Mouse wheel` | zoom in/out |
| `F` | fit to view |
| `R` | reset zoom |
| `+` or `=` | zoom in |
| `-` | zoom out |
## Sample Queue
| Control | Action |
| -------- | ---------------------------- |
| `Delete` | remove selected samples |
| `Space` | run / pause queue automation |
## Workflow Panel
| Control | Action |
| --------------- | -------------------------------------- |
| `Delete` | remove selected queue items |
| `Space` | pause / resume workflow |
| `Ctrl + R` | refresh workflow queue |
| `Ctrl + Delete` | clear non-running workflow queue items |
## Global Shortcuts
| Control | Action |
| ------------------ | ------------------------------------ |
| `F1` | open mouse / keyboard controls help |
| `Ctrl + Q` | quit application |
| `Ctrl + Shift + R` | restore default view layout |
| `Ctrl + 1` | switch to Sample camera tab |
| `Ctrl + 2` | switch to Gonio camera tab |
| `Ctrl + 3` | switch to Beamline view tab |
| `Ctrl + 4` | switch to Beamline combined view tab |
| `Ctrl + L` | raise Sample List panel |
| `Ctrl + J` | raise Automation list panel |
| `Ctrl + M` | raise manual sample dock |
| `Ctrl + W` | toggle Workflow panel |
| `Ctrl + Shift + T` | toggle Target stability panel |
| `Ctrl + Shift + P` | toggle Prediction Metrics panel |
| `Ctrl + Shift + S` | toggle Smargon trace panel |
+1 -7
View File
@@ -2,10 +2,4 @@
icon: lucide/rocket
---
# AareDAQ
AareDAQ is the Data Acquisition application for MX beamlines at PSI.
# Get started
See the list of controls in the [cheat sheet](./cheatsheet.md)!
AareAuth is the authentication helper for MX DAQ services at SLS
-32
View File
@@ -1,32 +0,0 @@
import cv2
# %%
bkg_old = cv2.imread(
"/home/leonarski_f/aaredaq/daq/src/aaredaq/alc_test_images/bkg280_50_50_old.jpg"
)
bkg_new = cv2.imread("/home/leonarski_f/aaredaq/daq/src/aaredaq/alc_test_images/bkg280_50_50.jpg")
grey_old = cv2.cvtColor(bkg_old, cv2.COLOR_RGB2GRAY)
grey_new = cv2.cvtColor(bkg_new, cv2.COLOR_RGB2GRAY)
diff_image = cv2.absdiff(grey_old, grey_new)
_, thresh_diff = cv2.threshold(diff_image, 1, 255, cv2.THRESH_BINARY)
# Display the results
cv2.imshow("Original Image 1", bkg_old)
cv2.imshow("Original Image 2", bkg_new)
cv2.imshow("Grayscale 1", grey_old)
cv2.imshow("Grayscale 2", grey_new)
cv2.imshow("Difference Image", diff_image)
cv2.imshow("Thresholded Difference", thresh_diff)
# Save the difference image
cv2.imwrite(
"/home/leonarski_f/aaredaq/daq/src/aaredaq/alc_test_images/bkg_difference_image.jpg", diff_image
)
cv2.imwrite(
"/home/leonarski_f/aaredaq/daq/src/aaredaq/alc_test_images/bkg_thresholded_difference.jpg",
thresh_diff,
)
# Wait for a key press and close all windows
cv2.waitKey(0)
cv2.destroyAllWindows()
-431
View File
@@ -1,431 +0,0 @@
import json
import threading
import time
from typing import Any
import cv2
import numpy as np
import zmq
from aarecommon.config.logger import setup_logger
logger = setup_logger("aareDAQ")
class ImageStatsReceiver:
def __init__(self, zmq_url: str):
"""Initialize ZeroMQ receiver for image statistics calculation"""
context = zmq.Context()
self._socket = context.socket(zmq.SUB)
self._socket.setsockopt(zmq.SUBSCRIBE, b"")
self._socket.setsockopt(zmq.RCVTIMEO, 1000) # 1 second timeout
self._socket.setsockopt(zmq.LINGER, 0) # Don't linger on close
try:
self._socket.connect(zmq_url)
print(f"Connected to ZeroMQ socket: {zmq_url}")
except Exception as e:
print(f"Failed to connect to {zmq_url}: {e}")
raise
self.running = False
self.latest_stats = None
self.stats_lock = threading.Lock()
self.message_count = 0
self.connection_attempts = 0
self.last_message_time = None
self.connection_attempts = 0
self.last_message_time = None
def calculate_projections(self, image: np.ndarray) -> dict[str, Any]:
"""Calculate X and Y projections of the image"""
# Convert to grayscale if color image
if len(image.shape) == 3:
gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
else:
gray_image = image.copy()
# Calculate projections (sum along each axis)
x_projection = np.mean(gray_image, axis=0) # Sum along Y axis -> X profile
y_projection = np.mean(gray_image, axis=1) # Sum along X axis -> Y profile
# Also calculate max projections (useful for finding peaks)
x_projection_max = np.max(gray_image, axis=0)
y_projection_max = np.max(gray_image, axis=1)
# Find peak positions and values
x_peak_idx = np.argmax(x_projection)
y_peak_idx = np.argmax(y_projection)
x_peak_value = x_projection[x_peak_idx]
y_peak_value = y_projection[y_peak_idx]
# Calculate centroid positions (intensity-weighted center)
x_coords = np.arange(len(x_projection))
y_coords = np.arange(len(y_projection))
x_centroid = (
np.sum(x_coords * x_projection) / np.sum(x_projection)
if np.sum(x_projection) > 0
else len(x_projection) / 2
)
y_centroid = (
np.sum(y_coords * y_projection) / np.sum(y_projection)
if np.sum(y_projection) > 0
else len(y_projection) / 2
)
# Calculate FWHM (Full Width at Half Maximum) approximation
def calculate_fwhm(profile):
peak_val = np.max(profile)
half_max = peak_val / 2
indices = np.where(profile >= half_max)[0]
if len(indices) > 0:
return indices[-1] - indices[0]
return 0
x_fwhm = calculate_fwhm(x_projection)
y_fwhm = calculate_fwhm(y_projection)
return {
"x_projection": x_projection.tolist(),
"y_projection": y_projection.tolist(),
"x_projection_max": x_projection_max.tolist(),
"y_projection_max": y_projection_max.tolist(),
"x_peak_position": int(x_peak_idx),
"y_peak_position": int(y_peak_idx),
"x_peak_value": float(x_peak_value),
"y_peak_value": float(y_peak_value),
"x_centroid": float(x_centroid),
"y_centroid": float(y_centroid),
"x_fwhm": float(x_fwhm),
"y_fwhm": float(y_fwhm),
"x_coords": list(range(len(x_projection))),
"y_coords": list(range(len(y_projection))),
}
def calculate_radial_integration(self, image: np.ndarray, num_bins: int = 50) -> dict[str, Any]:
"""Calculate radial integration of the image"""
# Convert to grayscale if color image
if len(image.shape) == 3:
gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
else:
gray_image = image.copy()
# Get image center
center_y, center_x = np.array(gray_image.shape) // 2
# Create coordinate grids
y_coords, x_coords = np.ogrid[: gray_image.shape[0], : gray_image.shape[1]]
# Calculate distance from center for each pixel
distances = np.sqrt((x_coords - center_x) ** 2 + (y_coords - center_y) ** 2)
# Maximum possible radius (to corner of image)
max_radius = np.sqrt((gray_image.shape[0] / 2) ** 2 + (gray_image.shape[1] / 2) ** 2)
# Create radial bins
r_bins = np.linspace(0, max_radius, num_bins + 1)
r_centers = (r_bins[:-1] + r_bins[1:]) / 2
# Calculate radial profile
radial_profile = []
radial_std = []
pixel_counts = []
for i in range(num_bins):
# Create mask for current radial bin
mask = (distances >= r_bins[i]) & (distances < r_bins[i + 1])
if np.any(mask):
# Get pixel values in this radial bin
pixel_values = gray_image[mask]
radial_profile.append(float(np.mean(pixel_values)))
radial_std.append(float(np.std(pixel_values)))
pixel_counts.append(int(np.sum(mask)))
else:
radial_profile.append(0.0)
radial_std.append(0.0)
pixel_counts.append(0)
return {
"r_centers": r_centers.tolist(),
"radial_profile": radial_profile,
"radial_std": radial_std,
"pixel_counts": pixel_counts,
"max_radius": float(max_radius),
"center": [int(center_x), int(center_y)],
"num_bins": num_bins,
}
def calculate_image_stats(self, image: np.ndarray) -> dict[str, Any]:
"""Calculate comprehensive statistics for an image"""
image_float = image.astype(np.float64)
stats = {
"timestamp": time.time(),
"shape": image.shape,
"dtype": str(image.dtype),
"mean": float(np.mean(image_float)),
"std": float(np.std(image_float)),
"median": float(np.median(image_float)),
"min": float(np.min(image_float)),
"max": float(np.max(image_float)),
"message_count": self.message_count,
}
# Calculate per-channel stats if color image
if len(image.shape) == 3 and image.shape[2] > 1:
for channel in range(image.shape[2]):
channel_data = image_float[:, :, channel]
stats[f"mean_ch{channel}"] = float(np.mean(channel_data))
stats[f"std_ch{channel}"] = float(np.std(channel_data))
stats[f"median_ch{channel}"] = float(np.median(channel_data))
radial_data = self.calculate_radial_integration(image)
stats["radial"] = radial_data
# projection_data = self.calculate_projections(image)
# stats['projections'] = projection_data
return stats
def process_message(self):
"""Process a single ZeroMQ message"""
try:
r = self._socket.recv_multipart(zmq.NOBLOCK)
if len(r) != 2:
return None
meta, data = r
header = json.loads(meta)
header_shape = header["shape"]
self.message_count += 1
if header["type"] == "uint8" and len(header_shape) == 2:
# Bayer image
bayer_image = np.frombuffer(data, dtype=np.uint8)
bayer_image = bayer_image.reshape(header_shape)
# Convert to RGB for main stats
rgb_image = cv2.cvtColor(bayer_image, cv2.COLOR_BAYER_GB2RGB)
rgb_image = rgb_image[:, ::-1, :].copy()
stats = self.calculate_image_stats(rgb_image)
stats["image_type"] = "rgb_from_bayer"
with self.stats_lock:
self.latest_stats = stats
return stats
elif header["type"] == "uint8" and len(header_shape) == 3:
# RGB image
rgb_image = np.frombuffer(data, dtype=np.uint8)
rgb_image = rgb_image.reshape(header_shape)
stats = self.calculate_image_stats(rgb_image)
stats["image_type"] = "rgb_direct"
with self.stats_lock:
self.latest_stats = stats
return stats
except zmq.Again:
return None
except Exception:
logger.exception("Error processing ZMQ message")
return None
def receiver_thread(self):
"""Background thread for receiving messages"""
while self.running:
self.process_message()
time.sleep(0.001) # Small sleep to prevent busy waiting
def print_stats_thread(self):
"""Background thread for printing stats every second"""
while self.running:
time.sleep(5.0) # Print once per second
with self.stats_lock:
if self.latest_stats:
self.print_formatted_stats(self.latest_stats)
else:
print(f"[{time.strftime('%H:%M:%S')}] Waiting for image data...")
def print_formatted_stats(self, stats: dict[str, Any]):
"""Print formatted statistics in a compact terminal format"""
timestamp = time.strftime("%H:%M:%S", time.localtime(stats["timestamp"]))
# Compact one-line format
print(
f"[{timestamp}] #{stats['message_count']:4d} | "
f"Shape: {stats['shape']} | "
f"Mean: {stats['mean']:6.1f} | "
f"Std: {stats['std']:6.1f} | "
f"Median: {stats['median']:6.1f} | "
f"Range: [{stats['min']:3.0f}-{stats['max']:3.0f}]",
flush=True,
)
if "radial" in stats:
radial = stats["radial"]
center_intensity = radial["radial_profile"][0] if radial["radial_profile"] else 0
edge_intensity = radial["radial_profile"][-1] if radial["radial_profile"] else 0
peak_radius_idx = np.argmax(radial["radial_profile"]) if radial["radial_profile"] else 0
peak_radius = radial["r_centers"][peak_radius_idx] if radial["r_centers"] else 0
print(
f"{'':21} Radial: Center={center_intensity:.1f} | "
f"Edge={edge_intensity:.1f} | "
f"Peak@r={peak_radius:.1f} | "
f"Center=({radial['center'][0]},{radial['center'][1]})",
flush=True,
)
# Print projection summary
if "projections" in stats:
proj = stats["projections"]
print(
f"{'':21} X-Profile: Peak@{proj['x_peak_position']}({proj['x_peak_value']:.1f}) | "
f"Centroid={proj['x_centroid']:.1f} | FWHM={proj['x_fwhm']:.1f}",
flush=True,
)
print(
f"{'':21} Y-Profile: Peak@{proj['y_peak_position']}({proj['y_peak_value']:.1f}) | "
f"Centroid={proj['y_centroid']:.1f} | FWHM={proj['y_fwhm']:.1f}",
flush=True,
)
# Optional: Print per-channel stats if available
if any(k.startswith("mean_ch") for k in stats):
channels = []
i = 0
while f"mean_ch{i}" in stats:
channels.append(f"Ch{i}({stats[f'mean_ch{i}']:.1f})")
i += 1
if channels:
print(f"{'':21} Channels: {' '.join(channels)}", flush=True)
def get_radial_profile_summary(self):
"""Get a summary of the current radial profile"""
with self.stats_lock:
if self.latest_stats and "radial" in self.latest_stats:
radial = self.latest_stats["radial"]
return {
"r_centers": radial["r_centers"],
"radial_profile": radial["radial_profile"],
"center_intensity": radial["radial_profile"][0]
if radial["radial_profile"]
else 0,
"edge_intensity": radial["radial_profile"][-1]
if radial["radial_profile"]
else 0,
"max_intensity_radius": radial["r_centers"][np.argmax(radial["radial_profile"])]
if radial["radial_profile"]
else 0,
"max_intensity_value": max(radial["radial_profile"])
if radial["radial_profile"]
else 0,
}
return None
def save_radial_profile_to_file(self, filename: str | None = None):
"""Save the current radial profile to a file"""
if filename is None:
filename = f"radial_profile_{int(time.time())}.txt"
with self.stats_lock:
if self.latest_stats and "radial" in self.latest_stats:
radial = self.latest_stats["radial"]
with open(filename, "w") as f:
f.write("# Radial Integration Profile\n")
f.write(f"# Timestamp: {time.ctime(self.latest_stats['timestamp'])}\n")
f.write(f"# Image shape: {self.latest_stats['shape']}\n")
f.write(f"# Center: {radial['center']}\n")
f.write("# Radius(pixels)\tMean_Intensity\tStd_Intensity\tPixel_Count\n")
f.writelines(
f"{radial['r_centers'][i]:.2f}\t"
f"{radial['radial_profile'][i]:.2f}\t"
f"{radial['radial_std'][i]:.2f}\t"
f"{radial['pixel_counts'][i]}\n"
for i in range(len(radial["r_centers"]))
)
print(f"Radial profile saved to {filename}")
return filename
print("No radial profile data available")
return None
def start(self):
"""Start the background threads"""
self.running = True
# Start receiver thread
self.receiver_thread_obj = threading.Thread(target=self.receiver_thread, daemon=True)
self.receiver_thread_obj.start()
# Start stats printing thread
self.print_thread_obj = threading.Thread(target=self.print_stats_thread, daemon=True)
self.print_thread_obj.start()
print("Image stats receiver started - printing every 1 second")
def stop(self):
"""Stop the receiver and all threads"""
self.running = False
if self._socket:
self._socket.close()
print("Image stats receiver stopped")
# Global stats receiver instance
stats_receiver = None
def start_image_stats_receiver(zmq_url: str = "tcp://localhost:5555"):
"""Start the image stats receiver in background"""
global stats_receiver
if stats_receiver is None or not stats_receiver.running:
try:
stats_receiver = ImageStatsReceiver(zmq_url)
stats_receiver.start()
print(f"Started image statistics monitoring on {zmq_url}")
except Exception:
logger.exception("Failed to start image stats receiver")
stats_receiver = None
def stop_image_stats_receiver():
"""Stop the image stats receiver"""
global stats_receiver
if stats_receiver and stats_receiver.running:
stats_receiver.stop()
stats_receiver = None
def get_latest_image_stats():
"""Get the latest image statistics"""
if stats_receiver and stats_receiver.latest_stats:
with stats_receiver.stats_lock:
return stats_receiver.latest_stats.copy()
return None
def get_radial_profile():
"""Get just the radial profile data"""
if stats_receiver:
return stats_receiver.get_radial_profile_summary()
return None
def save_current_radial_profile(filename: str | None = None):
"""Save the current radial profile to a file"""
if stats_receiver:
return stats_receiver.save_radial_profile_to_file(filename)
return None
-587
View File
@@ -1,587 +0,0 @@
import math
import sys
from typing import ClassVar
from PySide6.QtCore import QPointF, QRectF, Qt
from PySide6.QtGui import QColor, QFont, QFontMetrics, QLinearGradient, QPainter, QPen
from PySide6.QtWidgets import (
QApplication,
QFrame,
QHBoxLayout,
QLabel,
QPushButton,
QScrollArea,
QStackedWidget,
QVBoxLayout,
QWidget,
)
# ---------------------------------------------------------------------------
# Colour palette
# ---------------------------------------------------------------------------
BG = "#071018"
CARD_BG = "#0E1A26"
ACCENT = "#62D8C8"
ACCENT_DIM = "#1A3A36"
TEXT = "#F5F7FA"
SUBTEXT = "#8A9BB0"
BUTTON_BG = "#132131"
LED_OFF = "#1C2E3E"
LED_ON = ACCENT
ACTIVE_STEP = "#FFFFFF"
STYLE = f"""
QWidget {{
background: {BG};
color: {TEXT};
font-family: 'Inter', 'SF Pro Display', Arial, sans-serif;
font-size: 14px;
}}
QScrollArea {{
border: none;
background: transparent;
}}
QScrollBar:vertical {{
background: {CARD_BG};
width: 4px;
border-radius: 2px;
}}
QScrollBar::handle:vertical {{
background: {ACCENT_DIM};
border-radius: 2px;
min-height: 20px;
}}
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {{
height: 0px;
}}
"""
# ---------------------------------------------------------------------------
# Orbit / camera placeholder widget
# ---------------------------------------------------------------------------
class OrbitWidget(QWidget):
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.Antialiasing)
w, h = self.width(), self.height()
cx, cy = w / 2, h / 2
# Background gradient
bg = QLinearGradient(0, 0, w, h)
bg.setColorAt(0, QColor("#0D2A2C"))
bg.setColorAt(1, QColor("#0D1E2E"))
p.fillRect(self.rect(), bg)
# Corner brackets
pen = QPen(QColor(ACCENT))
pen.setWidth(2)
p.setPen(pen)
size = 28
margin = 24
for x, y, dx, dy in [
(margin, margin, 1, 1),
(w - margin, margin, -1, 1),
(margin, h - margin, 1, -1),
(w - margin, h - margin, -1, -1),
]:
p.drawLine(x, y, x + dx * size, y)
p.drawLine(x, y, x, y + dy * size)
# Orbit rings
pen.setWidth(1)
pen.setColor(QColor(ACCENT + "80")) # semi-transparent
p.setPen(pen)
for r in [38, 68, 98]:
p.drawEllipse(QPointF(cx, cy), r, r)
# Centre dot
p.setBrush(QColor(ACCENT))
p.setPen(Qt.NoPen)
p.drawEllipse(QPointF(cx, cy), 9, 9)
# Orbiting dots on outer ring
p.setBrush(QColor("#F5FFFF"))
for angle in range(0, 360, 45):
rad = math.radians(angle)
ox = cx + math.cos(rad) * 98
oy = cy + math.sin(rad) * 98
p.drawEllipse(QPointF(ox, oy), 4, 4)
# ---------------------------------------------------------------------------
# LED step indicator
# ---------------------------------------------------------------------------
class LEDStages(QWidget):
STEPS: ClassVar[list[str]] = ["Mount", "Centre", "Raster", "Collect"]
def __init__(self, active_step: int = 1, parent=None):
"""
active_step: 0-based index of the currently active step.
Steps before active_step are shown as 'done' (filled accent),
active_step is highlighted, later steps are dim.
"""
super().__init__(parent)
self._active = active_step
self.setFixedHeight(72)
def set_active_step(self, step: int):
self._active = step
self.update()
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.Antialiasing)
w = self.width()
n = len(self.STEPS)
step_w = w / n
led_r = 10
cy = 44 # vertical centre of LEDs
label_y = 16
for i, name in enumerate(self.STEPS):
cx = step_w * i + step_w / 2
# --- connector line to next step ---
if i < n - 1:
next_cx = step_w * (i + 1) + step_w / 2
line_color = QColor(ACCENT) if i < self._active else QColor(LED_OFF)
pen = QPen(line_color, 2)
p.setPen(pen)
p.drawLine(QPointF(cx + led_r + 3, cy), QPointF(next_cx - led_r - 3, cy))
# --- LED circle ---
p.setPen(Qt.NoPen)
if i < self._active:
# completed
p.setBrush(QColor(ACCENT))
p.drawEllipse(QPointF(cx, cy), led_r, led_r)
# tick mark
pen = QPen(QColor(BG), 2)
pen.setCapStyle(Qt.RoundCap)
p.setPen(pen)
p.drawLine(QPointF(cx - 4, cy), QPointF(cx - 1, cy + 3))
p.drawLine(QPointF(cx - 1, cy + 3), QPointF(cx + 4, cy - 3))
elif i == self._active:
# active — bright with glow ring
glow_pen = QPen(QColor(ACCENT + "55"), 4)
p.setPen(glow_pen)
p.setBrush(Qt.NoBrush)
p.drawEllipse(QPointF(cx, cy), led_r + 4, led_r + 4)
p.setPen(Qt.NoPen)
p.setBrush(QColor(ACTIVE_STEP))
p.drawEllipse(QPointF(cx, cy), led_r, led_r)
else:
# pending
p.setBrush(QColor(LED_OFF))
p.drawEllipse(QPointF(cx, cy), led_r, led_r)
# --- label ---
label_color = QColor(ACCENT) if i <= self._active else QColor(SUBTEXT)
p.setPen(label_color)
font = QFont("Inter", 10)
if i == self._active:
font.setWeight(QFont.Weight.DemiBold)
p.setFont(font)
fm = QFontMetrics(font)
text_w = fm.horizontalAdvance(name)
p.drawText(
QRectF(cx - text_w / 2 - 4, 0, text_w + 8, label_y + 2), Qt.AlignCenter, name
)
# ---------------------------------------------------------------------------
# Transport / control button
# ---------------------------------------------------------------------------
class ControlButton(QPushButton):
def __init__(self, symbol: str, primary: bool = False, parent=None):
super().__init__(parent)
self._symbol = symbol
self._primary = primary
self._hovered = False
size = 64 if primary else 52
self.setFixedSize(size, size)
self.setMouseTracking(True)
def enterEvent(self, event):
self._hovered = True
self.update()
def leaveEvent(self, event):
self._hovered = False
self.update()
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.Antialiasing)
rect = self.rect()
cx, cy = rect.width() / 2, rect.height() / 2
r = min(rect.width(), rect.height()) / 2 - 2
if self._primary:
if self._hovered:
p.setBrush(QColor("#FFFFFF"))
else:
p.setBrush(QColor(ACCENT))
p.setPen(Qt.NoPen)
p.drawEllipse(QPointF(cx, cy), r, r)
sym_color = QColor(BG)
else:
if self._hovered:
p.setBrush(QColor(ACCENT))
else:
p.setBrush(QColor(BUTTON_BG))
p.setPen(Qt.NoPen)
p.drawEllipse(QPointF(cx, cy), r, r)
sym_color = QColor(TEXT) if not self._hovered else QColor(BG)
p.setPen(QPen(sym_color, 2))
font = QFont("Arial", 16 if self._primary else 13)
p.setFont(font)
p.drawText(rect, Qt.AlignCenter, self._symbol)
# ---------------------------------------------------------------------------
# Queue item card
# ---------------------------------------------------------------------------
class QueueItemCard(QFrame):
def __init__(
self,
index: int | str,
title: str,
subtitle: str,
frames_done: int = 0,
frames_total: int = 0,
is_next: bool = False,
parent=None,
):
super().__init__(parent)
self._index = index
self._title = title
self._subtitle = subtitle
self._frames_done = frames_done
self._frames_total = frames_total
self._is_next = is_next
self.setFixedHeight(72)
self.setStyleSheet(f"""
QFrame {{
background: {"#112030" if is_next else "#0C1720"};
border-radius: 14px;
border: {"1px solid " + ACCENT_DIM if is_next else "none"};
}}
""")
self._build_layout()
def _build_layout(self):
layout = QHBoxLayout(self)
layout.setContentsMargins(14, 0, 14, 0)
layout.setSpacing(12)
# Index badge / play icon
badge = QLabel()
badge.setFixedSize(32, 32)
badge.setAlignment(Qt.AlignCenter)
if self._is_next:
badge.setText("▶")
badge.setStyleSheet(f"""
color: {ACCENT};
background: {ACCENT_DIM};
border-radius: 16px;
font-size: 12px;
font-weight: bold;
""")
else:
badge.setText(str(self._index))
badge.setStyleSheet(f"""
color: {SUBTEXT};
background: {BUTTON_BG};
border-radius: 16px;
font-size: 12px;
""")
layout.addWidget(badge)
# Text block
text_col = QVBoxLayout()
text_col.setSpacing(2)
text_col.setContentsMargins(0, 0, 0, 0)
title_lbl = QLabel(self._title)
title_lbl.setStyleSheet(
f"color: {TEXT}; font-size: 13px; font-weight: 600; background: transparent;"
)
sub_lbl = QLabel(self._subtitle)
sub_lbl.setStyleSheet(f"color: {SUBTEXT}; font-size: 11px; background: transparent;")
text_col.addWidget(title_lbl)
text_col.addWidget(sub_lbl)
layout.addLayout(text_col, stretch=1)
# Frame count + mini bar
right_col = QVBoxLayout()
right_col.setSpacing(4)
right_col.setContentsMargins(0, 0, 0, 0)
right_col.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
if self._frames_total > 0:
frame_lbl = QLabel(f"{self._frames_done:,} / {self._frames_total:,}")
frame_lbl.setAlignment(Qt.AlignRight)
color = ACCENT if self._is_next else SUBTEXT
frame_lbl.setStyleSheet(f"color: {color}; font-size: 11px; background: transparent;")
right_col.addWidget(frame_lbl)
bar = MiniProgressBar(self._frames_done, self._frames_total)
right_col.addWidget(bar)
layout.addLayout(right_col)
class MiniProgressBar(QWidget):
def __init__(self, done: int, total: int, parent=None):
super().__init__(parent)
self._done = done
self._total = total
self.setFixedSize(80, 4)
def paintEvent(self, event):
p = QPainter(self)
p.setRenderHint(QPainter.Antialiasing)
w, h = self.width(), self.height()
# background track
p.setBrush(QColor(LED_OFF))
p.setPen(Qt.NoPen)
p.drawRoundedRect(0, 0, w, h, 2, 2)
# fill
if self._total > 0:
fill_w = max(4, int(w * self._done / self._total))
p.setBrush(QColor(ACCENT))
p.drawRoundedRect(0, 0, fill_w, h, 2, 2)
# ---------------------------------------------------------------------------
# Main SAM Camera widget
# ---------------------------------------------------------------------------
class SampleCamera(QWidget):
def __init__(self):
super().__init__()
self.setWindowFlags(Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
self.resize(390, 860)
self.setStyleSheet(STYLE)
self._stack = QStackedWidget()
self._player_page = self._build_player()
self._queue_page = self._build_queue()
self._stack.addWidget(self._player_page)
self._stack.addWidget(self._queue_page)
root = QVBoxLayout(self)
root.setContentsMargins(12, 12, 12, 12)
root.addWidget(self._stack)
# ------------------------------------------------------------------
# Player page
# ------------------------------------------------------------------
def _build_player(self) -> QWidget:
page = QWidget()
layout = QVBoxLayout(page)
layout.setSpacing(10)
layout.setContentsMargins(0, 0, 0, 0)
# ── Title ──────────────────────────────────────────────────────
title = QLabel("S A M C A M E R A")
title.setAlignment(Qt.AlignCenter)
title.setStyleSheet(
f"color: {ACCENT}; font-size: 13px; letter-spacing: 3px; font-weight: 600;"
)
layout.addWidget(title)
# ── Camera card ────────────────────────────────────────────────
cam_card = QFrame()
cam_card.setStyleSheet(f"QFrame {{ background: {CARD_BG}; border-radius: 18px; }}")
cam_card_layout = QVBoxLayout(cam_card)
cam_card_layout.setContentsMargins(0, 0, 0, 0)
cam_card_layout.setSpacing(0)
orbit = OrbitWidget()
orbit.setMinimumHeight(220)
cam_card_layout.addWidget(orbit)
layout.addWidget(cam_card)
# ── Sample name ────────────────────────────────────────────────
name_lbl = QLabel("Crystal Plate 14 · Well C7")
name_lbl.setStyleSheet(f"color: {TEXT}; font-size: 18px; font-weight: 700;")
sub_lbl = QLabel("Serial MX · 1 kHz · Beamline X06SA")
sub_lbl.setStyleSheet(f"color: {SUBTEXT}; font-size: 12px;")
layout.addWidget(name_lbl)
layout.addWidget(sub_lbl)
# ── LED step indicator ─────────────────────────────────────────
self._leds = LEDStages(active_step=1) # 0=Mount done, 1=Centre active
layout.addWidget(self._leds)
# ── Transport controls ─────────────────────────────────────────
ctrl_frame = QFrame()
ctrl_frame.setStyleSheet(f"QFrame {{ background: {CARD_BG}; border-radius: 18px; }}")
ctrl_layout = QHBoxLayout(ctrl_frame)
ctrl_layout.setContentsMargins(16, 12, 16, 12)
ctrl_layout.setSpacing(0)
buttons = [
("⏮", False),
("⏪", False),
("⏸", True), # primary / highlighted
("⏩", False),
("⏭", False),
]
for sym, primary in buttons:
btn = ControlButton(sym, primary=primary)
ctrl_layout.addWidget(btn, alignment=Qt.AlignCenter)
if not primary:
ctrl_layout.addStretch(1)
layout.addWidget(ctrl_frame)
# ── Up next header ─────────────────────────────────────────────
up_next_row = QHBoxLayout()
up_next_lbl = QLabel("UP NEXT")
up_next_lbl.setStyleSheet(
f"color: {ACCENT}; font-size: 11px; letter-spacing: 2px; font-weight: 700;"
)
samples_lbl = QLabel("5 SAMPLES")
samples_lbl.setStyleSheet(f"color: {SUBTEXT}; font-size: 11px; letter-spacing: 1px;")
up_next_row.addWidget(up_next_lbl)
up_next_row.addStretch()
up_next_row.addWidget(samples_lbl)
layout.addLayout(up_next_row)
# ── Queue preview cards ────────────────────────────────────────
queue_items = [
("Crystal Plate 14 · Well C8", "Serial MX · 1 kHz", 4100, 6000, True),
("Crystal Plate 15 · Grid Scan", "Raster · 10 Hz", 0, 2000, False),
("Crystal Plate 13 · Well A1", "Serial MX · 1 kHz", 0, 5000, False),
("Crystal Plate 13 · Well B3", "Serial MX · 1 kHz", 0, 4500, False),
("Crystal Plate 14 · Well D5", "Serial MX · 1 kHz", 0, 6000, False),
]
queue_widget = QWidget()
queue_layout = QVBoxLayout(queue_widget)
queue_layout.setSpacing(6)
queue_layout.setContentsMargins(0, 0, 0, 0)
for i, (title, sub, done, total, is_next) in enumerate(queue_items):
card = QueueItemCard(
index="▶" if is_next else i + 1,
title=title,
subtitle=sub,
frames_done=done,
frames_total=total,
is_next=is_next,
)
queue_layout.addWidget(card)
layout.addWidget(queue_widget)
# ── View full queue button ────────────────────────────────────
view_btn = self._accent_button("VIEW FULL QUEUE ☰")
view_btn.clicked.connect(lambda: self._stack.setCurrentWidget(self._queue_page))
layout.addWidget(view_btn)
return page
# ------------------------------------------------------------------
# Queue / full list page
# ------------------------------------------------------------------
def _build_queue(self) -> QWidget:
page = QWidget()
layout = QVBoxLayout(page)
layout.setSpacing(10)
layout.setContentsMargins(0, 0, 0, 0)
title = QLabel("SAMPLE QUEUE")
title.setAlignment(Qt.AlignCenter)
title.setStyleSheet(
f"color: {ACCENT}; font-size: 13px; letter-spacing: 3px; font-weight: 700;"
)
layout.addWidget(title)
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
inner = QWidget()
inner_layout = QVBoxLayout(inner)
inner_layout.setSpacing(6)
inner_layout.setContentsMargins(0, 4, 0, 4)
for i in range(1, 20):
card = QueueItemCard(
index=i,
title=f"Crystal Plate {i} · Well C{i}",
subtitle="Serial MX · 1 kHz",
frames_done=0,
frames_total=6000,
)
inner_layout.addWidget(card)
scroll.setWidget(inner)
layout.addWidget(scroll, stretch=1)
back_btn = self._accent_button("← BACK TO CAMERA")
back_btn.clicked.connect(lambda: self._stack.setCurrentWidget(self._player_page))
layout.addWidget(back_btn)
return page
# ------------------------------------------------------------------
# Helper: styled accent button
# ------------------------------------------------------------------
@staticmethod
def _accent_button(text: str) -> QPushButton:
btn = QPushButton(text)
btn.setFixedHeight(48)
btn.setStyleSheet(f"""
QPushButton {{
background: transparent;
border: 1.5px solid {ACCENT};
border-radius: 14px;
color: {ACCENT};
font-size: 12px;
font-weight: 700;
letter-spacing: 1.5px;
}}
QPushButton:hover {{
background: {ACCENT_DIM};
}}
QPushButton:pressed {{
background: {ACCENT};
color: {BG};
}}
""")
return btn
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
def export_png():
app = QApplication.instance() or QApplication(sys.argv)
ui = SampleCamera()
ui.show()
app.processEvents()
ui._stack.setCurrentWidget(ui._player_page)
app.processEvents()
ui.grab().save("sam_camera_player.png")
ui._stack.setCurrentWidget(ui._queue_page)
app.processEvents()
ui.grab().save("sam_camera_queue.png")
if __name__ == "__main__":
app = QApplication(sys.argv)
ui = SampleCamera()
ui.show()
sys.exit(app.exec())
-299
View File
@@ -1,299 +0,0 @@
import json
from urllib.parse import quote
import requests
class PShellClient:
def __init__(self, url):
self.url = url
self.sse_event_loop_thread = None
self.subscribed_events = None
self.event_callback = None
def _get_response(self, response, is_json=True):
if response.status_code != 200:
raise RuntimeError(response.text)
return json.loads(response.text) if is_json else response.text
def _get_binary_response(self, response):
if response.status_code != 200:
raise RuntimeError(response.text)
return response.raw.read()
def get_version(self):
"""Return application version.
Args:
Returns:
String with application version.
"""
return self._get_response(requests.get(url=self.url + "/version"), False)
def get_config(self):
"""Return application configuration.
Args:
Returns:
Dictionary.
"""
return self._get_response(requests.get(url=self.url + "/config"))
def get_state(self):
"""Return application state.
Args:
Returns:
String: Invalid, Initializing,Ready, Paused, Busy, Disabled, Closing, Fault, Offline
"""
return self._get_response(requests.get(url=self.url + "/state"))
def get_logs(self):
"""Return application logs.
Args:
Returns:
List of logs.
Format of each log: [date, time, origin, level, description]
"""
return self._get_response(requests.get(url=self.url + "/logs"))
def get_history(self, index):
"""Access console command history.
Args:
index(int): Index of history entry (0 is the most recent)
Returns:
History entry
"""
return self._get_response(requests.get(url=self.url + "/history/" + str(index)), False)
def get_script(self, path):
"""Return script.
Args:
path(str): Script path (absolute or relative to script folder)
Returns:
String with file contents.
"""
return self._get_response(requests.get(url=self.url + "/script/" + str(path)), False)
def get_devices(self):
"""Return global devices.
Args:
Returns:
List of devices.
Format of each device record: [name, type, state, value, age]
"""
return self._get_response(requests.get(url=self.url + "/devices"))
def abort(self, command_id=None):
"""Abort execution of command
Args:
command_id(optional, int): id of the command to be aborted.
if None (default), aborts the foreground execution.
Returns:
"""
if command_id is None:
requests.get(url=self.url + "/abort")
else:
return requests.get(url=self.url + "/abort/" + str(command_id))
def reinit(self):
"""Reinitialize the software.
Args:
Returns:
"""
requests.get(url=self.url + "/reinit")
def stop(self):
"""Stop all devices implementing the 'Stoppable' interface.
Args:
Returns:
"""
requests.get(url=self.url + "/stop")
def update(self):
"""Update all global devices.
Args:
Returns:
"""
requests.get(url=self.url + "/update")
def eval(self, statement):
"""Evaluates a statement in the interpreter.
If the statement finishes by '&', it is executed in background.
Otherwise statement is executed in foreground (exclusive).
Args:
statement(str): input statement
Returns:
String containing the console return.
If an exception is produces in the interpretor, it is re-thrown here.
"""
statement = quote(statement)
return self._get_response(requests.get(url=self.url + "/eval/" + statement), False)
def run(self, script, pars=None, background=False):
"""Executes script in the interpreter.
Args:
script(str): name of the script (absolute or relative to the script base folder). Extension may be omitted.
pars(optional, list or dict): if a list is given, it sets sys.argv for the script.
If a dict is given, it sets global variable for the script.
background(optional, bool): if True script is executed in background.
Returns:
Return value of the script.
If an exception is produces in the interpretor, it is re-thrown here.
"""
return self._get_response(
requests.put(
url=self.url + "/run",
json={"script": script, "pars": pars, "background": background, "async": False},
)
)
def start_eval(self, statement):
"""Starts evaluation of a statement in the interpreter.
If the statement finishes by '&', it is executed in background.
Otherwise statement is executed in foreground (exclusive).
Args:
statement(str): input statement
Returns:
Command id (int), which is used to retrieve command execution status/result (get_result).
"""
statement = quote(statement)
return int(
self._get_response(requests.get(url=self.url + "/evalAsync/" + statement), False)
)
def start_run(self, script, pars=None, background=False):
"""Starts execution of a script in the interpreter.
Args:
script(str): name of the script (absolute or relative to the script base folder). Extension may be omitted.
pars(optional, list or dict): if a list is given, it sets sys.argv for the script.
If a dict is given, it sets global variable for the script.
background(optional, bool): if True script is executed in background.
Returns:
Command id (int), which is used to retrieve command execution status/result (get_result).
"""
return int(
self._get_response(
requests.put(
url=self.url + "/run",
json={"script": script, "pars": pars, "background": background, "async": True},
)
)
)
def get_result(self, command_id=-1):
"""Gets status/result of a command executed asynchronously (start_eval and start_run).
Args:
command_id(optional, int): command id. If equals to -1 (default) return status/result of the foreground task.
Returns:
Dictionary with the fields: 'id' (int): command id
'status' (str): unlaunched, invalid, removed, running, aborted, failed or completed.
'exception' (str): if status equals 'failed', holds exception string.
'return' (obj): if status equals 'completed', holds return value of script (start_run)
or console return (start_eval)
"""
return self._get_response(requests.get(url=self.url + "/result/" + str(command_id)))
def help(self, input="<builtins>"):
"""Returns help or auto-completion strings.
Args:
input(optional, str): - ":" for control commands
- "<builtins>" for builtin functions
- "devices" for device names
- builtin function name for function help
- else contains entry for auto-completion
Returns:
List
"""
return self._get_response(requests.get(url=self.url + "/autocompletion/" + input))
def get_contents(self, path=None):
"""Returns contents of data path.
Args:
path(optional, str): Path to data relative to data home path.
- Folder
- File
- File (data root) | internal path
- internal path (on currently open data root)
Returns:
List of contents
"""
return self._get_response(
requests.get(url=self.url + "/contents" + ("" if path is None else ("/" + path))), False
)
def get_data(self, path, type="txt"):
"""Returns data on a given path.
Args:
path(str): Path to data relative to data home path.
- File (data root) | internal path
- internal path (on currently open data root)
type(optional, str): txt, "json", "bin", "bs"
Returns:
Data accordind to selected format/.
"""
if type == "json":
return self._get_response(requests.get(url=self.url + "/data-json/" + path), True)
elif type == "bin":
return self._get_binary_response(
requests.get(url=self.url + "/data-bin/" + path, stream=True)
)
return self._get_response(
requests.get(url=self.url + "/data" + ("" if path is None else ("/" + path))), False
)
def print_logs(self):
for log_line in self.get_logs():
print("{} {} {:<20} {:<8} {}".format(*log_line))
def print_devices(self):
for log_line in self.get_devices():
print("{:<16} {:<32} {:<10} {:<32} {}".format(*log_line))
-124
View File
@@ -1,124 +0,0 @@
# python
import argparse
import sys
from typing import Any
import redis
import yaml
def decode_bulk(value: Any):
if isinstance(value, bytes):
try:
return value.decode("utf-8")
except UnicodeDecodeError:
return repr(value)
if isinstance(value, (list, tuple, set)):
return type(value)(decode_bulk(v) for v in value)
if isinstance(value, dict):
return {decode_bulk(k): decode_bulk(v) for k, v in value.items()}
return value
def fetch_key(r: redis.Redis, key: bytes) -> tuple[str, Any]:
decode_bulk(key)
t = r.type(key)
if isinstance(t, bytes):
t = t.decode()
if t == "string":
val = r.get(key)
return t, decode_bulk(val)
if t == "list":
# LRANGE 0 -1
vals = r.lrange(key, 0, -1)
return t, decode_bulk(vals)
if t == "set":
vals = r.smembers(key)
# sets are unordered; convert to sorted list for stable YAML
return t, sorted(decode_bulk(vals))
if t == "zset":
# Withscores=True to preserve order/score
vals = r.zrange(key, 0, -1, withscores=True)
# Represent as list of {member, score}
out = [{"member": decode_bulk(m), "score": float(s)} for m, s in vals]
return t, out
if t == "hash":
vals = r.hgetall(key)
return t, decode_bulk(vals)
# Unknown or none
return t, None
def dump_redis_to_yaml(
host: str,
port: int,
db: int,
password: str | None,
output_path: str,
match: str | None,
scan_count: int,
include_ttl: bool,
):
r = redis.Redis(host=host, port=port, db=db, password=password)
dump: dict[str, Any] = {"meta": {"host": host, "port": port, "db": db}, "data": {}}
cursor = 0
while True:
cursor, keys = r.scan(cursor=cursor, match=match, count=scan_count)
for key in keys:
key_s = decode_bulk(key)
t, val = fetch_key(r, key)
entry = {"type": t, "value": val}
if include_ttl:
ttl = r.ttl(key)
entry["ttl"] = ttl # seconds; -1 no expire, -2 key missing
dump["data"][key_s] = entry
if cursor == 0:
break
with open(output_path, "w", encoding="utf-8") as f:
yaml.safe_dump(dump, f, sort_keys=True, allow_unicode=True)
def main(argv=None):
parser = argparse.ArgumentParser(description="Dump a Redis DB to a YAML file.")
parser.add_argument("--host", default="127.0.0.1", help="Redis host")
parser.add_argument("--port", type=int, default=6379, help="Redis port")
parser.add_argument("--db", type=int, default=0, help="Redis DB index")
parser.add_argument("--password", default=None, help="Redis password")
parser.add_argument("-o", "--output", required=True, help="Output YAML file path")
parser.add_argument(
"--match",
default=None,
help="Key pattern for SCAN (e.g., 'user:*'). If omitted, all keys are scanned.",
)
parser.add_argument(
"--scan-count", type=int, default=1000, help="Hint for SCAN per iteration (not a limit)."
)
parser.add_argument(
"--include-ttl", action="store_true", help="Include TTL (seconds) for each key."
)
args = parser.parse_args(argv)
dump_redis_to_yaml(
host=args.host,
port=args.port,
db=args.db,
password=args.password,
output_path=args.output,
match=args.match,
scan_count=args.scan_count,
include_ttl=args.include_ttl,
)
if __name__ == "__main__":
sys.exit(main())
-1
View File
@@ -1 +0,0 @@
"""A single API to dispatch functions based on the current beamline"""
@@ -1,24 +0,0 @@
from aarecommon.config.beamline import MXBeamline, mx_beamline
from aare.beamline_dispatch.protocols import BeamlineDispatch
def get_beamline_dispatch() -> BeamlineDispatch:
"""Fetch the dispatch object for the beamline detected from the BEAMLINE environment variable."""
match mx_beamline():
case MXBeamline.SIMULATED:
from .simulated import SimulatedDispatch
return SimulatedDispatch()
case MXBeamline.X06DA:
from .x06da import X06daDispatch
return X06daDispatch(MXBeamline.X06DA)
case MXBeamline.X06SA:
from .x06sa import X06saDispatch
return X06saDispatch()
case MXBeamline.X10SA:
from .x10sa import X10saDispatch
return X10saDispatch(MXBeamline.X10SA)
@@ -1,3 +0,0 @@
from .beamline_dispatch import DefaultDispatch
__all__ = ["DefaultDispatch"]
@@ -1,65 +0,0 @@
import json
import os
from abc import ABC
from importlib.resources import files
from typing import Any
from aarecommon.config.beamline import MXBeamline
from aarecommon.models.beam_centre import BeamCentre
from aare.beamline_dispatch.protocols import (
AuthDispatch,
BeamCenterModel,
BeamlineDispatch,
Geometry,
)
class DefaultAuthDispatch(AuthDispatch):
def get_jwt_key(self) -> str:
if (key := os.environ.get("JWT_AAREDAQ_KEY")) is None:
raise RuntimeError(
"JWT_AAREDAQ_KEY environment variable not set, cannot guarantee safe authentication."
)
return key
class DefaultGeometry(Geometry):
def __init__(self, beamline: MXBeamline) -> None:
super().__init__()
with open(str(files("aarecommon.config") / "beamline_configs" / "beam_centres.json")) as f:
measured = json.loads(f.read())[beamline.value.lower()]
self._model = BeamCentre.model_validate(measured)
self._beamline = beamline
@property
def beam_centre_model(self) -> BeamCenterModel:
return self._model.model
class DefaultDispatch(BeamlineDispatch, ABC):
"""Default implementation for anything which can vary between beamlines and/or simulation.
Should be safe and fail rather than assuming anything."""
def __init__(
self, beamline: MXBeamline, geo_class: type[DefaultGeometry] = DefaultGeometry
) -> None:
self._auth = DefaultAuthDispatch()
self._geo = geo_class(beamline=beamline)
@property
def auth(self):
return self._auth
@property
def geo(self):
return self._geo
@property
def default_rotation_parameters(self) -> dict[str, Any]:
return {"exp_time_s": 0.04, "dtz": 110, "incr_omega_deg": 0.2}
@property
def default_auto_raster_parameters(self) -> dict[str, Any]:
"""Fixed raster parameters used by the automated measurement sequence."""
return {"exp_time_s": 0.04, "transmission": 1.0, "dtz": 200}
-72
View File
@@ -1,72 +0,0 @@
from abc import ABC, abstractmethod
from typing import Any, Protocol
import numpy as np
from numpy.typing import ArrayLike, NDArray
class AuthDispatch(ABC):
@abstractmethod
def get_jwt_key(self) -> str: ...
class BecMacros(ABC):
@staticmethod
@abstractmethod
def save_and_reload() -> tuple[Any, Any]: ...
@staticmethod
@abstractmethod
def save_current_position(device, position, axis=None, force=False, max_delta=0.5) -> None: ...
@staticmethod
@abstractmethod
def init_beamline_environment() -> tuple[Any, Any]: ...
@staticmethod
@abstractmethod
def bl_energy(energy_ev, move_gap=True, mono_scan=True, plot=True): ...
@staticmethod
@abstractmethod
def get_current_energy() -> float: ...
@staticmethod
@abstractmethod
def mono_pitch_scan(plot=True): ...
@staticmethod
@abstractmethod
def auto_exposure(): ...
@staticmethod
@abstractmethod
def full_flux_ph_per_s() -> float: ...
class BeamCenterModel(Protocol):
def predict(
self, det_z_mm: ArrayLike, det_y_mm: ArrayLike
) -> tuple[NDArray[np.float64], NDArray[np.float64]]: ...
class Geometry(ABC):
@property
@abstractmethod
def beam_centre_model(self) -> BeamCenterModel: ...
@property
@abstractmethod
def detector_tilt(self) -> tuple[float, float]:
"""A tuple of PONI rot1 and rot2 in radians"""
class BeamlineDispatch(ABC):
@property
@abstractmethod
def auth(self) -> AuthDispatch: ...
@property
@abstractmethod
def bec_macros(self) -> BecMacros: ...
@property
@abstractmethod
def geo(self) -> Geometry: ...
@property
@abstractmethod
def default_rotation_parameters(self) -> dict[str, Any]: ...
@property
@abstractmethod
def default_auto_raster_parameters(self) -> dict[str, Any]: ...
@@ -1,3 +0,0 @@
from .beamline_dispatch import SimulatedDispatch
__all__ = ["SimulatedDispatch"]
@@ -1,43 +0,0 @@
from typing import Any
from aare.beamline_dispatch.default.beamline_dispatch import DefaultDispatch
from aare.beamline_dispatch.protocols import AuthDispatch, BecMacros
class SimulatedAuthDispatch(AuthDispatch):
def get_jwt_key(self) -> str:
return "Ns93ijN8VHv4ybvXaGNEDKUb3Sif4m4MYpfcEBIcs1h"
class SimulatedBecMacros(BecMacros):
@staticmethod
def save_and_reload() -> tuple[Any, Any]:
return (None, None)
@staticmethod
def save_current_position(device, position, axis=None, force=False, max_delta=0.5) -> None: ...
@staticmethod
def init_beamline_environment() -> tuple[Any, Any]:
return (None, None)
@staticmethod
def bl_energy(energy_ev, move_gap=True, mono_scan=True, plot=True): ...
@staticmethod
def get_current_energy(): ...
@staticmethod
def mono_pitch_scan(plot=True): ...
@staticmethod
def auto_exposure(): ...
@staticmethod
def full_flux_ph_per_s() -> float:
return 42
class SimulatedDispatch(DefaultDispatch):
def __init__(self) -> None:
self._auth = SimulatedAuthDispatch()
self._bec_macros = SimulatedBecMacros()
@property
def bec_macros(self):
return self._bec_macros
@@ -1,3 +0,0 @@
from .beamline_dispatch import X06daDispatch
__all__ = ["X06daDispatch"]
@@ -1,119 +0,0 @@
from typing import Any
import numpy as np
from aarecommon.config.beamline import MXBeamline
from aare.beamline_dispatch.default.beamline_dispatch import DefaultDispatch, DefaultGeometry
from aare.beamline_dispatch.protocols import BecMacros
# fmt: off
FLUX_ENERGY_KEV = np.asarray([
4.0, 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9,
5.0, 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 5.9,
6.0, 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7, 6.8, 6.9,
7.0, 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.8, 7.9,
8.0, 8.1, 8.2, 8.3, 8.4, 8.5, 8.6, 8.7, 8.8, 8.9,
9.0, 9.1, 9.2, 9.3, 9.4, 9.5, 9.6, 9.7, 9.8, 9.9,
10.0, 10.1, 10.2, 10.3, 10.4, 10.5, 10.6, 10.7, 10.8, 10.9,
11.0, 11.1, 11.2, 11.3, 11.4, 11.5, 11.6, 11.7, 11.8, 11.9,
12.0, 12.1, 12.2, 12.3, 12.4, 12.5, 12.6, 12.7, 12.8, 12.9,
13.0, 13.1, 13.2, 13.3, 13.4, 13.5, 13.6, 13.7, 13.8, 13.9,
14.0, 14.1, 14.2, 14.3, 14.4, 14.5, 14.6, 14.7, 14.8, 14.9,
15.0,
], dtype=np.float64)
FLUX_PH_S = np.asarray([
9.6319e+09, 1.2625e+10, 1.6152e+10, 2.0210e+10, 2.4794e+10, 2.9898e+10,
3.5492e+10, 4.1577e+10, 4.8186e+10, 5.5296e+10, 6.2874e+10, 7.0892e+10,
7.9292e+10, 8.8026e+10, 9.7061e+10, 1.0637e+11, 1.1587e+11, 1.2552e+11,
1.3528e+11, 1.4509e+11, 1.5000e+11, 1.5959e+11, 1.6925e+11, 1.7890e+11,
1.8852e+11, 1.9807e+11, 2.0754e+11, 2.1689e+11, 2.2610e+11, 2.3520e+11,
2.4416e+11, 2.5294e+11, 2.6151e+11, 2.6986e+11, 2.7799e+11, 2.8587e+11,
2.9352e+11, 3.0091e+11, 3.0810e+11, 3.1506e+11, 3.2177e+11, 3.2830e+11,
3.3458e+11, 3.4061e+11, 3.4640e+11, 3.5196e+11, 3.5730e+11, 3.6243e+11,
3.6743e+11, 3.7225e+11, 3.7690e+11, 3.8139e+11, 3.8574e+11, 3.8994e+11,
3.9402e+11, 3.9798e+11, 4.0182e+11, 4.0554e+11, 4.0914e+11, 4.1265e+11,
4.1598e+11, 4.1920e+11, 4.2220e+11, 4.2496e+11, 4.2743e+11, 4.2962e+11,
4.3149e+11, 4.3304e+11, 4.3427e+11, 4.3518e+11, 4.3579e+11, 4.3613e+11,
4.3620e+11, 4.3598e+11, 4.3551e+11, 4.3478e+11, 4.3381e+11, 4.3260e+11,
4.3116e+11, 4.2949e+11, 4.2760e+11, 4.2549e+11, 4.2315e+11, 4.2058e+11,
4.1780e+11, 4.1477e+11, 4.1150e+11, 4.0795e+11, 4.0413e+11, 4.0000e+11,
3.9555e+11, 3.9075e+11, 3.8557e+11, 3.7995e+11, 3.7386e+11, 3.6722e+11,
3.5995e+11, 3.5196e+11, 3.4312e+11, 3.3325e+11, 3.2213e+11, 3.0944e+11,
2.9474e+11, 2.7742e+11, 2.5658e+11, 2.3096e+11, 1.9893e+11, 1.5947e+11,
1.1576e+11, 7.7492e+10, 5.0923e+10,
], dtype=np.float64)
# fmt: on
class X06daBecMacros(BecMacros):
def __init__(self) -> None:
from pxiii_bec.macros.build_devices import save_and_reload, save_current_position # pyright: ignore[reportMissingImports, reportMissingModuleSource]
from pxiii_bec.macros.init_beamline import init_beamline_environment # pyright: ignore[reportMissingImports, reportMissingModuleSource]
from pxiii_bec.macros.katscripts import auto_exposure # pyright: ignore[reportMissingImports, reportMissingModuleSource]
from pxiii_bec.macros.pxiii_energy import bl_energy, get_current_energy, mono_pitch_scan # pyright: ignore[reportMissingImports, reportMissingModuleSource]
self.save_and_reload = save_and_reload
self.save_current_position = save_current_position
self.init_beamline_environment = init_beamline_environment
def _bl_energy(energy_ev, move_gap=True, mono_scan=True, plot=True):
return bl_energy(energy_ev=energy_ev, plot=plot)
self.bl_energy = _bl_energy
self.get_current_energy = get_current_energy
self.mono_pitch_scan = mono_pitch_scan
self.auto_exposure = auto_exposure
def full_flux_ph_per_s():
current_energy_kev = self.get_current_energy() / 1000
idx = (np.abs(FLUX_ENERGY_KEV - current_energy_kev)).argmin()
if idx < len(FLUX_PH_S):
return float(FLUX_PH_S[idx])
return 0
self.full_flux_ph_per_s = full_flux_ph_per_s
@staticmethod
def save_and_reload() -> tuple[Any, Any]: ...
@staticmethod
def save_current_position(device, position, axis=None, force=False, max_delta=0.5) -> None: ...
@staticmethod
def init_beamline_environment() -> tuple[Any, Any]: ...
@staticmethod
def bl_energy(energy_ev, move_gap=True, mono_scan=True, plot=True): ...
@staticmethod
def get_current_energy() -> float: ...
@staticmethod
def mono_pitch_scan(plot=True): ...
@staticmethod
def auto_exposure(): ...
@staticmethod
def full_flux_ph_per_s() -> float: ...
class X06daGeometry(DefaultGeometry):
@property
def detector_tilt(self) -> tuple[float, float]:
poni_rot1_rad = -0.001396263
poni_rot2_rad = -0.003839724
return poni_rot1_rad, poni_rot2_rad
class X06daDispatch(DefaultDispatch):
def __init__(self, beamline: MXBeamline) -> None:
super().__init__(beamline=beamline, geo_class=X06daGeometry)
self._bec_macros = X06daBecMacros()
@property
def bec_macros(self) -> BecMacros:
return self._bec_macros
@property
def default_rotation_parameters(self) -> dict[str, Any]:
default = super().default_rotation_parameters
return default | {"transmission": 1.0}
@property
def default_auto_raster_parameters(self) -> dict[str, Any]:
return {"exp_time_s": 0.04, "transmission": 1.0, "dtz": 150}
@@ -1,3 +0,0 @@
from .beamline_dispatch import X06saDispatch
__all__ = ["X06saDispatch"]
@@ -1,4 +0,0 @@
from aare.beamline_dispatch.default.beamline_dispatch import DefaultDispatch
class X06saDispatch(DefaultDispatch): ...
@@ -1,3 +0,0 @@
from .beamline_dispatch import X10saDispatch
__all__ = ["X10saDispatch"]
@@ -1,10 +0,0 @@
{
"det_z": [190, 200, 250, 300, 350, 400, 450, 500, 550],
"center_x": [
2081.3, 2081.37, 2081.29, 2081.81, 2081.51, 2080.22, 2079.81, 2080.24,
2078.89
],
"center_y": [
2242.0, 2242.99, 2242.72, 2242.05, 2241.46, 2240.96, 2239.9, 2239.8, 2238.23
]
}
@@ -1,121 +0,0 @@
import json
from importlib.resources import files
from typing import Any
import numpy as np
from aarecommon.config.beamline import MXBeamline
from numpy.typing import ArrayLike, NDArray
from aare.beamline_dispatch.default.beamline_dispatch import (
BeamCenterModel,
DefaultDispatch,
DefaultGeometry,
)
from aare.beamline_dispatch.protocols import BecMacros
class X10SaBecMacros(BecMacros):
def __init__(self) -> None:
from pxii_bec.macros.build_devices import save_and_reload, save_current_position # pyright: ignore[reportMissingImports, reportMissingModuleSource]
from pxii_bec.macros.flux_macros import bpm2flux # pyright: ignore[reportMissingImports, reportMissingModuleSource]
from pxii_bec.macros.pxii_energy import bl_energy, get_current_energy, mono_pitch_scan # pyright: ignore[reportMissingImports, reportMissingModuleSource]
from pxii_bec.macros.pxii_setup import auto_exposure # pyright: ignore[reportMissingImports, reportMissingModuleSource]
from pxii_bec.scripts.init_beamline import init_beamline_environment # pyright: ignore[reportMissingImports, reportMissingModuleSource]
def _save_and_reload():
save_and_reload()
_, planner, devices = init_beamline_environment()
return planner, devices
def _init_beamline_environment():
_, planner, devices = init_beamline_environment()
return planner, devices
self.save_and_reload = _save_and_reload
self.save_current_position = save_current_position
self.init_beamline_environment = _init_beamline_environment
self.bl_energy = bl_energy
self.get_current_energy = get_current_energy
self.mono_pitch_scan = mono_pitch_scan
def _auto_exposure():
auto_exposure()
self.auto_exposure = _auto_exposure
def full_flux_ph_per_s():
return bpm2flux()[1]
self.full_flux_ph_per_s = full_flux_ph_per_s
@staticmethod
def save_and_reload() -> tuple[Any, Any]: ...
@staticmethod
def save_current_position(device, position, axis=None, force=False, max_delta=0.5) -> None: ...
@staticmethod
def init_beamline_environment() -> tuple[Any, Any]: ...
@staticmethod
def bl_energy(energy_ev, move_gap=True, mono_scan=True, plot=True): ...
@staticmethod
def get_current_energy() -> float: ...
@staticmethod
def mono_pitch_scan(plot=True): ...
@staticmethod
def auto_exposure(): ...
@staticmethod
def full_flux_ph_per_s() -> float: ...
class _1dModel(BeamCenterModel):
def __init__(self, x_fit: NDArray[np.float64], y_fit: NDArray[np.float64]) -> None:
self._x_fit = x_fit
self._y_fit = y_fit
def predict(
self, det_z_mm: ArrayLike, det_y_mm: ArrayLike
) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
y_offset_px = (det_y_mm * 1000.0) / 75
return (
np.asarray([self._x_fit[1] + self._x_fit[0] * det_z_mm]),
# positive offset means detector height increased -> beam lower on image -> higher pixel number
np.asarray([(self._y_fit[1] + self._y_fit[0] * det_z_mm) + y_offset_px]),
)
class X10saGeometry(DefaultGeometry):
def __init__(self, beamline: MXBeamline) -> None:
super().__init__(beamline)
with open(str(files("aare.beamline_dispatch.x10sa") / "beam_centers.json")) as f:
data = json.loads(f.read())
x_fit = np.polyfit(data["det_z"], data["center_x"], 1)
y_fit = np.polyfit(data["det_z"], data["center_y"], 1)
self._model = _1dModel(x_fit, y_fit)
self._beamline = beamline
@property
def beam_centre_model(self) -> BeamCenterModel:
return self._model
@property
def detector_tilt(self) -> tuple[float, float]:
return 0, 0
class X10saDispatch(DefaultDispatch):
def __init__(self, beamline: MXBeamline) -> None:
super().__init__(beamline=beamline, geo_class=X10saGeometry)
self._bec_macros = X10SaBecMacros()
@property
def bec_macros(self) -> BecMacros:
return self._bec_macros
@property
def default_rotation_parameters(self) -> dict[str, Any]:
default = super().default_rotation_parameters
return default | {"transmission": 0.1}
@property
def default_auto_raster_parameters(self) -> dict[str, Any]:
# Full transmission for 20 keV rastering
return {"exp_time_s": 0.02, "transmission": 0.1, "dtz": 200}
-33
View File
@@ -1,33 +0,0 @@
import cv2
import numpy as np
def calculate_focus_measure(
image: np.ndarray, center_x: float, center_y: float, radius: float
) -> float:
"""
Calculate the focus measure within a circular region around a point.
Args:
image: Input image
center_x: X coordinate of the center point
center_y: Y coordinate of the center point
radius: Radius of the circular region to analyze
Returns:
Focus measure value (higher means more in focus)
"""
if len(image.shape) > 2:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
else:
gray = image
# Create a circular mask
height, width = gray.shape
y, x = np.ogrid[:height, :width]
mask = (x - center_x) ** 2 + (y - center_y) ** 2 <= radius**2
# Apply Laplacian operator
laplacian = cv2.Laplacian(gray, cv2.CV_64F)
# Apply mask and calculate variance of only the circular region
return laplacian[mask].var()
-85
View File
@@ -1,85 +0,0 @@
import cv2
import numpy as np
from scipy.optimize import curve_fit
class Gaussian2Dfit:
center_x: float
center_y: float
sigma_x: float
sigma_y: float
rotation_angle: float
peak_intensity: float
def gaussian_2d(xy, x0, y0, sigma_x, sigma_y, theta, A, offset):
x, y = xy
x_rot = (x - x0) * np.cos(theta) + (y - y0) * np.sin(theta)
y_rot = -(x - x0) * np.sin(theta) + (y - y0) * np.cos(theta)
gaussian = A * np.exp(-(x_rot**2 / (2 * sigma_x**2) + y_rot**2 / (2 * sigma_y**2))) + offset
return gaussian.ravel()
def beamcenter_fit(image: np.ndarray) -> Gaussian2Dfit:
"""
Takes a np.ndarray image and returns a Gaussian2Dfit object containing the fitted parameters
Returns None if the fit did not converge
Returns center_x, center_y, sigma_x, sigma_y, rotation_angle, peak_intensity if success
"""
# Preprocess the image
blurred_image = cv2.GaussianBlur(image, (5, 5), 0)
normalized_image = cv2.normalize(
blurred_image, None, 0, 255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U
)
# Threshold to isolate the brightest spot (main blob)
_, binary_mask = cv2.threshold(normalized_image, 180, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(binary_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
largest_contour = max(contours, key=cv2.contourArea)
# Extract bounding box of the ROI
x, y, w, h = cv2.boundingRect(largest_contour)
# Enlarge the bounding box to enclose the whole spot
enlargement_factor = 2 # Increase bounding box by 50%
new_x = max(0, int(x - w * enlargement_factor // 2))
new_y = max(0, int(y - h * enlargement_factor // 2))
new_w = min(image.shape[1] - new_x, int(w * (1 + enlargement_factor)))
new_h = min(image.shape[0] - new_y, int(h * (1 + enlargement_factor)))
# Update the ROI
roi = normalized_image[new_y : new_y + new_h, new_x : new_x + new_w]
# Fit the 2D Gaussian
X, Y = np.meshgrid(np.arange(roi.shape[1]), np.arange(roi.shape[0]))
xy = (X, Y)
# Initial guess for Gaussian parameters
initial_guess = (
new_w / 2, # x0
new_h / 2, # y0
new_w / 4, # sigma_x
new_h / 4, # sigma_y
0, # theta
np.max(roi), # A (peak intensity)
np.min(roi), # offset
)
# Flatten ROI for curve fitting
roi_flat = roi.ravel()
try:
popt, _ = curve_fit(gaussian_2d, xy, roi_flat, p0=initial_guess)
except RuntimeError as e:
print(f"Error: Gaussian fitting did not converge: {e}")
return None
# Extract fitted parameters
x0, y0, sigma_x, sigma_y, ini_theta, intensity, _ = popt
result = Gaussian2Dfit()
result.center_x = x0 + new_x
result.center_y = y0 + new_y
result.sigma_x = sigma_x
result.sigma_y = sigma_y
result.rotation_angle = np.degrees(ini_theta) % 360
result.peak_intensity = intensity
return result
File diff suppressed because it is too large. Load diff
-30
View File
@@ -1,30 +0,0 @@
from pydantic import BaseModel, Field
class LocalContactConfigModel(BaseModel):
mount_to_center_sleep_s: float = Field(
default=0.0,
ge=0.0,
le=120.0,
description="Delay after mount and before loop centering, in seconds.",
)
line_scan_loop_face_y_padding_fraction_each_side: float = Field(
default=0.5,
ge=0.0,
le=5.0,
description=(
"Second auto-center line-scan Y padding fraction per side when "
"the ML prediction is loop_face. 0.5 means add 50% of the detected "
"cell count above and below, making the scan 200% of the detected height."
),
)
line_scan_loop_all_y_padding_fraction_each_side: float = Field(
default=0.5,
ge=0.0,
le=5.0,
description=(
"Second auto-center line-scan Y padding fraction per side when "
"the ML prediction is loop_all. 0.5 means add 50% of the detected "
"cell count above and below."
),
)
-3308
View File
File diff suppressed because it is too large. Load diff
-377
View File
@@ -1,377 +0,0 @@
# Abstractions of devices for beamline
import time
from aarecommon.config.beamline import cfg_get
from aarecommon.config.logger import setup_logger
from aarecommon.config.logger_events import log_timing
from aarecommon.config.util import suppress_output
from aarecommon.math.coordinate import AerotechCoordinate, SmargonCoordinate
from aarecommon.models.beamline import MXBeamline
from aarecommon.models.models import BeamlineStateEnum, SampleCameraSettings, StagePositionEnum
from epics import PV
# Each "standard" device needs three elements:
# - property to read device value
# - setter with option to do sync/async move
# - property setter, which assumes that sync move is done (excl. zoom, which is async by default)
from aare.beamline_dispatch.protocols import BeamlineDispatch
from aare.daq.config import BeamlineConfig
from aare.devices import aerotech, smargon
from aare.devices.area_detector import AutoEnum, epicsAD
from aare.devices.bec_worker import BECClientWorker
from aare.devices.enum_pv import EnumPV
from aare.devices.experimental_hutch_shutter import ExperimentalHutchShutter
from aare.devices.my_motor import MyMotor
from aare.devices.pss_state import PssState
from aare.devices.set_get_pv import PredefinedPV, SetGetPV
from aare.devices.tell_client import make_tell_client
logger = setup_logger("aareDAQ")
CHI_ZERO_TOLERANCE_DEG = 1e-3
class BeamlineDevices:
def __init__(self, beamline: MXBeamline, dispatch: BeamlineDispatch, cfg: BeamlineConfig):
self._cfg = cfg
self._dispatch = dispatch
self._beamline = beamline
BEAMLINE = beamline.value.upper()
self.tell = make_tell_client(beamline)
self.aerotech = aerotech.AerotechController(beamline)
self.bec_worker = BECClientWorker(beamline, cfg=self._cfg)
self._smargon = smargon.Smargon(beamline)
self.exp_shutter = ExperimentalHutchShutter(beamline=self._beamline)
# Personnel Safety System: gates whether the robot is allowed to move.
self.pss = PssState(beamline=self._beamline)
# faster to define the dtz object here than in functions and then use
self._dtz = self.bec_worker.dev.det_z
self._dty = self.bec_worker.dev.det_y
self.dtz_mod = cfg_get("daq.detector_distance_limit_modifier", 1.0)
# TODO convert epics pvs to BEC
self._sample_cam = epicsAD(f"{BEAMLINE}-ES-MS:")
self._front_light = PredefinedPV(
name="front_light",
setpv=f"{BEAMLINE}-ES-FL:SET",
getpv=f"{BEAMLINE}-ES-FL:SET",
predefs={"off": 1.49, "half": 2.0, "max": 3.0},
timeout=10.0,
)
self._back_light = PredefinedPV(
name="back_light",
setpv=f"{BEAMLINE}-ES-BL:SET",
getpv=f"{BEAMLINE}-ES-BL:SET",
predefs={"off": 0, "half": 0.98, "max": 1.2},
timeout=10.0,
)
# self._front_light = self.bec_worker.dev.fl_bright # need wrapper on bec_worker layer
# self._back_light = self.bec_worker.dev.bl_bright #need wrapper on bec_worker layer
self._back_light_pos = EnumPV(
name="back_light_pos",
setpv=f"{BEAMLINE}-ES-BL:POS-SET",
getpv=f"{BEAMLINE}-ES-BL:POS-GET",
timeout=10.0,
)
self._ringcurrent = self.bec_worker.ring_current
self._zoom = SetGetPV(
name="zoom", setpv=f"{BEAMLINE}-ES-MS:ZOOM.VAL", getpv=f"{BEAMLINE}-ES-MS:ZOOM.RBV"
)
self._cryojet_pos = EnumPV(
name="cryojet_pos",
setpv=f"{BEAMLINE}-ES-CS:POS-SET",
getpv=f"{BEAMLINE}-ES-CS:POS-GET",
timeout=10.0,
)
self._cryojet_x = MyMotor(f"{BEAMLINE}-ES-CS:TRX") # currently in is 5 out is 15?
self._cryojet_temperature_get = PV(f"{BEAMLINE}-ES-CS:TEMP_RBV")
self._cryojet_temperature_set = PV(f"{BEAMLINE}-ES-CS:TEMP.VAL")
if self._beamline == MXBeamline.X06DA:
self._transmission = SetGetPV(
name="transmission",
setpv=f"{BEAMLINE}-ES-BCFI:TRANSM-SET",
getpv=f"{BEAMLINE}-ES-BCFI:TRANSM-GET",
)
else:
self._transmission = SetGetPV(
name="transmission",
setpv=f"{BEAMLINE}-ES-SSFI:TRANSM-SET",
getpv=f"{BEAMLINE}-ES-SSFI:TRANSM-GET",
)
self._fast_shutter = PV(f"{BEAMLINE}-ES-SHUTTER:SET")
self.magnet_position_sensor = PV(f"{BEAMLINE}-ES-DFS:CBOX-CMP1")
self.magnet_position_sensor_readout = PV(f"{BEAMLINE}-ES-DFS:CBOX-USER1")
# self.magnet_position_sensor_readout = PV(f"{BEAMLINE}-ES-DFS:CBOX-REFVAL1")
self.magnet_position_sensor_state = PV(f"{BEAMLINE}-ES-DFS:CBOX-STATE")
def restart_bec_worker(self, simulated: bool = False) -> None:
try:
if getattr(self, "bec_worker", None) is not None and not simulated:
try:
self.bec_worker.shutdown_client()
except Exception as e:
logger.warning(
f"Failed to shutdown previous BEC worker cleanly: {e}", exc_info=True
)
finally:
beamline = MXBeamline.SIMULATED if simulated else self._beamline
logger.info(f"Restarting BEC worker with simulated={simulated}")
self.bec_worker = BECClientWorker(beamline, cfg=self._cfg)
def restart_tell(self, simulated: bool = False) -> None:
beamline = MXBeamline.SIMULATED if simulated else self._beamline
logger.info(f"Restarting TELL client with simulated={simulated}")
self.tell = make_tell_client(beamline)
def restart_aerotech(self, simulated: bool = False) -> None:
beamline = MXBeamline.SIMULATED if simulated else self._beamline
logger.info(f"Restarting Aerotech controller with simulated={simulated}")
self.aerotech = aerotech.AerotechController(beamline)
def restart_smargon(self, simulated: bool = False) -> None:
beamline = MXBeamline.SIMULATED if simulated else self._beamline
logger.info(f"Restarting Smargon controller with simulated={simulated}")
self._smargon = smargon.Smargon(beamline)
# Transmission
@property
def transmission(self) -> float:
return self._transmission.value
@transmission.setter
def transmission(self, value: float):
self.set_transmission(value, wait=False)
def set_transmission(self, value: float, /, wait: bool = True):
logger.warning("Setting Transmission is untested")
self._transmission.move(value, wait=wait)
# Lamp light
@property
def lamp_light(self) -> float:
return self._front_light.value
@property
def detector_beam_centre_px(self) -> tuple[float, float]:
beam_center_x, beam_center_y = self._dispatch.geo.beam_centre_model.predict(
self.dtz, self.dty
)
return float(beam_center_x[0]), float(beam_center_y[0])
@lamp_light.setter
def lamp_light(self, v: float):
self.set_front_light(v, wait=False)
def set_front_light(self, v: float, /, wait: bool = True):
self._front_light.move(v, wait=wait)
# Back light
@property
def back_light(self) -> float:
return self._back_light.value
@back_light.setter
def back_light(self, v: float):
self.set_back_light(v, wait=False)
def set_back_light(self, v: float, /, wait: bool = True):
self._back_light.move(v, wait=wait)
# Zoom
@property
def zoom(self) -> float:
return self._zoom.value
@zoom.setter
def zoom(self, value: float):
self.set_zoom(value, wait=True)
def set_zoom(self, value: float, /, wait: bool = True):
self._zoom.move(value, wait=wait)
self._cfg.current_zoom_level = value
# Optics
@property
def energy_kev(self) -> float:
return self.bec_worker.check_current_energy()
@property
def ring_current(self) -> float:
return max(0.0, self.bec_worker.ring_current)
@property
def flux(self) -> float:
return self.transmission * self.full_flux
@property
def full_flux(self) -> float:
try:
with suppress_output():
return self._dispatch.bec_macros.full_flux_ph_per_s()
except Exception as e: # noqa
logger.error(f"Could not get flux from BEC macro {e}")
return 9.99e12
# Cryojet
@property
def cryojet_temp(self) -> float:
return self._cryojet_temperature_get.get()
def anneal(self, wait_time: float):
logger.warning("Untested annealing procedure, use with caution")
logger.info(f"Annealing for {wait_time} seconds")
self.tell.anneal_in()
time.sleep(wait_time)
self.tell.anneal_out()
@property
def cryojet_pos(self) -> StagePositionEnum:
return StagePositionEnum(self._cryojet_pos.position.upper())
@cryojet_pos.setter
def cryojet_pos(self, value: StagePositionEnum):
self.cryojet_pos_setter(value, wait=True)
def cryojet_pos_setter(self, value: StagePositionEnum, wait: bool = False):
self._cryojet_pos.move(value, wait=wait)
# Shutter
@property
def shutter(self) -> bool:
return self._fast_shutter.get()
@shutter.setter
def shutter(self, opened: bool):
self._fast_shutter.put(opened)
# Sample camera
@property
def samcam_settings(self) -> SampleCameraSettings:
return SampleCameraSettings(
gain=self._sample_cam.gain_rbv.value, exposure=self._sample_cam.expo_rbv.value
)
@samcam_settings.setter
def samcam_settings(self, settings: SampleCameraSettings):
self._sample_cam.setup(settings.gain, settings.exposure)
@log_timing(logger, "auto exposure of camera")
def samcam_auto(self, state: AutoEnum):
self._sample_cam.set_auto(state)
def samcam_frame_id(self) -> int:
"""
Camera UniqueId for the last produced frame (monotonic counter from AreaDetector).
"""
return int(self._sample_cam.uid.get())
# Detector Z
@property
def dtz(self) -> float:
return self._dtz.user_setpoint.get(cached=True)
@property
def dty(self) -> float:
return self._dty.user_setpoint.get(cached=True)
@dtz.setter
def dtz(self, value: float):
self.set_dtz(value, wait=True)
def set_dtz(self, value: float, /, wait: bool = True):
if value < self._dtz.low_limit:
# raise ValueError(f"Detector distance cannot be less than {self.detector_distance_minimum} mm")
logger.warning(
f"Requested detector distance {value} is less than minimum: {self._dtz.low_limit}, setting to minimum"
)
value = self._dtz.low_limit + self.dtz_mod
if value > self._dtz.high_limit:
logger.warning(
f"Requested detector distance {value} is greater than maximum: {self._dtz.high_limit}, setting to maximum"
)
value = self._dtz.high_limit - self.dtz_mod
if wait:
status = self.bec_worker.det_z(value, timeout=60)
return status
else:
status = self.bec_worker.det_z(value)
return status
@property
def dtz_low(self) -> float:
logger.info(f"dtz_low: {self._dtz.low_limit}")
return self._dtz.low_limit
@property
def dtz_high(self) -> float:
logger.info(f"dtz_high: {self._dtz.high_limit}")
return self._dtz.high_limit
@property
def aerotech_pos(self) -> AerotechCoordinate:
# TODO add u/omega????
return self.aerotech.get_position()
@aerotech_pos.setter
def aerotech_pos(
self, coord: AerotechCoordinate, /, wait: bool = True, incremental: bool = False
):
self.aerotech.position(coord, wait=wait, incremental=incremental)
@property
def aerotech_omega(self) -> float:
return self.aerotech.status().u.pos
@aerotech_omega.setter
def aerotech_omega(self, val: float):
self.set_aerotech_omega(val, wait=True)
def set_aerotech_omega(self, val: float, /, wait: bool = True, incremental: bool = False):
target = AerotechCoordinate(omega_deg=val)
return self.aerotech.position(target, wait=wait, incremental=incremental)
def aerotech_stop(self):
# TODO link cancel in GUI to cancel in aerotech if not already done
pass
# Smargon goniometer
@property
def smargon_pos(self) -> SmargonCoordinate:
return self._smargon.readback
def set_smargon_pos(self, pos: SmargonCoordinate, /, wait: bool = True):
# TELL air blower must be off before chi leaves zero
if pos.chi_deg is not None and abs(pos.chi_deg) > CHI_ZERO_TOLERANCE_DEG:
logger.info(f"Switching TELL blower off before moving chi to {pos.chi_deg:.3f} deg")
self.tell.blower_off()
self._smargon.target = pos
@smargon_pos.setter
def smargon_pos(self, pos: SmargonCoordinate):
self.set_smargon_pos(pos, wait=True)
def smargon_wait(self, timeout: float = 10.0):
self._smargon.wait(timeout=timeout)
def smargon_move_home(self):
self._smargon.move_home(wait=True)
def smargon_aerotech_wait(self):
self._smargon.wait_aerotech(timeout=10.0)
def smargon_initialize(self):
self._smargon.initialize()
def read_current_state_from_bec(self) -> BeamlineStateEnum:
return self.bec_worker.read_current_state()
-677
View File
@@ -1,677 +0,0 @@
import time
from collections.abc import Iterable
from dataclasses import dataclass, field
import cv2
import numpy as np
from aarecommon.config.logger import setup_logger
from aarecommon.config.logger_events import log_timing
from aarecommon.models.beamline import MXBeamline
from aarecommon.models.models import BoundingBoxModel, MLBoxModel, MLBoxType, MLOutputModel
from aarelcinfer_client.models import LatestPredictionModel
logger = setup_logger("aareDAQ")
@dataclass
class MLBundleMeta:
target_point: tuple[float, float] | None = None
focus: float | None = None
@dataclass
class MLBoxPredictionResult:
box: MLBoxModel | None
image: np.ndarray | None
target_point: tuple[float, float] | None = None
focus: float | None = None
@dataclass
class MLBoxPredictionsResult:
predictions: MLOutputModel | None
image: np.ndarray | None
target_point: tuple[float, float] | None = None
focus: float | None = None
@dataclass
class MLBundle:
predictions: MLOutputModel | None = None
image: np.ndarray | None = None
bundle_meta: MLBundleMeta = field(default_factory=MLBundleMeta)
class MlBox:
RETRY_COUNT = 3
RETRY_SLEEP_S = 0.1
def __init__(self, bl: MXBeamline, wrapper=None):
"""
wrapper:
Optional injected inference wrapper for tests.
If None, the production wrapper is created lazily.
"""
self._beamline = bl
if wrapper is not None:
self._wrapper = wrapper
return
if bl == MXBeamline.SIMULATED:
raise NotImplementedError(f"MLBox bundle mode not implemented for {bl}")
elif bl == MXBeamline.X06DA:
from aarecommon.lc_infer_wrapper import AareLCInferWrapper
self._wrapper = AareLCInferWrapper(bl)
elif bl == MXBeamline.X10SA:
# Lazy import keeps module importable without external client installed
from aarecommon.lc_infer_wrapper import AareLCInferWrapper
self._wrapper = AareLCInferWrapper(bl)
elif bl == MXBeamline.X06SA:
raise NotImplementedError(f"MLBox bundle mode not implemented for {bl}")
else:
raise ValueError(f"unknown beamline {bl}")
@staticmethod
def _decode_bundle_image(jpeg_bytes: bytes | None) -> np.ndarray | None:
if not jpeg_bytes:
return None
try:
encoded = np.frombuffer(jpeg_bytes, dtype=np.uint8)
image = cv2.imdecode(encoded, cv2.IMREAD_COLOR)
if image is None:
logger.warning(
"Failed to decode prediction bundle image: cv2.imdecode returned None"
)
return None
return image
except Exception as e:
logger.warning(f"Failed to decode prediction bundle image: {e}", exc_info=True)
return None
@staticmethod
def _coerce_prediction_metadata(metadata) -> LatestPredictionModel | None:
if metadata is None:
return None
try:
if isinstance(metadata, LatestPredictionModel):
return metadata
if isinstance(metadata, dict):
return LatestPredictionModel.model_validate(metadata)
return LatestPredictionModel.model_validate(metadata.model_dump())
except Exception as e:
logger.warning(f"Failed to validate prediction metadata: {e}", exc_info=True)
return None
@staticmethod
def _prediction_score(predictions: MLOutputModel | None) -> tuple[int, float]:
if predictions is None or not predictions.boxes:
return (0, 0.0)
confs = [float(m.conf or 0.0) for m in predictions.boxes.values() if m is not None]
return (len(confs), max(confs) if confs else 0.0)
def _fetch_prediction_bundle(self):
last_error = None
for attempt in range(1, self.RETRY_COUNT + 1):
try:
bundle = self._wrapper.get_latest_prediction_bundle()
logger.debug(f"Fetched prediction bundle on attempt {attempt}/{self.RETRY_COUNT}")
return bundle
except Exception as e:
last_error = e
logger.warning(
f"Prediction bundle fetch failed on attempt {attempt}/{self.RETRY_COUNT}: {e}",
exc_info=True,
)
if attempt < self.RETRY_COUNT:
time.sleep(self.RETRY_SLEEP_S)
raise last_error
@staticmethod
def _extract_target_point(
prediction: LatestPredictionModel | None,
) -> tuple[float, float] | None:
if prediction is None:
return None
raw = getattr(prediction, "target_point", None)
if raw is None:
return None
try:
if isinstance(raw, dict):
x = raw.get("x")
y = raw.get("y")
if x is not None and y is not None:
return float(x), float(y)
if hasattr(raw, "x") and hasattr(raw, "y"):
return float(raw.x), float(raw.y)
if isinstance(raw, (list, tuple)) and len(raw) >= 2:
return float(raw[0]), float(raw[1])
except Exception as e:
logger.warning(
f"Failed to parse target_point from prediction metadata: {e}", exc_info=True
)
return None
@staticmethod
def _extract_bundle_meta(prediction: LatestPredictionModel | None) -> MLBundleMeta:
target_point = MlBox._extract_target_point(prediction)
focus = None
if prediction is not None:
try:
raw_focus = getattr(prediction, "focus_score", None)
if raw_focus is not None:
focus = float(raw_focus)
except Exception as e:
logger.warning(
f"Failed to parse focus_score from prediction metadata: {e}", exc_info=True
)
return MLBundleMeta(target_point=target_point, focus=focus)
def _extract_bundle_candidate(self, bundle) -> MLBundle:
prediction = self._coerce_prediction_metadata(getattr(bundle, "metadata", None))
image = self._decode_bundle_image(getattr(bundle, "image_jpeg", None))
predictions = self._all_from_prediction_model(prediction)
bundle_meta = self._extract_bundle_meta(prediction)
return MLBundle(predictions=predictions, image=image, bundle_meta=bundle_meta)
@log_timing(logger, "Collect best bundle")
def _collect_best_bundle(self, attempts: int = RETRY_COUNT) -> MLBundle:
best_predictions: MLOutputModel | None = None
best_image: np.ndarray | None = None
best_score = (0, 0.0)
best_meta = MLBundleMeta()
for attempt in range(1, attempts + 1):
bundle = self._fetch_prediction_bundle()
ml_bundle = self._extract_bundle_candidate(bundle)
predictions, image, bundle_meta = (
ml_bundle.predictions,
ml_bundle.image,
ml_bundle.bundle_meta,
)
if best_image is None and image is not None:
best_image = image
if best_meta.target_point is None and bundle_meta.target_point is not None:
best_meta.target_point = bundle_meta.target_point
if best_meta.focus is None and bundle_meta.focus is not None:
best_meta.focus = bundle_meta.focus
score = self._prediction_score(predictions)
logger.debug(
f"Bundle candidate {attempt}/{attempts}: detections={score[0]}, max_conf={score[1]:.3f}"
)
if score > best_score:
best_score = score
best_predictions = predictions
if image is not None:
best_image = image
best_meta = bundle_meta
if score[0] > 0:
logger.debug("Using non-empty prediction bundle candidate")
break
if attempt < attempts:
time.sleep(self.RETRY_SLEEP_S)
if best_predictions is None:
logger.info("No valid prediction bundle metadata was available")
elif not best_predictions.boxes:
logger.info("Prediction bundle candidates contained no supported detections")
return MLBundle(predictions=best_predictions, image=best_image, bundle_meta=best_meta)
def _get_latest_bundle_image(self) -> np.ndarray | None:
bundle = self._fetch_prediction_bundle()
image = self._decode_bundle_image(getattr(bundle, "image_jpeg", None))
if image is None:
logger.info("Latest prediction bundle did not contain a decodable image")
return image
def get_latest_image(self) -> np.ndarray | None:
return self._get_latest_bundle_image()
def check_box_relation(self, box0: MLBoxModel, box1: MLBoxModel):
# Extract (x1,y1,x2,y2) from MLBoxModel/BoundingBoxModel
if not box0 or not box0.box or not box1 or not box1.box:
raise ValueError("Invalid boxes passed to check_box_relation")
x10, y10, x20, y20 = (box0.box.top_x, box0.box.top_y, box0.box.bottom_x, box0.box.bottom_y)
x11, y11, x21, y21 = (box1.box.top_x, box1.box.top_y, box1.box.bottom_x, box1.box.bottom_y)
left, top, overlap_x, overlap_y = False, False, False, False
# Compute centers for robustness
c0x = (x10 + x20) / 2.0
c1x = (x11 + x21) / 2.0
if c0x < c1x:
left = True
elif c0x > c1x:
left = False
else:
overlap_x = True
# Determine relative vertical (y increases downward in images; define top=True if box0 above box1)
c0y = (y10 + y20) / 2.0
c1y = (y11 + y21) / 2.0
if c0y < c1y:
top = True
elif c0y > c1y:
top = False
else:
overlap_y = True
return {"left": left, "top": top, "overlap_x": overlap_x, "overlap_y": overlap_y}
def box_relation(self, boxes: MLOutputModel, classes: list[str] | None = None):
pin: MLBoxModel | None = boxes.get_best_for_class(MLBoxType.PIN)
if not pin or not classes:
return None
box_relative_to_pin: dict[str, bool] = {}
for box_type in classes:
# Ensure the entry exists and is an MLBoxModel
model = boxes.get(box_type) if hasattr(boxes, "get") else boxes.boxes.get(box_type)
if model:
box_relative_to_pin = self.check_box_relation(pin, model)
return box_relative_to_pin
@staticmethod
def _check_overlap(a: MLBoxModel, b: MLBoxModel) -> float:
if not a or not b or not a.box or not b.box:
logger.debug(f"Invalid box data for overlap check {a} or {b}")
return 0.0
ax1, ay1, ax2, ay2 = a.box.top_x, a.box.top_y, a.box.bottom_x, a.box.bottom_y
bx1, by1, bx2, by2 = b.box.top_x, b.box.top_y, b.box.bottom_x, b.box.bottom_y
ix1, iy1 = max(ax1, bx1), max(ay1, by1)
ix2, iy2 = min(ax2, bx2), min(ay2, by2)
inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1)
if inter <= 0:
return 0.0
a_area = max(0.0, ax2 - ax1) * max(0.0, ay2 - ay1)
b_area = max(0.0, bx2 - bx1) * max(0.0, by2 - by1)
denominator = a_area + b_area - inter
return inter / denominator if denominator > 0 else 0.0
def box_filter_overlap(
self, model: MLBoxModel, pin: MLBoxModel, overlap_parameter: float = 0.5
) -> bool:
return self._check_overlap(model, pin) >= overlap_parameter
def _filter_predictions(
self,
predictions: MLOutputModel,
overlap_with_pin: float | None = None,
confidence_min: float | None = None,
):
pin = predictions.get_best_for_class(MLBoxType.PIN)
keys_to_remove = []
for key, model in predictions.boxes.items():
if model is None or model.box is None:
keys_to_remove.append(key)
continue
if confidence_min is not None and (model.conf or 0.0) < confidence_min:
keys_to_remove.append(key)
continue
if model.cls == MLBoxType.PIN:
continue
if (
overlap_with_pin is not None
and pin
and self._check_overlap(model, pin) >= overlap_with_pin
):
keys_to_remove.append(key)
for k in keys_to_remove:
predictions.boxes.pop(k, None)
@staticmethod
def _best_by_class(results) -> MLOutputModel | None:
out = MLOutputModel()
for pred in results:
try:
cls = MLBoxType(int(pred.get("class")))
conf = float(pred.get("confidence"))
box = pred.get("box") or {}
x1 = float(box.get("x1"))
y1 = float(box.get("y1"))
x2 = float(box.get("x2"))
y2 = float(box.get("y2"))
except Exception as e:
logger.debug(f"Failed to parse prediction: {e}", exc_info=True)
continue
base_key = MLOutputModel.get_class_str(klass=cls)
if base_key not in out.boxes:
out.boxes[base_key] = MLBoxModel(
cls=cls,
box=BoundingBoxModel(top_x=x1, top_y=y1, bottom_x=x2, bottom_y=y2),
conf=conf,
)
continue
current = out.boxes[base_key]
if (current.conf or 0.0) < conf:
out.boxes[base_key] = MLBoxModel(
cls=cls,
box=BoundingBoxModel(top_x=x1, top_y=y1, bottom_x=x2, bottom_y=y2),
conf=conf,
)
return out if out.boxes else None
@staticmethod
def _all_from_prediction_model(
prediction: LatestPredictionModel | None,
) -> MLOutputModel | None:
if prediction is None or not getattr(prediction, "boxes", None):
return None
out = MLOutputModel()
for det in prediction.boxes:
try:
cls = MLBoxType(int(det.cls))
conf = float(det.conf)
x1 = float(det.x1)
y1 = float(det.y1)
x2 = float(det.x2)
y2 = float(det.y2)
except Exception as e:
logger.debug(f"Failed to parse bundle detection: {e}", exc_info=True)
continue
out.add_box(cls=cls, box_tuple=(x1, y1, x2, y2), conf=conf)
logger.debug(f"Parsed {len(out.boxes)} supported detections from bundle metadata")
return out
def get_best_detections(self, results) -> MLOutputModel | None:
best_by_class = self._best_by_class(results)
if not best_by_class:
return None
return best_by_class
@staticmethod
def get_preferred_class_box_with_confidence_threshold(
boxes: MLOutputModel,
preferred_class: Iterable[int] | int | MLBoxType | None = None,
loop_preference_margin: float = 0.1,
) -> MLBoxModel | None:
"""
Get best box, preferring loops over pin even if pin has higher confidence,
unless pin's confidence exceeds loops by the margin.
Args:
boxes: MLOutputModel with detections
preferred_class: Override preference order (default: Crystal, Loop_face, Loop_all, Pin)
loop_preference_margin: Minimum confidence advantage pin needs to override loop preference (default 0.1)
Returns:
Best MLBoxModel according to preferences
"""
if preferred_class is None:
order = (MLBoxType.CRYSTAL, MLBoxType.LOOP_FACE, MLBoxType.LOOP_ALL, MLBoxType.PIN)
else:
if isinstance(preferred_class, MLBoxType):
order = (preferred_class,)
elif isinstance(preferred_class, int):
order = (MLBoxType(preferred_class),)
else:
order = tuple(MLBoxType(c) if isinstance(c, int) else c for c in preferred_class)
# Get best box from each class
best_boxes = {}
for cls in order:
m = boxes.get_best_for_class(cls)
if m:
best_boxes[cls] = m
if not best_boxes:
return None
# Special handling: prefer loops over pin unless pin is significantly better
pin_box = best_boxes.get(MLBoxType.PIN)
loop_face_box = best_boxes.get(MLBoxType.LOOP_FACE)
loop_all_box = best_boxes.get(MLBoxType.LOOP_ALL)
best_loop = loop_face_box if loop_face_box else loop_all_box
if best_loop and pin_box:
pin_conf = pin_box.conf or 0.0
loop_conf = best_loop.conf or 0.0
# Only use pin if its confidence exceeds loop by margin
if pin_conf > (loop_conf + loop_preference_margin):
return pin_box
return best_loop
# Normal priority if no special case
for cls in order:
if cls in best_boxes:
return best_boxes[cls]
return None
@staticmethod
def get_preferred_class_box(
boxes: MLOutputModel, preferred_class: Iterable[int] | int | MLBoxType | None = None
) -> MLBoxModel | None:
if preferred_class is None:
order = (MLBoxType.CRYSTAL, MLBoxType.LOOP_FACE, MLBoxType.LOOP_ALL, MLBoxType.PIN)
else:
if isinstance(preferred_class, MLBoxType):
order = (preferred_class,)
elif isinstance(preferred_class, int):
order = (MLBoxType(preferred_class),)
else:
order = tuple(MLBoxType(c) if isinstance(c, int) else c for c in preferred_class)
for cls in order:
m = boxes.get_best_for_class(cls)
if m:
return m
return None
def predict(
self,
preferred_class=None,
overlap_with_pin: float | None = None,
confidence_min: float | None = None,
return_image: bool = False,
return_bundle_meta: bool = False,
) -> None | MLBoxModel | tuple[MLBoxModel | None, np.ndarray | None] | MLBoxPredictionResult:
ml_bundle = self._collect_best_bundle()
predictions, image, bundle_meta = (
ml_bundle.predictions,
ml_bundle.image,
ml_bundle.bundle_meta,
)
if not predictions:
if return_bundle_meta:
return MLBoxPredictionResult(
box=None,
image=image if return_image else None,
target_point=bundle_meta.target_point,
focus=bundle_meta.focus,
)
return (None, image) if return_image else None
self._filter_predictions(
predictions=predictions,
overlap_with_pin=overlap_with_pin,
confidence_min=confidence_min,
)
box = self.get_preferred_class_box(predictions, preferred_class)
if return_bundle_meta:
return MLBoxPredictionResult(
box=box,
image=image if return_image else None,
target_point=bundle_meta.target_point,
focus=bundle_meta.focus,
)
return (box, image) if return_image else box
def predict_best_no_filter(
self, return_image: bool = False, return_bundle_meta: bool = False
) -> (
MLOutputModel
| None
| tuple[MLOutputModel | None, np.ndarray | None]
| MLBoxPredictionsResult
):
ml_bundle = self._collect_best_bundle()
predictions, image, bundle_meta = (
ml_bundle.predictions,
ml_bundle.image,
ml_bundle.bundle_meta,
)
if return_bundle_meta:
return MLBoxPredictionsResult(
predictions=predictions,
image=image if return_image else None,
target_point=bundle_meta.target_point,
focus=bundle_meta.focus,
)
if return_image:
return predictions, image
return predictions
def predict_all_best(
self,
overlap_with_pin: float | None = None,
confidence_min: float | None = None,
return_image: bool = False,
return_bundle_meta: bool = False,
) -> (
MLOutputModel
| None
| tuple[MLOutputModel | None, np.ndarray | None]
| MLBoxPredictionsResult
):
ml_bundle = self._collect_best_bundle()
best, image, bundle_meta = (ml_bundle.predictions, ml_bundle.image, ml_bundle.bundle_meta)
if not best:
logger.debug(f"No best predictions from ML bundle: {best}")
if return_bundle_meta:
return MLBoxPredictionsResult(
predictions=None,
image=image if return_image else None,
target_point=bundle_meta.target_point,
focus=bundle_meta.focus,
)
return (None, image) if return_image else None
logger.debug(f"Best predictions from ML bundle: {best}")
self._filter_predictions(
best, overlap_with_pin=overlap_with_pin, confidence_min=confidence_min
)
logger.debug(f"Filtered best predictions from ML bundle: {best}")
if return_bundle_meta:
return MLBoxPredictionsResult(
predictions=best,
image=image if return_image else None,
target_point=bundle_meta.target_point,
focus=bundle_meta.focus,
)
return (best, image) if return_image else best
def predict_all(
self,
overlap_parameter: float | None = None,
confidence_filter: float | None = None,
return_image: bool = False,
) -> dict[str, list[MLBoxModel]] | tuple[dict[str, list[MLBoxModel]], np.ndarray | None]:
"""
Return a dict keyed by '<MLBoxTypeName>_<ordinal>' -> [MLBoxModel, ...] for each detection.
The ordinal is the running count per class (1-based) in the order they appear after filtering.
Example keys: 'Crystal_1', 'Crystal_2', 'Loop_face_1', 'Pin_1', ...
"""
ml_bundle = self._collect_best_bundle()
grouped, image, _bundle_meta = (
ml_bundle.predictions,
ml_bundle.image,
ml_bundle.bundle_meta,
)
if not grouped:
return ({}, image) if return_image else {}
self._filter_predictions(
grouped, overlap_with_pin=overlap_parameter, confidence_min=confidence_filter
)
per_class_counter: dict[MLBoxType, int] = {}
out: dict[str, list[MLBoxModel]] = {}
all_models: list[MLBoxModel] = list(grouped.boxes.values())
for m in all_models:
if m is None or m.box is None:
continue
cls: MLBoxType = m.cls
per_class_counter[cls] = per_class_counter.get(cls, 0) + 1
ordinal = per_class_counter[cls]
key = f"{MLOutputModel.get_class_str(cls)}_{ordinal}"
out.setdefault(key, []).append(m)
return (out, image) if return_image else out
def predict_best_n_frames(
self,
n_frames: int = 5,
preferred_class=None,
overlap_with_pin: float | None = None,
confidence_min: float | None = None,
return_image: bool = False,
) -> MLBoxModel | None | tuple[MLBoxModel | None, np.ndarray | None]:
"""
Request bounding boxes for the next N bundle fetches and return the best available box.
"""
best_box: MLBoxModel | None = None
best_image: np.ndarray | None = None
best_conf = -1.0
for frame_idx in range(n_frames):
try:
box, image = self.predict(
preferred_class=preferred_class,
overlap_with_pin=overlap_with_pin,
confidence_min=confidence_min,
return_image=True,
)
if box is not None and (box.conf or 0.0) > best_conf:
best_box = box
best_image = image
best_conf = box.conf or 0.0
logger.info(
f"ML detection successful at frame {frame_idx + 1}/{n_frames}: {box}"
)
if box is None:
logger.debug(f"Frame {frame_idx + 1}/{n_frames}: no detection")
except Exception as e:
logger.warning(
f"Frame {frame_idx + 1}/{n_frames}: prediction error: {e}", exc_info=True
)
continue
if best_box is None:
logger.warning(f"No detections in any of {n_frames} frames")
return (best_box, best_image) if return_image else best_box
View File
Whitespace-only changes.
Whitespace-only changes.
@@ -1,536 +0,0 @@
import time
from collections.abc import Callable
from dataclasses import dataclass
from math import ceil, floor
from aarecommon.config.beamline import cfg_get
from aarecommon.config.logger_events import (
geom_log_context,
log_ml_bundle_meta,
merge_log_context,
sample_log_context,
)
from aarecommon.errors.exception_handler import AutoRasterSampleSkipped
from aarecommon.math.coordinate import Coordinate, SmargonCoordinate
from aarecommon.math.sample_geometry import SampleGeometryModel
from aarecommon.models.models import MLBoxType, SampleShortInfo
from aarecommon.models.raster_grid import RasterGridRequest
from aare.daq.mlbox import MlBox, MLBoxPredictionResult, MLBoxPredictionsResult
BoxTuple = tuple[float, float, float, float]
@dataclass
class MLRasterPlan:
"""Result of an auto-center ML detection: the raster grid request plus the
raw loop boxes (at the current zoom) needed to drive zoom-to-fit."""
grid_request: RasterGridRequest
loop_all_box: BoxTuple | None
loop_face_box: BoxTuple | None
image_width: int | None
image_height: int | None
pin_box: BoxTuple | None = None
def _box_tuple(model) -> BoxTuple | None:
if model is None or model.box is None:
return None
return (model.box.top_x, model.box.top_y, model.box.bottom_x, model.box.bottom_y)
def _box_extends_beyond(inner: BoxTuple, outer: BoxTuple) -> bool:
return inner[0] < outer[0] or inner[1] < outer[1] or inner[2] > outer[2] or inner[3] > outer[3]
def _box_union(a: BoxTuple, b: BoxTuple) -> BoxTuple:
return (min(a[0], b[0]), min(a[1], b[1]), max(a[2], b[2]), max(a[3], b[3]))
@dataclass(frozen=True)
class PinExclusion:
"""Outcome of :func:`exclude_pin_x_overlap`.
``box`` is the grid box with the pin's x-range removed. ``limit_x_min`` /
``limit_x_max`` is the pixel column the raster grid (padding included) must
not cross on the pin side. ``side`` is ``None`` when no exclusion was
applied, in which case ``reason`` says why.
"""
box: BoxTuple
side: str | None
limit_x_min: float | None
limit_x_max: float | None
clipped_px: float
reason: str | None
def exclude_pin_x_overlap(
box: BoxTuple, pin: BoxTuple, *, max_overlap_fraction: float
) -> PinExclusion:
"""Remove the x-range shared with the pin from a raster grid box.
The pin is metal: rastering it gives strong scattering that perturbs the
diffraction analysis. The pin sits on one side of the loop along x (decided
from the box centres); the grid box is cut at the pin's near edge and that
edge becomes a hard limit for grid padding on that side. The y-range of the
grid box is kept as is. With no x-overlap the box is untouched, but the pin
edge still caps the padding.
No exclusion is applied (``side`` is ``None``) when the pin's x-range covers
the whole box or the overlap exceeds ``max_overlap_fraction`` of the box
width: both point to a mis-detected pin rather than a stem running into it.
"""
x1, y1, x2, y2 = box
px1, _, px2, _ = pin
width = x2 - x1
if width <= 0:
return PinExclusion(box, None, None, None, 0.0, "grid box has no width")
if px1 <= x1 and px2 >= x2:
return PinExclusion(box, None, None, None, 0.0, "pin x-range covers the whole grid box")
pin_on_right = (px1 + px2) / 2.0 >= (x1 + x2) / 2.0
if pin_on_right:
overlap = max(0.0, x2 - max(px1, x1))
else:
overlap = max(0.0, min(px2, x2) - x1)
if overlap > max_overlap_fraction * width:
return PinExclusion(
box, None, None, None, 0.0, "pin x-overlap exceeds the allowed fraction of the grid box"
)
if pin_on_right:
return PinExclusion((x1, y1, min(x2, px1), y2), "right", None, px1, overlap, None)
return PinExclusion((max(x1, px2), y1, x2, y2), "left", px2, None, overlap, None)
def scale_auto_raster_grid(
*,
n_x: int,
n_y: int,
grid_size: Coordinate,
max_images: int,
min_cell_size_mm: float,
skip: bool,
) -> tuple[int, int, Coordinate]:
n_x = max(1, int(n_x))
n_y = max(1, int(n_y))
image_count = n_x * n_y
if image_count <= max_images:
return n_x, n_y, grid_size
if skip:
raise AutoRasterSampleSkipped(
f"Auto-raster grid has {image_count} images, which exceeds "
f"the automation limit of {max_images}; skipping sample"
)
physical_size_x_mm = n_x * grid_size.x
physical_size_y_mm = n_y * grid_size.y
scale = (image_count / max_images) ** 0.5
scaled_n_x = max(1, floor(n_x / scale))
scaled_n_y = max(1, floor(n_y / scale))
while scaled_n_x * scaled_n_y > max_images:
if scaled_n_x >= scaled_n_y and scaled_n_x > 1:
scaled_n_x -= 1
elif scaled_n_y > 1:
scaled_n_y -= 1
else:
break
scaled_grid_size = Coordinate(
x=max(min_cell_size_mm, physical_size_x_mm / scaled_n_x),
y=max(min_cell_size_mm, physical_size_y_mm / scaled_n_y),
)
return scaled_n_x, scaled_n_y, scaled_grid_size
def get_ml_bounding_box(
*,
mlbox: MlBox,
sample: SampleShortInfo | None,
sample_geometry: SampleGeometryModel,
upload_image: Callable[[int | None, str, object], None],
logger,
filename: str | None = None,
max_images: int,
min_cell_size_mm: float,
skip_if_exceed_max_image_threshold: bool,
) -> RasterGridRequest | None:
time.sleep(0.2)
sample_id = getattr(sample, "db_id", None)
prediction_result: MLBoxPredictionResult = mlbox.predict(
preferred_class=(3, 0), return_image=True, return_bundle_meta=True
)
m = prediction_result.box
log_ml_bundle_meta(
logger,
f"ml_bounding_box:{filename or 'unnamed'}",
target_point=prediction_result.target_point,
focus=prediction_result.focus,
)
if m is None:
logger.warning(
"ML bounding box returned no detection",
extra={
"sample_id": sample_id,
"ml_image_name": filename,
"target_point": prediction_result.target_point,
},
)
# if filename is not None and bundle_image is not None:
# upload_image(sample_id, f"{filename}_no_detection", bundle_image)
return None
x1, y1, x2, y2 = m.box.top_x, m.box.top_y, m.box.bottom_x, m.box.bottom_y
# if filename is not None and bundle_image is not None:
# annotated_image = bundle_image.copy()
# cv2.rectangle(annotated_image, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
# upload_image(sample_id, filename, annotated_image)
geom = sample_geometry
logger.info(
"ML bounding box selected",
extra=merge_log_context(
sample_log_context(sample),
{"sample_id": sample_id, "ml_image_name": filename},
geom_log_context(geom),
{
"box_x1": x1,
"box_y1": y1,
"box_x2": x2,
"box_y2": y2,
"target_point": prediction_result.target_point,
},
),
)
return _box_to_raster_request(
x1=x1,
y1=y1,
x2=x2,
y2=y2,
sample=sample,
sample_geometry=geom,
logger=logger,
filename=filename,
sample_id=sample_id,
max_images=max_images,
min_cell_size_mm=min_cell_size_mm,
skip_if_exceed_max_image_threshold=skip_if_exceed_max_image_threshold,
)
def _box_to_raster_request(
*,
x1: float,
y1: float,
x2: float,
y2: float,
sample: SampleShortInfo | None,
sample_geometry: SampleGeometryModel,
logger,
filename: str | None,
sample_id: int | None,
max_images: int,
min_cell_size_mm: float,
skip_if_exceed_max_image_threshold: bool,
grid_padding: bool = False,
pad_limit_x_min: float | None = None,
pad_limit_x_max: float | None = None,
) -> RasterGridRequest:
"""Convert a pixel box into a raster grid request.
``pad_limit_x_min`` / ``pad_limit_x_max`` is a pixel column the grid must
not cross (the near edge of the pin, see :func:`exclude_pin_x_overlap`):
the cell-rounding overshoot is moved away from that edge and the grid
padding on that side is capped so no cell lands beyond it.
"""
geom = sample_geometry
grid_size = Coordinate(x=geom.beam_size_mm.x * 0.8, y=geom.beam_size_mm.y * 0.8)
cell_px_x = grid_size.x / geom.pixel_in_mm
n_x = max(1, abs(ceil((x2 - x1) * geom.pixel_in_mm / grid_size.x)))
n_y = max(1, abs(ceil((y2 - y1) * geom.pixel_in_mm / grid_size.y)))
if pad_limit_x_max is not None:
# ceil() lets the last cell reach up to one cell past x2; when the pin
# sits right after x2, shift the grid left so it ends on the pin edge.
# (A pin on the left needs no shift: the overshoot is on the far side.)
overshoot_px = x1 + n_x * cell_px_x - pad_limit_x_max
if overshoot_px > 0:
x1 = x1 - overshoot_px
if grid_padding:
# Pad the grid by a fraction of its size on each side (at least one cell),
# extending *before* cell 0 as well, so the top-left moves outward and
# smargon_top_left shifts with it. Y is asymmetric: the bottom (far end
# of the n_y scan) can be padded more than the top. X padding is capped
# on a side that has a pin limit.
frac_x = float(cfg_get("daq.auto_raster.grid_padding_fraction_x", 0.15))
frac_y_top = float(cfg_get("daq.auto_raster.grid_padding_fraction_y", 0.15))
frac_y_bottom = float(cfg_get("daq.auto_raster.grid_padding_fraction_y_bottom", frac_y_top))
pad_x = max(1, ceil(frac_x * n_x))
pad_x_left = pad_x
pad_x_right = pad_x
if pad_limit_x_min is not None:
room_px = x1 - pad_limit_x_min
pad_x_left = min(pad_x_left, max(0, floor(room_px / cell_px_x)))
if pad_limit_x_max is not None:
room_px = pad_limit_x_max - (x1 + n_x * cell_px_x)
pad_x_right = min(pad_x_right, max(0, floor(room_px / cell_px_x)))
pad_y_top = max(1, ceil(frac_y_top * n_y))
pad_y_bottom = max(1, ceil(frac_y_bottom * n_y))
x1 = x1 - pad_x_left * cell_px_x
y1 = y1 - pad_y_top * grid_size.y / geom.pixel_in_mm
n_x = n_x + pad_x_left + pad_x_right
n_y = n_y + pad_y_top + pad_y_bottom
logger.info(
"Padded auto-center raster grid",
extra=merge_log_context(
sample_log_context(sample),
{
"sample_id": sample_id,
"ml_image_name": filename,
"pad_cells_x_left": pad_x_left,
"pad_cells_x_right": pad_x_right,
"pad_cells_y_top": pad_y_top,
"pad_cells_y_bottom": pad_y_bottom,
"pad_limit_x_min": pad_limit_x_min,
"pad_limit_x_max": pad_limit_x_max,
"n_x": n_x,
"n_y": n_y,
},
),
)
start_coord = geom.picture_to_smargon(Coordinate(x=x1, y=y1))
original_n_x = n_x
original_n_y = n_y
original_grid_size = grid_size
n_x, n_y, grid_size = scale_auto_raster_grid(
n_x=n_x,
n_y=n_y,
grid_size=grid_size,
max_images=max_images,
min_cell_size_mm=min_cell_size_mm,
skip=skip_if_exceed_max_image_threshold,
)
if (n_x, n_y, grid_size.x, grid_size.y) != (
original_n_x,
original_n_y,
original_grid_size.x,
original_grid_size.y,
):
logger.info(
"Scaled ML raster grid to stay within auto-raster image limit",
extra=merge_log_context(
sample_log_context(sample),
{
"sample_id": sample_id,
"ml_image_name": filename,
"max_images": max_images,
"original_n_x": original_n_x,
"original_n_y": original_n_y,
"original_image_count": original_n_x * original_n_y,
"original_grid_size_x_mm": original_grid_size.x,
"original_grid_size_y_mm": original_grid_size.y,
"scaled_n_x": n_x,
"scaled_n_y": n_y,
"scaled_image_count": n_x * n_y,
"scaled_grid_size_x_mm": grid_size.x,
"scaled_grid_size_y_mm": grid_size.y,
},
),
)
logger.info(
"Converted ML bounding box to raster request",
extra=merge_log_context(
sample_log_context(sample),
{
"sample_id": sample_id,
"ml_image_name": filename,
"start_sh_x_mm": start_coord.x,
"start_sh_y_mm": start_coord.y,
"start_sh_z_mm": start_coord.z,
"grid_size_x_mm": grid_size.x,
"grid_size_y_mm": grid_size.y,
"n_x": n_x,
"n_y": n_y,
"smargon_phi_deg": geom.smargon.phi_deg,
"smargon_chi_deg": geom.smargon.chi_deg,
},
),
)
return RasterGridRequest(
exp_time_s=0.01,
transmission=1.0,
smargon_top_left=SmargonCoordinate(
chi_deg=geom.smargon.chi_deg, phi_deg=geom.smargon.phi_deg, sh_mm=start_coord
),
n_x=n_x,
n_y=n_y,
grid_size_mm=grid_size,
omega_deg=geom.omega_deg,
)
def build_ml_raster_plan(
*,
mlbox: MlBox,
sample: SampleShortInfo | None,
sample_geometry: SampleGeometryModel,
upload_image: Callable[[int | None, str, object], None],
logger,
filename: str | None = None,
max_images: int,
min_cell_size_mm: float,
skip_if_exceed_max_image_threshold: bool,
) -> MLRasterPlan | None:
"""Like :func:`get_ml_bounding_box`, but used by the auto-center path.
It runs a single prediction and returns the raster grid request together
with the raw ``loop_all`` / ``loop_face`` boxes (so the caller can drive
zoom-to-fit). The grid box is loop_face (else loop_all); a loop_face box is
padded by ``daq.auto_raster.loop_face_padding_fraction`` and, when
``daq.auto_raster.include_crystal`` is enabled, the box is extended to the
union of itself and any detected crystal boxes that lie beyond it. When a
pin is detected and ``daq.auto_raster.exclude_pin_x_overlap`` is enabled
(default), the x-range shared with the pin is removed from the grid and no
padding cell is placed on the pin (see :func:`exclude_pin_x_overlap`).
"""
time.sleep(0.2)
sample_id = getattr(sample, "db_id", None)
result: MLBoxPredictionsResult = mlbox.predict_all_best(
return_image=True, return_bundle_meta=True
)
predictions = result.predictions
bundle_image = result.image
log_ml_bundle_meta(
logger,
f"ml_raster_plan:{filename or 'unnamed'}",
target_point=result.target_point,
focus=result.focus,
)
loop_all = predictions.get_best_for_class(MLBoxType.LOOP_ALL) if predictions else None
loop_face = predictions.get_best_for_class(MLBoxType.LOOP_FACE) if predictions else None
pin = predictions.get_best_for_class(MLBoxType.PIN) if predictions else None
# Grid box: prefer loop_face, else loop_all (matches the legacy (3, 0) order).
grid_model = loop_face if loop_face is not None else loop_all
if grid_model is None:
logger.warning(
"ML raster plan returned no loop detection",
extra={
"sample_id": sample_id,
"ml_image_name": filename,
"target_point": result.target_point,
},
)
return None
x1, y1, x2, y2 = (
grid_model.box.top_x,
grid_model.box.top_y,
grid_model.box.bottom_x,
grid_model.box.bottom_y,
)
# Optionally extend the grid to cover crystals detected outside the loop box.
if cfg_get("daq.auto_raster.include_crystal", False) and predictions is not None:
for crystal in predictions.get_models_for_class(MLBoxType.CRYSTAL):
cbox = (
crystal.box.top_x,
crystal.box.top_y,
crystal.box.bottom_x,
crystal.box.bottom_y,
)
if _box_extends_beyond(cbox, (x1, y1, x2, y2)):
x1, y1, x2, y2 = _box_union((x1, y1, x2, y2), cbox)
logger.info(
"Extended ML raster grid to include crystal outside the loop box",
extra={"sample_id": sample_id, "ml_image_name": filename, "crystal_box": cbox},
)
# Keep the grid off the pin: drop the x-range shared with the pin box and
# stop the padding at the pin edge (metal scattering perturbs spot finding).
pin_box = _box_tuple(pin)
pad_limit_x_min: float | None = None
pad_limit_x_max: float | None = None
if pin_box is not None and cfg_get("daq.auto_raster.exclude_pin_x_overlap", True):
exclusion = exclude_pin_x_overlap(
(x1, y1, x2, y2),
pin_box,
max_overlap_fraction=float(
cfg_get("daq.auto_raster.exclude_pin_max_overlap_fraction", 0.75)
),
)
pin_log = {
"sample_id": sample_id,
"ml_image_name": filename,
"grid_box": (x1, y1, x2, y2),
"pin_box": pin_box,
}
if exclusion.side is None:
logger.warning(
"Kept ML raster grid unchanged despite a detected pin",
extra={**pin_log, "reason": exclusion.reason},
)
else:
x1, y1, x2, y2 = exclusion.box
pad_limit_x_min = exclusion.limit_x_min
pad_limit_x_max = exclusion.limit_x_max
logger.info(
"Excluded pin x-range from ML raster grid",
extra={
**pin_log,
"pin_side": exclusion.side,
"clipped_px": exclusion.clipped_px,
"clipped_grid_box": exclusion.box,
},
)
grid_request = _box_to_raster_request(
x1=x1,
y1=y1,
x2=x2,
y2=y2,
sample=sample,
sample_geometry=sample_geometry,
logger=logger,
filename=filename,
sample_id=sample_id,
max_images=max_images,
min_cell_size_mm=min_cell_size_mm,
skip_if_exceed_max_image_threshold=skip_if_exceed_max_image_threshold,
grid_padding=True,
pad_limit_x_min=pad_limit_x_min,
pad_limit_x_max=pad_limit_x_max,
)
image_height = int(bundle_image.shape[0]) if bundle_image is not None else None
image_width = int(bundle_image.shape[1]) if bundle_image is not None else None
return MLRasterPlan(
grid_request=grid_request,
loop_all_box=_box_tuple(loop_all),
loop_face_box=_box_tuple(loop_face),
image_width=image_width,
image_height=image_height,
pin_box=pin_box,
)
-56
View File
@@ -1,56 +0,0 @@
from dataclasses import dataclass
from typing import Generic, Protocol, TypeVar
from aare.daq.config import BeamlineConfig
from aare.daq.devices import BeamlineDevices
from aare.daq.operations.common.runtime import DAQRuntimeState
from aare.daq.operations.common.services import OperationServices
class OperationDependencies(Protocol):
"""Marker protocol for operation dependency bundles."""
class OperationSettings(Protocol):
"""Marker protocol for operation settings bundles."""
DepsT = TypeVar("DepsT", bound=OperationDependencies)
SettingsT = TypeVar("SettingsT", bound=OperationSettings)
@dataclass
class BeamlineDependencies:
cfg: BeamlineConfig
devs: BeamlineDevices
@dataclass
class OperationResult:
success: bool
error: Exception | None = None
comment: str | None = None
@property
def failed(self) -> bool:
return not self.success
@dataclass
class BaseOperationContext(Generic[DepsT, SettingsT]):
deps: DepsT
runtime: DAQRuntimeState
services: OperationServices
settings: SettingsT
@property
def sample(self):
return self.runtime.sample
@property
def sample_geometry(self):
return self.runtime.sample_geometry
@property
def status(self):
return self.runtime.status
-39
View File
@@ -1,39 +0,0 @@
from dataclasses import dataclass
from typing import Protocol
from aarecommon.math.sample_geometry import SampleGeometryModel
from aarecommon.models.models import DAQStatusModel, SampleShortInfo
class SampleProvider(Protocol):
@property
def sample(self) -> SampleShortInfo | None: ...
class SampleGeometryProvider(Protocol):
@property
def sample_geometry(self) -> SampleGeometryModel: ...
class StatusProvider(Protocol):
@property
def status(self) -> DAQStatusModel: ...
@dataclass(frozen=True)
class DAQRuntimeState:
sample_provider: SampleProvider
sample_geometry_provider: SampleGeometryProvider
status_provider: StatusProvider
@property
def sample(self) -> SampleShortInfo | None:
return self.sample_provider.sample
@property
def sample_geometry(self) -> SampleGeometryModel:
return self.sample_geometry_provider.sample_geometry
@property
def status(self) -> DAQStatusModel:
return self.status_provider.status
-144
View File
@@ -1,144 +0,0 @@
from dataclasses import dataclass
from typing import Protocol
from aarecommon.math.find_xtal import CenterOfMassModel
from aarecommon.models.models import SampleGeometryModel, SampleShortInfo
from aarecommon.models.raster_grid import GridScanDecision, RasterGridRequest
from jfjoch_client import ScanResult
from aare.daq.config import BeamlineStateEnum
from aare.daq.operations.screenshot.service import ScreenshotService
class StateSetter(Protocol):
def set_state(self, target: BeamlineStateEnum) -> None: ...
class SmargonTraceAppender(Protocol):
def append_smargon_trace(self, *, sample_id: int | None, event: str) -> None: ...
class PredictionGetter(Protocol):
def get_predictions(self): ...
class FaceDetectionProgressReporter(Protocol):
def emit_progress(self, payload: dict) -> None: ...
class SampleEventSender(Protocol):
def send_sample_event(self, sample_id: int, event_type, comment: str | None = None) -> None: ...
class ScanIngestor(Protocol):
def ingest_scan(self, *, sample, result, geom, beam_mark_pxl) -> None: ...
def ingest_gridscan(
self,
*,
sample: SampleShortInfo | None,
raster_result: ScanResult,
raster_request: RasterGridRequest,
analysis_image_scores: list[float | None] | None,
geom: SampleGeometryModel,
com: CenterOfMassModel,
beam_mark_pxl: tuple[float, float],
decision: GridScanDecision | None,
) -> None: ...
class DatacollectionSetupRunner(Protocol):
def prepare(self, request, screening: bool = False) -> None: ...
@dataclass(frozen=True)
class StateController:
setter: StateSetter
def set_state(self, target: BeamlineStateEnum) -> None:
self.setter.set_state(target)
@dataclass(frozen=True)
class TraceWriter:
appender: SmargonTraceAppender
def append_smargon_trace(self, *, sample_id: int | None, event: str) -> None:
self.appender.append_smargon_trace(sample_id=sample_id, event=event)
@dataclass(frozen=True)
class PredictionProvider:
getter: PredictionGetter
def get_predictions(self):
return self.getter.get_predictions()
@dataclass(frozen=True)
class FaceDetectionProgressEmitter:
reporter: FaceDetectionProgressReporter
def emit_progress(self, payload: dict) -> None:
self.reporter.emit_progress(payload)
@dataclass(frozen=True)
class SampleEventPublisher:
sender: SampleEventSender
def send(self, sample_id: int, event_type, comment: str | None = None) -> None:
self.sender.send_sample_event(sample_id, event_type, comment)
@dataclass(frozen=True)
class ScanIngestionService:
ingestor: ScanIngestor
def ingest_scan(self, *, sample, result, geom, beam_mark_pxl) -> None:
self.ingestor.ingest_scan(
sample=sample, result=result, geom=geom, beam_mark_pxl=beam_mark_pxl
)
def ingest_gridscan(
self,
*,
sample: SampleShortInfo | None,
raster_result: ScanResult,
raster_request: RasterGridRequest,
analysis_image_scores: list[float | None] | None,
geom: SampleGeometryModel,
com: CenterOfMassModel,
beam_mark_pxl: tuple[float, float],
decision: GridScanDecision | None,
) -> None:
self.ingestor.ingest_gridscan(
sample=sample,
raster_result=raster_result,
raster_request=raster_request,
analysis_image_scores=analysis_image_scores,
geom=geom,
com=com,
beam_mark_pxl=beam_mark_pxl,
decision=decision,
)
@dataclass(frozen=True)
class DataCollectionPreparer:
runner: DatacollectionSetupRunner
def prepare(self, request, screening: bool = False) -> None:
self.runner.prepare(request, screening=screening)
@dataclass
class OperationServices:
screenshots: ScreenshotService
state: StateController | None = None
traces: TraceWriter | None = None
predictions: PredictionProvider | None = None
face_detection_progress: FaceDetectionProgressEmitter | None = None
events: SampleEventPublisher | None = None
ingestion: ScanIngestionService | None = None
datacollection: DataCollectionPreparer | None = None
@@ -1,49 +0,0 @@
import copy
from aarecommon.models.raster_grid import CompletedRasterGridElem, RasterGridRequest
from aarecommon.models.rotation_scan import CompletedRotationScan, RotationScanRequest
from jfjoch_client import ScanResult, ScanResultImagesInner
def build_fake_scan_result(
*, file_prefix: str | None, image_count: int, rotation: bool = False, start_angle: float = 0.0
) -> ScanResult:
total_images = max(1, image_count)
angle_step = 360.0 / total_images if rotation else 0.0
images = [
ScanResultImagesInner(
number=i,
efficiency=1.0,
bkg=0.0,
spots=0,
spots_low_res=0,
spots_indexed=0,
index=0,
b=0.0,
angle=start_angle + i * angle_step if rotation else None,
)
for i in range(total_images)
]
return ScanResult(file_prefix=file_prefix, images=images)
def build_fake_rotation_result(
request: RotationScanRequest, *, start_angle: float = 0.0
) -> CompletedRotationScan:
result = build_fake_scan_result(
file_prefix=request.file_prefix,
image_count=request.steps,
rotation=True,
start_angle=start_angle,
)
return CompletedRotationScan(request=copy.deepcopy(request), result=result)
def build_fake_raster_result(request: RasterGridRequest) -> CompletedRasterGridElem:
result = build_fake_scan_result(
file_prefix=request.file_prefix, image_count=request.n_x * request.n_y, rotation=False
)
return CompletedRasterGridElem(
request=copy.deepcopy(request), result=result, centre_of_mass=None
)
@@ -1,4 +0,0 @@
from aare.daq.operations.face_detection.models import FaceDetectionContext, FaceDetectionResult
from aare.daq.operations.face_detection.service import FaceDetectionService
__all__ = ["FaceDetectionContext", "FaceDetectionResult", "FaceDetectionService"]
@@ -1,29 +0,0 @@
from dataclasses import dataclass
from aare.daq.mlbox import MlBox
from aare.daq.operations.common.models import BaseOperationContext, BeamlineDependencies
@dataclass
class FaceDetectionDependencies(BeamlineDependencies):
mlbox: MlBox
@dataclass
class FaceDetectionSettings:
steps: int = 14
step_size: int = 15
face_min_ratio: float = 0.3
@dataclass
class FaceDetectionContext(BaseOperationContext[FaceDetectionDependencies, FaceDetectionSettings]):
pass
@dataclass
class FaceDetectionResult:
success: bool
payload: dict
error: Exception | None = None
comment: str | None = None
@@ -1,219 +0,0 @@
import time
from aarecommon.config.logger_events import log_duration, log_ml_bundle_meta
from aarecommon.math.coordinate import Coordinate, SmargonCoordinate
from aarecommon.models.models import MLBoxModel, ZoomModeEnum
import aare.daq.operations.face_detection.utils as fd
from aare.daq.mlbox import MLBoxPredictionResult
from aare.daq.operations.face_detection.models import FaceDetectionContext, FaceDetectionResult
class FaceDetectionService:
def __init__(self, *, context: FaceDetectionContext, logger):
self.ctx = context
self.logger = logger
def _progress_emitter(self):
emitter = self.ctx.services.face_detection_progress
if emitter is None:
raise RuntimeError("FaceDetectionService requires services.face_detection_progress")
return emitter
def _log_warning(self, message: str) -> None:
warning = getattr(self.logger, "warning", None)
if callable(warning):
warning(message)
return
fallback = getattr(self.logger, "error", None)
if callable(fallback):
fallback(message)
def _emit_running_progress(
self, *, angle: int, boxes_face: dict[int, tuple[float, float, float, float]]
) -> None:
self._progress_emitter().emit_progress(
{
"running": True,
"current_angle_deg": angle,
"samples": fd.get_samples_out(boxes_face),
"height_fit": {},
"area_fit": {},
}
)
def _emit_empty_result(self) -> dict:
payload = {"running": False, "samples": [], "height_fit": {}, "area_fit": {}}
self._progress_emitter().emit_progress(payload)
return payload
def _centre_correction(self, model: MLBoxModel, tolerance: float = 0.2) -> None:
geom = self.ctx.runtime.sample_geometry
beam_y = geom.beam_location_pxl.y
beam_x = geom.beam_location_pxl.x
y1 = model.box.top_y
y2 = model.box.bottom_y
centre_y = y1 + (y2 - y1) / 2
if beam_y != 0 and abs(centre_y - beam_y) / abs(beam_y) > tolerance:
coord = geom.picture_to_smargon(Coordinate(x=beam_x, y=centre_y))
self.ctx.deps.devs.smargon_pos = SmargonCoordinate(sh_mm=coord)
self.ctx.deps.devs.smargon_wait(60)
def run(
self,
*,
steps: int | None = None,
step_size: int | None = None,
face_min_ratio: float | None = None,
) -> FaceDetectionResult:
steps = self.ctx.settings.steps if steps is None else steps
step_size = self.ctx.settings.step_size if step_size is None else step_size
face_min_ratio = (
self.ctx.settings.face_min_ratio if face_min_ratio is None else face_min_ratio
)
try:
self.ctx.deps.cfg.zoom_mode = ZoomModeEnum.LoopCenter
self.ctx.deps.devs.lamp_light = 2.5
zoom_value = self.ctx.deps.devs.zoom
self.logger.info("Starting face detection sequence")
self.ctx.deps.devs.set_zoom(zoom_value, wait=True)
boxes_face: dict[int, tuple[float, float, float, float]] = {}
boxes_loop: dict[int, tuple[float, float, float, float]] = {}
curr_angle = int(self.ctx.deps.devs.aerotech_omega)
total_range = steps * step_size + 1
start_angle = curr_angle if curr_angle + total_range < 720 else 0
end_angle = curr_angle + total_range
for angle in range(start_angle, end_angle, step_size):
self.logger.debug(f"moving to angle: {angle}")
rotate_time = time.perf_counter()
self.ctx.deps.devs.aerotech_omega = angle
log_duration(
self.logger,
"Completed Aerotech move during face detection",
time.perf_counter() - rotate_time,
extra={"angle_deg": angle},
)
prediction_result: MLBoxPredictionResult = self.ctx.deps.mlbox.predict(
preferred_class=(3, 0), return_image=True, return_bundle_meta=True
)
model = prediction_result.box
log_ml_bundle_meta(
self.logger,
f"face_detection_angle_{angle}",
target_point=prediction_result.target_point,
focus=prediction_result.focus,
)
if not model or not model.box:
self._log_warning(f"no box found for angle {angle}")
self._emit_running_progress(angle=angle, boxes_face=boxes_face)
continue
cls_id = int(model.cls.value)
x1, y1, x2, y2 = (
model.box.top_x,
model.box.top_y,
model.box.bottom_x,
model.box.bottom_y,
)
self._centre_correction(model, tolerance=0.2)
if cls_id == 3:
boxes_face[angle] = (x1, y1, x2, y2)
self.logger.debug(
f"accepted box at angle {angle}, cls={cls_id}, box={(x1, y1, x2, y2)}"
)
elif cls_id == 0:
boxes_loop[angle] = (x1, y1, x2, y2)
self.logger.debug(
f"accepted box at angle {angle}, cls={cls_id}, box={(x1, y1, x2, y2)}"
)
else:
self.logger.debug(f"ignoring class {cls_id} at angle {angle}")
self._emit_running_progress(angle=angle, boxes_face=boxes_face)
if not boxes_face and not boxes_loop:
self._log_warning("no boxes found")
payload = self._emit_empty_result()
return FaceDetectionResult(success=True, payload=payload)
total_detections = len(boxes_face) + len(boxes_loop)
face_ratio = len(boxes_face) / total_detections if total_detections > 0 else 0.0
if boxes_face and face_ratio >= face_min_ratio:
boxes = boxes_face
self.logger.debug(
f"using loop_face boxes ({len(boxes_face)}/{total_detections}, ratio={face_ratio:.2f})"
)
elif boxes_loop:
boxes = boxes_loop
self.logger.debug(
f"falling back to loop_all boxes ({len(boxes_loop)}/{total_detections}, ratio={1 - face_ratio:.2f})"
)
else:
boxes = boxes_face
self.logger.debug(f"using loop_face boxes (only source, {len(boxes_face)} entries)")
best_fit_angle_area, area_params = fd.get_flat_face(boxes, start_angle, end_angle, True)
best_fit_angle_height, height_params = fd.get_flat_face(
boxes, start_angle, end_angle, False
)
fit_results = {
"Area": {"angle": best_fit_angle_area, "params": area_params},
"Height": {"angle": best_fit_angle_height, "params": height_params},
}
self.logger.debug(f"best angle by area: {best_fit_angle_area}")
self.logger.debug(f"best angle by height: {best_fit_angle_height}")
flat_face_angle, best_params, best_name = fd.choose_best_fit(fit_results)
self.logger.debug(f"best params: {best_params}")
self.logger.debug(f"chosen fit: {best_name}")
self.logger.info(f"best angle: {flat_face_angle}")
self.ctx.deps.devs.aerotech_omega = flat_face_angle
samples_out = fd.get_samples_out(boxes)
self.logger.info("Face detection sequence complete")
payload = {
"running": False,
"samples": samples_out,
"height_fit": {
"A": height_params["A"],
"B": height_params["B"],
"phi_rad": height_params["phi_rad"],
"C": height_params["C"],
"best_angle_deg": best_fit_angle_height,
},
"area_fit": {
"A": area_params["A"],
"B": area_params["B"],
"phi_rad": area_params["phi_rad"],
"C": area_params["C"],
"best_angle_deg": best_fit_angle_area,
},
}
self._progress_emitter().emit_progress(payload)
return FaceDetectionResult(success=True, payload=payload)
except Exception as e:
self.logger.exception("error in face detection sequence")
payload = self._emit_empty_result()
return FaceDetectionResult(
success=False, payload=payload, error=e, comment="Face detection sequence failed"
)
finally:
self.ctx.deps.cfg.zoom_mode = ZoomModeEnum.User
@@ -1,217 +0,0 @@
import json
import math
import statistics
import time
import warnings
import numpy as np
from aarecommon.config.logger import setup_logger
from scipy.optimize import OptimizeWarning, curve_fit
logger = setup_logger("aareDAQ")
def box_height_from_tuple(box: tuple[float, float, float, float]) -> float:
_x1, y1, _x2, y2 = box
return abs(y2 - y1)
def box_area_from_tuple(box: tuple[float, float, float, float]) -> float:
x1, y1, x2, y2 = box
return abs(y2 - y1) * abs(x2 - x1)
def prepare_samples(
boxes_by_angle: dict[int, tuple[float, float, float, float]], area=False
) -> list[tuple[float, float]]:
# angles in degrees -> (theta_rad, height)
samples = []
for deg, box in boxes_by_angle.items():
v = box_area_from_tuple(box) if area else box_height_from_tuple(box)
samples.append((float(deg), v))
return samples
def cos_model(theta_deg: float | np.ndarray, A: float, B: float, phi_rad: float, C: float):
return A + B * np.cos(C * np.deg2rad(theta_deg) - phi_rad)
def mad_filter(samples: list[tuple[float, float]], k: float = 3.5) -> list[tuple[float, float]]:
if not samples:
return samples
ys = [y for _, y in samples]
med = statistics.median(ys)
mad = statistics.median([abs(y - med) for y in ys]) or 1.0
return [(d, y) for d, y in samples if abs(y - med) <= k * mad]
def samples_to_json(samples):
output_data = {
"timestamp": time.ctime(),
"scan_results": samples,
"total_results": len(samples),
}
with open("cos_test.json", "w") as f:
json.dump(output_data, f, indent=2)
def fit_metrics(y_true: np.ndarray, y_pred: np.ndarray) -> tuple[float, float, float]:
resid = y_true - y_pred
rmse = float(np.sqrt(np.mean(resid**2)))
mae = float(np.mean(np.abs(resid)))
# R² with protection against zero variance
ss_tot = float(np.sum((y_true - np.mean(y_true)) ** 2))
r2 = float(1.0 - np.sum(resid**2) / ss_tot) if ss_tot > 0 else float("nan")
return rmse, mae, r2
def fit_cosine(samples: list[tuple[float, float]]) -> dict:
samples = mad_filter(samples, k=3.5)
if len(samples) < 3:
A = sum(y for _, y in samples) / max(1, len(samples))
return {"A": A, "B": 1.0, "phi_rad": 0.0, "C": 1.0, "rmse": None, "mae": None, "r2": None}
degs = np.array([d for d, _ in samples], dtype=float)
ys = np.array([y for _, y in samples], dtype=float)
# Initial guess via linearized cosine/sine fit
cosv = np.cos(np.deg2rad(degs))
sinv = np.sin(np.deg2rad(degs))
X = np.column_stack([np.ones_like(degs), cosv, sinv]) # [A, C, S]
try:
beta, _, _, _ = np.linalg.lstsq(X, ys, rcond=None)
A0, C0, S0 = beta.tolist()
except Exception:
logger.debug("Cosine fit seeding failed; falling back to the mean", exc_info=True)
A0, C0, S0 = float(np.mean(ys)), 0.0, 0.0
B0 = float(math.hypot(C0, S0))
phi0 = float(math.atan2(S0, C0))
C0 = 1.0
# Bounds to keep B reasonable and phi in [-pi, pi]
y_std = float(np.std(ys)) or 1.0
B_max = 10.0 * y_std
bounds = ([-np.inf, 0.0, -math.pi, -np.inf], [np.inf, B_max, math.pi, np.inf])
try:
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", OptimizeWarning)
popt, _ = curve_fit(
cos_model, degs, ys, p0=[A0, B0, phi0, C0], bounds=bounds, maxfev=10000
)
if w:
logger.debug(f"curve_fit OptimizeWarning: {w[-1].message}")
logger.info(f"fit cosine: {popt}")
A, B, phi, C = map(float, popt)
B = max(0.0, B)
yhat = cos_model(degs, A, B, phi, C)
rmse, mae, r2 = fit_metrics(ys, yhat)
return {"A": A, "B": B, "phi_rad": phi, "C": C, "rmse": rmse, "mae": mae, "r2": r2}
except Exception as e:
# Fallback to initial
logger.info(f"error in curve fit {e}", exc_info=True)
yhat0 = cos_model(degs, A0, max(0.0, B0), phi0, C0)
rmse0, mae0, r2_0 = fit_metrics(ys, yhat0)
return {
"A": float(A0),
"B": max(0.0, float(B0)),
"phi_rad": float(phi0),
"C": float(C0),
"rmse": rmse0,
"mae": mae0,
"r2": r2_0,
}
def get_samples_out(boxes):
samples_out = []
for deg, box in boxes.items():
h = box_height_from_tuple(box)
a = box_area_from_tuple(box)
samples_out.append({"angle_deg": float(deg), "height": float(h), "area": float(a)})
samples_out.sort(key=lambda x: x["angle_deg"])
return samples_out
def choose_best_fit(fits_by_name: dict[str, dict]) -> tuple[float | None, dict | None, str | None]:
def key(entry: dict):
params = entry.get("params") or {}
rmse = params.get("rmse")
mae = params.get("mae")
r2 = params.get("r2")
logger.info(f"params: {params}")
# Treat None/NaN as non-comparable
if rmse is None or mae is None or r2 is None:
return None
try:
logger.info(f"rmse: {rmse}, mae: {mae}, r2: {r2}")
return float(rmse), float(mae), -float(r2)
except Exception:
logger.debug("Could not score a candidate fit", exc_info=True)
return None
best_name = None
best_fit = None
best_key = None
for name, entry in fits_by_name.items():
k = key(entry)
logger.info(f"name: {name}, entry: {entry}, key : {k}")
if k is None:
continue
if best_key is None or k < best_key:
best_key = k
best_fit = entry
best_name = name
if best_fit is None:
return None, None, None
best_angle = best_fit.get("angle")
best_angle = float(best_angle) if isinstance(best_angle, (int, float)) else None
return (best_angle, best_fit, best_name)
def get_flat_face(
boxes: dict[int, tuple[float, float, float, float]],
start_angle: int,
end_angle: int,
area: bool = False,
) -> tuple[int, dict]:
samples = prepare_samples(boxes, area=area)
parameters = fit_cosine(samples)
def safe_best_angle(params: dict) -> int:
if not params:
return 0
search_grid = range(start_angle, end_angle, 1)
A = float(params.get("A", 0.0))
B = float(max(0.0, params.get("B", 0.0)))
C = float(params.get("C", 0.0))
phi = float(params.get("phi_rad", 0.0))
if B <= 1e-9 or not math.isfinite(A) or not math.isfinite(phi):
return 0
return max(search_grid, key=lambda d: cos_model(d, A, B, phi, C))
best_fit_angle = safe_best_angle(parameters)
return best_fit_angle, parameters
def chose_best_angle(boxes: dict[int, tuple[float, float, float, float]], fit_results) -> int:
measured_angles = list(boxes.keys())
choose_best_fit(fit_results)
candidates = [
a
for a in (fit_results["Area"]["angle"], fit_results["Height"]["angle"])
if isinstance(a, (int, float))
]
if measured_angles and candidates:
chosen = min(
candidates, key=lambda a: min(abs(((a - m + 180) % 360) - 180) for m in measured_angles)
)
else:
chosen = candidates[0] if candidates else 0
return chosen
@@ -1,17 +0,0 @@
from aare.daq.operations.loop_centering.analyzer import LoopCenteringAnalyzer
from aare.daq.operations.loop_centering.models import (
AngleAnalysis,
AttemptSummary,
LoopCenteringContext,
LoopCenteringSettings,
)
from aare.daq.operations.loop_centering.service import LoopCenteringService
__all__ = [
"AngleAnalysis",
"AttemptSummary",
"LoopCenteringAnalyzer",
"LoopCenteringContext",
"LoopCenteringService",
"LoopCenteringSettings",
]
@@ -1,178 +0,0 @@
from aarecommon.config.logger_events import log_ml_bundle_meta
from aarecommon.math.coordinate import Coordinate, SmargonCoordinate
from aarecommon.models.models import MLBoxType
from aare.daq.operations.loop_centering.models import AngleAnalysis, LoopCenteringContext
class LoopCenteringAnalyzer:
def __init__(self, *, context: LoopCenteringContext, logger):
self.ctx = context
self.logger = logger
def is_ignore_only_classes(self, classes: list[int] | None) -> bool:
if not classes:
return False
ignore_classes = {MLBoxType.PIN.value, MLBoxType.NEEDLE.value, MLBoxType.ICE.value}
found = {int(cls) for cls in classes if cls is not None}
return bool(found) and found.issubset(ignore_classes)
def has_valid_target_classes(self, classes: list[int] | None) -> bool:
if not classes:
return False
valid_classes = {
MLBoxType.LOOP_ALL.value,
MLBoxType.LOOP_FACE.value,
MLBoxType.CRYSTAL.value,
}
return any(int(cls) in valid_classes for cls in classes if cls is not None)
def select_smargon_target(
self,
*,
calculated_target: SmargonCoordinate | None,
predicted_target: SmargonCoordinate | None,
tolerance_um: float | None = None,
) -> SmargonCoordinate | None:
if calculated_target is None:
return predicted_target
if predicted_target is None:
return calculated_target
if tolerance_um is None:
tolerance_um = self.ctx.settings.target_tolerance_um
tolerance_mm = tolerance_um / 1000.0
dx = abs(calculated_target.sh_mm.x - predicted_target.sh_mm.x)
dy = abs(calculated_target.sh_mm.y - predicted_target.sh_mm.y)
dz = abs(calculated_target.sh_mm.z - predicted_target.sh_mm.z)
if dx <= tolerance_mm and dy <= tolerance_mm and dz <= tolerance_mm:
self.logger.info(
"Using prediction target because it is within %.0f um of calculated target "
"(dx=%.4f mm, dy=%.4f mm, dz=%.4f mm)",
tolerance_um,
dx,
dy,
dz,
)
return predicted_target
self.logger.info(
"Keeping calculated target because prediction target is outside %.0f um "
"(dx=%.4f mm, dy=%.4f mm, dz=%.4f mm)",
tolerance_um,
dx,
dy,
dz,
)
return calculated_target
def _extract_prediction_target(
self, *, target_point: tuple[float, float] | None
) -> SmargonCoordinate | None:
if target_point is None:
return None
geom = self.ctx.runtime.sample_geometry
return SmargonCoordinate(
sh_mm=geom.picture_to_smargon(Coordinate(x=target_point[0], y=target_point[1]))
)
def _interpret_ml_loop_centre_box(
self, boxes
) -> tuple[SmargonCoordinate | None, int | None, list[int]]:
if boxes is None:
return None, None, []
classes: list[int] = []
pin = None
centre_x, centre_y = None, None
for box in boxes.boxes.values():
if box and box.cls is not None:
classes.append(int(box.cls.value))
if box.cls == MLBoxType.PIN:
pin = box
best_box = self.ctx.deps.mlbox.get_preferred_class_box(
boxes, (MLBoxType.CRYSTAL, MLBoxType.LOOP_FACE, MLBoxType.LOOP_ALL, MLBoxType.PIN)
)
if best_box is None or best_box.box is None or best_box.cls is None:
return None, None, classes
cls = int(best_box.cls.value)
x1 = best_box.box.top_x
y1 = best_box.box.top_y
x2 = best_box.box.bottom_x
y2 = best_box.box.bottom_y
geom = self.ctx.runtime.sample_geometry
if cls == MLBoxType.LOOP_ALL.value:
if y1 + y2 <= x1 + x2:
centre_y = y1 + (y2 - y1) / 2
centre_x = x1
elif pin:
position_dict = self.ctx.deps.mlbox.check_box_relation(pin, best_box)
if position_dict["overlap_y"] and position_dict["overlap_x"]:
centre_y = y1 + (y2 - y1) / 2
centre_x = x1
cls = MLBoxType.PIN.value
else:
centre_y = y2 if position_dict["top"] else y1
centre_x = x1 + (x2 - x1) / 2
else:
centre_y = y1
centre_x = x1 + (x2 - x1) / 2
elif cls == MLBoxType.PIN.value:
centre_y = y1 + (y2 - y1) / 2
centre_x = x1
elif cls in (MLBoxType.CRYSTAL.value, MLBoxType.LOOP_FACE.value):
centre_y = y1 + (y2 - y1) / 2
centre_x = x1 + (x2 - x1) / 2
else:
return None, cls, classes
coord = geom.picture_to_smargon(Coordinate(x=centre_x, y=centre_y))
return SmargonCoordinate(sh_mm=coord), cls, classes
def analyze_angle(
self, *, angle_deg: int, zoom_value: float, sample_id: int | None
) -> AngleAnalysis:
if self.ctx.services.predictions is None:
raise RuntimeError("LoopCenteringAnalyzer requires services.predictions")
prediction_result = self.ctx.services.predictions.get_predictions()
log_ml_bundle_meta(
self.logger,
f"loop_center_angle_{angle_deg}_zoom_{zoom_value:.0f}",
target_point=prediction_result.target_point,
focus=prediction_result.focus,
)
predicted_target = self._extract_prediction_target(
target_point=prediction_result.target_point
)
calculated_target, selected_class, classes = self._interpret_ml_loop_centre_box(
prediction_result.predictions
)
analysis = AngleAnalysis(
angle_deg=angle_deg,
classes=classes,
selected_class=selected_class,
calculated_target=calculated_target,
predicted_target=predicted_target,
)
analysis.ignore_only = self.is_ignore_only_classes(analysis.classes)
analysis.has_valid_target = self.has_valid_target_classes(analysis.classes)
analysis.final_target = self.select_smargon_target(
calculated_target=analysis.calculated_target, predicted_target=analysis.predicted_target
)
return analysis
@@ -1,46 +0,0 @@
from dataclasses import dataclass, field
from aarecommon.math.coordinate import SmargonCoordinate
from aare.daq.mlbox import MlBox
from aare.daq.operations.common.models import BaseOperationContext, BeamlineDependencies
@dataclass
class LoopCenteringDependencies(BeamlineDependencies):
mlbox: MlBox
@dataclass
class AngleAnalysis:
angle_deg: int
classes: list[int] = field(default_factory=list)
selected_class: int | None = None
calculated_target: SmargonCoordinate | None = None
predicted_target: SmargonCoordinate | None = None
final_target: SmargonCoordinate | None = None
moved: bool = False
ignore_only: bool = False
has_valid_target: bool = False
@dataclass
class AttemptSummary:
attempt_number: int
first_pass: list[AngleAnalysis] = field(default_factory=list)
correction_pass: list[AngleAnalysis] = field(default_factory=list)
@dataclass
class LoopCenteringSettings:
overlap_with_pin: float = 0.5
confidence_min: float | None = None
zoom_value: float = 200.0
max_attempts: int = 2
target_tolerance_um: float = 500.0
angles: tuple[int, int] = (0, 90)
@dataclass
class LoopCenteringContext(BaseOperationContext[LoopCenteringDependencies, LoopCenteringSettings]):
pass
@@ -1,206 +0,0 @@
import time
from aarecommon.config.logger_events import log_duration
from aarecommon.errors.exception_handler import LoopCenteringFailed
from aarecommon.models.models import LoopCenteringResult, MLBoxType
from aare.daq.operations.loop_centering.analyzer import LoopCenteringAnalyzer
from aare.daq.operations.loop_centering.models import (
AngleAnalysis,
AttemptSummary,
LoopCenteringContext,
)
from aare.devices.area_detector import AutoEnum
class LoopCenteringService:
def __init__(self, *, context: LoopCenteringContext, logger):
self.ctx = context
self.logger = logger
self.analyzer = LoopCenteringAnalyzer(context=context, logger=logger)
def _run_angle_pass(
self,
*,
angle: int,
zoom_value: float,
sample_id: int | None,
trace_all_alc_moves: bool,
wait_screenshot_sleep_sec: float = 0.3,
) -> AngleAnalysis:
self.logger.debug(f"Moving to new omega: {angle}")
time_to_move_aerotech = time.perf_counter()
self.ctx.deps.devs.aerotech_omega = angle
log_duration(
self.logger,
"Completed Aerotech move during loop centering",
time.perf_counter() - time_to_move_aerotech,
extra={"angle_deg": angle, "zoom": zoom_value},
)
analysis = self.analyzer.analyze_angle(
angle_deg=angle, zoom_value=zoom_value, sample_id=sample_id
)
if (
analysis.has_valid_target
and not analysis.ignore_only
and analysis.final_target is not None
):
time_to_move_smargon = time.perf_counter()
self.ctx.deps.devs.smargon_pos = analysis.final_target
self.ctx.deps.devs.smargon_wait(60)
log_duration(
self.logger,
"Completed Smargon move during loop centering",
time.perf_counter() - time_to_move_smargon,
extra={"angle_deg": angle, "zoom": zoom_value},
)
analysis.moved = True
if sample_id is not None and trace_all_alc_moves:
self.ctx.services.traces.append_smargon_trace(
sample_id=sample_id, event=f"alc_move_zoom_{zoom_value:.0f}_angle_{angle}"
)
else:
self.logger.debug(f"Skipping move at angle {angle}; classes={analysis.classes}")
if sample_id is not None and analysis.selected_class in (
MLBoxType.LOOP_ALL.value,
MLBoxType.LOOP_FACE.value,
MLBoxType.CRYSTAL.value,
):
self.ctx.services.screenshots.save_to_db(
sample_id, f"{sample_id}_{angle}_{zoom_value:.0f}", wait_screenshot_sleep_sec
)
return analysis
def run(
self,
*,
sample_id: int | None,
trace_all_alc_moves: bool = False,
wait_screenshot_sleep_sec: float = 0.3,
max_attempts: int | None = None,
) -> LoopCenteringResult:
settings = self.ctx.settings
found_classes_count: dict[int, int] = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
angles = settings.angles
max_attempts = settings.max_attempts if max_attempts is None else max_attempts
failure_reason: str | None = None
attempts: list[AttemptSummary] = []
try:
zoom_value = settings.zoom_value
if abs(self.ctx.deps.devs.zoom - zoom_value) > 1e-6:
self.ctx.deps.devs.samcam_auto(AutoEnum.AUTO)
self.ctx.deps.devs.zoom = zoom_value
time.sleep(0.2)
self.ctx.deps.devs.samcam_auto(AutoEnum.ONCE)
if sample_id is not None:
self.logger.info(
f"submitting to db loop center sequence for sample {sample_id}, zoom={zoom_value}"
)
self.ctx.services.screenshots.save_to_db(
sample_id, "pre_alc", wait_screenshot_sleep_sec
)
for attempt_number in range(1, max_attempts + 1):
self.logger.info(f"Starting ALC attempt {attempt_number}/{max_attempts}")
attempt = AttemptSummary(attempt_number=attempt_number)
for angle in angles:
result = self._run_angle_pass(
angle=angle,
zoom_value=zoom_value,
sample_id=sample_id,
trace_all_alc_moves=trace_all_alc_moves,
wait_screenshot_sleep_sec=wait_screenshot_sleep_sec,
)
attempt.first_pass.append(result)
for c in result.classes:
found_classes_count[int(c)] = found_classes_count.get(int(c), 0) + 1
if attempt_number == 1:
valid_seen_first_pass = any(
result.has_valid_target for result in attempt.first_pass
)
if not valid_seen_first_pass:
failure_reason = (
"ALC failed on attempt 1: no loop face, loop all or crystal "
"detected at 0 and 90 degrees"
)
raise LoopCenteringFailed(failure_reason)
for angle in angles:
result = self._run_angle_pass(
angle=angle,
zoom_value=zoom_value,
sample_id=sample_id,
trace_all_alc_moves=trace_all_alc_moves,
wait_screenshot_sleep_sec=wait_screenshot_sleep_sec,
)
attempt.correction_pass.append(result)
for c in result.classes:
found_classes_count[int(c)] = found_classes_count.get(int(c), 0) + 1
attempts.append(attempt)
valid_seen_correction = any(
result.has_valid_target for result in attempt.correction_pass
)
self.logger.debug(
f"ALC attempt {attempt_number}: valid_seen_correction={valid_seen_correction}"
)
if valid_seen_correction:
if sample_id is not None:
self.logger.info(f"sample {sample_id} centered")
self.ctx.services.traces.append_smargon_trace(
sample_id=sample_id, event="alc_success"
)
return LoopCenteringResult(success=True)
failure_reason = f"ALC exceeded max attempts ({max_attempts})"
raise LoopCenteringFailed(failure_reason)
except Exception as e:
total_detections = sum(found_classes_count.values())
if failure_reason is not None and total_detections > 0:
alc_comment = (
f"{failure_reason}. "
f"Detected objects - "
f"Crystal: {found_classes_count.get(2, 0)}, "
f"Loop_face: {found_classes_count.get(3, 0)}, "
f"Loop_all: {found_classes_count.get(0, 0)}, "
f"Pin: {found_classes_count.get(1, 0)}, "
f"Ice: {found_classes_count.get(4, 0)}, "
f"Needle: {found_classes_count.get(5, 0)}"
)
elif failure_reason is not None:
alc_comment = failure_reason
elif total_detections == 0:
alc_comment = "No objects detected"
else:
alc_comment = (
"Failed to centre but detected objects - "
f"Crystal: {found_classes_count.get(2, 0)}, "
f"Loop_face: {found_classes_count.get(3, 0)}, "
f"Loop_all: {found_classes_count.get(0, 0)}, "
f"Pin: {found_classes_count.get(1, 0)}, "
f"Ice: {found_classes_count.get(4, 0)}, "
f"Needle: {found_classes_count.get(5, 0)}"
)
self.logger.exception(f"ALC exception: {alc_comment}")
return LoopCenteringResult(success=False, comment=alc_comment, error=e)
@@ -1,4 +0,0 @@
from aare.daq.operations.mounting.models import MountingContext, MountingResult
from aare.daq.operations.mounting.service import MountingService
__all__ = ["MountingContext", "MountingResult", "MountingService"]
@@ -1,36 +0,0 @@
from dataclasses import dataclass
from aarecommon.math.coordinate import AerotechCoordinate
from aarecommon.models.models import SampleShortInfo
from aare.daq.operations.common.models import BeamlineDependencies
@dataclass
class MountingDependencies(BeamlineDependencies):
pass
@dataclass
class MountingSettings:
mount_position: AerotechCoordinate
@dataclass
class MountingContext:
deps: MountingDependencies
settings: MountingSettings
@dataclass
class MountingResult:
success: bool
mounted_sample: SampleShortInfo | None = None
previous_sample: SampleShortInfo | None = None
did_unmount_previous: bool = False
error: Exception | None = None
comment: str | None = None
@property
def is_error(self) -> bool:
return self.error is not None
-251
View File
@@ -1,251 +0,0 @@
import time
from aarecommon.errors.exception_handler import (
CriticalTellException,
DoorSafetyError,
MountingFailed,
TellCommunicationError,
UnmountingFailed,
)
from aare.daq.operations.mounting.models import MountingContext, MountingResult
from aare.devices.tell_client import TellEventValueEnum
DRY_AFTER_FAIL_COUNT = 3
STOP_AFTER_FAIL_COUNT = 5
class MountingService:
def __init__(self, *, context: MountingContext, logger):
self.ctx = context
self.logger = logger
def reset_mount_failure_counter(self, reason: str) -> None:
previous_count = self.ctx.deps.cfg.get_mount_failure_streak()
if previous_count > 0:
self.logger.warning(
f"Resetting mount failure counter from {previous_count} due to: {reason}"
)
else:
self.logger.debug(f"Mount failure counter already clear: {reason}")
self.ctx.deps.cfg.reset_mount_failure_streak()
def _magnet_position_sensor_check(self, timeout: float = 1.0) -> None:
if self.ctx.deps.devs.magnet_position_sensor.value != 0:
self.logger.warning(
"Goniometer is not in position based on magnet position sensor readout"
)
for _ in range(round(timeout * 10.0)):
if self.ctx.deps.devs.magnet_position_sensor.value == 0:
return
time.sleep(0.1)
self.logger.error(
"Goniometer didn't reach position based on magnet position sensor readout"
)
raise RuntimeError(
"Goniometer is not in position based on magnet position sensor readout"
)
def _handle_consecutive_mount_failure(self) -> None:
count = self.ctx.deps.cfg.increment_mount_failure_streak()
self.logger.warning(f"Consecutive mount failure count is now {count}")
if count == DRY_AFTER_FAIL_COUNT:
self.logger.warning(f"Mount failed {count} times in a row; drying")
try:
self.dry(park=False)
except Exception:
self.logger.exception("Failed to dry after mount failure")
if count >= STOP_AFTER_FAIL_COUNT:
self.logger.error(f"Mount failed {count} times in a row, stopping automation")
self.logger.error("Unmounting sample and drying")
try:
self._unmount_current_sample(timeout=60.0)
self.dry(park=True)
except Exception:
self.logger.exception("Failed to clean up after repeated mount failure")
raise MountingFailed(
f"Mount failed {count} times in a row, stopping automation.", critical=True
)
def _mount_handler(self, target) -> None:
self._prepare_mount_hardware()
value = self.ctx.deps.devs.tell.mount(
address=target.tell_address(),
force=True,
auto_unmount=True,
read_dm=False,
wait=True,
timeout=360.0,
)
if isinstance(value, str):
self.ctx.deps.devs.tell.check_command_ok()
self.logger.error(
f"{self.ctx.deps.devs.tell.get_result(self.ctx.deps.devs.tell._last_cmd_id)}"
)
self.logger.error(f"Unexpected string response from Tell mount: {value}")
raise CriticalTellException(
f"Critical error in TELL mount: unexpected response '{value}'"
)
if value is None:
self.logger.error("Tell mount returned no response (None)")
raise CriticalTellException("Critical error in TELL mount: no response")
safe_val = getattr(value, "value", str(value))
self.logger.debug(f"Mount response: {safe_val}")
if value == TellEventValueEnum.NO_PIN_IN_GRIPPER:
raise MountingFailed("No Pin in Gripper")
if value == TellEventValueEnum.PIN_IS_LOST_GRIPPER:
self.logger.error("Pin is lost")
raise MountingFailed("Pin is lost")
if value in (
TellEventValueEnum.ROBOT_CLEAR_AFTER_MOUNT,
TellEventValueEnum.DRY,
TellEventValueEnum.COLD,
TellEventValueEnum.SUCCESS,
):
self.logger.info(f"Robot is {safe_val} - freeing beamline for user")
return
message = f"Mount response not handled: {safe_val}"
self.logger.error(message)
raise CriticalTellException(f"Critical error in TELL mount: {message}")
def _check_hutch_safety(self) -> None:
"""Block robot motion unless the hutch PSS permits it.
The robot only moves when the hutch is in the *prohibited* state; if it
is not, the door safety could not be activated. A non-zero alarm state
is also blocked. Always raised critical so automation halts and the GUI
shows a pop-up.
"""
pss = self.ctx.deps.devs.pss
if not pss.is_prohibited():
self.logger.error("Hutch is not in prohibited state; robot motion not permitted")
raise DoorSafetyError(
"Door safety could not be activated: close the hutch doors and "
"complete the safety search before mounting."
)
if pss.alarm_active():
self.logger.error("Hutch safety alarm is active; blocking robot motion")
raise DoorSafetyError("Hutch safety alarm is active. Mounting blocked.")
def _prepare_mount_hardware(self) -> None:
self._check_hutch_safety()
self.ctx.deps.devs.smargon_move_home()
self.ctx.deps.devs.aerotech_pos = self.ctx.settings.mount_position
self._magnet_position_sensor_check(timeout=10.0)
self.ctx.deps.devs.tell.check_enable_motion()
self.ctx.deps.devs.tell.wait_not_busy()
# enable_motion releases the door safety, so the door can only be
# validated once motion is enabled.
self.ctx.deps.devs.tell.validate_door_closed()
self.ctx.deps.devs.tell.set_in_mount_position(True)
def _unmount_current_sample(self, timeout: float = 60.0):
# Timeout here is reduced from the default 360s because an error should be caught by
# the retry handler later. If errors from this function are not propagated correctly
# (e.g. through _handle_operation_error) it may cause weird problems that appear as timeouts!
self._prepare_mount_hardware()
previous_sample = self.ctx.deps.cfg.current_sample
if previous_sample is not None:
self.logger.debug(f"Unmounting sample: {previous_sample}")
self.ctx.deps.devs.tell.unmount(wait=True, timeout=timeout)
self.ctx.deps.cfg.current_sample = None
return previous_sample
def dry(self, *, park: bool, unmount: bool = False) -> None:
self.ctx.deps.devs.tell.check_enable_motion()
self.ctx.deps.devs.tell.wait_not_busy()
self.ctx.deps.devs.tell.set_in_mount_position(True)
if self.ctx.deps.cfg.current_sample and unmount:
self._prepare_mount_hardware()
self._unmount_current_sample(timeout=60.0)
if park:
self.ctx.deps.devs.tell.dry(wait_cold=-1, wait=True)
else:
self.ctx.deps.devs.tell.dry(wait=True)
def execute(self, *, target) -> MountingResult:
previous_sample = self.ctx.deps.cfg.current_sample
try:
if target is None:
try:
unmounted_sample = self._unmount_current_sample(timeout=60.0)
return MountingResult(
success=True,
mounted_sample=None,
previous_sample=unmounted_sample,
did_unmount_previous=unmounted_sample is not None,
)
except DoorSafetyError:
raise
except Exception as e:
raise UnmountingFailed(f"Failed to unmount: {e}") from e
log_msg = f"Mounting sample: {target}"
if previous_sample is not None:
log_msg = f"Unmounting sample: {previous_sample}\nand {log_msg}"
self.logger.debug(log_msg)
try:
self._mount_handler(target)
except (MountingFailed, TellCommunicationError):
self._handle_consecutive_mount_failure()
raise
self.logger.debug("Mounting succeeded, resetting mount failure counter")
self.ctx.deps.cfg.reset_mount_failure_streak()
self.ctx.deps.cfg.current_sample = target
return MountingResult(
success=True,
mounted_sample=target,
previous_sample=previous_sample,
did_unmount_previous=previous_sample is not None,
)
except CriticalTellException as e:
self.logger.error(f"Critical Tell error: {e}")
return MountingResult(
success=False,
mounted_sample=None,
previous_sample=previous_sample,
did_unmount_previous=False,
error=e,
comment=str(e),
)
except MountingFailed as e:
self.logger.error(f"Mount failed: {e}")
return MountingResult(
success=False,
mounted_sample=None,
previous_sample=previous_sample,
did_unmount_previous=False,
error=e,
comment=str(e),
)
except Exception as e:
self.logger.exception("Mount failed")
return MountingResult(
success=False,
mounted_sample=None,
previous_sample=previous_sample,
did_unmount_previous=False,
error=e,
comment=str(e),
)
@@ -1,4 +0,0 @@
from aare.daq.operations.raster.models import RasterBoundingBoxResult, RasterContext
from aare.daq.operations.raster.service import RasterService
__all__ = ["RasterBoundingBoxResult", "RasterContext", "RasterService"]
-37
View File
@@ -1,37 +0,0 @@
from dataclasses import dataclass
from typing import TYPE_CHECKING
from aarecommon.models.raster_grid import RasterGridRequest
from aare.daq.mlbox import MlBox
from aare.daq.operations.common.models import BaseOperationContext, BeamlineDependencies
if TYPE_CHECKING:
from aare.daq.aaredb import AareWrapper
from aare.devices.jfjoch import JFJochWrapper
@dataclass
class RasterDependencies(BeamlineDependencies):
mlbox: MlBox
jfjoch: "JFJochWrapper"
aare: "AareWrapper"
@dataclass
class RasterSettings:
auto_raster_max_images: int
auto_raster_min_cell_size_mm: float
auto_raster_skip_if_exceed_max_image_threshold: bool
wait_for_screenshot_s: float = 0.3
@dataclass
class RasterContext(BaseOperationContext[RasterDependencies, RasterSettings]):
pass
@dataclass
class RasterBoundingBoxResult:
request: RasterGridRequest | None
uploaded_filename: str | None = None
-769
View File
@@ -1,769 +0,0 @@
import copy
import time
from dataclasses import dataclass
from math import ceil, floor
from aarecommon.config.config_models import GridscanAnalysisMode
from aarecommon.config.logger_events import (
geom_log_context,
log_ml_bundle_meta,
merge_log_context,
raster_request_log_context,
sample_log_context,
)
from aarecommon.errors.exception_handler import RasterScanException
from aarecommon.math.coordinate import AerotechCoordinate, Coordinate, SmargonCoordinate
from aarecommon.math.find_xtal import (
center_of_grid,
compute_crystal_score_array,
get_best_b_factor,
get_res_of_image_number,
get_xtal_size,
raster_highest_score,
)
from aarecommon.math.jfjoch_gridscan_union import GridScanResult, Thresholds, analyse
from aarecommon.math.raster_grid import grid_to_image_id
from aarecommon.models.gridscan_decision import GridScanDecision
from aarecommon.models.models import BeamlineStateEnum
from aarecommon.models.raster_grid import (
CenterOfMassModel,
CompletedRasterGrid,
CompletedRasterGridElem,
RasterGridRequest,
)
from aareDB import SampleEventType
from jfjoch_client import ScanResult
from jfjoch_client.exceptions import NotFoundException
from jfjoch_client.models.grid_scan import GridScan
from aare.daq.daq import DAQStatusModel
from aare.daq.mlbox import MLBoxPredictionResult
from aare.daq.operations.common.ml_bounding_box import (
MLRasterPlan,
build_ml_raster_plan,
get_ml_bounding_box,
)
from aare.daq.operations.raster.models import RasterContext
@dataclass
class _AnalysisResults:
center_smargon_coord: SmargonCoordinate
com: CenterOfMassModel
scores: list[float | None] | None
v2_results: GridScanResult | None = None
class RasterService:
def __init__(self, *, context: RasterContext, logger):
self.ctx = context
self.logger = logger
self.ingestor = self.ctx.deps.aare
self.send_sample_event = (
self.ctx.services.events.send
if self.ctx.services.events is not None
else self.ctx.deps.aare.send_sample_event
)
def _get_anaylsis_results(
self,
mode: GridscanAnalysisMode,
scan_result: ScanResult,
request: RasterGridRequest,
*,
daq: DAQStatusModel | None = None,
thresholds: Thresholds | None = None,
z_um: float | None = None,
):
if mode == GridscanAnalysisMode.FindXtal:
com = raster_highest_score(scan_result.images)
_scores = compute_crystal_score_array(scan_result.images)
scores = [
float(_scores[img.nx, img.ny])
if img.nx is not None and img.ny is not None
else None
for img in scan_result.images
]
smargon_coord = self._smargon_offset_from_scan_result(scan_result, request, com)
v2_results = None
else:
step_x_um = request.grid_size_mm.x * 1000
step_y_um = request.grid_size_mm.y * 1000
grid_scan = GridScan(
n_fast=request.n_x, step_x_um=step_x_um, step_y_um=step_y_um, snake=True
)
v2_results = analyse(scan_result, grid_scan, daq=daq, thresholds=thresholds, z_um=z_um)
self.logger.info(
f"experimental gridscan analaysis results: \n {v2_results.model_dump_json(indent=2)}"
)
if v2_results.centre is not None:
com = CenterOfMassModel(
n_x=v2_results.centre.nx,
n_y=v2_results.centre.ny,
max_image=v2_results.centre.image_number,
)
smargon_coord = self._smargon_offset_from_scan_result(scan_result, request, com)
else:
com = center_of_grid(request.n_x, request.n_y)
smargon_coord = self._smargon_offset_from_scan_result(scan_result, request, com)
scores = None
return _AnalysisResults(smargon_coord, com, scores, v2_results)
def _smargon_offset_from_scan_result(
self, scan_result: ScanResult, request: RasterGridRequest, com: CenterOfMassModel
):
target_coor = com.get_com_mm(request)
target_coor_offset = self.ctx.sample_geometry.smargon_nudge(target_coor)
self.logger.info(
"Calculated raster centre offset",
extra=merge_log_context(
sample_log_context(self.ctx.sample),
raster_request_log_context(request),
{
"centre_offset_x_mm": target_coor_offset.x,
"centre_offset_y_mm": target_coor_offset.y,
"centre_offset_z_mm": target_coor_offset.z,
"grid_half_width_x_mm": request.grid_size_mm.x / 2,
"grid_half_height_y_mm": request.grid_size_mm.y / 2,
"top_left_x_mm": getattr(request.smargon_top_left.sh_mm, "x", None),
"top_left_y_mm": getattr(request.smargon_top_left.sh_mm, "y", None),
"top_left_z_mm": getattr(request.smargon_top_left.sh_mm, "z", None),
},
),
)
self.logger.info(f"moving Smargon to grid centre offset {target_coor_offset}")
return SmargonCoordinate(
sh_mm=request.smargon_top_left.sh_mm + target_coor_offset,
phi_deg=request.smargon_top_left.phi_deg,
chi_deg=request.smargon_top_left.chi_deg,
)
@staticmethod
def _scan_result_image_count(scan_result) -> int | None:
if scan_result is None or scan_result.images is None:
return None
return len(scan_result.images)
@staticmethod
def _grid_image_id_from_centre_offset(
*, x_mm: float, y_mm: float, request: RasterGridRequest
) -> int:
if request.grid_size_mm.x <= 0 or request.grid_size_mm.y <= 0:
raise ValueError("grid_size_mm must be positive")
if request.n_x < 1 or request.n_y < 1:
raise ValueError("Raster grid dimensions must be >= 1")
grid_x = floor(x_mm / request.grid_size_mm.x) + 1
grid_y = floor(y_mm / request.grid_size_mm.y) + 1
grid_x = min(max(1, grid_x), request.n_x)
grid_y = min(max(1, grid_y), request.n_y)
return grid_to_image_id(grid_x=grid_x, grid_y=grid_y, number_of_cols=request.n_x)
def _upload_raster_diffraction_preview(
self,
*,
sample_id: int,
filename: str,
image_id: int,
scan_result,
request: RasterGridRequest,
) -> None:
image_count = self._scan_result_image_count(scan_result)
if image_count is not None and not (0 <= image_id < image_count):
self.logger.warning(
"Skipping diffraction image upload because image id is outside scan result range",
extra=merge_log_context(
sample_log_context(self.ctx.sample),
raster_request_log_context(request),
{"diffraction_image_id": image_id, "image_count": image_count},
),
)
return
try:
diffraction_image = self.ctx.deps.jfjoch.get_diffraction_image(
image_id, show_spots=True, show_res_est=True, show_beam_center=True
)
except NotFoundException:
self.logger.warning(
"JFJoch diffraction preview image was not found after raster; continuing without upload",
extra=merge_log_context(
sample_log_context(self.ctx.sample),
raster_request_log_context(request),
{"diffraction_image_id": image_id, "image_count": image_count},
),
exc_info=True,
)
return
# Stamp spots/resolution from the best cell into the comment so the
# Results diffraction modal can show them as a legend (like screening).
comment = "Raster diffraction"
try:
best = scan_result.images[image_id]
bits = []
spots = getattr(best, "spots", None)
res = getattr(best, "res", None)
if spots is not None:
bits.append(f"{spots} spots")
if res is not None:
bits.append(f"{res:.2f} Å")
if bits:
comment = f"Raster diffraction ({', '.join(bits)})"
except Exception:
self.logger.debug(
"Could not build the raster diffraction preview comment", exc_info=True
)
self.ctx.deps.aare.upload_jpg(sample_id, filename, diffraction_image, message=comment)
def ml_bounding_box(
self, sample_id: int | None = None, filename: str | None = None
) -> RasterGridRequest | None:
return get_ml_bounding_box(
mlbox=self.ctx.deps.mlbox,
sample=self.ctx.sample,
sample_geometry=self.ctx.sample_geometry,
upload_image=self.ctx.deps.aare.upload_image,
logger=self.logger,
filename=filename,
max_images=self.ctx.settings.auto_raster_max_images,
min_cell_size_mm=self.ctx.settings.auto_raster_min_cell_size_mm,
skip_if_exceed_max_image_threshold=self.ctx.settings.auto_raster_skip_if_exceed_max_image_threshold,
)
def ml_raster_plan(
self, sample_id: int | None = None, filename: str | None = None
) -> MLRasterPlan | None:
return build_ml_raster_plan(
mlbox=self.ctx.deps.mlbox,
sample=self.ctx.sample,
sample_geometry=self.ctx.sample_geometry,
upload_image=self.ctx.deps.aare.upload_image,
logger=self.logger,
filename=filename,
max_images=self.ctx.settings.auto_raster_max_images,
min_cell_size_mm=self.ctx.settings.auto_raster_min_cell_size_mm,
skip_if_exceed_max_image_threshold=self.ctx.settings.auto_raster_skip_if_exceed_max_image_threshold,
)
@staticmethod
def _box_touches_frame_edge(
box, width: int | None, height: int | None, margin: int = 2
) -> bool:
if width is None or height is None:
return False
x1, y1, x2, y2 = box
return x1 <= margin or y1 <= margin or x2 >= width - margin or y2 >= height - margin
def auto_center_line_scan_top_left(
self,
*,
omega_deg: float,
file_prefix: str | None,
grid_size_mm: Coordinate,
default_n_y: int = 50,
y_retarget_threshold_mm: float | None = None,
y_padding_fraction_each_side: float | None = None,
) -> tuple[SmargonCoordinate, int]:
geom = self.ctx.sample_geometry
beam_x_pxl = geom.beam_location_pxl.x
beam_y_pxl = geom.beam_location_pxl.y
line_scan_centre = geom.picture_to_smargon(Coordinate(x=beam_x_pxl, y=beam_y_pxl))
n_y = default_n_y
prediction_result: MLBoxPredictionResult = self.ctx.deps.mlbox.predict(
preferred_class=(3, 0), return_image=False, return_bundle_meta=True
)
log_ml_bundle_meta(
self.logger,
f"auto_center_line_scan_{omega_deg:.2f}deg",
target_point=prediction_result.target_point,
focus=prediction_result.focus,
)
prediction_box = prediction_result.box
if prediction_box is not None:
box_y_height_px = abs(prediction_box.box.bottom_y - prediction_box.box.top_y)
box_y_center_px = prediction_box.box.top_y + box_y_height_px / 2
else:
box_y_center_px = None
if box_y_center_px is not None:
target_y_pxl = box_y_center_px
y_delta_mm = abs(target_y_pxl - beam_y_pxl) * geom.pixel_in_mm
if y_retarget_threshold_mm is None:
y_retarget_threshold_mm = geom.beam_size_mm.y * 2.0
if y_delta_mm > y_retarget_threshold_mm:
line_scan_centre = geom.picture_to_smargon(Coordinate(x=beam_x_pxl, y=target_y_pxl))
self.logger.info(
"Using ML target y for second auto-center raster",
extra=merge_log_context(
sample_log_context(self.ctx.sample),
{
"file_prefix": file_prefix,
"omega_deg": omega_deg,
"beam_y_pxl": beam_y_pxl,
"target_y_pxl": target_y_pxl,
"y_delta_mm": y_delta_mm,
"threshold_mm": y_retarget_threshold_mm,
"target_sh_x_mm": line_scan_centre.x,
"target_sh_y_mm": line_scan_centre.y,
"target_sh_z_mm": line_scan_centre.z,
},
),
)
else:
self.logger.info(
"Keeping beam-centred y line scan because ML target y shift is small",
extra=merge_log_context(
sample_log_context(self.ctx.sample),
{
"file_prefix": file_prefix,
"omega_deg": omega_deg,
"beam_y_pxl": beam_y_pxl,
"target_y_pxl": target_y_pxl,
"y_delta_mm": y_delta_mm,
"threshold_mm": y_retarget_threshold_mm,
},
),
)
else:
self.logger.info(
"No ML target point for second auto-center raster; using beam-centred line scan",
extra=merge_log_context(
sample_log_context(self.ctx.sample),
{
"file_prefix": file_prefix,
"omega_deg": omega_deg,
"beam_x_pxl": beam_x_pxl,
"beam_y_pxl": beam_y_pxl,
},
),
)
if prediction_box is not None and prediction_box.box is not None and grid_size_mm.y > 0:
box_height_pxl = abs(prediction_box.box.bottom_y - prediction_box.box.top_y)
padded_height_px = box_height_pxl * 2
padded_height_mm = padded_height_px * geom.pixel_in_mm
n_y = max(1, ceil(padded_height_mm / grid_size_mm.y))
self.logger.info(
"Computed second auto-center raster y size from ML box height",
extra=merge_log_context(
sample_log_context(self.ctx.sample),
{
"file_prefix": file_prefix,
"omega_deg": omega_deg,
"box_height_pxl": box_height_pxl,
"pixel_in_mm": geom.pixel_in_mm,
"grid_size_y_mm": grid_size_mm.y,
"prediction_type": str(getattr(prediction_box, "type", None)),
"padding_fraction_each_side": y_padding_fraction_each_side,
"padded_height_mm": padded_height_mm,
"computed_n_y": n_y,
},
),
)
else:
self.logger.info(
"Using default y size for second auto-center raster",
extra=merge_log_context(
sample_log_context(self.ctx.sample),
{
"file_prefix": file_prefix,
"omega_deg": omega_deg,
"default_n_y": default_n_y,
"has_prediction_box": prediction_box is not None
and prediction_box.box is not None,
},
),
)
offset = Coordinate(x=-grid_size_mm.x / 2.0, y=-(n_y - 1) * grid_size_mm.y / 2.0)
top_left = SmargonCoordinate(
sh_mm=line_scan_centre + geom.smargon_nudge(offset),
phi_deg=geom.smargon.phi_deg,
chi_deg=geom.smargon.chi_deg,
)
self.logger.info(
"Prepared second auto-center raster top-left from helper",
extra=merge_log_context(
sample_log_context(self.ctx.sample),
{
"file_prefix": file_prefix,
"omega_deg": omega_deg,
"n_y": n_y,
"offset_x_mm": offset.x,
"offset_y_mm": offset.y,
"offset_z_mm": offset.z,
"top_left_x_mm": getattr(top_left.sh_mm, "x", None),
"top_left_y_mm": getattr(top_left.sh_mm, "y", None),
"top_left_z_mm": getattr(top_left.sh_mm, "z", None),
},
),
)
return top_left, n_y
def _do_gridscan_move_on_aerotech(self, request: RasterGridRequest, expected_time: float):
self.ctx.deps.devs.set_dtz(request.dtz, wait=True)
self.ctx.deps.devs.aerotech.grid_scan(
grid_elem_size_y_um=request.grid_size_mm.y * 1000,
grid_elem_size_x_um=request.grid_size_mm.x * 1000,
grid_elem_count_x=request.n_x,
grid_elem_count_y=request.n_y,
time_per_element_s=request.exp_time_s,
run_async=True,
)
self.ctx.deps.devs.aerotech.wait_till_done(
timeout=int(round(expected_time + expected_time * 0.1 + 60, 0))
)
if isinstance(self.ctx.deps.cfg.abr_meas_pos, Coordinate):
coord = self.ctx.deps.cfg.abr_meas_pos
else:
coord = self.ctx.deps.cfg.abr_meas_pos.at_mm
self.ctx.deps.devs.aerotech_pos = AerotechCoordinate(
at_mm=coord, omega_deg=self.ctx.deps.devs.aerotech_omega
)
self.ctx.deps.devs.aerotech.wait_till_done(timeout=60)
def _check_setup(self, request: RasterGridRequest, wait_for_screenshot_s: float | None):
total_time = request.exp_time_s * request.n_x * request.n_y + request.n_y * 0.3
if wait_for_screenshot_s is None:
wait_for_screenshot_s = self.ctx.settings.wait_for_screenshot_s
if total_time > 1200:
raise RasterScanException(f"Raster scan is too long {total_time}s > 20min")
return total_time, wait_for_screenshot_s
def _initial_gridscan_ingestion(
self,
request: RasterGridRequest,
scan_result: ScanResult,
analysis_result: _AnalysisResults,
wait_for_screenshot_s: float,
sample_id: int,
):
self.logger.debug("moving to XtalSnapshot to take a screenshot of the sample")
if self.ctx.services.state is None:
raise RuntimeError("RasterService requires services.state")
self.ctx.services.state.set_state(BeamlineStateEnum.XtalSnapshot)
time.sleep(wait_for_screenshot_s)
self.ctx.services.screenshots.save_to_db(
sample_id, f"{sample_id}_post_raster_{int(request.omega_deg)}deg"
)
if analysis_result.v2_results is not None:
decision = GridScanDecision(algorithm="unknown", result=analysis_result.v2_results)
else:
decision = None
self.ingestor.ingest_gridscan(
sample=self.ctx.sample,
raster_result=scan_result,
raster_request=request,
analysis_image_scores=analysis_result.scores,
geom=self.ctx.sample_geometry,
com=analysis_result.com,
beam_mark_pxl=self.ctx.deps.cfg.get_beam_mark(self.ctx.deps.devs.zoom),
decision=decision,
)
def execute(
self, request: RasterGridRequest, wait_for_screenshot: float | None = None
) -> CompletedRasterGridElem:
try:
total_time, wait_for_screenshot = self._check_setup(request, wait_for_screenshot)
status = self.ctx.status
if request.smargon_top_left is not None:
self.ctx.deps.devs.set_smargon_pos(request.smargon_top_left)
self.logger.info(
"Starting raster acquisition",
extra=merge_log_context(
sample_log_context(self.ctx.sample),
raster_request_log_context(request),
{"state": getattr(status, "state", None)},
),
)
if self.ctx.sample is not None and self.ctx.sample.db_id is not None:
self.ctx.deps.aare.create_gridscan_run(self.ctx.sample, request, status)
self.ctx.deps.jfjoch.wait_till_running(timeout=60.0)
self.logger.debug(
f"Starting grid scan with {request.n_x}x{request.n_y} points, exp time {request.exp_time_s}s"
)
self._do_gridscan_move_on_aerotech(request, total_time)
scan_result = self.ctx.deps.jfjoch.wait_till_done(60)
if scan_result is None:
self.logger.error(
"JFJoch returned no ScanResult for raster",
extra=merge_log_context(
sample_log_context(self.ctx.sample),
raster_request_log_context(request),
{"exp_time_s": request.exp_time_s},
),
)
raise RasterScanException("JFJoch returned no ScanResult for raster")
else:
truncated_images = (
scan_result.images[:3] if len(scan_result.images) > 3 else scan_result.images
)
self.logger.debug(
f"Raster scan results from JFJoch: file {scan_result.file_prefix} with images {truncated_images} ..."
)
analysis_results = self._get_anaylsis_results(
self.ctx.deps.cfg.gridscan_analysis_mode, scan_result, request, daq=self.ctx.status
)
self.ctx.deps.devs.smargon_pos = analysis_results.center_smargon_coord
self.ctx.deps.devs.smargon_wait(timeout=180)
self.logger.info(
f"Moved Smargon to raster centre: {analysis_results.center_smargon_coord}"
)
sample_id = (
self.ctx.sample.db_id
if self.ctx.sample and self.ctx.sample.db_id is not None
else None
)
if sample_id:
self._initial_gridscan_ingestion(
request, scan_result, analysis_results, wait_for_screenshot, sample_id
)
diffraction_image_id = analysis_results.com.max_image
diffraction_image_filename = (
f"{sample_id}_best_diffraction_from_raster_image_{diffraction_image_id}"
)
self._upload_raster_diffraction_preview(
sample_id=sample_id,
filename=diffraction_image_filename,
image_id=diffraction_image_id,
scan_result=scan_result,
request=request,
)
self.send_sample_event(
sample_id,
SampleEventType.RASTERED,
comment=f"Raster completed at {request.omega_deg:.1f} deg",
)
self.logger.info(
"Raster finished",
extra=merge_log_context(
sample_log_context(self.ctx.sample),
raster_request_log_context(request),
{"scan_result_is_none": scan_result is None, "sample_id": sample_id},
),
)
self.ctx.deps.cfg.crystal_size = get_xtal_size(
self.ctx.deps.cfg.crystal_size,
compute_crystal_score_array(scan_result.images),
r=request,
)
res_of_center = get_res_of_image_number(
scan_result.images, analysis_results.com.max_image
)
if res_of_center is None:
self.logger.warning("Selected image has no resolution estimate")
self.ctx.deps.cfg.last_best_res = res_of_center
self.ctx.deps.cfg.last_best_b_factor = get_best_b_factor(result_list=scan_result.images)
return CompletedRasterGridElem(
request=copy.deepcopy(request),
result=scan_result,
centre_of_mass=analysis_results.com,
)
except Exception:
self.logger.exception(
"Failed during raster",
extra=merge_log_context(
sample_log_context(self.ctx.sample),
raster_request_log_context(request),
{"exp_time_s": request.exp_time_s},
),
)
raise
def execute_auto_center(self, request: RasterGridRequest) -> CompletedRasterGrid | None:
sample = self.ctx.sample
if sample is None:
raise RuntimeError("Sample must be mounted to auto center")
old_prefix = request.file_prefix
geom = self.ctx.sample_geometry
self.logger.info(
"Starting auto-center raster workflow",
extra=merge_log_context(
sample_log_context(sample),
geom_log_context(geom, prefix="current_"),
{
"omega_deg": geom.omega_deg,
"beam_x_pxl": geom.beam_location_pxl.x,
"beam_y_pxl": geom.beam_location_pxl.y,
"pixel_in_mm": geom.pixel_in_mm,
"file_prefix": old_prefix,
},
),
)
self.send_sample_event(
sample.db_id, SampleEventType.RASTERING, comment=f"Raster at {geom.omega_deg:.1f} deg"
)
plan = self.ml_raster_plan(sample.db_id, f"ml_{geom.omega_deg:.2f}deg")
if plan is None:
self.logger.warning(
"No ML bounding box found at primary angle during auto-center raster",
extra=merge_log_context(
sample_log_context(sample),
{"omega_deg": geom.omega_deg, "file_prefix": old_prefix},
),
)
self.ctx.deps.devs.aerotech_omega = geom.omega_deg + 90.0
time.sleep(0.2)
plan = self.ml_raster_plan(sample.db_id, f"ml_{geom.omega_deg + 90.0:.2f}deg")
if plan is None:
self.logger.error(
"Auto-center raster aborted because no ML bounding box was found at either angle",
extra=merge_log_context(
sample_log_context(sample),
{
"primary_omega_deg": geom.omega_deg,
"secondary_omega_deg": geom.omega_deg + 90.0,
"file_prefix": old_prefix,
},
),
)
return None
r = plan.grid_request
self.logger.info(
"ML bounding box found for auto-center raster",
extra=merge_log_context(
sample_log_context(sample),
{
"ml_omega_deg": r.omega_deg,
"ml_n_x": r.n_x,
"ml_n_y": r.n_y,
"ml_grid_size_x_mm": getattr(r.grid_size_mm, "x", None),
"ml_grid_size_y_mm": getattr(r.grid_size_mm, "y", None),
"ml_top_left_x_mm": getattr(
getattr(r.smargon_top_left, "sh_mm", None), "x", None
),
"ml_top_left_y_mm": getattr(
getattr(r.smargon_top_left, "sh_mm", None), "y", None
),
"ml_top_left_z_mm": getattr(
getattr(r.smargon_top_left, "sh_mm", None), "z", None
),
},
),
)
geom = self.ctx.sample_geometry
grid = copy.deepcopy(request)
grid.smargon_top_left = r.smargon_top_left
grid.grid_size_mm = r.grid_size_mm
grid.n_x = r.n_x
grid.n_y = r.n_y
grid.file_prefix = f"{old_prefix}_raster2d"
grid.omega_deg = geom.omega_deg
status = self.ctx.status
self.logger.info("initialise detector")
self.ctx.deps.jfjoch.measure_raster(grid, status)
self.logger.info("detector initialised")
if self.ctx.services.state is None:
raise RuntimeError("RasterService requires services.state")
self.ctx.services.state.set_state(BeamlineStateEnum.DataCollection)
self.logger.info(
"Running first auto-center raster",
extra=merge_log_context(
sample_log_context(self.ctx.sample),
raster_request_log_context(grid),
{
"top_left_x_mm": getattr(grid.smargon_top_left.sh_mm, "x", None),
"top_left_y_mm": getattr(grid.smargon_top_left.sh_mm, "y", None),
"top_left_z_mm": getattr(grid.smargon_top_left.sh_mm, "z", None),
},
),
)
res1 = self.execute(grid)
grid.omega_deg += 90
self.send_sample_event(
self.ctx.sample.db_id,
SampleEventType.RASTERING,
comment=f"Raster at {geom.omega_deg:.1f} deg",
)
self.ctx.deps.devs.aerotech_omega = grid.omega_deg
grid.n_x = 1
grid.file_prefix = f"{old_prefix}_raster1d"
geom = self.ctx.sample_geometry
grid.grid_size_mm = Coordinate(x=geom.beam_size_mm.x, y=geom.beam_size_mm.y * 0.25)
grid.smargon_top_left, grid.n_y = self.auto_center_line_scan_top_left(
omega_deg=grid.omega_deg,
file_prefix=grid.file_prefix,
grid_size_mm=grid.grid_size_mm,
default_n_y=50,
y_retarget_threshold_mm=max(geom.beam_size_mm.y * 2.0, grid.grid_size_mm.y * 4.0),
)
self.logger.info(
"Prepared second auto-center raster",
extra=merge_log_context(
sample_log_context(self.ctx.sample),
raster_request_log_context(grid),
{
"top_left_x_mm": getattr(grid.smargon_top_left.sh_mm, "x", None),
"top_left_y_mm": getattr(grid.smargon_top_left.sh_mm, "y", None),
"top_left_z_mm": getattr(grid.smargon_top_left.sh_mm, "z", None),
},
),
)
status = self.ctx.status
self.logger.info(f"initialise detector for raster at {grid.omega_deg:.2f}")
self.ctx.deps.jfjoch.measure_raster(grid, status)
self.logger.info("detector initialised")
if self.ctx.services.state is None:
raise RuntimeError("RasterService requires services.state")
self.ctx.services.state.set_state(BeamlineStateEnum.DataCollection)
self.logger.info(
"Running second auto-center raster",
extra=merge_log_context(
sample_log_context(self.ctx.sample), raster_request_log_context(grid)
),
)
res2 = self.execute(grid)
return CompletedRasterGrid(r=[res1, res2])
Whitespace-only changes.
@@ -1,24 +0,0 @@
from dataclasses import dataclass
from typing import TYPE_CHECKING
from aare.daq.operations.common.models import BaseOperationContext, BeamlineDependencies
if TYPE_CHECKING:
from aare.daq.aaredb import AareWrapper
from aare.devices.jfjoch import JFJochWrapper
@dataclass
class RotationDependencies(BeamlineDependencies):
jfjoch: "JFJochWrapper"
aare: "AareWrapper"
@dataclass
class RotationSettings:
preview_filename: str = "scan_preview"
@dataclass
class RotationContext(BaseOperationContext[RotationDependencies, RotationSettings]):
pass
-162
View File
@@ -1,162 +0,0 @@
import copy
import time
from aarecommon.math.coordinate import SmargonCoordinate
from aarecommon.models.models import BeamlineStateEnum
from aarecommon.models.rotation_scan import CompletedRotationScan, RotationScanRequest
from aareDB import SampleEventType
from aare.daq.operations.common.simulate_scan_result import build_fake_rotation_result
from aare.daq.operations.rotation.models import RotationContext
class RotationService:
def __init__(self, *, context: RotationContext, logger):
self.ctx = context
self.logger = logger
def _prepare_detector(self, request: RotationScanRequest) -> None:
if self.ctx.deps.cfg.simulated_detector:
self.logger.info("Simulated detector mode enabled; skipping JFJoch start.")
return
self.ctx.deps.jfjoch.measure_rotation(request, self.ctx.status, self.ctx.deps.cfg.xrf)
def _execute_scan(self, request: RotationScanRequest) -> CompletedRotationScan:
omega_start = self.ctx.deps.devs.aerotech_omega
total_time = request.exp_time_s * request.steps
sample = self.ctx.sample
if sample is not None and sample.db_id is not None:
self.ctx.deps.aare.create_rotation_run(sample, request, self.ctx.status)
if not self.ctx.deps.cfg.simulated_detector:
self.ctx.deps.jfjoch.wait_till_running(timeout=60.0)
# The detector move (sa2dc) is non-blocking; ensure it has reached the
# requested distance before triggering the scan, so data is collected
# at the dtz already reported to JFJoch/DB.
self.ctx.deps.devs.set_dtz(request.dtz, wait=True)
if request.screening:
if request.wedge_omega_deg is None:
raise ValueError("Must supply a wedge angle for screening requests")
self.logger.debug(f"Starting screening scan with {request.steps} steps")
self.ctx.deps.devs.aerotech.screening_scan(
rotation_deg=request.incr_omega_deg,
wedge_deg=request.wedge_omega_deg,
time_per_element_s=request.exp_time_s,
steps=request.steps,
run_async=True,
)
else:
self.logger.debug(f"Starting rotation scan with {request.steps} steps")
self.ctx.deps.devs.aerotech.rotation_scan(
rotation_deg=request.steps * request.incr_omega_deg,
time_sec=total_time,
start_pos_deg=request.start_omega_deg,
run_async=True,
)
if request.start is not None and request.end is not None:
smargon_time_step = request.exp_time_s / float(request.steps)
pos_step = (request.end.sh_mm - request.start.sh_mm) * (1.0 / float(request.steps))
for i in range(request.steps):
self.ctx.deps.devs.smargon.target = SmargonCoordinate(
sh_mm=request.start.sh_mm + pos_step * i
)
time.sleep(smargon_time_step)
self.ctx.deps.devs.aerotech.wait_till_done(timeout=int(round(total_time + 60, 0)))
self.ctx.deps.devs.aerotech_omega = omega_start
if self.ctx.deps.cfg.simulated_detector:
self.logger.warning("Detector in simulation mode, returning fake zero rotation result.")
return build_fake_rotation_result(request, start_angle=float(omega_start))
scan_result = self.ctx.deps.jfjoch.wait_till_done(60)
return CompletedRotationScan(request=copy.deepcopy(request), result=scan_result)
def _ingest_screening_diffraction(self, sample, scan_result) -> None:
"""Pull each screening wedge's diffraction image from JFJoch (with spot
finding + resolution-estimate ring drawn in) and upload it to the DB,
linked to this run's sample. One image per wedge (1/2/4 typically).
Best-effort: a missing/failed image is logged and skipped, never fatal.
"""
images = getattr(scan_result, "images", None) or []
for idx, img in enumerate(images, start=1):
image_id = getattr(img, "number", None)
if image_id is None:
continue
try:
jpg = self.ctx.deps.jfjoch.get_diffraction_image(
image_id, show_spots=True, show_res_est=True, show_beam_center=True
)
except Exception:
self.logger.warning(
"Screening diffraction image %s unavailable; skipping", image_id, exc_info=True
)
continue
bits = []
angle = getattr(img, "angle", None)
spots = getattr(img, "spots", None)
res = getattr(img, "res", None)
if angle is not None:
bits.append(f"{angle:.2f}°")
if spots is not None:
bits.append(f"{spots} spots")
if res is not None:
bits.append(f"{res:.2f} Å")
comment = "Screening diffraction (wedge {}{})".format(
idx, (", " + ", ".join(bits)) if bits else ""
)
filename = f"{sample.db_id}_screening_diffraction_{image_id}"
self.ctx.deps.aare.upload_jpg(sample.db_id, filename, jpg, message=comment)
def run(self, request: RotationScanRequest) -> CompletedRotationScan:
sample = self.ctx.sample
# Validate + set the requested dtz (cfg.dtz, requires request.dtz) BEFORE
# configuring JFJoch, so JFJoch receives the commanded target rather than
# the live, still-in-transit detector position.
self.ctx.services.datacollection.prepare(request)
self._prepare_detector(request)
if sample is not None and sample.db_id is not None and self.ctx.services.events is not None:
self.ctx.services.events.send(sample.db_id, SampleEventType.COLLECTING)
if self.ctx.services.state is not None:
self.ctx.services.state.set_state(BeamlineStateEnum.DataCollection)
result = self._execute_scan(request)
if self.ctx.services.state is not None:
self.ctx.services.state.set_state(BeamlineStateEnum.SampleAlignment)
if sample is not None and sample.db_id is not None:
if self.ctx.services.screenshots is not None:
self.ctx.services.screenshots.save_to_db(
sample.db_id, self.ctx.settings.preview_filename
)
# For screening runs, ingest the per-wedge diffraction images. Done
# before the COLLECTED event so they pin to the same sample event the
# run is bound to (the COLLECTING event), matching the preview above.
self.logger.debug(f"Ingesting screening diffraction images: {request.screening}")
if request.screening and not self.ctx.deps.cfg.simulated_detector:
self._ingest_screening_diffraction(sample, result.result)
if self.ctx.services.events is not None:
self.ctx.services.events.send(sample.db_id, SampleEventType.COLLECTED)
if self.ctx.services.ingestion is not None:
self.ctx.services.ingestion.ingest_scan(
sample=sample,
result=result.result,
geom=self.ctx.sample_geometry,
beam_mark_pxl=self.ctx.deps.cfg.get_beam_mark(self.ctx.deps.devs.zoom),
)
return result
Whitespace-only changes.
@@ -1,108 +0,0 @@
import time
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Protocol
import cv2
import numpy as np
from aarecommon.models.models import SampleShortInfo
from aare.daq.aaredb import AareWrapper
from aare.daq.mlbox import MlBox
from aare.devices.mx_lib import clean_filename
class NonCriticalRunner(Protocol):
def __call__(
self, action, *, description: str, sample: SampleShortInfo | None = None
) -> object | None: ...
class SampleProvider(Protocol):
@property
def sample(self) -> SampleShortInfo | None: ...
class PGroupProvider(Protocol):
@property
def pgroup(self) -> str | None: ...
@dataclass
class ScreenshotService:
mlbox: MlBox
aare: AareWrapper
logger: object
run_noncritical: NonCriticalRunner
sample_provider: SampleProvider
pgroup_provider: PGroupProvider
output_dir: str = "/sls/mx/applications/logs"
photos_root: str = "/sls/mx/data"
def _get_inference_image(self) -> np.ndarray:
image = self.mlbox.get_latest_image()
if image is None:
raise RuntimeError("No inference image available from aarelc-infer")
return image
def _current_sample(self) -> SampleShortInfo | None:
provider = self.sample_provider
if callable(provider):
return provider()
return provider.sample
def _current_pgroup(self) -> str | None:
provider = self.pgroup_provider
if callable(provider):
return provider()
return provider.pgroup
def save_local(self, filename: str, settle_time_s: float = 0.2) -> None:
time.sleep(settle_time_s)
bgr_image = self._get_inference_image()
self.logger.debug(f"saving screenshot {filename} from inference image")
cv2.imwrite(f"{self.output_dir}/{filename}.jpg", bgr_image)
def save_to_db(self, sample_id: int, filename: str, settle_time_s: float = 0.2) -> None:
time.sleep(settle_time_s)
sample = self._current_sample()
bgr_image = self._get_inference_image()
def _upload() -> None:
self.aare.upload_image(sample_id, filename, bgr_image)
self.run_noncritical(_upload, description=f"screenshot upload '{filename}'", sample=sample)
def send_to_db(
self, *, filename: str | None = None, message: str | None = None, default_message: str
) -> None:
sample = self._current_sample()
if sample is None or sample.db_id is None or sample.db_id < 0:
raise ValueError("No sample with a valid sample_id is mounted.")
sample_id = sample.db_id
pgroup = self._current_pgroup()
bgr_image = self._get_inference_image()
if filename:
safe_filename = clean_filename(filename)
if not pgroup:
raise ValueError(
"No active pgroup set; cannot save screenshot to photos directory."
)
photos_dir = Path(self.photos_root) / pgroup / "raw" / "photos" / str(sample_id)
photos_dir.mkdir(parents=True, exist_ok=True)
photo_path = photos_dir / f"{safe_filename}.jpeg"
cv2.imwrite(str(photo_path), bgr_image)
upload_name = safe_filename
else:
upload_name = f"{sample_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
final_message = (message or "").strip() or default_message
def _upload() -> None:
self.aare.upload_image(sample_id, upload_name, bgr_image, message=final_message)
self.run_noncritical(_upload, description=f"send screenshot '{upload_name}'", sample=sample)
-7
View File
@@ -50,15 +50,8 @@ from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi import status as api_status
from fastapi.concurrency import run_in_threadpool
from fastapi.security import OAuth2PasswordBearer
from redis.lock import Lock as RedisLock
from starlette.responses import StreamingResponse
from aare.beamline_dispatch.beamline_dispatch import get_beamline_dispatch
from aare.beamline_dispatch.protocols import BeamlineDispatch
from aare.daq import auth
from aare.daq.config import BeamlineConfig
from aare.daq.config_model import LocalContactConfigModel
from aare.daq.daq import AareDAQ
from aare.daq.server_exception_handler import register_exception_handlers
logger = setup_logger("aareDAQ")
-191
View File
@@ -1,191 +0,0 @@
import json
import os
import time
from aarecommon.config.beamline import mx_beamline
from aarecommon.config.logger import setup_logger
from aarecommon.models.models import DewarAddress, SampleShortInfo, SampleShortInfoList
from aareDB.models import PuckWithTellPosition
from aare.daq.config import BeamlineConfig
logger = setup_logger("aareDAQ")
beamline = mx_beamline()
config = BeamlineConfig(bl=beamline)
def get_ws_headers() -> list[str]:
password = os.getenv("AAREDB_SHARED_PASSWORD")
if not password:
raise ValueError("The AAREDB_SHARED_PASSWORD environment variable is not set.")
return [f"X-Shared-Password: {password}"]
def set_spreadsheet_in_redis(spreadsheet):
"""
Store the spreadsheet in Redis using your BeamlineConfig instance.
"""
print(
"[REDIS][DEBUG] Data to write:", json.dumps(spreadsheet, indent=4)
) # Pretty-print the data
print("[REDIS][INFO] Writing spreadsheet to Redis...")
config.redis.set(f"{config._bl}:spreadsheet", json.dumps(spreadsheet))
def on_message(ws, message):
"""
Handle incoming WebSocket messages.
"""
try:
data = json.loads(message)
pucks_data = data["samples"] if isinstance(data, dict) and "samples" in data else data
pucks = [PuckWithTellPosition(**item) for item in pucks_data]
print(f"INFO: Received pucks: {[p.puck_name for p in pucks]}")
normal_short_infos = []
reference_short_infos = []
for p in pucks:
for s in p.samples or []:
dewar_address = None
target_list = None
# Reference tool
if isinstance(p.tell_position, str) and p.tell_position.startswith("X"):
dewar_address = DewarAddress(
segment="X", pos=int(p.tell_position[1:]) if len(p.tell_position) > 1 else 1
)
target_list = reference_short_infos
# Normal puck like "A1", "B5", "C3"
elif isinstance(p.tell_position, str):
segment = p.tell_position[0]
pos = int(p.tell_position[1:])
dewar_address = DewarAddress(segment=segment, pos=pos)
target_list = normal_short_infos
else:
print(f"[WARN] Skipping unknown tell_position format: {p.tell_position}")
continue
info = SampleShortInfo(
db_id=s.id,
puck_name=p.puck_name,
dewar_name=p.dewar_name or "Unknown",
sample_name=s.sample_name,
run_number=s.run_number,
user=s.pgroup,
pin=s.position,
location=dewar_address,
priority=s.priority, # getattr(s, "priority", 1.0),
comment=getattr(s, "comments", None),
mount_count=s.mount_count or 0,
screening_count=s.screening_count or 0,
raster_count=s.raster_count or 0,
rotation_count=s.rotation_count or 0,
aaredb_params=s.data_collection_parameters,
)
target_list.append(info)
# Write normal pucks to sample_spreadsheet
normal_key = f"{config._bl}:sample_spreadsheet"
normal_list = SampleShortInfoList(s=normal_short_infos)
config.redis.set(normal_key, normal_list.model_dump_json())
print("[REDIS][INFO] Written normal spreadsheet to:", normal_key)
# Write reference tools to reference-tools
ref_key = f"{config._bl}:reference-tools"
if reference_short_infos:
ref_list = SampleShortInfoList(s=reference_short_infos)
config.redis.set(ref_key, ref_list.model_dump_json())
print("[REDIS][INFO] Written reference tools to:", ref_key)
else:
# Clear key if empty
try:
config.redis.delete(ref_key)
print("[REDIS][INFO] Cleared reference tools key:", ref_key)
except Exception:
logger.debug("Could not clear the reference tools key", exc_info=True)
except Exception:
logger.exception("[WS] Failed to parse or convert message")
def on_error(ws, error):
"""
Handle WebSocket errors.
"""
print("[WS][ERROR]", error)
def on_close(ws, close_status_code, close_msg):
"""
Handle WebSocket closure.
"""
print("[WS][CLOSE]", close_status_code, close_msg)
def on_open(ws):
"""
Handle WebSocket connection opening.
"""
print("[WS][OPEN] WebSocket opened.")
def main():
"""
Main function to initiate WebSocket connection.
"""
SLOT_IDENTIFIER = beamline.value.upper()
# WS_URL = f"wss://mx-db-01.psi.ch/dispatcher/protected_router/tell_runner/ws/samples-spreadsheet/{SLOT_IDENTIFIER}"
WS_URL = f"wss://mx-aaredb-dmz-01.psi.ch/dispatcher/protected_router/tell_runner/ws/samples-spreadsheet/{SLOT_IDENTIFIER}"
WS_HEADERS = get_ws_headers()
while True:
try:
import ssl
import websocket
# FORCE a clean context
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
context.load_verify_locations(
cafile="/etc/ssl/certs/secrets/mx-aaredb-dmz-01_Full_Chain_CA.pem"
)
beamline_name = beamline.value.lower()
context.load_cert_chain(
certfile=f"/etc/ssl/certs/secrets/mx-{beamline_name}-queue-01_from_dmz-01.crt",
keyfile=f"/etc/ssl/certs/secrets/mx-{beamline_name}-queue-01_from_dmz-01.key",
)
# Explicitly set the SNI hostname to match NGINX server_name
# This is often what's missing when NGINX says "No cert sent"
ssl_opt = {
"context": context,
"server_hostname": "mx-aaredb-dmz-01.psi.ch",
"check_hostname": True,
}
ws = websocket.WebSocketApp(
WS_URL,
header=WS_HEADERS,
on_message=on_message,
on_error=on_error,
on_close=on_close,
on_open=on_open,
)
print(f"[WS][INFO] Connecting to {WS_URL}...")
ws.run_forever(sslopt=ssl_opt)
except Exception:
logger.exception("[MAIN] WebSocket connection failed")
time.sleep(5)
if __name__ == "__main__":
main()
-351
View File
@@ -1,351 +0,0 @@
from __future__ import annotations
import re
from datetime import UTC, datetime
from aarecommon.models.tell import TellActivityEnum, TellPhaseEnum, TellStateModel
MOUNT_CMD_RE = re.compile(r'^mount\("([^"]+)",\s*(\d+),\s*(\d+)')
UNMOUNT_CMD_RE = re.compile(r"^unmount\(")
UNMOUNT_STATUS_RE = re.compile(r"^unmount:\s*")
def _utc_now_iso() -> str:
return datetime.now(UTC).isoformat()
def initial_tell_state() -> TellStateModel:
return TellStateModel(
activity=TellActivityEnum.IDLE,
message="Ready",
operation="idle",
phase=TellPhaseEnum.IDLE,
last_update_ts=_utc_now_iso(),
)
def _parse_sample_position_from_mount_command(value: str) -> str | None:
match = MOUNT_CMD_RE.match(value)
if match is None:
return None
segment, puck, pin = match.groups()
return f"{segment}{int(puck)}-{int(pin)}"
def _update_state(
state: TellStateModel,
*,
activity: TellActivityEnum | None = None,
message: str | None = None,
event_name: str | None = None,
event_value: str | None = None,
operation: str | None = None,
phase: TellPhaseEnum | None = None,
sample_position: str | None = None,
mount_success: bool | None = None,
mount_error: str | None = None,
) -> TellStateModel:
updates = {"last_update_ts": _utc_now_iso()}
if activity is not None:
updates["activity"] = activity
if message is not None:
updates["message"] = message
if event_name is not None:
updates["last_event_class"] = event_name
if event_value is not None:
updates["last_event_value"] = event_value
if operation is not None:
updates["operation"] = operation
if phase is not None:
updates["phase"] = phase
if sample_position is not None:
updates["sample_position"] = sample_position
if mount_success is not None:
updates["mount_success"] = mount_success
if mount_error is not None:
updates["mount_error"] = mount_error
return state.model_copy(update=updates)
def _ready_state(state: TellStateModel, event_name: str, event_value: str | None) -> TellStateModel:
return _update_state(
state,
activity=TellActivityEnum.IDLE,
message="Ready",
event_name=event_name,
event_value=event_value,
operation="idle",
phase=TellPhaseEnum.IDLE,
mount_error="",
)
def advance_tell_state(
state: TellStateModel, event_name: str, event_value: str | None
) -> TellStateModel:
value = (event_value or "").strip()
if event_name == "Motion Task" and value == "dry":
return _update_state(
state,
activity=TellActivityEnum.DRYING,
message="Drying",
event_name=event_name,
event_value=value,
operation="dry",
phase=TellPhaseEnum.PREPARING,
mount_success=None,
mount_error="",
)
if event_name == "Motion Sync" and value == "Gripper cooling down":
return _update_state(
state,
activity=TellActivityEnum.COOLING,
message="Cooling after drying",
event_name=event_name,
event_value=value,
operation="dry",
phase=TellPhaseEnum.FINALIZING,
)
if event_name == "shell":
if value == "true":
return _update_state(state, event_name=event_name, event_value=value)
if value.startswith("mount("):
sample_position = _parse_sample_position_from_mount_command(value)
return _update_state(
state,
activity=TellActivityEnum.MOUNTING,
message=f"Mounting {sample_position}" if sample_position else "Mounting sample",
event_name=event_name,
event_value=value,
operation="mount",
phase=TellPhaseEnum.PREPARING,
sample_position=sample_position or "",
mount_success=None,
mount_error="",
)
if UNMOUNT_CMD_RE.match(value):
return _update_state(
state,
activity=TellActivityEnum.UNMOUNTING,
message="Unmounting sample",
event_name=event_name,
event_value=value,
operation="unmount",
phase=TellPhaseEnum.PREPARING,
mount_success=None,
mount_error="",
)
if UNMOUNT_STATUS_RE.match(value):
next_operation = "mount" if state.operation == "mount" else "unmount"
next_phase = (
TellPhaseEnum.AUTO_UNMOUNT
if state.operation == "mount"
else TellPhaseEnum.PREPARING
)
return _update_state(
state,
activity=TellActivityEnum.UNMOUNTING,
message="Unmounting current sample",
event_name=event_name,
event_value=value,
operation=next_operation,
phase=next_phase,
mount_success=None,
mount_error="",
)
if value == "got result True":
if state.operation == "mount" and state.phase in {
TellPhaseEnum.PREPARING,
TellPhaseEnum.AUTO_UNMOUNT,
TellPhaseEnum.RETURNING_OLD_SAMPLE,
TellPhaseEnum.OLD_SAMPLE_RETURNED,
TellPhaseEnum.PICKING_NEW_SAMPLE,
TellPhaseEnum.PLACING_NEW_SAMPLE,
TellPhaseEnum.FINALIZING,
}:
return _update_state(
state,
message=state.message or "Mount in progress",
event_name=event_name,
event_value=value,
)
if state.operation == "unmount":
return _update_state(
state,
message="Unmount step completed",
event_name=event_name,
event_value=value,
)
return _update_state(state, event_name=event_name, event_value=value)
if value == "got result False":
if state.operation == "mount" and state.phase in {
TellPhaseEnum.AUTO_UNMOUNT,
TellPhaseEnum.RETURNING_OLD_SAMPLE,
TellPhaseEnum.OLD_SAMPLE_RETURNED,
}:
return _update_state(
state,
activity=TellActivityEnum.UNMOUNTING,
message="Unmounting current sample",
event_name=event_name,
event_value=value,
)
if state.operation == "unmount" and state.phase in {
TellPhaseEnum.RETURNING_OLD_SAMPLE,
TellPhaseEnum.COMPLETE,
}:
return _update_state(
state,
activity=TellActivityEnum.UNMOUNTING,
message=state.message or "Unmounting sample",
event_name=event_name,
event_value=value,
)
operation = state.operation or "robot operation"
return _update_state(
state,
activity=TellActivityEnum.ERROR,
message=f"{operation.capitalize()} failed",
event_name=event_name,
event_value=value,
mount_success=False,
mount_error=f"{operation.capitalize()} failed",
phase=TellPhaseEnum.FAILED,
)
if value.startswith("setting mounted sample to"):
sample_position = value.removeprefix("setting mounted sample to").strip()
return _update_state(
state,
activity=TellActivityEnum.MOUNTING,
message=f"Mounted {sample_position}",
event_name=event_name,
event_value=value,
operation="mount",
phase=TellPhaseEnum.COMPLETE,
sample_position=sample_position,
mount_success=True,
mount_error="",
)
return _update_state(state, event_name=event_name, event_value=value)
if event_name == "Motion Sync":
if value == "Sample get from Gonio":
next_phase = TellPhaseEnum.RETURNING_OLD_SAMPLE
next_operation = "mount" if state.operation == "mount" else "unmount"
return _update_state(
state,
activity=TellActivityEnum.UNMOUNTING,
message="Removing sample from gonio",
event_name=event_name,
event_value=value,
operation=next_operation,
phase=next_phase,
)
if value == "Sample put on Puck":
next_phase = (
TellPhaseEnum.OLD_SAMPLE_RETURNED
if state.operation == "mount"
else TellPhaseEnum.COMPLETE
)
next_operation = "mount" if state.operation == "mount" else "unmount"
next_message = (
"Returning sample to puck"
if state.operation == "mount"
else "Sample returned to puck"
)
return _update_state(
state,
activity=TellActivityEnum.UNMOUNTING,
message=next_message,
event_name=event_name,
event_value=value,
operation=next_operation,
phase=next_phase,
mount_success=True if state.operation == "unmount" else state.mount_success,
mount_error="" if state.operation == "unmount" else state.mount_error,
)
if value == "Sample get on Puck":
return _update_state(
state,
activity=TellActivityEnum.MOUNTING,
message="Picking sample from puck",
event_name=event_name,
event_value=value,
operation="mount",
phase=TellPhaseEnum.PICKING_NEW_SAMPLE,
mount_error="",
)
if value == "Sample put on Gonio":
return _update_state(
state,
activity=TellActivityEnum.MOUNTING,
message="Placing sample on gonio",
event_name=event_name,
event_value=value,
operation="mount",
phase=TellPhaseEnum.PLACING_NEW_SAMPLE,
mount_error="",
)
if value == "Robot Clear after mount":
return _update_state(
state,
activity=TellActivityEnum.MOUNTING,
message="Robot clear after mount",
event_name=event_name,
event_value=value,
operation="mount",
phase=TellPhaseEnum.FINALIZING,
mount_error="",
)
if event_name == "Gripper detection" and value in {
"No Pin in Gripper",
"Pin still in Gripper",
"Pin is lost",
}:
return _update_state(
state,
activity=TellActivityEnum.ERROR,
message=value,
event_name=event_name,
event_value=value,
mount_success=False,
mount_error=value,
phase=TellPhaseEnum.FAILED,
)
if event_name == "state":
if value == "Ready":
return _ready_state(state, event_name, value)
if value == "Busy":
return _update_state(
state,
message=state.message if state.operation not in {None, "idle"} else "Busy",
event_name=event_name,
event_value=value,
)
return _update_state(state, event_name=event_name, event_value=value)
-389
View File
@@ -1,389 +0,0 @@
import json
import os
import ssl
import threading
import time
from collections import deque
from datetime import UTC, datetime
from typing import Any, cast
import requests
import sseclient
import websocket
from aarecommon.config.beamline import mx_beamline
from aarecommon.config.logger import setup_logger
from aarecommon.errors.exception_handler import TellCommunicationError, TellConnectionException
from aarecommon.models.beamline import MXBeamline
from aarecommon.models.tell import TellStateModel
from aareDB.exceptions import ApiException
from aareDB.models import PuckWithTellPosition
from pydantic import BaseModel, ValidationError
from requests import RequestException
from aare.daq.aaredb import AareWrapper
from aare.daq.config import BeamlineConfig
from aare.daq.tell_state_machine import advance_tell_state, initial_tell_state
from aare.devices.tell_client import TellClient
logger = setup_logger(__name__)
# Initialize TELL client and DB wrapper to None so they can be patched in tests
tell_client = None
aare_db = None
config = None
# Track current state
current_pucks = []
last_pucks_sent = []
DEWAR_CONTENT_UPDATE_EVENT = "DewarContentUpdate"
TRACKED_TELL_EVENT_VALUES = {
"Gripper detection": {"Pin still in Gripper", "No Pin in Gripper", "Pin is lost"}
}
TRACKED_MOTION_EVENT_VALUES = {"Motion Task": {"dry"}}
TRACKED_MOTION_SYNC_EVENTS = {
"Motion Sync": {
"Robot Clear after mount",
"Gripper cooling down",
"Sample put on Gonio",
"Sample get from Gonio",
"Sample put on Puck",
"Sample get on Puck",
}
}
TRACKED_STATE_EVENTS = {"state": {"Ready", "Busy"}}
latest_tell_events = {}
tell_event_history = deque(maxlen=25)
current_tell_state = initial_tell_state()
TELL_JOURNAL_PREFIX = "[TELL][JOURNAL]"
TELL_EVENTS_REDIS_KEY_SUFFIX = "tell_events"
TELL_STATE_REDIS_KEY_SUFFIX = "tell_state"
SSE_RECONNECT_DELAY_S = 5
SSE_RECOVERABLE_EXCEPTIONS = (RequestException, OSError, ssl.SSLError)
WS_RECOVERABLE_EXCEPTIONS = (OSError, ssl.SSLError, websocket.WebSocketException)
class TellSsePayload(BaseModel):
value: str | None = None
eventValue: str | None = None
data: str | None = None
message: str | None = None
state: str | None = None
@property
def normalized_value(self) -> str | None:
for candidate in (self.value, self.eventValue, self.data, self.message, self.state):
if candidate is None:
continue
stripped = candidate.strip()
if stripped:
return stripped
return None
class TellEventRecord(BaseModel):
timestamp: str
class_: str
event: str
def redis_dict(self) -> dict[str, str]:
return {"timestamp": self.timestamp, "class": self.class_, "event": self.event}
def _get_redis_context() -> tuple[Any | None, str | None]:
if config is None:
logger.debug("[REDIS] BeamlineConfig unavailable; skipping TELL redis write")
return None, None
redis_client = getattr(config, "redis", None)
beamline_key = getattr(config, "_bl", None)
if redis_client is None or beamline_key is None:
logger.error("[REDIS] BeamlineConfig internals unavailable; skipping TELL redis write")
return None, None
return cast(Any, redis_client), str(beamline_key)
def _set_json_in_redis(key_suffix: str, payload: Any, *, log_label: str) -> None:
redis_client, beamline_key = _get_redis_context()
if redis_client is None or beamline_key is None:
return
redis_key = f"{beamline_key}:{key_suffix}"
redis_client.set(redis_key, json.dumps(payload))
logger.info(f"[REDIS] Written {log_label} to: {redis_key}")
def _normalize_event_data(data):
if data is None:
return None
if not isinstance(data, str):
data = str(data)
stripped = data.strip()
if not stripped:
return None
try:
payload = TellSsePayload.model_validate_json(stripped)
except (ValidationError, json.JSONDecodeError, ValueError, TypeError):
try:
decoded = json.loads(stripped)
except (json.JSONDecodeError, ValueError, TypeError):
return stripped
return str(decoded).strip() if decoded is not None else None
return payload.normalized_value
def extract_tracked_tell_event(event_name, event_data):
normalized_data = _normalize_event_data(event_data)
if event_name in TRACKED_TELL_EVENT_VALUES:
allowed_values = TRACKED_TELL_EVENT_VALUES[event_name]
if normalized_data in allowed_values:
return event_name, normalized_data
return None
if event_name in TRACKED_MOTION_EVENT_VALUES:
allowed_values = TRACKED_MOTION_EVENT_VALUES[event_name]
if normalized_data in allowed_values:
return event_name, normalized_data
return None
if event_name in TRACKED_MOTION_SYNC_EVENTS:
allowed_values = TRACKED_MOTION_SYNC_EVENTS[event_name]
if normalized_data in allowed_values:
return event_name, normalized_data
return None
if event_name in TRACKED_STATE_EVENTS:
allowed_values = TRACKED_STATE_EVENTS[event_name]
if normalized_data in allowed_values:
return event_name, normalized_data
return None
return None
def set_tell_events_in_redis(events: list[dict[str, str]]) -> None:
_set_json_in_redis(TELL_EVENTS_REDIS_KEY_SUFFIX, events, log_label="TELL events")
def set_tell_state_in_redis(state: TellStateModel) -> None:
_set_json_in_redis(TELL_STATE_REDIS_KEY_SUFFIX, state.model_dump(), log_label="TELL state")
def record_tell_event(event_name, event_value):
event_record = TellEventRecord(
timestamp=datetime.now(UTC).isoformat(), class_=event_name, event=event_value
)
latest_tell_events[event_name] = event_value
tell_event_history.append(event_record)
set_tell_events_in_redis([item.redis_dict() for item in tell_event_history])
logger.info(f"{TELL_JOURNAL_PREFIX} event={event_name} value={event_value}")
def get_dmz_client_cert_paths(bl: MXBeamline) -> tuple[str, str]:
beamline = bl.value.lower()
cert_dir = "/etc/ssl/certs/secrets"
return (
f"{cert_dir}/mx-{beamline}-queue-01_from_dmz-01.crt",
f"{cert_dir}/mx-{beamline}-queue-01_from_dmz-01.key",
)
def listen_to_sse():
logger.info("[SSE] listener started")
if not tell_client.url:
logger.warning("[SSE] No TELL URL configured; listener not started")
return
sse_url = tell_client.url + "/events"
cert_pair = get_dmz_client_cert_paths(mx_beamline())
while True:
try:
logger.info(f"[SSE] Connecting to {sse_url}")
if sse_url.startswith("https://mx-aaredb-dmz-01"): # "https://mx-db-01"
# mTLS path
# ca_root = "/etc/ssl/certs/secrets/mx-db-01_Full_Chain_CA.pem"
ca_root = "/etc/ssl/certs/secrets/mx-aaredb-dmz-01_Full_Chain_CA.pem"
response = requests.get(sse_url, stream=True, cert=cert_pair, verify=ca_root)
response.raise_for_status()
client = sseclient.SSEClient(response)
else:
# Robot path (PC17488) - Pass URL STRING directly
# SSEClient will handle the simple HTTP GET itself
client = sseclient.SSEClient(sse_url)
logger.info("[SSE] Connected; refreshing detected pucks")
handle_tell_change_event()
# Compatibility: some SSEClient versions are iterable, others expose .events().
events_iter = client.events() if hasattr(client, "events") else iter(client)
for event in events_iter:
# print(f"event = {event.event} with data: {event.data}")
on_sse_event(event)
except SSE_RECOVERABLE_EXCEPTIONS:
logger.exception("[SSE] Recoverable failure while consuming TELL event stream")
logger.info(f"[SSE] Reconnecting in {SSE_RECONNECT_DELAY_S} seconds")
time.sleep(SSE_RECONNECT_DELAY_S)
def compare_and_report_change(old, new):
"""
Compare two lists of pucks.
Detects if puck names, dewars, OR positions have changed.
"""
def get_puck_keys(pucks):
return {
# Including tell_position ensures we sync if a puck moves
(p.puck_name, p.dewar_id, getattr(p, "tell_position", None))
for p in pucks
if getattr(p, "tell_position", None) != "X1"
}
old_keys = get_puck_keys(old)
new_keys = get_puck_keys(new)
joined = new_keys - old_keys
left = old_keys - new_keys
return joined, left
def ws_update_samples_info(pucks):
"""Send sample info to TELL robot."""
tell_client.set_samples_info(pucks)
logger.info(f"Payload sent to TELL: {pucks}")
def handle_tell_change_event():
"""Fetch the latest detected pucks from TELL and update the database."""
try:
detected_pucks = tell_client.get_detected_pucks()
aare_db.set_pucks_beamline(detected_pucks)
logger.info("[SSE] Updated pucks in database after TELL change")
except (TellCommunicationError, TellConnectionException, RequestException):
logger.exception("[SSE] Failed to fetch detected pucks from TELL")
except (ApiException, json.JSONDecodeError, KeyError, TypeError, ValueError):
logger.exception("[SSE] Failed to update puck state after TELL change")
def on_sse_event(event):
global current_tell_state
logger.debug(f"[EVENT] SSE event={event.event} data={event.data!r}")
normalized_data = _normalize_event_data(event.data)
current_tell_state = advance_tell_state(current_tell_state, event.event, normalized_data)
set_tell_state_in_redis(current_tell_state)
tracked_event = extract_tracked_tell_event(event.event, normalized_data)
if tracked_event is not None:
record_tell_event(*tracked_event)
if event.event == DEWAR_CONTENT_UPDATE_EVENT:
logger.info("[SSE] Dewar content changed; updating")
handle_tell_change_event()
def on_message(ws, message):
try:
data = json.loads(message)
new_pucks = [PuckWithTellPosition(**item) for item in data]
global current_pucks
joined, left = compare_and_report_change(current_pucks, new_pucks)
if joined or left:
logger.info(f"[WS] Changes detected: joined={joined} left={left}")
ws_update_samples_info(new_pucks)
current_pucks = new_pucks
logger.info("[WS] Sent current pucks state to TELL")
else:
logger.info("[WS] No change (same pucks and dewars); skipping send.")
except Exception:
logger.exception("[WS] Failed to process message")
def on_error(ws, error):
logger.error(f"[WS] Error: {error}")
def on_close(ws, close_status_code, close_msg):
logger.info(f"[WS] Closed status={close_status_code} message={close_msg}")
def on_open(ws):
logger.info("[WS] WebSocket opened")
global current_pucks
# Clear the cache to force a re-sync with the robot on the first message
current_pucks = []
def main():
# Start SSE listener in a separate background thread
sse_thread = threading.Thread(target=listen_to_sse, daemon=True)
sse_thread.start()
cert_file, key_file = get_dmz_client_cert_paths(mx_beamline())
"""
Main function to initiate WebSocket connection with mTLS.
"""
while True:
try:
# 1. Create a modern SSL Context for a TLS Client
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
# 2. Load the CA to verify the NGINX server's identity
context.load_verify_locations(
cafile="/etc/ssl/certs/secrets/mx-aaredb-dmz-01_Full_Chain_CA.pem"
)
# 3. Load the Client Certificate and Key (mTLS)
context.load_cert_chain(certfile=cert_file, keyfile=key_file)
# Optional: Ensure hostname matching is active (recommended)
context.check_hostname = True
ws = websocket.WebSocketApp(
WS_URL,
header=WS_HEADERS,
on_message=on_message,
on_error=on_error,
on_close=on_close,
on_open=on_open,
)
# 4. Pass the context directly via sslopt
logger.info(f"[WS] Connecting to {WS_URL} using mTLS")
ws.run_forever(sslopt={"context": context})
except WS_RECOVERABLE_EXCEPTIONS:
logger.exception("[MAIN] Recoverable WebSocket connection failure")
logger.info(f"[WS] Reconnecting in {SSE_RECONNECT_DELAY_S} seconds")
time.sleep(SSE_RECONNECT_DELAY_S)
if __name__ == "__main__":
# Configuration
beamline = mx_beamline()
tell_client = TellClient(bl=beamline)
aare_db = AareWrapper(bl=beamline)
config = BeamlineConfig(bl=beamline)
SLOT_IDENTIFIER = beamline.value.upper()
# WS_URL = f"wss://mx-db-01.psi.ch/dispatcher/protected_router/wstell/ws/slot/{SLOT_IDENTIFIER}"
WS_URL = f"wss://mx-aaredb-dmz-01.psi.ch/dispatcher/protected_router/wstell/ws/slot/{SLOT_IDENTIFIER}"
# WS_URL = f"wss://localhost:8001/protected_router/wstell/ws/slot/{SLOT_IDENTIFIER}"
WS_HEADERS = [f"X-Shared-Password: {os.getenv('AAREDB_SHARED_PASSWORD')}"]
logger.debug(f"[WS] Headers configured: {WS_HEADERS}")
set_tell_state_in_redis(current_tell_state)
main()
-291
View File
@@ -1,291 +0,0 @@
import time
from aarecommon.config.logger import setup_logger
from aarecommon.models.models import SampleCameraSettings
from aare.beamline_dispatch.beamline_dispatch import get_beamline_dispatch
from aare.daq.config import ABR_OMEGA_MOUNT, ABR_POS_MOUNT, BeamlineConfig
from aare.daq.devices import BeamlineDevices
from aare.devices.area_detector import AutoEnum
from aare.devices.bec_worker import BeamlineState
logger = setup_logger("aareDAQ")
SAFE_POSITION = 600
def _move_detector_to_safe_position_if_needed(devs: BeamlineDevices, cfg: BeamlineConfig):
safe_position = cfg.dtz_safe_position
current_dtz = devs.dtz
if safe_position is None:
logger.debug("No dtz_safe_position configured; skipping detector move")
return
if current_dtz is None:
logger.debug("Current dtz is unknown; skipping detector safe-position move")
return
if current_dtz < safe_position:
logger.info(f"Moving detector to safe position {safe_position}")
return devs.bec_worker.det_z(value=safe_position)
logger.debug(
f"Detector already at or beyond safe position "
f"(current={current_dtz}, safe={safe_position}); skipping move"
)
return None
def common_2rse(devs: BeamlineDevices, cfg: BeamlineConfig):
_move_detector_to_safe_position_if_needed(devs, cfg)
devs.bec_worker.move_to(BeamlineState.ROBOT_SAMPLE_EXCHANGE)
print("move smargon home")
devs.smargon_move_home()
print("try to move aerotech")
devs.aerotech_pos = ABR_POS_MOUNT
devs.aerotech_omega = ABR_OMEGA_MOUNT
def rse2se(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.samcam_auto(AutoEnum.AUTO)
common_2rse(devs, cfg)
devs.samcam_auto(AutoEnum.ONCE)
def m2se(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.samcam_auto(AutoEnum.AUTO)
devs.bec_worker.move_to(BeamlineState.MANUAL_SAMPLE_EXCHANGE)
logger.info(f"moved to sample exchange, now moving to {cfg.abr_meas_pos}")
devs.aerotech_pos = ABR_POS_MOUNT
devs.aerotech_omega = ABR_OMEGA_MOUNT
devs.smargon_move_home()
devs.samcam_auto(AutoEnum.ONCE)
def m2sa(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.samcam_auto(AutoEnum.AUTO)
devs.bec_worker.move_to(BeamlineState.SAMPLE_ALIGNMENT)
devs.samcam_auto(AutoEnum.ONCE)
def sa2se(devs: BeamlineDevices, cfg: BeamlineConfig):
try:
devs.samcam_auto(AutoEnum.AUTO)
devs.bec_worker.move_to(BeamlineState.MANUAL_SAMPLE_EXCHANGE)
logger.info(f"moved to sample exchange, now moving to {cfg.abr_meas_pos}")
devs.aerotech_pos = ABR_POS_MOUNT
devs.aerotech_omega = ABR_OMEGA_MOUNT
devs.smargon_move_home()
devs.samcam_auto(AutoEnum.ONCE)
except Exception as e:
logger.error(f"Failed to move to sample exchange: {e}")
devs.aerotech_pos = ABR_POS_MOUNT
devs.aerotech_omega = ABR_OMEGA_MOUNT
devs.smargon_move_home()
raise
def sa2rse(devs: BeamlineDevices, cfg: BeamlineConfig):
common_2rse(devs, cfg)
def sa2xtal_snapshot(devs: BeamlineDevices, cfg: BeamlineConfig):
logger.info("SA to Xtal Snapshot")
devs.samcam_settings = SampleCameraSettings(gain=0.0, exposure=0.001)
logger.debug(f"new sam cam settings: {devs.samcam_settings}")
devs.bec_worker.move_to(BeamlineState.XTAL_SNAPSHOT)
def dc2xtal_snapshot(devs: BeamlineDevices, cfg: BeamlineConfig):
logger.debug("DC to Xtal Snapshot")
devs.samcam_settings = SampleCameraSettings(gain=0.0, exposure=0.001)
logger.debug(f"new sam cam settings: {devs.samcam_settings}")
devs.bec_worker.move_to(BeamlineState.XTAL_SNAPSHOT)
def xtal_snapshot2dc(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.samcam_auto(AutoEnum.AUTO)
devs.bec_worker.move_to(BeamlineState.DATA_COLLECTION)
devs.samcam_auto(AutoEnum.ONCE)
def xtal_snapshot2sa(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.samcam_auto(AutoEnum.AUTO)
devs.bec_worker.move_to(BeamlineState.SAMPLE_ALIGNMENT)
devs.samcam_auto(AutoEnum.ONCE)
def xtal_snapshot2rse(devs: BeamlineDevices, cfg: BeamlineConfig):
common_2rse(devs, cfg)
def xtal_snapshot2se(devs: BeamlineDevices, cfg: BeamlineConfig):
sa2se(devs, cfg)
def xtal_snapshot2xrf(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.bec_worker.move_to(BeamlineState.FLUX_MEASUREMENT)
def xtal_snapshot2bl(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.bec_worker.move_to(BeamlineState.BEAM_VISUALISATION)
def xtal_snapshot2dh(devs: BeamlineDevices, cfg: BeamlineConfig):
xtal_snapshot2sa(devs, cfg)
sa2dh(devs, cfg)
def dc2rse(devs: BeamlineDevices, cfg: BeamlineConfig):
common_2rse(devs, cfg)
def se2sa(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.samcam_auto(AutoEnum.AUTO)
devs.bec_worker.move_to(BeamlineState.SAMPLE_ALIGNMENT)
devs.aerotech_pos = cfg.abr_meas_pos
devs.samcam_auto(AutoEnum.ONCE)
def rse2sa(devs: BeamlineDevices, cfg: BeamlineConfig):
se2sa(devs, cfg)
def sa2dc(devs: BeamlineDevices, cfg: BeamlineConfig):
start = time.perf_counter()
det_z_pos = cfg.dtz
status = devs.bec_worker.det_z(value=det_z_pos)
logger.info(f"start detector move to {cfg.dtz} at {time.perf_counter() - start:.2f}")
devs.samcam_auto(AutoEnum.AUTO)
logger.info(f"sam cam auto exposure in {time.perf_counter() - start:.2f}")
devs.bec_worker.move_to(BeamlineState.DATA_COLLECTION)
logger.info(f"changed to data collection in {time.perf_counter() - start:.2f}s")
status.wait(timeout=60)
logger.info(f"det z moved to {cfg.dtz} in {time.perf_counter() - start:.2f}s")
devs.samcam_auto(AutoEnum.ONCE)
logger.info(f"sam cam auto exposure in {time.perf_counter() - start:.2f}")
def dc2sa(devs: BeamlineDevices, cfg: BeamlineConfig):
status = _move_detector_to_safe_position_if_needed(devs, cfg)
devs.samcam_auto(AutoEnum.AUTO)
devs.bec_worker.move_to(BeamlineState.SAMPLE_ALIGNMENT)
devs.aerotech_pos = cfg.abr_meas_pos
if hasattr(status, "wait"):
status.wait(timeout=60)
devs.samcam_auto(AutoEnum.ONCE)
def sa2xrf(devs: BeamlineDevices, cfg: BeamlineConfig):
"""sample alignment to XrfCollection"""
devs.samcam_auto(AutoEnum.AUTO)
devs.bec_worker.move_to(BeamlineState.FLUX_MEASUREMENT)
devs.samcam_auto(AutoEnum.ONCE)
def xrf2sa(devs: BeamlineDevices, cfg: BeamlineConfig):
"""XrfCollection to sample alignment"""
devs.samcam_auto(AutoEnum.AUTO)
devs.bec_worker.move_to(BeamlineState.SAMPLE_ALIGNMENT)
devs.samcam_auto(AutoEnum.ONCE)
def common2flux_measurement(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.bec_worker.move_to(BeamlineState.FLUX_MEASUREMENT)
def sa2flux_measurement(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.bec_worker.move_to(BeamlineState.FLUX_MEASUREMENT)
def flux_measurement2sa(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.bec_worker.move_to(BeamlineState.SAMPLE_ALIGNMENT)
def flux_measurement2ba(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.bec_worker.move_to(BeamlineState.BEAMSTOP_ALIGNMENT)
def flux_measurement2bl(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.bec_worker.move_to(BeamlineState.BEAM_VISUALISATION)
def ba2flux_measurement(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.bec_worker.move_to(BeamlineState.FLUX_MEASUREMENT)
def bl2flux_measurement(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.bec_worker.move_to(BeamlineState.FLUX_MEASUREMENT)
def sa2ba(devs: BeamlineDevices, cfg: BeamlineConfig):
"""Sample alignment to BeamstopAlignment"""
devs.bec_worker.move_to(BeamlineState.BEAMSTOP_ALIGNMENT)
devs.samcam_auto(AutoEnum.ONCE)
def ba2sa(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.bec_worker.move_to(BeamlineState.SAMPLE_ALIGNMENT)
devs.samcam_auto(AutoEnum.ONCE)
def sa2bl(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.bec_worker.move_to(BeamlineState.BEAM_VISUALISATION)
devs.samcam_settings.exposure = 0.001
# TODO SAMCAM SETTINGS SHOULD BE DOEN via zoom settings
def bl2sa(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.bec_worker.move_to(BeamlineState.SAMPLE_ALIGNMENT)
devs.samcam_auto(AutoEnum.ONCE)
def bl2ba(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.bec_worker.move_to(BeamlineState.BEAMSTOP_ALIGNMENT)
devs.samcam_auto(AutoEnum.ONCE)
def ba2bl(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.bec_worker.move_to(BeamlineState.BEAM_VISUALISATION)
devs.samcam_settings.exposure = 0.001
def sa2dh(devs: BeamlineDevices, cfg: BeamlineConfig):
common2dh(devs, cfg)
def common2dh(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.samcam_auto(AutoEnum.AUTO)
common_2rse(devs, cfg)
devs.samcam_auto(AutoEnum.ONCE)
if devs.tell.is_position("pPark") and devs.tell.get_mounted_sample() is None:
logger.info("TELL already in pPark; skipping dry/park preparation for dewar transfer")
return
if devs.tell.get_mounted_sample() is not None:
try:
devs.tell.unmount(wait=True)
except Exception:
logger.exception("Error for unmounting")
devs.tell.dry(wait_cold=-1, wait=False)
def dh2sa(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.bec_worker.move_to(BeamlineState.SAMPLE_ALIGNMENT)
def common2maintenance(devs: BeamlineDevices, cfg: BeamlineConfig):
devs.bec_worker.move_to(BeamlineState.MAINTENANCE)
if __name__ == "__main__":
from aarecommon.config.beamline import mx_beamline
beamline = mx_beamline()
config = BeamlineConfig(beamline)
devices = BeamlineDevices(beamline, get_beamline_dispatch(), config)
common_2rse(devices, config)
time.sleep(10.0)
rse2sa(devices, config)
View File
Whitespace-only changes.
-303
View File
@@ -1,303 +0,0 @@
from aarecommon.config.beamline import cfg_get, mx_beamline
from aarecommon.config.logger import setup_logger
from aarecommon.errors.exception_handler import AerotechCommunicationError
from aarecommon.math.coordinate import AerotechCoordinate, Coordinate
from aarecommon.models.beamline import MXBeamline
from aarescan_client import ApiClient, Configuration, DefaultApi, RotationRequest, Status, Target
from aarescan_client.models.grid_request import GridRequest
from aarescan_client.models.screen_request import ScreenRequest
AEROTECH_HOME = AerotechCoordinate(at_mm=Coordinate(x=0, y=0, z=0), omega_deg=0)
logger = setup_logger("aareDAQ")
class AerotechController:
def __init__(self, bl: MXBeamline):
if bl == MXBeamline.X06DA:
self._simulated = False
self._base = cfg_get(
"daq.hardware.aerotech_url", "http://mx-x06da-queue-01.psi.ch:5234"
)
elif bl == MXBeamline.X10SA:
self._simulated = False
self._base = cfg_get(
"daq.hardware.aerotech_url", "http://mx-x10sa-queue-01.psi.ch:5234"
)
elif bl == MXBeamline.X06SA:
raise NotImplementedError("Not implemented aerotech url for X06SA")
elif bl == MXBeamline.SIMULATED:
self._simulated = True
self._pos = AEROTECH_HOME
self._vel = 0
else:
raise ValueError("unknown beamline")
if not self._simulated:
self._client = ApiClient(Configuration(host=self._base))
self._api = DefaultApi(self._client)
def _make_aerotech_target(
self, coord: AerotechCoordinate, wait: bool = False, incremental: bool = False
) -> Target:
at_mm = coord.at_mm
return Target(
x=at_mm.x if at_mm is not None else None,
y=at_mm.y if at_mm is not None else None,
z=at_mm.z if at_mm is not None else None,
u=coord.omega_deg,
run_async=not wait,
incremental=incremental,
)
def _make_aerotech_coordinate(self, target: Target) -> AerotechCoordinate:
return AerotechCoordinate(
at_mm=Coordinate(x=target.x, y=target.y, z=target.z), omega_deg=target.u
)
def cancel(self):
try:
self._api.cancel_post()
except Exception as e:
raise AerotechCommunicationError(
"Aerotech cancel failed",
endpoint="cancel_post",
base_url=self._base,
operation="POST",
) from e
def is_idle(self) -> bool:
try:
status = self._api.status_get()
return status.state == "Idle"
except Exception as e:
raise AerotechCommunicationError(
"Aerotech status check failed",
endpoint="status_get",
base_url=self._base,
operation="GET",
) from e
def get_position(self) -> AerotechCoordinate:
status = self.status()
return AerotechCoordinate(
at_mm=Coordinate(x=status.x.pos, y=status.y.pos, z=status.z.pos), omega_deg=status.u.pos
)
def status(self) -> Status:
try:
return self._api.status_get()
except Exception as e:
raise AerotechCommunicationError(
"Aerotech status request failed",
endpoint="status_get",
base_url=self._base,
operation="GET",
) from e
def move_home(self, wait: bool = True, incremental: bool = False):
if self._simulated:
self._pos = AEROTECH_HOME
return self._pos
return self.position(AEROTECH_HOME, wait=wait, incremental=incremental)
def home_aerotech(self):
try:
return self._api.home_post()
except Exception as e:
raise AerotechCommunicationError(
"Aerotech home failed", endpoint="home_post", base_url=self._base, operation="POST"
) from e
def wait_till_done(self, timeout=60):
try:
return self._api.wait_till_done_post(timeout=timeout)
except Exception as e:
raise AerotechCommunicationError(
"Aerotech wait_till_done failed",
endpoint="wait_till_done_post",
base_url=self._base,
operation="POST",
) from e
def position(self, target: AerotechCoordinate, /, wait: bool = True, incremental: bool = False):
if self._simulated:
return self._pos
payload = self._make_aerotech_target(target, wait=wait, incremental=incremental)
try:
return self._api.position_post(payload)
except Exception as e:
raise AerotechCommunicationError(
"Aerotech position move failed",
endpoint="position_post",
base_url=self._base,
operation="POST",
) from e
def rotation_scan(
self, rotation_deg: float, time_sec: float, start_pos_deg: float, run_async: bool = False
):
payload = RotationRequest(
rotation_deg=rotation_deg,
total_time_sec=time_sec,
start_pos_deg=start_pos_deg,
run_async=run_async,
)
logger.debug(f"Payload sent to AareScan for rotation execution: {payload}")
try:
return self._api.rotation_scan_post(payload)
except Exception as e:
raise AerotechCommunicationError(
"Aerotech rotation scan failed",
endpoint="rotation_scan_post",
base_url=self._base,
operation="POST",
) from e
def validate_rotation_scan(
self, rotation_deg: float, time_sec: float, start_pos_deg: float, run_async: bool = False
):
payload = RotationRequest(
rotation_deg=rotation_deg,
total_time_sec=time_sec,
start_pos_deg=start_pos_deg,
run_async=run_async,
)
logger.debug(f"Payload sent to AareScan for validating rotation: {payload}")
try:
return self._api.validate_rotation_scan_post(payload)
except Exception as e:
raise AerotechCommunicationError(
f"Aerotech rotation scan failed validation: {e}",
endpoint="rotation_scan_post",
base_url=self._base,
operation="POST",
) from e
def grid_scan(
self,
grid_elem_count_y: int,
grid_elem_size_y_um: float,
time_per_element_s: float,
grid_elem_size_x_um: float,
grid_elem_count_x: int,
run_async: bool = False,
):
payload = GridRequest(
grid_elem_count_x=grid_elem_count_x,
grid_elem_count_y=grid_elem_count_y,
grid_elem_size_x_um=grid_elem_size_x_um,
grid_elem_size_y_um=grid_elem_size_y_um,
time_per_element_sec=time_per_element_s,
run_async=run_async,
)
logger.debug(f"Payload sent to AareScan for grid_scan execution: {payload}")
if self._simulated:
return payload
try:
return self._api.grid_scan_post(payload)
except Exception as e:
raise AerotechCommunicationError(
f"Aerotech grid scan failed: {e}",
endpoint="grid_scan_post",
base_url=self._base,
operation="POST",
) from e
def validate_grid_scan(
self,
grid_elem_count_y: int,
grid_elem_size_y_um: float,
time_sec: float,
grid_elem_size_x_um: float,
grid_elem_count_x: int,
run_async: bool | None = False,
):
payload = GridRequest(
grid_elem_count_x=grid_elem_count_x,
grid_elem_count_y=grid_elem_count_y,
grid_elem_size_x_um=grid_elem_size_x_um,
grid_elem_size_y_um=grid_elem_size_y_um,
time_per_element_sec=time_sec,
run_async=run_async,
)
logger.debug(f"Payload sent to AareScan for grid_scan validation: {payload}")
if self._simulated:
return payload
try:
return self._api.validate_grid_scan_post(payload)
except Exception as e:
raise AerotechCommunicationError(
f"Aerotech grid scan validation failed: {e}",
endpoint="grid_scan_post",
base_url=self._base,
operation="POST",
) from e
def screening_scan(
self,
rotation_deg: float,
wedge_deg: float,
time_per_element_s: float,
steps: int,
run_async: bool = False,
):
payload = ScreenRequest(
rotation_deg=rotation_deg,
wedge_deg=wedge_deg,
time_per_element_sec=time_per_element_s,
steps=steps,
run_async=run_async,
)
if self._simulated:
return payload
try:
logger.info(f"sending screening scan request to aerotech with payload {payload}")
return self._api.screening_post(payload)
except Exception as e:
raise AerotechCommunicationError(
"Aerotech screening scan failed",
endpoint="screening_post",
base_url=self._base,
operation="POST",
) from e
def validate_screening_scan(
self,
rotation_deg: float,
wedge_deg: float,
time_sec: float,
steps: int,
run_async: bool = False,
):
payload = ScreenRequest(
rotation_deg=rotation_deg,
wedge_deg=wedge_deg,
time_per_element_sec=time_sec,
steps=steps,
run_async=run_async,
)
try:
logger.info(
f"sending screening scan request to aarescan for validation with payload {payload}"
)
return self._api.validate_screening_post(payload)
except Exception as e:
raise AerotechCommunicationError(
f"Aerotech screening validation failed: {e}",
endpoint="screening_post",
base_url=self._base,
operation="POST",
) from e
if __name__ == "__main__":
beamline = mx_beamline()
# print(beamline)
controller = AerotechController(beamline)
# controller.print_status(colored=True, compact=True)
print(controller.get_position())
controller.cancel()
-127
View File
@@ -1,127 +0,0 @@
import dataclasses
from enum import Enum
import epics
import numpy as np
from aarecommon.config.logger import setup_logger
logger = setup_logger("aareDAQ")
class AutoEnum(Enum):
MANUAL = 0
ONCE = 1
AUTO = 2
@dataclasses.dataclass
class AutoExposureSettings:
aoi_offset_x: int = 500
aoi_offset_y: int = 500
aoi_size_x: int = 1000
aoi_size_y: int = 1000
gain_max: float = 5.000
exp_max: float = 30000.000
class epicsAD:
def __init__(self, prefix, cam="cam1:", image="image1:"):
self.img = None
self.monitored = False
self.image_mode = epics.PV(prefix + cam + "ImageMode")
self.gain = epics.PV(prefix + cam + "Gain")
self.acquire = epics.PV(prefix + cam + "Acquire")
self.color = epics.PV(prefix + cam + "ColorMode")
self.gain_mode = epics.PV(prefix + cam + "GainAuto")
self.gain_mode_rbv = epics.PV(prefix + cam + "GainAuto_RBV")
# 0 - manual, GainMode, 2 - auto GainAuto
self.expo_mode = epics.PV(prefix + cam + "ExposureAuto")
self.expo_mode_rbv = epics.PV(prefix + cam + "ExposureAuto_RBV")
# 0 - manual, ExposureMode, 1 - once 2 - auto ExposureAuto
self.gain = epics.PV(prefix + cam + "Gain")
self.gain_rbv = epics.PV(prefix + cam + "Gain_RBV")
self.expo = epics.PV(prefix + cam + "AcquireTime")
self.expo_rbv = epics.PV(prefix + cam + "AcquireTime_RBV")
self.ndim = epics.PV(prefix + image + "NDimensions_RBV")
self.dim0 = epics.PV(prefix + image + "ArraySize0_RBV")
self.dim1 = epics.PV(prefix + image + "ArraySize1_RBV")
self.dim2 = epics.PV(prefix + image + "ArraySize2_RBV")
self.uid = epics.PV(prefix + image + "UniqueId_RBV")
self.data = epics.PV(prefix + image + "ArrayData")
self.counter = epics.PV(prefix + cam + "ArrayCounter_RBV")
self.busy = epics.PV(prefix + cam + "AcquireBusy", auto_monitor=True)
self.aoi_start_x = epics.PV(prefix + cam + "GC_AutFunAOIOffsetX")
self.aoi_start_y = epics.PV(prefix + cam + "GC_AutFunAOIOffsetY")
self.aoi_size_x = epics.PV(prefix + cam + "GC_AutFunAOIWidth")
self.aoi_size_y = epics.PV(prefix + cam + "GC_AutFunAOIHeight")
self.gain_max = epics.PV(prefix + cam + "GC_AutGainUpperLimit")
self.exp_max = epics.PV(prefix + cam + "GC_AutExpTimUppLimit")
self.auto_white_balance = epics.PV(prefix + cam + "GC_BalanceWhiteAuto")
self._init_auto_exp()
try:
epics.ca.pend_io()
except Exception:
logger.exception("EPICS error")
def _init_auto_exp(self, settings: AutoExposureSettings | None = None):
settings = settings or AutoExposureSettings()
self.acquire.put(0)
self.aoi_start_x.put(settings.aoi_offset_x)
self.aoi_start_y.put(settings.aoi_offset_y)
self.aoi_size_x.put(settings.aoi_size_x)
self.aoi_size_y.put(settings.aoi_size_y)
self.gain_max.put(settings.gain_max)
self.exp_max.put(settings.exp_max)
self.set_auto(AutoEnum.ONCE)
# TODO add a white_balance button to GUI or set it so it happens with backlight in and on
# self.auto_white_balance.put(1)
self.acquire.put(1)
def get_image(self, gray=True) -> np.ndarray:
if self.monitored:
return self.img
ndim = self.ndim.get()
dim0 = self.dim0.get()
dim1 = self.dim1.get()
dim2 = self.dim2.get()
if ndim == 3:
size = dim0 * dim1 * dim2
else:
size = dim0 * dim1
data = self.data.get(count=size)
data.dtype = np.uint8
if ndim == 3:
data.shape = (dim2, dim1, dim0)
# convert to grayscale
if gray:
data = (
data[:, :, 0] * 299.0 / 1000.0
+ data[:, :, 1] * 587.0 / 1000.0
+ data[:, :, 2] * 114.0 / 1000.0
)
else:
data.shape = (dim1, dim0)
return data
def setup(self, gain: float = 15, expo: float = 0.025):
# self.color.put(0) # black and white
self.acquire.put(0, wait=True)
self.gain_mode.put(0) # manual gain control
self.gain.put(gain)
self.expo_mode.put(0) # manual exposure control
self.expo.put(expo) # 20 hz acquisition
self.acquire.put(1)
def set_auto(self, state: AutoEnum):
"""Uses AutoEnum 0 is Manual, 1 is Once, 2 is Auto"""
self.acquire.put(0, wait=True)
self.gain_mode.put(state.value) # automatic gain control
self.expo_mode.put(state.value) # automatic exposure control
self.acquire.put(1)
-668
View File
@@ -1,668 +0,0 @@
import sys
import time
from enum import Enum
from typing import Any
from aarecommon.config.beamline import cfg_get, mx_beamline
from aarecommon.config.logger import setup_logger
from aarecommon.config.logger_events import log_timing
from aarecommon.errors.exception_handler import BECCommunicationError
from aarecommon.models.beamline import MXBeamline
from aarecommon.models.models import BeamlineStateEnum
from bec_ipython_client import BECIPythonClient
from bec_ipython_client.signals import OperationMode
from bec_lib.device import RPCError, ScanRequestError
from bec_lib.service_config import ServiceConfig
from aare.beamline_dispatch.beamline_dispatch import get_beamline_dispatch
from aare.daq.config import BeamlineConfig
logger = setup_logger("aareDAQ")
class DetectorCoverEnum(str, Enum):
"""Enum for the detector cover position
position devices can take string or number to move
Currently dictated string in DAQ for consitency"""
OPEN = "open" # 2
CLOSED = "closed" # 1
class BrightnessEnum(str, Enum):
"""Enum for the backlight brightness
position devices can take string or number to move
"""
ON = "on"
OFF = "off"
class BeamlineState(str, Enum):
ROBOT_SAMPLE_EXCHANGE = "robot_sample_exchange"
SAMPLE_ALIGNMENT = "sample_alignment"
DATA_COLLECTION = "data_collection"
DC_XRF = "DC_XRF"
MANUAL_SAMPLE_EXCHANGE = "manual_sample_exchange"
BEAM_VISUALISATION = "beam_visualisation"
FLUX_MEASUREMENT = "flux_measurement"
BEAMSTOP_ALIGNMENT = "beamstop_alignment"
MAINTENANCE = "maintenance"
XTAL_SNAPSHOT = "xtal_snapshot"
def _bec_state_to_aare_state(bec_state: str) -> BeamlineStateEnum:
map = {
"BEAMSTOP_ALIGNMENT": BeamlineStateEnum.BeamstopAlignment,
"SAMPLE_ALIGNMENT": BeamlineStateEnum.SampleAlignment,
"DATA_COLLECTION": BeamlineStateEnum.DataCollection,
"DC_XRF": BeamlineStateEnum.XrayFluorescence,
"MANUAL_SAMPLE_EXCHANGE": BeamlineStateEnum.SampleExchange,
"BEAM_VISUALISATION": BeamlineStateEnum.BeamLocation,
"FLUX_MEASUREMENT": BeamlineStateEnum.FluxMeasurement,
"MAINTENANCE": BeamlineStateEnum.Maintenance,
"XTAL_SNAPSHOT": BeamlineStateEnum.XtalSnapshot,
}
if bec_state in map:
return map[bec_state]
logger.warning(f"No match for state: {bec_state}")
return BeamlineStateEnum.Maintenance
class BECClientWorker:
def __init__(self, beamline: MXBeamline, cfg: BeamlineConfig, name: str = "default"):
logger.debug(f"initialising BEC worker for {beamline}")
BEAMLINE = beamline.value.lower()
self.beamline = beamline
self._backlight_brightness: Any
self._cfg = cfg
if self.beamline is MXBeamline.X06DA:
self._beamline_name = "pxiii"
elif self.beamline is MXBeamline.X10SA:
self._beamline_name = "pxii"
elif self.beamline is MXBeamline.X06DA:
self._beamline_name = "pxi"
elif self.beamline is MXBeamline.SIMULATED:
self._beamline_name = "SIMULATED"
else:
raise ValueError(f"Unknown beamline: {beamline}")
self.dispatch = get_beamline_dispatch()
if self.beamline is MXBeamline.SIMULATED:
self.simulated = True
host = "localhost"
else:
self.simulated = False
host = cfg_get("daq.hardware.bec_url", f"{BEAMLINE}-bec-001.psi.ch")
service_config = ServiceConfig(redis={"host": host, "port": 6379})
service_config.config["log_writer"]["base_path"] = "/tmp/logs"
try:
self.client = BECIPythonClient(config=service_config, mode=OperationMode.Procedure)
self.client.start()
self.dev = self.client.device_manager.devices
self.scans = self.client.scans
self.macros = self.dispatch.bec_macros
self._set_scilog_tags()
self._init_beamline_environment()
except Exception:
logger.exception("Error initialising BEC devices")
self.client.shutdown()
sys.exit(1)
logger.debug(f"simulated is {self.simulated}")
def shutdown(self):
self.client.shutdown()
def _init_beamline_environment(self):
try:
self.position_devices, self.planner = self.macros.init_beamline_environment()
self._backlight_brightness = self.position_devices["bl_bright"]
self._frontlight_brightness = self.position_devices["fl_bright"]
self._zoom = self.dev.scam_zoom
self._ring_current = self.dev.sls_current
except Exception as e:
logger.error(f"Error initialising planner and position devices: {e}")
self.position_devices = None
self.planner = None
self._backlight_brightness = None
self._frontlight_brightness = None
try:
self._zoom = self.dev.scam_zoom
self._ring_current = self.dev.sls_current
except Exception as e:
logger.exception("Error initialising zoom and ring_current")
self._zoom = None
self.ring_current = None
raise RuntimeError(f"Error initialising BEC devices: {e}") from e
def read_current_state(self) -> BeamlineStateEnum:
if self.planner is None:
return BeamlineStateEnum.Maintenance
matching_states = self.planner.current_state()
if matching_states is None or len(matching_states) < 1:
return BeamlineStateEnum.Maintenance
logger.debug(f"BEC planner returned matching states: {matching_states}")
current_state = _bec_state_to_aare_state(matching_states[0][0])
logger.info(f"Current state detected from BEC: {current_state}")
return current_state
def _bec_error(
self, exc: Exception, *, operation: str, tags: list[str] | None = None
) -> BECCommunicationError:
"""Report a failed BEC operation and build the error; callers ``raise ... from`` it."""
message = f"BEC operation '{operation}' failed: {type(exc).__name__}: {exc}"
# logger.exception(message)
if tags is None:
tags = ["error", "bec"]
else:
tags += ["error", "bec"]
try:
bec_alarms = self.client.alarms()
if bec_alarms:
alarms = [alarm for alarm in bec_alarms]
logger.debug(f"alarms: {alarms}")
last_alarm = self.client.show_last_alarm()
message += f"\n\nAlarm: {last_alarm}\n\n"
logger.error(f"last_alarm: {last_alarm}")
except Exception:
logger.exception("Couldn't raise BEC alarms")
try:
self.scilog_msg(
message=message,
error=True,
error_message=f"Error during '{operation}': {exc}",
tags=tags,
)
except Exception:
logger.exception("Error sending scilog message")
if isinstance(exc, AssertionError):
return BECCommunicationError(
f"BEC internal assertion failed during '{operation}'",
operation=operation,
exception=exc,
)
return BECCommunicationError(message, operation=operation, exception=exc)
def _set_scilog_tags(self, tags: list[str] | None = None):
try:
if tags:
self.client.messaging.scilog.set_default_tags(tags)
else:
self.client.messaging.scilog.set_default_tags(["AareDAQ"])
except Exception as e:
logger.exception("Error setting scilog tags")
raise self._bec_error(e, operation="set scilog tags") from e
def scilog_msg(
self,
message: str,
error: bool = False,
warning: bool = False,
error_message: str | None = None,
attachments=None,
bold: bool = False,
italic: bool = False,
color: str | None = None,
additonal_text: list[str] | None = None,
tags: list[str] | None = None,
):
if color and color not in ["red", "green", "yellow", "blue", "pink"]:
logger.warning("specified color not in allowed list,using default")
color = None
try:
msg = self.client.messaging.scilog.new()
except Exception as e:
raise self._bec_error(e, operation="scilog_msg") from e
try:
msg.add_text(message, bold=bold, italic=italic, color=color)
if error:
msg.add_text(error_message, bold=True, color="red")
elif warning:
msg.add_text(error_message, bold=True, color="yellow")
except Exception as e:
logger.exception("Error adding text")
msg.add_text(f"Error adding text: {e}")
try:
if attachments:
for attachment in attachments:
msg.add_attachment(attachment)
except Exception as e:
logger.exception("Error adding attachment")
msg.add_text(f"Error adding attachment: {e}")
try:
if additonal_text:
for text in additonal_text:
msg.add_text(text)
except Exception as e:
logger.exception("Error adding additional text")
msg.add_text(f"Error adding additional text: {e}")
try:
if tags:
msg.add_tags(tags)
except Exception as e:
logger.exception("Error setting scilog tags")
msg.add_text(f"Error setting scilog tags: {e}")
try:
msg.send()
except Exception:
logger.exception("Error sending scilog message")
@log_timing(logger, "BEC move_to")
def move_to(self, state: BeamlineState):
start = time.perf_counter()
logger.debug(f"simulated is {self.simulated}")
logger.info(f"BEC move_to requested: {state.value}")
if self.simulated:
logger.debug(f"Simulating move to {state.value}")
return True
try:
self.planner.move_to(state)
if self.planner.is_state(state):
logger.info(
f"BEC move_to completed: {state.value} in {time.perf_counter() - start:.2f}s"
)
return True
else:
logger.warning(
f"Failed to move to {state.value} in {time.perf_counter() - start:.2f}s"
)
return False
except Exception as e:
raise self._bec_error(e, operation=f"planner.move_to:{state.value}") from e
def is_state(self, state: BeamlineState):
if self.simulated:
logger.debug(f"Simulating check_beamline_state: {state.value}")
return True
return self.planner.is_state(state)
def list_position_devices(self):
"""List the position devices available for the BEC worker"""
if self.simulated or self.position_devices is None:
return []
return list(self.position_devices.keys())
def show_all_devices(self):
return self.dev.show_all
def list_all_user_macros(self) -> list[str] | None:
if self.simulated:
logger.debug("Simulating list_all_user_macros")
return []
try:
self._list_all_macros()
raw_macros = [name for name, _ in self.client.macros._update_handler.macros.items()]
if raw_macros is None:
logger.warning("BEC returned no user macros; treating as empty list")
return []
return [str(macro) for macro in raw_macros]
except Exception as e:
raise self._bec_error(e, operation="list_all_user_macros") from e
def _list_all_macros(self):
result = self.client.macros.list_user_macros()
if result is None:
return []
return result
def load_user_macros(self):
if self.simulated:
logger.debug("Simulating load_user_macros")
return None
try:
return self._load_user_macros()
except Exception as e:
raise self._bec_error(e, operation="load_user_macros") from e
def _load_user_macros(self):
# load user macros is common to all clients, not part of beamline dispatch
result = self.client.macros.load_all_user_macros()
if result is None:
logger.warning("BEC load_all_user_macros returned None")
return result
def reinitialise_planner_and_position_devices(self, method: str = "auto"):
"""
Reinitialise BEC position devices and planner.
Args:
method:
"auto" - use the beamline-specific default.
"beamline" - force init_beamline_environment().
"sample" - force init_se_devices() + planner creation.
Returns:
List of position device names after reinitialisation.
"""
if self.simulated:
logger.debug(f"Simulating reinitialise_planner_and_position_devices(method={method})")
return []
try:
self.client.config.update_session_with_file(
f"/sls/{self.beamline}/config/bec/production/{self._beamline_name}_bec/{self._beamline_name}_bec/device_configs/{self._beamline_name}-devices.yaml"
)
self._init_beamline_environment()
logger.info(f"Reinitialised BEC planner and position devices using method={method}")
return self.list_position_devices()
except Exception as e:
raise self._bec_error(
e, operation=f"reinitialise_planner_and_position_devices:{method}"
) from e
def shutdown_client(self):
self.client.shutdown()
def mono_pitch_scan_runner(self, plot: bool = False):
try:
self.macros.mono_pitch_scan(plot)
except Exception as e:
raise self._bec_error(e, operation="mono_pitch_scan", tags=["mono_pitch_scan"]) from e
if self.beamline is MXBeamline.X10SA:
additional_text = [f"New dcm_pitch position: {self.dev.dcm_pitch.position:5f}"]
elif self.beamline is MXBeamline.X06DA:
additional_text = [f"New dcm_theta2 position: {self.dev.dccm_theta2.position:5f}"]
else:
additional_text = ["What beamline did you run this on???"]
self.scilog_msg(
message="Mono pitch scan completed",
bold=True,
color="green",
tags=["mono_pitch_scan"],
additonal_text=additional_text,
)
def check_current_energy(self):
"""Get the current energy from the BEC in eV"""
energy_ev = self.macros.get_current_energy()
energy_kev = energy_ev / 1000
return energy_kev
def change_energy(self, value: float, plot: bool = False):
current_energy = self.check_current_energy()
logger.info(f"Current energy: {current_energy:.1f} eV")
logger.info(f"Change energy requested: from {current_energy:.1f} to {value:.1f} eV")
try:
self.macros.bl_energy(value, move_gap=True, mono_scan=True, plot=plot)
except Exception as e:
raise self._bec_error(
e,
operation=f"Requested energy change from:{current_energy:.1f} to {value} eV",
tags=["energy_change"],
) from e
if abs(value - self.check_current_energy()) > 1:
logger.warning(
f"Energy change may have failed, current energy: {self.check_current_energy()} eV"
)
if self.beamline is MXBeamline.X10SA:
additonal_text = [
f"New dcm_bragg position: {self.dev.dcm_bragg.position:4g} mrad",
f"New dcm_pitch position: {self.dev.dcm_pitch.position:4g} ",
f"Previous energy: {current_energy:.1f} eV ",
f"Requested energy: {value:.1f} eV ",
f"New current energy: {self.check_current_energy():.1f} eV",
]
else:
additonal_text = [
f"New dccm_theta1 position: {self.dev.dccm_theta1.position:4g} mrad",
f"New dccm_theta2 position: {self.dev.dccm_theta2.position:4g} mrad",
f"Previous energy: {current_energy:.1f} eV ",
f"Requested energy: {value:.1f} eV ",
f"New current energy: {self.check_current_energy():.1f} eV",
]
self.scilog_msg(
message=f"Moved from {current_energy:.1f} eV to {value:.1f} eV",
bold=True,
color="green",
tags=["energy_change"],
additonal_text=additonal_text,
)
def get_det_z(self):
try:
return self.dev.det_z.position
except Exception as e:
raise self._bec_error(e, operation="get_det_z", tags=["det_z"]) from e
def det_z(self, value: float, timeout: int | None = None):
"""timeout is None or integer in s"""
try:
status = self.scans.mv(self.dev.det_z, value, relative=False)
if timeout:
status.wait(timeout=timeout)
return status
except Exception as e:
raise self._bec_error(e, operation=f"scans.mv:det_z:{value}", tags=["det_z"]) from e
def get_det_y(self):
try:
return self.dev.det_y.position
except Exception as e:
raise self._bec_error(e, operation="get_det_z", tags=["det_z"]) from e
def det_y(self, value: float, timeout: int | None = None):
"""timeout is None or integer in s"""
try:
status = self.scans.mv(self.dev.det_y, value, relative=False)
if timeout:
status.wait(timeout=timeout)
return status
except Exception as e:
raise self._bec_error(e, operation=f"scans.mv:det_y:{value}", tags=["det_z"]) from e
@property
def backlight_brightness(self) -> BrightnessEnum:
"""returns backlight brightness as an Enum: 'off' or 'on', can also be a value...
How to handle"""
try:
return BrightnessEnum(self._backlight_brightness.actual)
except Exception as e:
raise self._bec_error(
e,
operation="backlight brightness, could not get backlight brightness",
tags=["backlight"],
) from e
raise
@backlight_brightness.setter
def backlight_brightness(self, value: int | str):
"""Set the backlight brightness to the specified value"""
if self.simulated:
return
try:
self._backlight_brightness.move(value)
except Exception as e:
raise self._bec_error(
e, operation=f"backlight_brightness:{value}", tags=["backlight"]
) from e
raise
def get_backlight_pos(self) -> BrightnessEnum:
"""Returns the current backlight brightness position"""
return BrightnessEnum(self._backlight_brightness.pos)
def backlight_toggle(self):
"""Turn the backlight on or off"""
if self.simulated:
return
try:
current = self.get_backlight_pos()
if current is BrightnessEnum.ON:
target = BrightnessEnum.OFF
else:
target = BrightnessEnum.ON
self.backlight_brightness = target
except Exception as e:
raise self._bec_error(
e,
operation="backlight toggle, could not change backlight on/off ",
tags=["backlight"],
) from e
def save_current_bs_pos(self):
self.macros.save_current_position(self.dev.bs_y, "in")
self.macros.save_current_position(self.dev.bs_x, "in")
self.save_config_and_reload_devices()
def save_current_collimator_pos(self):
self.macros.save_current_position(self.dev.coll_x, "in")
self.macros.save_current_position(self.dev.coll_y, "in")
self.save_config_and_reload_devices()
def save_current_aerotech_position(self):
self.macros.save_current_position(self.dev.aerotech, "in", axis="x")
self.macros.save_current_position(self.dev.aerotech, "work", axis="y")
self.macros.save_current_position(self.dev.aerotech, "work", axis="z")
self.save_config_and_reload_devices()
def save_config_and_reload_devices(self):
self.position_devices, self.planner = self.macros.save_and_reload()
@property
def zoom(self):
return self._zoom.position
@zoom.setter
def zoom(self, value: float):
self.scans.umv(self._zoom, value, relative=False)
self._cfg.current_zoom_level = value
@property
def ring_current(self) -> float:
try:
return self._ring_current.get(cached=True)
except (RPCError, ScanRequestError):
return 0
if __name__ == "__main__":
import time
print(time.ctime(), " starting BEC Client")
beamline = mx_beamline()
try:
client = BECClientWorker(beamline)
except Exception:
logger.exception("Failed to start BEC client")
try:
client.shutdown_client()
except Exception:
logger.exception("Failed to shut the BEC client down cleanly")
sys.exit(1)
# print(client.get_det_cov(actual=True))
# print(client.is_state(BeamlineState.ROBOT_SAMPLE_EXCHANGE))
try:
print("startting backlight brightness test")
print("initial value")
# print(client.client.show_last_alarm())
# print(client._raise_bec_error(exc=Exception("test"), operation="test", tags=["test"]))
print(client.ring_current)
for i in range(10):
print(client._ring_current.get())
time.sleep(1)
# print('setting to 5')
# client.backlight_brightness = 5
# print(client.get_backlight_pos())
# print(client.backlight_brightness)
# print('setting to 1.2')
# client.backlight_brightness = 1.2
# print(client.get_backlight_pos())
# print(client.backlight_brightness)
# print('setting to ON')
# client.backlight_brightness = BrightnessEnum.ON
# print(client.get_backlight_pos())
# print(client.backlight_brightness)
# print('setting to 1.0')
# client.backlight_brightness = 1.0
# print(client.get_backlight_pos())
# print(client.backlight_brightness)
# print('setting to 0.0')
# client.backlight_brightness = 0.0
# print(client.get_backlight_pos())
# print(client.backlight_brightness)
# print('setting to OFF')
# client.backlight_brightness = BrightnessEnum.OFF
# client.backlight_toggle()
# print(client.get_backlight_pos())
# print(client.backlight_brightness)
# client.scilog_msg("Testing scilog messages with color = yellow and italic", italic=True,
# color="green", warning=False)
except Exception:
client.shutdown_client()
logger.exception("BEC client smoke test failed")
# try:
# det_value = 980
# print(f"moving detector to vale:{det_value}")
# start = time.perf_counter()
# # print(client.get_det_z())
# # client.det_z(value=det_value, timeout=10)
# # print(time.perf_counter() - start)
# # print(client.get_det_z)
# # det_value = 985
# # print(f"moving detector to vale:{det_value}")
# status = client.det_z(value=det_value)
# status.wait(timeout=5)
# print(status)
# print(client.get_det_z())
# #client.mono_pitch_scan_runner()
# #client.change_energy(12000)
#
# except Exception as e:
# print(f"Error: {e}")
# # client.planner.current_state()
# client.planner.move_to(BeamlineState.SAMPLE_ALIGNMENT)
# time.sleep(2.0)
# client.planner.current_state()
# client.move_to(BeamlineState.SAMPLE_ALIGNMENT)
# time.sleep(2.0)
# client.planner.current_state()
# client.load_user_macros()
# client.macros.mono_pitch_scan(False)
# status = client.run_macro("planner.current_state", queue="default")
# client.planner.move_to('manual_sample_exchange')
# print(status)
# status.wait()
# print(status)
# try:
# status=client.proc.run_macro("mono_pitch_scan", queue="test")
# planner.move_to('manual_sample_exchange')
# print(status)
# status.wait()
# status.cancel()
# print(status)
# client.client.macros.mono_pictch_scan(False)
# try:
# # a=client.a2e_runner(160, "iln")
# # print(a)
# # print(convert_from_energy(12))
# # energy = get_current_energy()
# # pos = get_dcm_motors_positions(energy)
# # print(energy, pos)
# print(bs_z_policy(15.0))
# #client.scans.umv(client.dev.xeye_x, 0, relative=False)
# #client.mono_pitch_scan_runner()
# #client.mono_pitch_scan_runner()
# #b=client.run_macro_blocked("a2e", 160, "iln", queue="test")
# #b = client.run_macro_blocked("mono_pitch_scan", False, queue="default")
#
# #status = client.mono_pitch_scan_runner
# #print(status)
#
# #client.rse2sa()
# #time.sleep(10.0)
# #time.sleep(10.0)
# #print(status)
# #client.common2rse()
# #print(status)
# except GuardViolation as e:
# print(f"GuardViolation: {e}")
# except RuntimeError as e:
# print(f"RuntimeError: {e}")
client.shutdown_client()
-36
View File
@@ -1,36 +0,0 @@
from enum import Enum
from typing import Any
from aare.devices.set_get_pv import MoveResult, SetGetPV
class EnumPV(SetGetPV):
def __init__(self, name: str, setpv: str, getpv: str, **kwargs):
super().__init__(name, setpv, getpv, **kwargs)
if not self.setpoint_pv.enum_strs:
raise RuntimeError(f"{setpv} is not an ENUM PV")
@property
def position(self) -> str:
return self.readback_pv.get(as_string=True)
def _resolve(self, x: Any) -> MoveResult:
# accept Enum member
if isinstance(x, Enum):
x = x.name
# accept index
if isinstance(x, int):
try:
return MoveResult(target=self.setpoint_pv.enum_strs[x], name=None)
except Exception as e:
raise ValueError(f"Bad enum index {x}") from e
# accept name -> match against enum strings (case-insensitive)
if isinstance(x, str):
for s in self.setpoint_pv.enum_strs:
if s.strip().lower() == x.strip().lower():
return MoveResult(target=s, name=s)
raise ValueError(f"'{x}' not in {list(self.setpoint_pv.enum_strs)}")
raise TypeError(f"Unsupported enum command type: {type(x).__name__}")
@@ -1,30 +0,0 @@
from aarecommon.models.beamline import MXBeamline
from epics import PV
class ExperimentalHutchShutter:
def __init__(self, beamline: MXBeamline):
BEAMLINE = beamline.value.upper()
self._close = PV(f"{BEAMLINE}-EH1-PSYS:SH-A-CLOSE-SET") # 1, 0
self._open = PV(f"{BEAMLINE}-EH1-PSYS:SH-A-OPEN-SET")
self._state = PV(f"{BEAMLINE}-OP-PSH1-EMLS-0010:OPEN")
def state(self):
state = self._state.get()
if state == "Open" or state == 1:
return True
elif state == "Not Open" or state == 0:
return False
else:
print(ValueError(f"unknown state: {state}"))
return False
def open(self):
self._open.put(0)
self._open.put(1)
# print(self._open.get())
self._open.put(0)
def close(self):
self._close.put(1)
self._close.put(0)
-53
View File
@@ -1,53 +0,0 @@
import time
from aarecommon.models.beamline import MXBeamline
from epics import PV, poll
class FilterTransmission:
def __init__(self, bl: MXBeamline, timeout=60.0, fail_on_timeout=True):
BEAMLINE = bl.value.upper()
self.device_name = "FilterTransmission"
self._fail_on_timeout = fail_on_timeout
self._timeout = timeout
self._set = PV(f"{BEAMLINE}-ES-FI:TRANSM-SET")
self._get = PV(f"{BEAMLINE}-ES-FI:TRANSM-GET")
self._done = PV(f"{BEAMLINE}-ES-FI:DONE")
def __repr__(self):
return f"<FilterTransmission: {self._set.get():.4f}>"
def __str__(self):
return f"{self._get.get():.4f}"
def is_done(self):
return 1 == int(self._done.value)
def is_busy(self):
return not self.is_done()
def set(self, val, wait=False):
val = float(val)
if not (0.0 <= val <= 1.0):
raise RuntimeError(
f"requested transmission ({val:.4f}) is out of bounds --- valid range : 0 <= trans <= 1.0"
)
self._set.put(val)
poll(0.2)
if wait:
self.wait()
def get(self) -> float | None:
if self.is_busy():
return None
return round(self._get.value, 5)
def wait(self):
timeisup = False
timeout = self._timeout + time.time()
while not timeisup and self.is_busy():
timeisup = time.time() > timeout
poll(0.1)
if timeisup and self._fail_on_timeout:
raise RuntimeError("timeout waiting for filters to achieve requested transmission.")
-173
View File
@@ -1,173 +0,0 @@
import time
from aarecommon.config.logger import setup_logger
from aarecommon.models.beamline import MXBeamline
from epics import PV, poll
logger = setup_logger("aareaDAQ")
class Fluorimeter:
def __init__(self, beamline: MXBeamline, **kwargs):
BEAMLINE = beamline.value.upper()
self._start = PV(f"{BEAMLINE}-ES-SiD:mca1Start") # 0 done ,1 start
self._stop = PV(f"{BEAMLINE}-ES-SiD:mca1Stop") # 0 done ,1 stop
self._erase_and_start = PV(f"{BEAMLINE}-ES-SiD:mca1EraseStart") # 0 done,1 start
self._erase = PV(f"{BEAMLINE}-ES-SiD:mca1Erase") # 0 done,1 erase
self._preset_mode = PV(f"{BEAMLINE}-ES-SiD:dxp1:PresetMode") # set mode
self._status = PV(f"{BEAMLINE}-ES-SiD:mca1.ACQG") # 0 done, 1 acquire
self._real_time = PV(f"{BEAMLINE}-ES-SiD:mca1.PRTM") # float
self._live_time = PV(f"{BEAMLINE}-ES-SiD:mca1.PLTM") # float
self._elapsed_real_time = PV(f"{BEAMLINE}-ES-SiD:mca1.ERTM") # float
self._elapsed_live_time = PV(f"{BEAMLINE}-ES-SiD:mca1.ELTM") # float
self._elapsed_trigger_live_time = PV(f"{BEAMLINE}-ES-SiD:dxp1:ElapsedTriggerLiveTime")
self._instant_dead_time = PV(f"{BEAMLINE}-ES-SiD:mca1.IDTIM")
self._average_dead_time = PV(f"{BEAMLINE}-ES-SiD:mca1.DTIM")
self._poll_time_rbv = PV(f"{BEAMLINE}-ES-SiD:PollTime_RBV")
self._poll_time = PV(f"{BEAMLINE}-ES-SiD:PollTime")
self._mca = PV(f"{BEAMLINE}-ES-SiD:mca1")
self._data = PV(f"{BEAMLINE}-ES-SiD:mca1.VAL")
self._background = PV(f"{BEAMLINE}-ES-SiD:mca1.BG")
self._saveFile = PV(f"{BEAMLINE}-ES-SiD:SaveSystemFile")
self._saveFile_name = PV(f"{BEAMLINE}-ES-SiD:SaveSystem")
self._saveFile_rbv = PV(f"{BEAMLINE}-ES-SiD:SaveSystem_RBV") # 1 ssave, 0 done
self._roi_1 = self.get_roi(BEAMLINE, 1) # currently SiEsc
self._roi_2 = self.get_roi(BEAMLINE, 2) # currently MnKa
self._calibration_offset = PV(f"{BEAMLINE}-ES-SiD:mca1.CALO")
self._calibration_slope = PV(f"{BEAMLINE}-ES-SiD:mca1.CALS")
def get_roi(self, bl, roi_num: int):
if roi_num not in [1, 2]:
raise ValueError(f"Invalid ROI number: {roi_num}")
roi_name = f"{bl}-ES-SiD:mca1.R{roi_num}NM"
return PV(roi_name)
def start_acquisition(self, erase: bool = False):
if erase:
self._erase_and_start.put(1)
else:
self._start.put(1)
def stop_acquisition(self):
self._stop.put(1)
def erase(self):
self._erase.put(1)
def poll_data(self, timeout_s: float = 30.0):
timeout = time.time() + timeout_s
while not self.check_status_done():
if time.time() > timeout:
self.stop_acquisition()
raise TimeoutError("timeout waiting for data to be acquired.")
self._mca.get()
poll(0.1)
def get_current_data(self):
return self._data.get()
def get_current_background(self):
return self._background.get()
def check_status(self):
return self._status.get()
def check_status_done(self):
if self.check_status() == 0:
return True
def check_status_acquiring(self):
if self.check_status() == 1:
return True
def wait_till_done(self, timeout_s: float = 30.0):
timeout = time.time() + timeout_s
while not self.check_status_done():
if time.time() > timeout:
raise TimeoutError("timeout waiting for done.")
poll(0.1)
def wait_till_acquiring(self, timeout_s: float = 30.0):
timeout = time.time() + timeout_s
while not self.check_status_acquiring():
if time.time() > timeout:
raise TimeoutError("timeout waiting for acquiring.")
poll(0.1)
def set_preset_mode(self, mode: int):
"""0 No preset, 1 Real time, 2 Live time, 3 Events, 4 Triggers"""
if mode not in [0, 1, 2, 3, 4]:
raise ValueError(f"Invalid preset mode: {mode}")
try:
self._preset_mode.put(mode)
except Exception:
logger.exception(f"Error setting preset mode to {mode}")
def save_file(self, filename: str | None = None, timeout_s: float = 30.0):
if not filename:
filename = f"KETEK_{time.strftime('%Y%m%d_%H%M%S')}.txt"
self._saveFile_name.put(filename)
try:
self._saveFile.put(1)
timeout = time.time() + timeout_s
while self._saveFile_rbv.get() == 1:
if time.time() > timeout:
raise TimeoutError("Timed out waiting for save to complete")
poll(0.1)
except Exception:
logger.exception(f"Error saving file {filename}")
@property
def real_time(self):
return self._real_time.get()
@real_time.setter
def real_time(self, value):
self._real_time.put(value)
@property
def live_time(self):
return self._live_time.get()
@live_time.setter
def live_time(self, value):
self._live_time.put(value)
def elapsed_real_time(self):
return self._elapsed_real_time.get()
def elapsed_live_time(self):
return self._elapsed_live_time.get()
def elapsed_trigger_live_time(self):
return self._elapsed_trigger_live_time.get()
def instant_dead_time(self):
return self._instant_dead_time.get()
def average_dead_time(self):
return self._average_dead_time.get()
@property
def slope(self):
return self._calibration_slope.get()
@property
def offset(self):
return self._calibration_offset.get()
@property
def poll_time(self):
return self._poll_time_rbv.get()
@poll_time.setter
def poll_time(self, value):
self._poll_time.put(value)
-494
View File
@@ -1,494 +0,0 @@
import functools
import math
import time
from collections.abc import Callable
from enum import Enum
from typing import Concatenate, ParamSpec, TypeVar, final
import jfjoch_client
from aare_config import AareConfigClient
from aarecommon.config.beamline import get_jfjoch_url
from aarecommon.config.logger import setup_logger
from aarecommon.errors.exception_handler import AareUserError, JFJochCommunicationError
from aarecommon.models.beamline import MXBeamline
from aarecommon.models.models import DAQStatusModel, FluorescenceSpectrumOutputModel
from aarecommon.models.raster_grid import RasterGridRequest
from aarecommon.models.rotation_scan import RotationScanRequest
from jfjoch_client.api.default_api import DefaultApi
from jfjoch_client.api_client import ApiClient
from jfjoch_client.models.dataset_settings_smargon import DatasetSettingsSmargon
from jfjoch_client.models.detector_list_element import DetectorListElement
from jfjoch_client.models.scan_result import ScanResult
logger = setup_logger("aareDAQ")
P = ParamSpec("P")
R = TypeVar("R")
class ScanTypeEnum(Enum):
RASTER = "Raster"
XRF = "XRF"
ROTATION = "Rotation"
SCREENING = "Screening"
HELICAL = "Helical"
UNKNOWN = "Unknown"
def needs_init(
method: Callable[Concatenate["JFJochWrapper", P], R],
) -> Callable[Concatenate["JFJochWrapper", P], R]:
"""Make sure the JFJoch client/api exist before the method touches them."""
@functools.wraps(method)
def wrapper(self: "JFJochWrapper", *args: P.args, **kwargs: P.kwargs) -> R:
self.connect()
return method(self, *args, **kwargs)
return wrapper
@final
class JFJochWrapper:
def __init__(self, bl: MXBeamline):
self._simulated = bl == MXBeamline.SIMULATED
self._url = get_jfjoch_url(bl)
self._connected: bool = False
_client: ApiClient
_api: DefaultApi
try:
self._config_client = AareConfigClient(
redis_url=f"redis://mx-{bl.value.lower()}-queue-01", key_prefix="config"
)
except Exception:
logger.exception("Failed to create aare config client")
self._config_client = None
def _get_images_per_file(self) -> int | None:
"""Images per file from aare config; None (JFJoch default) if unavailable."""
if self._config_client is None:
return None
try:
return self._config_client.jfjoch.n_images_per_file or None
except Exception:
logger.warning(
"jfjoch/n_images_per_file not available from aare config; using JFJoch default",
exc_info=True,
)
return None
def connect(self) -> None:
"""Connect to JFJoch on first use; a no-op once the client exists."""
if self._connected:
return
if self._url == "simulated":
from unittest.mock import MagicMock
self._client = MagicMock(spec=ApiClient)
self._api = MagicMock(spec=DefaultApi)
self._connected = True
return
self._client = jfjoch_client.ApiClient(jfjoch_client.Configuration(host=self._url))
self._api = jfjoch_client.DefaultApi(self._client)
# set before cancel(), which is itself decorated and would otherwise recurse
self._connected = True
try:
self.cancel(on_init=True)
except:
self._connected = False
raise
@staticmethod
def _extract_status_code(error: Exception) -> int | None:
for attr_name in ("status", "status_code"):
value = getattr(error, attr_name, None)
if isinstance(value, int):
return value
body = getattr(error, "body", None)
if isinstance(body, str) and "500" in body:
return 500
return None
def _jfjoch_error(
self, message: str, *, error: Exception, operation: str, endpoint: str
) -> JFJochCommunicationError:
"""Build the error for a failed JFJoch call; callers ``raise ... from`` it."""
return JFJochCommunicationError(
message,
operation=operation,
endpoint=endpoint,
base_url=self._url,
status_code=self._extract_status_code(error),
)
@needs_init
def initialize(self):
try:
self._api.initialize_post()
except Exception as e:
raise self._jfjoch_error(
"JFJoch initialize failed", error=e, operation="POST", endpoint="initialize_post"
) from e
@needs_init
def cancel(self, on_init: bool = False):
try:
self._api.cancel_post()
except Exception as e:
raise self._jfjoch_error(
f"JFJoch cancel failed{' on initialization' if on_init else ''}",
error=e,
operation="POST",
endpoint="cancel_post",
) from e
@needs_init
def is_idle(self) -> bool:
status = self._api.status_get()
return status.state == "Idle"
def _format_dataset_settings(
self,
r: RasterGridRequest | RotationScanRequest,
s: DAQStatusModel,
f: FluorescenceSpectrumOutputModel | None = None,
async_start: bool = True,
) -> jfjoch_client.DatasetSettings:
# common sample parameter intiialisation
if s.sample is None:
pgroup = "p16371"
sample = "unknown_sample"
else:
pgroup = s.sample.user
sample = s.sample.sample_name
# raster grid, rotation or screening specific parameter initialisation
wedge = None
if isinstance(r, RasterGridRequest):
data_folder = f"{pgroup}/raw/raster"
if r.n_x == 1:
trigger = 1
images = r.n_y
else:
trigger = r.n_y
images = r.n_x
else:
if r.screening:
data_folder = f"{pgroup}/raw/screening"
wedge = r.wedge_omega_deg
images = 1
trigger = r.steps
else:
data_folder = f"{pgroup}/raw"
wedge = None
images = r.steps
trigger = 1
if r.dtz is None:
raise ValueError(
"Scan request has no detector distance (dtz); setup_datacollection "
"must validate and set request.dtz before JFJoch is configured"
)
# build common dataset settings
if s.geom.smargon.phi_deg is not None and s.geom.smargon.chi_deg is not None:
smargon_phi_chi = DatasetSettingsSmargon(
phi_deg=s.geom.smargon.phi_deg, chi_deg=max(s.geom.smargon.chi_deg, 0)
)
else:
smargon_phi_chi = None
images_per_file = self._get_images_per_file()
dataset_settings = jfjoch_client.DatasetSettings(
beam_x_pxl=s.diffraction.beam_center_pxl[0],
beam_y_pxl=s.diffraction.beam_center_pxl[1],
ntrigger=trigger,
images_per_trigger=images,
detector_distance_mm=r.dtz,
file_prefix=f"{data_folder}/{r.file_prefix}",
incident_energy_keV=s.diffraction.energy_keV,
sample_name=sample,
image_time_us=round(r.exp_time_s * 1e6),
experiment_group=pgroup,
transmission=s.bl.transmission,
ring_current_mA=s.bl.ring_current_mA,
sample_temperature_K=s.bl.cryojet_K,
total_flux=s.bl.flux_ph_s * s.bl.transmission,
poni_rot1_rad=s.diffraction.poni_rot1_rad,
poni_rot2_rad=s.diffraction.poni_rot2_rad,
max_spot_count=1000,
detect_ice_rings=True,
async_start=async_start,
smargon=smargon_phi_chi,
beam_size_x_um=s.geom.beam_size_mm.x * 1000.0,
beam_size_y_um=s.geom.beam_size_mm.y * 1000.0,
polarization_factor=1.0,
images_per_file=images_per_file,
)
# settup grid or goniometer settings adn add to dataset settings
if isinstance(r, RasterGridRequest):
grid_settings = jfjoch_client.GridScan(
n_fast=r.n_x,
snake=True,
step_x_um=r.grid_size_mm.x * 1000.0,
step_y_um=r.grid_size_mm.y * 1000.0,
vertical=False,
)
goniometer_settings = jfjoch_client.RotationAxis(
step=0, start=r.omega_deg, name="omega", vector=[-1, 0, 0], screening_wedge_deg=0
)
dataset_settings.grid_scan = grid_settings
dataset_settings.goniometer = goniometer_settings
else:
goniometer_settings = jfjoch_client.RotationAxis(
step=r.incr_omega_deg,
start=r.start_omega_deg,
name="omega",
vector=[-1, 0, 0],
screening_wedge_deg=wedge,
)
dataset_settings.goniometer = goniometer_settings
# if measuring fluoresence, add to dataset settings
if f is not None:
xrf = jfjoch_client.DatasetSettingsXrayFluorescenceSpectrum(
energy_eV=f.energy_eV, data=f.spectrum
)
dataset_settings.xray_fluorescence_spectrum = xrf
if s.sample.aaredb_params and s.sample.aaredb_params.unitcell:
unit_cell_db = s.sample.aaredb_params.unitcell
unit_cell_split = unit_cell_db.replace(",", " ").split()
unit_cell_floats = [float(x) for x in unit_cell_split]
unit_cell = jfjoch_client.UnitCell(
a=unit_cell_floats[0],
b=unit_cell_floats[1],
c=unit_cell_floats[2],
alpha=unit_cell_floats[3],
beta=unit_cell_floats[4],
gamma=unit_cell_floats[5],
)
dataset_settings.unit_cell = unit_cell
if s.sample.aaredb_params.spacegroupnumber:
space_group_number = s.sample.aaredb_params.spacegroupnumber
dataset_settings.space_group_number = space_group_number
return dataset_settings
@needs_init
def _start_scan(
self,
scan_type: ScanTypeEnum,
r: RasterGridRequest | RotationScanRequest,
s: DAQStatusModel,
f: FluorescenceSpectrumOutputModel | None = None,
async_start: bool = True,
):
dataset_settings = self._format_dataset_settings(r, s, f, async_start=async_start)
try:
self._api.start_post(dataset_settings=dataset_settings)
except Exception as e:
raise self._jfjoch_error(
f"JFJoch data collection failed to initialize for {scan_type.value} scan with exception: {e}",
error=e,
operation="POST",
endpoint="start_post",
) from e
def measure_rotation(
self,
r: RotationScanRequest,
s: DAQStatusModel,
f: FluorescenceSpectrumOutputModel | None = None,
async_start: bool = True,
) -> None:
if r.screening:
self._start_scan(ScanTypeEnum.SCREENING, r, s, f, async_start=async_start)
else:
self._start_scan(ScanTypeEnum.ROTATION, r, s, f, async_start=async_start)
def measure_raster(self, r: RasterGridRequest, s: DAQStatusModel, async_start: bool = True):
self._start_scan(ScanTypeEnum.RASTER, r, s, async_start=async_start)
@needs_init
def wait_till_running(self, timeout: float = 60):
logger.info("Waiting for JFJoch to report detector armed")
if self._simulated:
return None
try:
self._api.wait_until_running_post_with_http_info(timeout=math.ceil(timeout))
status = self._api.status_get()
logger.debug(status)
if status.message_severity == "error":
raise self._jfjoch_error(
f"JFJoch status message has error severity after waiting for arm: {status.message}",
error=RuntimeError(status.message),
operation="POST",
endpoint="wait_until_running_post",
)
return True
except Exception as e:
if "Output file already exists" in str(e):
raise AareUserError(
"JFJoch reports output file already exists! Change the filename or increment the run number.",
critical=True,
) from e
raise self._jfjoch_error(
f"JFJoch wait until running returned an exception: {e}",
error=e,
operation="POST",
endpoint="wait_until_running_post",
) from e
@needs_init
def wait_till_done(self, timeout: float) -> ScanResult | None:
if self._simulated:
return None
try:
res = self._api.wait_till_done_post_with_http_info(timeout=math.ceil(timeout))
logger.info(f"wait_till_done response: {res}")
return self._api.result_scan_get()
except Exception as e:
raise self._jfjoch_error(
f"JFJoch wait till done retrieval returned an exception: {e}",
error=e,
operation="POST",
endpoint="wait_till_done_post / result_scan_get",
) from e
@needs_init
def detector(self) -> DetectorListElement:
try:
detector_list = self._api.config_select_detector_get()
except Exception as e:
raise self._jfjoch_error(
f"JFJoch detector configuration retrieval failed: {e}",
error=e,
operation="GET",
endpoint="config_select_detector_get",
) from e
if len(detector_list.detectors) == 0:
raise JFJochCommunicationError(
"JFJoch returned no configured detectors",
operation="GET",
endpoint="config_select_detector_get",
base_url=self._url,
status_code=None,
)
try:
return detector_list.detectors[detector_list.current_id]
except Exception as e:
raise self._jfjoch_error(
"JFJoch returned an invalid selected detector entry",
error=e,
operation="GET",
endpoint="config_select_detector_get",
) from e
@needs_init
def get_diffraction_image(
self,
image_id: int,
wait_between_retries_s: float = 0.1,
*,
show_spots: bool = False,
show_res_est: bool = False,
show_beam_center: bool = False,
):
last_error = None
for _ in range(3):
try:
return self._api.image_buffer_image_jpeg_get(
id=image_id,
show_spots=show_spots,
show_res_est=show_res_est,
show_beam_center=show_beam_center,
)
except Exception as e:
logger.debug("Diffraction image retrieval attempt failed; retrying", exc_info=True)
last_error = e
time.sleep(wait_between_retries_s)
raise last_error
if __name__ == "__main__":
import logging
from aarecommon.math.coordinate import Coordinate, SmargonCoordinate
from aarecommon.math.diffraction_geometry import DiffractionGeometry
from aarecommon.math.sample_geometry import SampleGeometryModel
from aarecommon.models.models import (
BeamlineStateEnum,
BeamlineStatus,
SampleCameraSettings,
SessionStatus,
)
logging.basicConfig(level=logging.DEBUG)
bl = MXBeamline.X10SA
wrapper = JFJochWrapper(bl)
# wrapper.initialize()
# wrapper.wait_till_done(timeout=360)
status = DAQStatusModel(
bl=BeamlineStatus(
name="X10SA",
ring_current_mA=400.0,
flux_ph_s=1e12,
transmission=1.0,
cryojet_K=100.0,
front_light=50.0,
back_light=50.0,
shutter_open=False,
exp_shutter_open=False,
sample_camera=SampleCameraSettings(gain=1.0, exposure=0.02),
zoom=1.0,
commissioning_mode=False,
dtz_min=120.0,
dtz_max=1600.0,
),
diffraction=DiffractionGeometry(
detector_description="EIGER",
detector_serial_number="123",
dtz_mm=200.0,
pixel_size_mm=0.075,
energy_keV=12.658,
beam_center_pxl=(1000.0, 1000.0),
detector_size_pxl=(4000, 4000),
poni_rot1_rad=0.0,
poni_rot2_rad=0.0,
),
geom=SampleGeometryModel(
beam_location_pxl=Coordinate(x=1000, y=1000),
pixel_in_mm=0.001,
aerotech=Coordinate(x=0, y=0),
aerotech_meas=Coordinate(x=0, y=0),
smargon=SmargonCoordinate(sh_mm=Coordinate(x=0, y=0, z=0), phi_deg=0, chi_deg=0),
omega_deg=10.5,
beam_size_mm=Coordinate(x=0.02, y=0.01),
),
session=SessionStatus(),
state=BeamlineStateEnum.Maintenance,
busy=False,
)
wrapper.measure_raster(
RasterGridRequest(
n_x=1,
n_y=1,
grid_size_mm=Coordinate(x=0.05, y=0.05),
file_prefix="test",
exp_time_s=0.1,
dtz=150,
transmission=1,
smargon_top_left=SmargonCoordinate(),
omega_deg=0.0,
),
status,
)
print("waiting for detector to start")
wrapper.wait_till_running()
print("success we can measure")
wrapper.cancel()
-289
View File
@@ -1,289 +0,0 @@
import re
import time
from collections.abc import Callable
from typing import Any
from aarecommon.config.logger import setup_logger
from epics import PV, Motor, poll
logger = setup_logger("aareDAQ")
def wait_for_movement_to_finish(*motors):
"""
Wait for all {motors} passed in argument to finish movement.
Requirements: epics.Motor -- each {motor} is an instance of this
class.
The overall timeout is the maximum of (.RBV - .VAL)/.VELO for each
concerned {motor}.
Returns: nothing
"""
poll(0.3)
longest = 0.0
for motor in motors:
time_to_target = motor.readback / motor.slew_speed
longest = max(longest, time_to_target)
timeout = time.time() + 1.5 * longest
done = False
while not done and time.time() < timeout:
done = all(m.done_moving for m in motors)
if time.time() > timeout:
print("TIMEOUT waiting for motors to be done moving; current motor positions:")
for m in motors:
print(f"...{m._prefix[:-1]} ({m.units}) VAL={m.drive:.1f}; RBV={m.readback:.1f}")
raise TimeoutError("timeout waiting for movement to finish.")
class ValueWaitTimeout(Exception):
pass
def pv_wait(
pv: PV | Motor,
value: Any,
*,
timeout: float = 60.0,
polling: float = 0.1,
tolerance: float | None = None,
verbose: bool = False,
):
"""wait until an epics.PV reaches a value
pv: epics.PV | epics.Motor
the PV on which you want to wait on
value/target: any
this value depends on the PV type: str, enum, double, ...
:timeout: float default = 60.0
timeout in seconds
:polling: float default = 0.1
polling interval in seconds
tolerance: float or None
provide a tolerance to accept when comparing values, currently None by default, however certain PVs and motors
have inbuilt tolerances that can be used instead
verbose: bool default = False
NotImplemented
"""
if isinstance(pv, Motor):
def checker(m, target=None, tolerance=None):
if tolerance is None:
tolerance = m.get("RDBD")
if tolerance is None:
print(f"WARNING: motor {m._prefix[:-1]} has no RDBD, using 0.001")
tolerance = 0.001 # FIXME
if target is None:
target = m.drive
diff = abs(target - m.readback)
return m.done_moving and diff < tolerance
wait_motor_position(
pv, checker, target=value, tolerance=tolerance, timeout=timeout, polling=polling
)
elif is_epics_type(pv, "double") or is_epics_type(pv, "time_double"):
wait_float_condition(pv, value, tolerance=tolerance, timeout=timeout, polling=polling)
elif is_epics_type(pv, "enum") or is_epics_type(pv, "time_enum"):
wait_enum_condition(pv, value, timeout=timeout, polling=polling)
elif is_epics_type(pv, "string") or is_epics_type(pv, "time_string"):
wait_string_condition(pv, value, timeout=timeout, polling=polling)
else:
raise ValueError(f"pv_wait() don't know how to handle {pv.pvname} of type {pv.type}")
def is_epics_type(pv: PV, pv_type: str) -> bool:
"""Check to see if a PV is of a certain type such as double, enum, string, ..."""
if isinstance(pv_type, type):
pv_type = pv_type.__name__
return pv_type == pv.type
def wait_string_condition(
pv: PV, target: str | re.Pattern, *, timeout: float = 60.0, polling: float = 0.1
):
"""wait until an epics.PV of type string reaches target
:pv: epics.PV
PV should be of type string
:target: str or re.Pattern
:timeout: float default = 60.0
timeout in seconds
:polling: float default = 0.1
polling interval in seconds
"""
if not (isinstance(pv, PV) and "string" not in pv.type):
raise AttributeError("argument 'pv' must be an epics.PV of type string")
if not isinstance(target, re.Pattern):
target = re.compile(f"^{target}$", re.IGNORECASE)
tout = time.time() + timeout
while time.time() < tout:
if target.match(pv.char_value):
return
poll(polling)
if time.time() > tout:
raise TimeoutError(
f"timeout waiting for string {pv.pvname} == {target}; actual value == {pv.char_value}"
)
def wait_float_condition(
pv: PV,
value: float,
*,
timeout: float = 60.0,
polling: float = 0.1,
tolerance: float | None = None,
):
"""wait until an epics.PV of type double reaches value
pv: epics.PV
the PV enum on which you want to wait on
value: float
the target value
polling: float
how often pv is checked during wait loop
tolerance: float or None
the tolerance to accept when comparing values, if None (default) we
try to figure an appropriate value
timeout: float default = 60.0
a timeout in seconds
return: nothing
raises: TimeoutError if a timeout occurs
"""
try:
value = float(value)
except ValueError:
raise AttributeError("argument 'value' must be a number")
if tolerance is None:
# If pv.precision is missing/None, fall back to a default
precision = getattr(pv, "precision", None)
if precision is None:
tolerance = 1e-6
else:
tolerance = pow(10, -(precision - 1))
tout = time.time() + timeout
while time.time() < tout:
if abs(pv.value - value) < tolerance:
return
poll(polling)
if time.time() > tout:
raise TimeoutError(f"timeout waiting for enum {pv.pvname} == {value}")
def wait_motor_position(
motor: Motor, tester: Callable, *, timeout: float = 50.0, polling: float = 0.1, **kwargs
):
"""wait until an epics.Motor reaches a condition
motor: epics.Motor
the motor on which you want to wait on
tester: Callable
a Callable which is passed motor and **kwargs
=> Callable(motor, **kwargs)
timeout: double
a timeout in seconds
**kwargs: extra arguments to tester
return: nothing
raises: TimeoutError if a timeout occurs
"""
if not callable(tester):
raise TypeError("argument 'tester' must be a function")
try:
move_time = abs(motor.drive - motor.readback) / motor.speed
except Exception:
logger.debug("Could not compute the motor move time; using the 1 s default", exc_info=True)
move_time = 1.0 # in case of unusual motor record
tout = move_time + time.time() + timeout
while time.time() < tout:
if tester(motor, **kwargs):
return
poll(polling)
if time.time() > tout:
raise TimeoutError(
f"timeout waiting for a condition on {motor} {motor.drive} != {motor.readback}"
)
def wait_enum_condition(
pv: PV, value: str | int | re.Pattern, *, timeout: float = 60.0, polling=0.1
):
"""wait until an epics.PV enum reaches value
pv: epics.PV
the PV enum on which you want to wait on
value: int or str
if int check against index of current value
timeout: double
a timeout in seconds
return: nothing
raises: TimeoutError if a timeout occurs
"""
if not (isinstance(pv, PV) and pv.type.lower().endswith("enum")):
raise AttributeError("argument 'pv' must be an epics.PV of type enum")
if not (isinstance(value, (str, int, re.Pattern))):
raise TypeError("argument 'value' must be either an int, str, or re.Pattern")
if type(value) is int:
tester = lambda pv: value == pv.get()
elif type(value) is str:
tester = lambda pv: str(value) == pv.get(as_string=True).lower()
value = str(value).lower() # it's already a str :-/
elif isinstance(value, re.Pattern):
tester = lambda pv: value.match(pv.get(as_string=True))
else:
raise AttributeError("argument 'value' must be either an int, str, or re.Pattern")
tout = time.time() + timeout
while time.time() < tout:
if tester(pv):
return
poll(polling)
if time.time() > tout:
raise TimeoutError(
f"timeout waiting for enum {pv.pvname} == {value},"
f"current value is {pv.get(as_string=True)}"
)
def clean_filename(filename: str) -> str:
cleaned = re.sub(r"[^A-Za-z0-9._-]", "_", filename.strip())
cleaned = cleaned.strip("._-")
if not cleaned:
raise ValueError("Filename is empty after sanitization.")
return cleaned
-104
View File
@@ -1,104 +0,0 @@
import time
from epics import Motor
class MyMotor(Motor):
"""Wrapper for the EPICS motor PV."""
def __init__(self, name, timeout=5.0):
super().__init__(name.upper(), timeout=timeout)
@property
def speed(self):
"""Gets the current motor.slew_speed value"""
return self.get("VELO")
@speed.setter
def speed(self, v):
"""Sets the motor slew speed"""
self.put("VELO", v)
@property
def position(self):
"""Gets the current motor readback value"""
return self.readback
@property
def value(self):
"""Gets the current motor.drive value"""
return self.drive
@value.setter
def value(self, v):
"""Sets motor.drive to a set value"""
self.drive = v
def stop(self):
"""Stops the motor"""
self.stop_motor()
@property
def moving(self):
"""Returns True if the motor is moving"""
return bool(self.get("MOVN"))
@property
def units(self):
"""Returns the units of the motor as a string"""
return self.get("EGU", as_string=True)
@property
def limits(self):
"""Returns (low_limit, high_limit)"""
return self.get("HLM"), self.get("LLM")
@limits.setter
def limits(self, limits):
"""Sets (low_limit, high_limit)"""
low, high = limits
self.put("LLM", low)
self.put("HLM", high)
def move_motor(self, val, relative=False, wait=False, timeout=300.0):
"""
Moves the motor to an absolute or relative position.
:param val: Position to move to
:param relative: If True, moves relative to current position
:param wait: If True, waits for completion (synchronous)
:param timeout: Maximum time to wait for completion
"""
return self.move(val, relative=relative, wait=wait, timeout=timeout)
def home(self, direction="forward", wait=False):
"""
Homes the motor.
:param direction: 'forward' or 'reverse'
"""
field = "HOMF" if direction == "forward" else "HOMR"
self.put(field, 1)
if wait:
self.wait_for_stop()
def wait_for_stop(self, timeout=300.0, poll_rate=0.01):
"""
Synchronous wait until the motor stops moving.
"""
start_time = time.time()
while self.moving:
time.sleep(poll_rate)
if time.time() - start_time > timeout:
raise RuntimeError(f"Timeout waiting for motor {self.name} to stop")
async def wait_for_stop_async(self, timeout=300.0, poll_rate=0.01):
"""
Asynchronous wait until the motor stops moving.
"""
import asyncio
start_time = time.time()
while self.moving:
await asyncio.sleep(poll_rate)
if time.time() - start_time > timeout:
raise RuntimeError(f"Timeout waiting for motor {self.name} to stop")
-63
View File
@@ -1,63 +0,0 @@
"""Personnel Safety System (PSS) state for the experimental hutch.
The sample-changer robot may only move when the hutch is in the *prohibited*
state (doors closed/searched, no personnel access). When
``…-EH1-PSYS:PROHIBITED-STATE`` reads ``0`` the robot will not move, so a
mount/unmount must be blocked. A non-zero ``…-EH1-PSYS:ALARM-STATE`` signals a
safety alarm.
This mirrors the simple PV-wrapper pattern used by
:class:`aare.devices.experimental_hutch_shutter.ExperimentalHutchShutter`
(same ``EH1-PSYS`` PV family). In ``SIMULATED`` the device reports a safe state
(prohibited, no alarm) so the simulated mount path runs without hardware.
"""
from aarecommon.config.logger import setup_logger
from aarecommon.models.beamline import MXBeamline
from epics import PV
logger = setup_logger("aareDAQ")
class PssState:
def __init__(self, beamline: MXBeamline):
self._simulated = beamline == MXBeamline.SIMULATED
BEAMLINE = beamline.value.upper()
if self._simulated:
self._prohibited = None
self._alarm = None
else:
self._prohibited = PV(f"{BEAMLINE}-EH1-PSYS:PROHIBITED-STATE")
self._alarm = PV(f"{BEAMLINE}-EH1-PSYS:ALARM-STATE")
def is_prohibited(self) -> bool:
"""True when the hutch is interlocked so the robot is allowed to move.
``PROHIBITED-STATE`` reports ``"PROHIBITED"`` (robot may move) or ``0``
(robot will not move). A disconnected/unknown PV is treated as *not*
prohibited, so the mount is blocked fail-safe.
"""
if self._simulated:
return True
value = self._prohibited.get()
if value is None:
logger.warning(
"PROHIBITED-STATE PV returned no value; treating hutch as not prohibited"
)
return False
if isinstance(value, str):
prohibited = value.strip().upper() == "PROHIBITED"
else:
prohibited = value != 0
return prohibited
def alarm_active(self) -> bool:
"""True when ``ALARM-STATE`` is non-zero (a safety alarm is active)."""
if self._simulated:
return False
value = self._alarm.get()
if value is None:
return False
if isinstance(value, str):
return value.strip().upper() not in ("", "0", "OK", "NONE", "NO ALARM")
return value != 0
-85
View File
@@ -1,85 +0,0 @@
from __future__ import annotations
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from typing import Any
from epics import PV
from aare.devices.mx_lib import pv_wait
RawValue = str | float | int
ResolverValue = (
RawValue
| tuple[Callable[..., RawValue], tuple[Any, ...]] # (func, args) pattern you already use
)
@dataclass
class MoveResult:
target: RawValue
name: str | None = None
class SetGetPV:
def __init__(
self,
name: str,
setpv: str,
getpv: str,
*,
timeout: float = 60.0,
tolerance: float | None = None,
):
self.name = name
self.setpoint_pv = PV(setpv)
self.readback_pv = PV(getpv)
self.default_timeout = timeout
self.tolerance = tolerance
self._last_target: RawValue | None = None
@property
def value(self) -> Any:
return self.readback_pv.get()
def _resolve(self, x: Any) -> MoveResult:
# Default: treat input as raw value
return MoveResult(target=x, name=None)
def move(self, x: Any, *, wait: bool = False, timeout: float | None = None) -> MoveResult:
res = self._resolve(x)
self._last_target = res.target
self.setpoint_pv.put(res.target)
if wait:
self.wait(timeout=timeout)
return res
def wait(self, *, timeout: float | None = None):
if self._last_target is None:
return
pv_wait(
self.readback_pv,
self._last_target,
timeout=timeout or self.default_timeout,
tolerance=self.tolerance,
)
class PredefinedPV(SetGetPV):
def __init__(
self, name: str, setpv: str, getpv: str, predefs: Mapping[str, ResolverValue], **kwargs
):
super().__init__(name, setpv, getpv, **kwargs)
self._predefs = dict(predefs)
@property
def positions(self) -> list[str]:
return list(self._predefs.keys())
def _resolve(self, x: Any) -> MoveResult:
if isinstance(x, str) and x in self._predefs:
v = self._predefs[x]
if isinstance(v, tuple) and callable(v[0]):
v = v[0](*v[1])
return MoveResult(target=v, name=x)
return MoveResult(target=x, name=None)
-236
View File
@@ -1,236 +0,0 @@
from enum import Enum
from time import perf_counter, sleep, time
import requests
from aarecommon.config.beamline import cfg_get
from aarecommon.errors.exception_handler import SmargonCommunicationError
from aarecommon.math.coordinate import AerotechCoordinate, Coordinate, SmargonCoordinate
from aarecommon.models.beamline import MXBeamline
class SmargonMode(Enum):
UNINITIALIZED = 0
INITIALIZING = 1
READY = 2
ERROR = 99
class Smargon:
SMARGON_HOME = SmargonCoordinate(sh_mm=Coordinate(x=0, y=0, z=18), phi_deg=0, chi_deg=0)
AERO_HOME = AerotechCoordinate(x=0, y=0, z=0, omega=0)
def __init__(self, bl: MXBeamline):
if bl == MXBeamline.X06DA:
self._simulated = False
self._base = cfg_get("daq.hardware.smargon_url", "http://x06da-smargopolo.psi.ch:3000")
elif bl == MXBeamline.X10SA:
self._simulated = False
self._base = cfg_get("daq.hardware.smargon_url", "http://x10sa-smargopolo.psi.ch:3000")
elif bl == MXBeamline.X06SA:
raise NotImplementedError("Not implemented smargon url for X06SA")
elif bl == MXBeamline.SIMULATED:
self._simulated = True
else:
raise ValueError("unknown beamline")
self._pos = self.SMARGON_HOME
self._pos_aero = self.AERO_HOME
def gonget(self, thing: str) -> dict:
"""issue a GET for some API component on the smargopolo server
short hand for goniometer get"""
cmd = f"{self._base}/{thing}"
try:
r = requests.get(cmd, timeout=2.0)
except requests.exceptions.RequestException as e:
raise SmargonCommunicationError(
f"Smargon GET failed for '{thing}'",
endpoint=thing,
base_url=self._base,
operation="GET",
) from e
if not r.ok:
raise SmargonCommunicationError(
f"Smargon GET returned HTTP {r.status_code} for '{thing}': {r.reason}",
endpoint=thing,
base_url=self._base,
operation="GET",
status_code=r.status_code,
)
try:
return r.json()
except ValueError as e:
raise SmargonCommunicationError(
f"Smargon GET returned invalid JSON for '{thing}'",
endpoint=thing,
base_url=self._base,
operation="GET",
status_code=r.status_code,
) from e
def gonput(self, thing: str):
"""issue a PUT command for some API component on the smargopolo server
short hand for goniometer put"""
cmd = f"{self._base}/{thing}"
try:
r = requests.put(cmd, timeout=2.0)
except requests.exceptions.RequestException as e:
raise SmargonCommunicationError(
f"Smargon PUT failed for '{thing}'",
endpoint=thing,
base_url=self._base,
operation="PUT",
) from e
if not r.ok:
raise SmargonCommunicationError(
f"Smargon PUT returned HTTP {r.status_code} for '{thing}': {r.reason}",
endpoint=thing,
base_url=self._base,
operation="PUT",
status_code=r.status_code,
)
def move_home(self, wait=False) -> None:
self.target = self.SMARGON_HOME
if wait:
self.wait()
@property
def mode(self) -> SmargonMode:
mode = self.gonget("mode")
return SmargonMode(mode)
@mode.setter
def mode(self, mode: SmargonMode):
if self._simulated:
return
self.gonput(f"mode?mode={mode}")
def initialize(self, timeout: float = 360.0):
self.mode = SmargonMode.UNINITIALIZED.value
sleep(0.1)
self.mode = SmargonMode.INITIALIZING.value
start = perf_counter()
mode = self.mode.value
while mode != SmargonMode.READY.value:
sleep(0.1)
if abs(perf_counter() - start) > timeout:
raise TimeoutError("Timed out waiting for Smargon to initialize")
mode = self.mode.value
return True
def enable_correction(self):
if self._simulated:
return
self.gonput("corr_type?corr_type=1")
def disable_correction(self):
if self._simulated:
return
self.gonput("corr_type?corr_type=0")
@property
def readback(self) -> SmargonCoordinate:
if self._simulated:
return self._pos
scs = self.gonget("readbackSCS")
return SmargonCoordinate(
sh_mm=Coordinate(x=scs["SHX"], y=scs["SHY"], z=scs["SHZ"]),
phi_deg=scs["PHI"],
chi_deg=scs["CHI"],
)
@property
def readback_aerotech(self) -> AerotechCoordinate:
if self._simulated:
return self._pos_aero
acs = self.gonget("readbackAEROTECH")
return AerotechCoordinate(
at_mm=Coordinate(x=acs["GMX"], y=acs["GMY"], z=acs["GMZ"]), omega_deg=acs["GMU"]
)
@property
def target(self) -> SmargonCoordinate:
if self._simulated:
return self._pos
scs = self.gonget("targetSCS") # targetAEROTECH, #targetOMEGA
return SmargonCoordinate(
sh_mm=Coordinate(x=scs["SHX"], y=scs["SHY"], z=scs["SHZ"]),
phi_deg=scs["PHI"],
chi_deg=scs["CHI"],
)
@target.setter
def target(self, coord: SmargonCoordinate):
if self._simulated:
self._pos = coord
return
target_string = ""
if coord.sh_mm is not None:
target_string += (
f"&SHX={coord.sh_mm.x:.5f}&SHY={coord.sh_mm.y:.5f}&SHZ={coord.sh_mm.z:.5f}"
)
if coord.chi_deg is not None:
target_string += f"&CHI={coord.chi_deg:.5f}"
if coord.phi_deg is not None:
target_string += f"&PHI={coord.phi_deg:.5f}"
if target_string:
self.gonput(f"targetSCS?{target_string}")
@property
def target_aerotech(self) -> AerotechCoordinate:
if self._simulated:
return self._pos_aero
acs = self.gonget("targetAEROTECH") # targetAEROTECH, #targetOMEGA
return AerotechCoordinate(
at_mm=Coordinate(x=acs["GMX"], y=acs["GMY"], z=acs["GMZ"]), omega_deg=acs["GMU"]
)
@target_aerotech.setter
def target_aerotech(self, coord: AerotechCoordinate):
if self._simulated:
self._pos_aero = coord
return
target_string = ""
if coord.at_mm is not None:
target_string += (
f"&GMX={coord.at_mm.x:.5f}&GMY={coord.at_mm.y:.5f}&GMZ={coord.at_mm.z:.5f}"
)
if coord.omega_deg is not None:
target_string += f"&GMU={coord.omega_deg:.5f}"
if target_string:
self.gonput(f"targetAEROTECH?{target_string}")
def wait(self, timeout=60.0, tol=0.01, poll_time=0.01):
target = self.target
timeout = timeout + time()
while time() < timeout:
if target.eq(self.readback, tol):
break
sleep(poll_time)
def wait_aerotech(self, timeout=60.0, tol=0.01, poll_time=0.01):
timeout = timeout + time()
while time() < timeout:
if self.target_aerotech.eq(self.readback_aerotech, tol):
break
if time() > timeout:
raise TimeoutError("Timed out waiting for Aerotech to reach target")
sleep(poll_time)
if __name__ == "__main__":
smargon = Smargon(MXBeamline.X10SA)
print(smargon.mode)
smargon.initialize(timeout=30.0)
print(smargon.mode)
-393
View File
@@ -1,393 +0,0 @@
import json
import re
import time
from collections.abc import Callable
from typing import Any, Protocol
from urllib.parse import urlparse
import requests
from aarecommon.config.beamline import cfg_get
from aarecommon.config.logger import setup_logger
from aarecommon.errors.exception_handler import TellCommunicationError
from aarecommon.models.beamline import MXBeamline
from pshell import PShellClient
from requests.exceptions import HTTPError
logger = setup_logger("aareDAQ")
VALID_DEWAR_POSITIONS = [f"{p}{n}" for n in "12345" for p in "ABCDEFX"]
def is_valid_dewar_position(position):
"""check if argument is a valid dewar position"""
return position in VALID_DEWAR_POSITIONS
POSITION_PARK = "pPark"
POSITION_COLD = "pCold"
POSITION_AUX = "pAux"
POSITION_DEWAR = "pDewar"
POSITION_HOME = "pHome"
POSITION_HEATER = "pHeatB"
class TellBackend(Protocol):
@property
def url(self) -> str | None: ...
def get_state(self) -> str: ...
def get_result(self, command_id: int = -1): ...
def wait_state(self, state: str, timeout: float) -> None: ...
def wait_state_not(self, state: str, timeout: float) -> None: ...
def wait_events(self, events: dict[str, Any], timeout: float): ...
def eval(self, expr: str): ...
def start_eval(self, expr: str) -> int: ...
def run(self, path: str, pars: list[str] | None = None, background: bool = False) -> None: ...
def abort(self) -> None: ...
class PShellTellBackend:
def __init__(self, bl: MXBeamline):
self._url = self._resolve_url(bl)
logger.info(f"Connecting TELL p-shell service at {self._url} ...")
hostname = urlparse(self._url).hostname
try:
requests.get(f"{self._url}/history/0", timeout=1.0)
except requests.exceptions.RequestException as e:
logger.error(f"...connection to {hostname} failed")
raise TellCommunicationError(
f"TELL connection failed ({hostname})",
base_url=self._url,
endpoint="history/0",
operation="GET",
) from e
except requests.ReadTimeout as e:
logger.error(f"...PShell service {hostname} is down")
raise TellCommunicationError(
f"TELL connection timedout ({hostname})",
base_url=self._url,
endpoint="history/0",
operation="GET",
) from e
self._pshell = PShellClient(self._url)
logger.info(f"...connected to {hostname}")
@staticmethod
def _resolve_url(bl: MXBeamline) -> str:
beamline = bl.value.lower()
if bl == MXBeamline.X06DA:
return cfg_get("daq.hardware.tell_url", f"http://{beamline}-tell.psi.ch:22222")
if bl == MXBeamline.X10SA:
return cfg_get("daq.hardware.tell_url", "http://PC17488:22222")
if bl == MXBeamline.X06SA:
raise NotImplementedError(f"TellClient not implemented for {beamline}")
if bl == MXBeamline.SIMULATED:
raise NotImplementedError("Use SimTellBackend for MXBeamline.SIMULATED")
raise ValueError(f"Unknown beamline {beamline}")
@property
def url(self) -> str | None:
return self._url
def get_state(self) -> str:
return self._pshell.get_state()
def get_result(self, command_id: int = -1):
return self._pshell.get_result(command_id)
def wait_state(self, state: str, timeout: float) -> None:
self._pshell.wait_state(state, timeout=timeout)
def wait_state_not(self, state: str, timeout: float) -> None:
self._pshell.wait_state_not(state, timeout=timeout)
def wait_events(self, events: dict[str, Any], timeout: float):
return self._pshell.wait_events(events, timeout=timeout)
def _handle_pshell_error(self, e: HTTPError, operation: str, endpoint: str):
"""Extract meaningful error message from HTTPError response."""
msg = "Unknown server error"
if e.response is not None and e.response.text:
msg = e.response.text.strip()
raise TellCommunicationError(
msg, base_url=self._url, endpoint=endpoint, operation=operation, critical=True
) from e
def eval(self, expr: str):
try:
return self._pshell.eval(expr)
except HTTPError as e:
self._handle_pshell_error(e, "EVAL", f"eval/{expr}")
except Exception:
raise
def start_eval(self, expr: str) -> int:
return self._pshell.start_eval(expr)
def run(self, path: str, pars: list[str] | None = None, background: bool = False) -> None:
self._pshell.run(path, pars=pars, background=background)
def abort(self) -> None:
self._pshell.abort()
class SimTellBackend:
def __init__(self):
self._url: str | None = None
self._state = "Ready"
self._last_cmd_id = 1000
self._mounted_sample = ""
self._settings: dict[str, str] = {"mounted_sample_position": ""}
self._results: dict[int, dict[str, Any]] = {}
self._robot_status: dict[str, Any] = {"powered": True, "pos": POSITION_PARK}
self._current_mA = 30.0
self._pin_offset = 0.0
self._detected_pucks: list[dict[str, Any]] = []
self._system_check_msg = "OK"
self._smart_magnet_state = "Ready"
self._in_mount_position = False
self._manual_mode = False
self._door_closed = True
@property
def url(self) -> str | None:
return self._url
def _next_cmd_id(self) -> int:
self._last_cmd_id += 1
return self._last_cmd_id
def _set_ready_soon(self) -> None:
time.sleep(0.01)
self._state = "Ready"
def get_state(self) -> str:
return self._state
def get_result(self, command_id: int = -1):
if command_id == -1:
command_id = self._last_cmd_id
return self._results.get(command_id, {"status": "completed"})
def wait_state(self, state: str, timeout: float) -> None:
if self._state != state:
time.sleep(min(timeout, 0.05))
self._state = state
def wait_state_not(self, state: str, timeout: float) -> None:
if self._state == state:
time.sleep(min(timeout, 0.05))
self._state = "Ready"
def wait_events(self, events: dict[str, Any], timeout: float):
self.wait_state_not("Busy", timeout)
if "Motion Sync" in events:
return "Motion Sync", "Robot Clear after mount"
if "Motion Task" in events:
return "Motion Task", "idle"
return None, self._state
def eval(self, expr: str):
expr = expr.strip()
if expr == "in_mount_position&":
return "true" if self._in_mount_position else "false"
if expr == "is_manual_mode()&":
return "true" if self._manual_mode else "false"
if expr == "is_door_closed()&":
return "true" if self._door_closed else "false"
if expr.startswith("in_mount_position = "):
self._in_mount_position = "True" in expr or "true" in expr
return None
if expr.startswith("set_setting("):
match = re.match(r"set_setting\('([^']+)', '([^']*)'\)&", expr)
if match:
key, value = match.groups()
self._settings[key] = value
return None
if expr.startswith("get_setting("):
match = re.match(r"get_setting\('([^']+)'\)&", expr)
if match:
key = match.group(1)
return self._settings.get(key, "")
return ""
if expr == "system_check_msg()&":
return self._system_check_msg
if expr == "robot.state&":
return self._state
if expr == "robot.take()&":
return str(self._robot_status)
if expr == "get_pucks_info()&":
return json.dumps(self._detected_pucks)
if expr == "get_pin_offset()&":
return str(self._pin_offset)
if expr == "smart_magnet.get_current_rb()&":
return str(self._current_mA)
if expr.startswith("smart_magnet.set_current("):
match = re.match(r"smart_magnet\.set_current\(([-+]?\d+(?:\.\d+)?)\)&", expr)
if match:
self._current_mA = float(match.group(1))
return None
if expr == "enable_motion()&":
self._robot_status["powered"] = True
return None
if expr == "smart_magnet.state&":
return self._smart_magnet_state
if expr == "smart_magnet.set_supress(True)&":
return None
if expr == "smart_magnet.set_supress(False)&":
return None
if expr == "smart_magnet.set_resting_current()&":
return None
if expr == "robot.stop_task()&":
self._state = "Ready"
return None
return None
def start_eval(self, expr: str) -> int:
cmd_id = self._next_cmd_id()
self._state = "Busy"
if expr.startswith("mount("):
parts = re.findall(r"'([^']*)'|([^,()]+)", expr)
values = [a if a else b.strip() for a, b in parts]
if len(values) >= 4:
segment = values[0]
puck = values[1]
sample = values[2]
mounted = f"{segment}{puck}{sample}"
self._mounted_sample = mounted
self._settings["mounted_sample_position"] = mounted
self._robot_status["pos"] = POSITION_DEWAR
elif expr.startswith("unmount("):
self._mounted_sample = ""
self._settings["mounted_sample_position"] = ""
self._robot_status["pos"] = POSITION_PARK
elif expr.startswith("move_park("):
self._robot_status["pos"] = POSITION_PARK
elif expr.startswith("move_cold("):
self._robot_status["pos"] = POSITION_COLD
elif expr.startswith("dry("):
self._robot_status["pos"] = POSITION_HEATER
self._results[cmd_id] = {"status": "completed", "command": expr}
self._set_ready_soon()
return cmd_id
def run(self, path: str, pars: list[str] | None = None, background: bool = False) -> None:
_ = background
if path == "data/set_samples_info" and pars:
try:
data = json.loads(pars[0])
self._detected_pucks = []
for item in data:
puck_address = item.get("puckAddress", "")
if puck_address:
self._detected_pucks.append(
{
"puckState": "Present",
"puckAddress": puck_address,
"puckBarcode": item.get("puckBarcode", ""),
}
)
except Exception:
logger.warning("Failed to load simulated samples info", exc_info=True)
def abort(self) -> None:
self._state = "Ready"
class LazyTellBackend:
def __init__(self, factory: Callable[[], TellBackend], *, retry_interval_s: float = 2.0):
self._factory = factory
self._backend: TellBackend | None = None
self._retry_interval_s = float(retry_interval_s)
self._last_attempt_ts = 0.0
self._last_error: Exception | None = None
def _get_backend(self) -> TellBackend:
if self._backend is not None:
return self._backend
now = time.monotonic()
if now - self._last_attempt_ts < self._retry_interval_s and self._last_error is not None:
raise self._last_error
self._last_attempt_ts = now
try:
self._backend = self._factory()
self._last_error = None
return self._backend
except TellCommunicationError as e:
self._last_error = e
raise
except Exception as e:
wrapped = TellCommunicationError("TELL connection failed", operation="CONNECT")
self._last_error = wrapped
raise wrapped from e
@property
def url(self) -> str | None:
return self._get_backend().url
def get_state(self) -> str:
return self._get_backend().get_state()
def get_result(self, command_id: int = -1):
return self._get_backend().get_result(command_id)
def wait_state(self, state: str, timeout: float) -> None:
self._get_backend().wait_state(state, timeout)
def wait_state_not(self, state: str, timeout: float) -> None:
self._get_backend().wait_state_not(state, timeout)
def wait_events(self, events: dict[str, Any], timeout: float):
return self._get_backend().wait_events(events, timeout)
def eval(self, expr: str):
return self._get_backend().eval(expr)
def start_eval(self, expr: str) -> int:
return self._get_backend().start_eval(expr)
def run(self, path: str, pars: list[str] | None = None, background: bool = False) -> None:
self._get_backend().run(path, pars=pars, background=background)
def abort(self) -> None:
self._get_backend().abort()
-595
View File
@@ -1,595 +0,0 @@
import ast
import json
import re
from datetime import UTC
from enum import Enum
from aarecommon.config.logger import setup_logger
from aarecommon.errors.exception_handler import (
ManualMountException,
MountingFailed,
SmartMagnetFaultException,
TellCommandWhileBusyException,
TellCommunicationError,
TellConnectionException,
)
from aarecommon.models.beamline import MXBeamline
from aarecommon.models.models import DewarAddress, PuckLoadedInfo, SampleDewarAddress
from aareDB import PuckWithTellPosition
from aare.devices.tell_backend import (
POSITION_COLD,
LazyTellBackend,
PShellTellBackend,
SimTellBackend,
TellBackend,
)
logger = setup_logger("aareDAQ")
class TellEventTypeEnum(Enum):
STATE = "state"
MOTION_TASK = "Motion Task"
MOTION_SYNC = "Motion Sync"
GIPPER_DETECTION = "Gripper detection"
UNKNOWN = "Unknown event type"
class TellEventValueEnum(Enum):
SUCCESS = "success"
NO_PIN_IN_GRIPPER = "No Pin in Gripper"
PIN_STILL_IN_GRIPPER = "Pin still in Gripper"
PIN_IS_LOST_GRIPPER = "Pin is lost"
UNKNOWN = "Unknown value"
ROBOT_CLEAR_AFTER_MOUNT = "Robot Clear after mount"
DRY = "dry"
COLD = "cold"
PARK = "park"
UNMOUNT = "unmount"
MOUNT = "mount"
MANUAL = "manual"
READY = "Ready"
BUSY = "Busy"
class TellClient:
"""High-level Tell robot API using a pluggable backend"""
def __init__(self, bl: MXBeamline, backend: TellBackend | None = None):
self._beamline = bl
self.backend = backend or PShellTellBackend(bl)
self._aborted = False
self.state = self.get_state()
self.debug = False
self._last_cmd_id = -1
@property
def url(self):
"""returns the configured base url for the Tell robot"""
return self.backend.url
def get_state(self):
"""returns the current state of the robot"""
self.state = self.backend.get_state()
return self.state
def get_result(self, command_id=-1):
"""returns the result of the last command issued to the robot"""
return self.backend.get_result(command_id)
def wait_ready(self, timeout: float = 360.0):
"""waits until the robot is ready to accept commands returns None if simulation
and raises an exception if the robot is not ready"""
self.backend.wait_state("Ready", timeout=timeout)
def wait_not_busy(self, timeout: float = 360.0):
"""waits until the robot is not busy and returns None if simulation
and raises an exception if the robot is busy"""
self.backend.wait_state_not("Busy", timeout=timeout)
state = self.get_state()
if state != "Ready":
if state == "Initializing":
raise TellConnectionException("Tell reconnecting")
elif state == "Closing":
raise TellConnectionException("Tell is disconnecting")
raise RuntimeError("Invalid state: " + str(state))
def set_in_mount_position(self, value):
"""tells the robot that the beamlien is safe and to set the in mount position flag allowing mounting
:param value"""
self.backend.eval("in_mount_position = " + str(value) + "&")
def _eval_bool(self, expr: str) -> bool:
value = self.backend.eval(expr)
return str(value).strip().lower() == "true"
def is_in_mount_position(self) -> bool:
"""checks to see if the robot is in the mount position and returns a boolean"""
return self._eval_bool("in_mount_position&")
def is_manual_mode(self) -> bool:
"""returns True if the robot is in manual mode"""
result = self._eval_bool("is_manual_mode()&")
logger.debug(f"manual mode: {result}")
return result
def is_door_closed(self) -> bool:
"""returns True if the robot doors are closed"""
result = self._eval_bool("is_door_closed()&")
logger.debug(f"door closed: {result}")
return result
def is_remote_mode(self) -> bool:
"""returns True if the robot is in remote (non-manual) mode"""
return not self.is_manual_mode()
def validate_mount_start_conditions(self) -> None:
"""validates preconditions that must hold *before* motion is enabled,
raising a TellCommunicationError if any fail. Uses the lightweight is_*
boolean checks rather than system_check() so the daq can still enable
motion afterwards.
Note: the door is NOT checked here. enable_motion() releases the door
safety, so is_door_closed() is always false before that runs - the door
check belongs after enable_motion (see validate_door_closed)."""
reasons: list[str] = []
try:
# if the robot is not in remote mode enable_motion() will not power
# it and the mount will silently hang, so guard before we get there.
if not self.is_remote_mode():
reasons.append("TELL is not in remote mode")
except Exception as e:
logger.debug("Failed to check TELL remote mode", exc_info=True)
reasons.append(f"failed to check remote mode: {e}")
if reasons:
raise TellCommunicationError(
"Mount can't start: " + "; ".join(reasons), operation="mount_precheck"
)
def validate_door_closed(self) -> None:
"""validates that the doors are closed, raising a TellCommunicationError
if they are open. Must be called *after* enable_motion() has released
the door safety, otherwise is_door_closed() always reports false."""
try:
door_closed = self.is_door_closed()
except Exception as e:
raise TellCommunicationError(
f"Mount can't start: failed to check door status: {e}", operation="mount_precheck"
) from e
if not door_closed:
raise TellCommunicationError(
"Mount can't start: TELL doors are open", operation="mount_precheck"
)
def set_samples_info(self, info: list[PuckWithTellPosition]):
"""sets the samples in the robot dewar based on the given list of PuckWithTellPosition objects
and runs set_sample_info in the background"""
j = []
for x in info:
j.append(
{
"userName": x.pgroup,
"dewarName": x.dewar_name or "",
"puckName": x.puck_name,
"puckType": "Unipuck",
"puckAddress": x.tell_position or "",
"puckBarcode": x.puck_name,
"sampleBarcode": "",
"sampleMountCount": 0,
"sampleName": "",
"samplePosition": 1,
"sampleStatus": "",
}
)
self.backend.run("data/set_samples_info", pars=[json.dumps(j)], background=True)
def start_cmd(self, cmd, *argv):
"""starts a command on the robot and returns the command id"""
cmd = cmd + "("
for a in argv:
cmd = cmd + (("'" + a + "'") if type(a) is str else str(a)) + ", "
cmd = cmd + ")"
ret = self.backend.start_eval(cmd)
self.get_state()
return ret
def check_command_ok(self, timeout: float = 360.0, msg: str = ""):
"""checks to see if the last command issued to the robot was completed and returns the result
Returns an exception if the command result doesnt return completed or removed"""
self.wait_not_busy(timeout)
result = self.get_result(self._last_cmd_id)
logger.debug(f"getting result for command {self._last_cmd_id}: {result}")
status = result["status"]
if "completed" != status and "removed" != status:
raise MountingFailed(f"{msg} {result}")
return f"{msg} {result}"
def estimate_mounting_time(self, segment) -> int:
"""Adds additional time if cooling/drying is expected based on requested segment,
current sample segment and gripper position.
:param segment: any - however valid segment ABCDEFX"""
try:
current_mounted = self.get_mounted_sample()
gripper_in_cold = self.is_in_cold()
if current_mounted is None:
unmount_needs_drying = 0
unmount_needs_cooling = 0
else:
segment_in_cold = current_mounted.puck.segment in "ABCDEF"
unmount_needs_drying = int(gripper_in_cold and not segment_in_cold)
unmount_needs_cooling = int(not gripper_in_cold and segment_in_cold)
mount_needs_cooling = int(segment in "ABCDEF" and not gripper_in_cold)
mount_needs_drying = int(segment not in "ABCDEF" and gripper_in_cold)
needs_cooling = mount_needs_cooling + unmount_needs_cooling
needs_drying = mount_needs_drying + unmount_needs_drying
return needs_cooling * 30 + needs_drying * 120
except Exception:
logger.debug("Could not estimate the mounting time", exc_info=True)
return 0
def mount(
self,
address: SampleDewarAddress,
force: bool = False,
read_dm: bool = False,
auto_unmount: bool = False,
wait: bool = False,
timeout: float = 600.0,
) -> TellEventTypeEnum | TellEventValueEnum | None:
SampleDewarAddress.model_validate(address)
segment = address.puck.segment
puck = address.puck.pos
sample = address.pin
if self.is_busy():
raise TellCommandWhileBusyException("mount received while robot is busy")
logger.info(f"loading sample {sample} from segment {segment} - {puck}")
wait_timeout = timeout + self.estimate_mounting_time(segment)
self._last_cmd_id = self.start_cmd(
"mount", segment, puck, sample, force, read_dm, auto_unmount
)
logger.info("waiting for mount to complete")
try:
if wait and segment in "ABCDEF":
logger.info("Waiting for events from TELL:")
event, value = self.backend.wait_events(
{
"state": None,
"Motion Task": None, # "dry",
"Gripper detection": None,
"Motion Sync": "Robot Clear after mount",
},
timeout=wait_timeout,
)
logger.info(f"event: {event} occurred with value: {value}")
if event is None or event == "state":
state_value = str(value).strip().strip("\"'").lower()
if state_value == "busy":
logger.warning(
"got busy response from robot, waiting for mount to complete"
)
logger.info(
f"event: {event} occurred with value: {value}, checking command completed okay"
)
msg = self.check_command_ok(
timeout=wait_timeout, msg=f"Mount {segment}{puck}-{sample}: "
)
logger.info(f"Check command okay response: {msg}")
if self.get_mounted_sample() is None:
logger.warning(
"Mount command completed but robot reports no sample mounted"
)
return TellEventValueEnum.NO_PIN_IN_GRIPPER
return TellEventValueEnum.SUCCESS
elif (
event == TellEventTypeEnum.GIPPER_DETECTION.value
and value == TellEventValueEnum.NO_PIN_IN_GRIPPER.value
):
logger.info(f"{TellEventValueEnum.NO_PIN_IN_GRIPPER.value}")
return TellEventValueEnum.NO_PIN_IN_GRIPPER
elif (
event == TellEventTypeEnum.GIPPER_DETECTION.value
and value == TellEventValueEnum.PIN_STILL_IN_GRIPPER.value
):
logger.info(f"{TellEventValueEnum.PIN_STILL_IN_GRIPPER.value}")
return TellEventValueEnum.PIN_STILL_IN_GRIPPER
elif (
event == TellEventTypeEnum.GIPPER_DETECTION.value
and value == TellEventValueEnum.PIN_IS_LOST_GRIPPER.value
):
logger.info(f"{TellEventValueEnum.PIN_IS_LOST_GRIPPER.value}")
return TellEventValueEnum.PIN_IS_LOST_GRIPPER
elif event == TellEventTypeEnum.GIPPER_DETECTION.value:
return TellEventTypeEnum.GIPPER_DETECTION
elif (
event == TellEventTypeEnum.MOTION_TASK.value
and value == TellEventValueEnum.DRY.value
):
logger.info(f"{TellEventValueEnum.DRY.value}")
return TellEventValueEnum.DRY
elif (
event == TellEventTypeEnum.MOTION_TASK.value
and value == TellEventValueEnum.COLD.value
):
logger.info(f"{TellEventValueEnum.COLD.value}")
logger.info(
"As cold, likely robot is cooling from previous mount/dry "
"DAQ will block until command is complete"
)
self.check_command_ok(
timeout=wait_timeout, msg=f"Mount {segment}{puck}-{sample}: "
)
return TellEventValueEnum.COLD
elif (
event == TellEventTypeEnum.MOTION_TASK.value
and value == TellEventValueEnum.UNKNOWN.value
):
logger.info(f"{TellEventValueEnum.UNKNOWN.value}")
return TellEventValueEnum.UNKNOWN
elif (
event == TellEventTypeEnum.MOTION_SYNC.value
and value == TellEventValueEnum.ROBOT_CLEAR_AFTER_MOUNT.value
):
logger.info(f"{TellEventValueEnum.ROBOT_CLEAR_AFTER_MOUNT.value}")
return TellEventValueEnum.ROBOT_CLEAR_AFTER_MOUNT
else:
logger.info(f"Unexpected event: {event} occurred with value: {value}")
logger.info("Checking command completed okay anyway")
self.check_command_ok(
timeout=wait_timeout, msg=f"Mount {segment}{puck}-{sample}: "
)
return TellEventValueEnum.UNKNOWN
elif wait and segment == "X":
logger.info("Loading an auxiliary puck")
self.check_command_ok(timeout=wait_timeout, msg=f"Mount {segment}{puck}-{sample}: ")
logger.info("post waiting")
return TellEventValueEnum.SUCCESS
except TellCommunicationError:
raise
except Exception as e:
logger.exception("Exception occurred")
raise TellCommunicationError(
message=f"Error during mount {segment}{puck}-{sample}: {e}", critical=True
)
def unmount(self, force=False, wait=False, timeout=360.0):
if self.is_busy():
raise TellCommandWhileBusyException("mount received while robot is busy")
self._last_cmd_id = self.start_cmd("unmount", None, None, None, force)
if wait:
try:
self.check_command_ok(timeout=timeout, msg="Unmount message: ")
except MountingFailed:
result = self.get_result(self._last_cmd_id)
logger.error(
f"Unmount failed with status '{result.get('status')}' and payload: {result}"
)
raise
return self._last_cmd_id
def dry(self, heat_time=None, speed=None, wait_cold=None, wait=False):
self.backend.wait_state("Ready", timeout=30.0)
self._last_cmd_id = self.start_cmd("dry", heat_time, speed, wait_cold)
if wait:
self.check_command_ok(timeout=360.0, msg="Dry failed")
def move_park(self, wait=False):
self._last_cmd_id = self.start_cmd("move_park")
if wait:
self.check_command_ok(timeout=360.0, msg="Move to park failed")
def move_cold(self, reset_timestamp=False, wait=False):
self._last_cmd_id = self.start_cmd("move_cold", reset_timestamp)
if wait:
self.check_command_ok(timeout=360.0, msg="Move to cold failed")
def abort_cmd(self):
self.backend.abort()
self.backend.eval("robot.stop_task()&")
def set_setting(self, key: str, value: str):
self.backend.eval(f"set_setting('{key}', '{value}')&")
def get_setting(self, key: str) -> str:
return self.backend.eval(f"get_setting('{key}')&")
def blower_on(self):
self.backend.eval("blower_on()&")
def blower_off(self):
self.backend.eval("blower_off()&")
def toggle_blower(self):
self.backend.eval("toggle_blower()")
def anneal_in(self):
self.backend.eval("anneal_in()&")
def anneal_out(self):
self.backend.eval("anneal_out()&")
def get_mounted_sample(self) -> SampleDewarAddress | None:
ret = self.get_setting("mounted_sample_position").strip()
if not ret:
return None
match = re.match(r"([A-Z])(\d)(\d{1,2})", ret)
if match:
segment, puck, sample = match.groups()
dewar_location = DewarAddress(segment=segment, pos=int(puck))
return SampleDewarAddress(puck=dewar_location, pin=int(sample))
logger.warning(f"Failed to decode mounted sample position: {ret}")
return None
def get_system_check(self):
msg = self.backend.eval("system_check()&")
logger.debug(f"SYSTEM CHECK: {msg}")
return msg
def get_robot_state(self):
msg = self.backend.eval("robot.state&")
logger.debug(f"robot state: {msg}")
return msg
def get_robot_status(self):
status = self.backend.eval("robot.take()&")
logger.debug(f"robot status: {status}")
# return eval(status)
return ast.literal_eval(status)
def get_detected_pucks(self) -> list[PuckLoadedInfo]:
j = json.loads(self.backend.eval("get_pucks_info()&"))
output = []
for i in j:
if i["puckState"] == "Present":
puck_address = i["puckAddress"]
if len(puck_address) == 2:
output.append(
PuckLoadedInfo(
puck_name=i["puckBarcode"],
location=DewarAddress(
segment=puck_address[0], pos=int(puck_address[1])
),
)
)
return output
def get_pin_offset(self):
try:
offset = float(self.backend.eval("get_pin_offset()&"))
except Exception:
logger.debug("Could not read the pin offset; assuming 0", exc_info=True)
offset = 0.0
return offset
def get_current(self):
current = self.backend.eval("smart_magnet.get_current_rb()&")
return float(current)
def set_current(self, current: float) -> float:
self.backend.eval(f"smart_magnet.set_current({current:.1f})&")
current = self.backend.eval("smart_magnet.get_current_rb()&")
return float(current)
def is_powered(self):
return self.get_robot_status()["powered"]
def check_enable_motion(self):
if not self.is_powered():
self.backend.eval("enable_motion()&")
def is_in_cold(self):
return self.is_position(POSITION_COLD)
def is_position(self, position: str) -> bool:
return position == self.get_robot_status()["pos"]
def is_ready(self):
return "ready" == self.get_state().lower()
def is_busy(self):
return "busy" == self.get_state().lower()
def check_smart_magnet_mounted(
self, timeout: float = 10.0, idle_time: float = 1.0, interval: float = 0.1
):
# Not sure why unused, potentially can remove them
_ = (timeout, idle_time, interval)
initial_state = self.backend.eval("smart_magnet.state&")
logger.debug(f"checking smart magnet_initial state: {initial_state}")
if initial_state == "Paused":
self.backend.eval("smart_magnet.set_supress(False)&")
self.backend.eval("smart_magnet.set_resting_current()&")
elif initial_state == "Fault":
logger.error(f"tell smart magnet is in unknown state {initial_state}")
raise SmartMagnetFaultException
state = self.backend.eval("smart_magnet.state&")
try:
if state == "Busy":
logger.debug("state busy")
self.backend.eval("smart_magnet.set_supress(True)&")
self.backend.eval("smart_magnet.state&")
if self.get_mounted_sample() is None:
logger.warning("Check mount: A manually mounted sample is detected.")
logger.warning("Remove before mounting with the robot.")
raise ManualMountException
return True
elif state == "Ready":
logger.debug("No sample detected, ready to mount")
if self.get_mounted_sample():
logger.error("Check mount: No sample detected, but robot thinks is mounted")
raise SmartMagnetFaultException
return False
elif state == "Paused":
logger.debug("Smart magnet detection is paused")
return None
else:
self.backend.eval("smart_magnet.set_supress(True)&")
logger.error(f"Tell smart magnet is in unknown state {state}")
raise SmartMagnetFaultException
except Exception as e:
logger.error(f"check_smart_magnet_mounted failed: {e}")
raise
def make_tell_client(bl: MXBeamline) -> TellClient:
if bl == MXBeamline.SIMULATED:
backend = SimTellBackend()
else:
backend = LazyTellBackend(factory=lambda: PShellTellBackend(bl), retry_interval_s=2.0)
return TellClient(bl, backend=backend)
if __name__ == "__main__":
from datetime import datetime
from aarecommon.config.beamline import mx_beamline
bl = mx_beamline()
tell_client = make_tell_client(bl)
# tell_client.toggle_blower()
# tell_client.check_enable_motion()
print("status ", tell_client.get_robot_status())
print("dry mount count: ", tell_client.get_setting("dry_mount_counter"))
ts = float(tell_client.get_setting("dry_timestamp"))
print("dry timestape: ", ts)
past = datetime.fromtimestamp(ts, tz=UTC)
now = datetime.now(UTC)
seconds_ago = int((now - past).total_seconds())
print(seconds_ago)
print("door closer :", tell_client.backend.eval("is_door_closed()&"))
print("manual mode: ", tell_client.backend.eval("is_manual_mode()&"))
print("position :", tell_client.get_robot_status()["pos"])
state = tell_client.get_robot_state()
manual_mode = tell_client.is_manual_mode()
print("state: ", state)
print("is manual mode True: ", manual_mode)
print(tell_client.backend.eval("is_manual_mode()&"))
print(tell_client.is_door_closed())
# print("release safety: ", tell_client.backend.eval('release_safety()&'))
# time.sleep(5)
# tell_client.blower_off()
-47
View File
@@ -1,47 +0,0 @@
import time
from epics import poll
def wait_position(motor, target, tolerance=None, timeout=60.0):
position = motor.readback
if isinstance(position, float) and tolerance is None:
tst = "%f == %s"
ltst = lambda x, y, z: x == y
elif isinstance(position, float) and tolerance is not None:
tst = "abs(%f - %f) < %f"
ltst = lambda x, y, z: abs(x - y) < z
elif isinstance(position, (bytes, str)):
tst = "'%s' == '%s'"
if isinstance(position, bytes):
def ltst(x, y, z):
return (
x.lower() == y.lower().encode()
if isinstance(y, str)
else x.lower() == y.lower()
)
else:
def ltst(x, y, z):
return x.lower() == y.lower()
else:
raise RuntimeError("BUG: could not understand arguments: ")
timeout = time.time() + timeout
timeisup = False
n = 20
condition = ltst(motor.readback, target, tolerance)
while not timeisup and not condition:
poll(0.1)
n = n + 1
if n > 20:
n = 0
print(f"waiting_position test: {tst} ({motor.readback!s}, {target!s}, {tolerance!s})")
timeisup = timeout < time.time()
condition = ltst(motor.readback, target, tolerance)
if timeisup:
msg = f"Timeout when waiting for {motor} to reach {target!s} with tolerance {tolerance!s}. Device was at: {motor.readback!s}"
print(msg)
raise RuntimeError(msg)
-185
View File
@@ -1,185 +0,0 @@
"""
ZMQ-based camera image source.
Provides on-demand image retrieval via ZMQ REQ/REP pattern,
with fallback to area_detector if ZMQ is unavailable.
"""
import json
import cv2
import numpy as np
import zmq
from aarecommon.config.logger import setup_logger
from aarecommon.models.beamline import MXBeamline
logger = setup_logger("aareDAQ")
class ZMQCameraClient:
"""
ZMQ camera client that requests the latest image from a ZMQ stream.
Uses a SUB socket with a short timeout to grab the most recent frame,
rather than maintaining a continuous subscription. This is suitable
for on-demand image retrieval in the DAQ server.
"""
def __init__(self, beamline: MXBeamline, timeout_ms: int = 2000):
"""
Initialize the ZMQ camera client.
Args:
zmq_url: ZMQ endpoint URL (e.g., "tcp://x10sa-spark-01:9091")
timeout_ms: Receive timeout in milliseconds
"""
if beamline == MXBeamline.X06DA:
self._simulated = False
self._zmq_url = "tcp://x06da-pserv-01:9089"
elif beamline == MXBeamline.X10SA:
self._simulated = False
self._zmq_url = "tcp://x10sa-spark-01:9091"
elif beamline == MXBeamline.SIMULATED:
self._simulated = True
self._zmq_url = None
else:
raise ValueError("unknown beamline")
self._timeout_ms = timeout_ms
self._context: zmq.Context | None = None
self._socket: zmq.Socket | None = None
self._last_image: np.ndarray | None = None
self._last_fetch_time: float = 0.0
self._connected = False
def _ensure_connected(self) -> bool:
"""Ensure the ZMQ socket is connected. Returns True if successful."""
if self._connected and self._socket is not None:
return True
if self._simulated or self._zmq_url is None:
return False
try:
if self._context is None:
self._context = zmq.Context()
if self._socket is not None:
self._socket.close()
self._socket = self._context.socket(zmq.SUB)
self._socket.setsockopt(zmq.SUBSCRIBE, b"")
self._socket.setsockopt(zmq.RCVTIMEO, self._timeout_ms)
# Discard old messages, keep only the latest
self._socket.setsockopt(zmq.CONFLATE, 1)
self._socket.connect(self._zmq_url)
self._connected = True
logger.debug(f"ZMQ camera connected to {self._zmq_url}")
return True
except Exception as e:
logger.warning(f"Failed to connect ZMQ camera to {self._zmq_url}: {e}", exc_info=True)
self._connected = False
return False
def get_image(self, gray: bool = False) -> np.ndarray | None:
"""
Fetch the latest image from the ZMQ stream.
Args:
gray: If True, return grayscale image; otherwise return RGB.
Returns:
numpy array with the image, or None if unavailable.
"""
if self._simulated:
return None
if not self._ensure_connected():
return None
try:
r = self._socket.recv_multipart()
if len(r) < 2:
logger.debug("ZMQ camera: incomplete message received")
return self._last_image
data = r[-1]
header = None
for part in r[:-1]:
try:
decoded = json.loads(part.decode("utf-8"))
if isinstance(decoded, dict) and "shape" in decoded:
header = decoded
break
except Exception:
logger.debug("Skipping an unparsable ZMQ message part", exc_info=True)
continue
if header and header.get("type") == "uint8":
h, w = header["shape"][:2]
raw = np.frombuffer(data, np.uint8).reshape((h, w))
# Convert from Bayer to RGB
rgb = cv2.cvtColor(raw, cv2.COLOR_BAYER_GB2RGB)
if gray:
gray_img = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
self._last_image = gray_img
return gray_img
else:
self._last_image = rgb
return rgb
else:
logger.debug("ZMQ camera: unexpected image format")
return self._last_image
except zmq.Again:
logger.debug("ZMQ camera: timeout waiting for frame")
return self._last_image
except Exception as e:
logger.warning(f"ZMQ camera error: {e}", exc_info=True)
self._connected = False
return self._last_image
def is_available(self) -> bool:
"""Check if ZMQ camera is available and responding."""
if self._simulated:
return False
if not self._ensure_connected():
return False
try:
old_timeout = self._socket.getsockopt(zmq.RCVTIMEO)
self._socket.setsockopt(zmq.RCVTIMEO, 500)
try:
self._socket.recv_multipart()
self._socket.setsockopt(zmq.RCVTIMEO, old_timeout)
return True
except zmq.Again:
self._socket.setsockopt(zmq.RCVTIMEO, old_timeout)
return False
except Exception:
logger.debug("Camera ZMQ socket is not available", exc_info=True)
return False
def close(self):
"""Close the ZMQ connection."""
if self._socket:
try:
self._socket.close()
except Exception:
logger.debug("Error closing the camera ZMQ socket", exc_info=True)
self._socket = None
if self._context:
try:
self._context.term()
except Exception:
logger.debug("Error terminating the camera ZMQ context", exc_info=True)
self._context = None
self._connected = False
@property
def url(self) -> str:
return self._zmq_url if self._zmq_url else "simulated"
View File
Whitespace-only changes.
-36
View File
@@ -1,36 +0,0 @@
from __future__ import annotations
import importlib
import sys
from typing import TYPE_CHECKING
from aarecommon.config.logger import setup_logger
from aare.gui.constants import LOGGER_NAME
logger = setup_logger(LOGGER_NAME)
if TYPE_CHECKING:
from aare.gui.threads.daq_worker import DAQWorker
def about_text(client: DAQWorker):
from aare.gui import gui
try:
version = importlib.metadata.version("aaredaq")
except Exception:
logger.debug("Could not resolve the installed package version", exc_info=True)
version = "Not found - package is not installed into the environment."
server_version, server_file_path = client.server_about_info()
return f"""Aare Macromolecular Crystallography GUI
Copyright: Paul Scherrer Institute 2023-2026
---
Version: {version}
GUI file: {gui.__file__}
Interpreter: {sys.executable}
Server version: {server_version}
Server file: {server_file_path}
"""
-79
View File
@@ -1,79 +0,0 @@
import json
import subprocess
import jwt
from aarecommon.config.logger import setup_logger
from aarecommon.models.auth import get_user
from aarecommon.models.models import TokenData
from aare.gui.constants import LOGGER_NAME
logger = setup_logger(LOGGER_NAME)
def auth(base_url: str | None, cert_path: str | None) -> str:
curr_user = get_user()
if base_url is None:
token_data = TokenData(sub=curr_user, staff=True, session=15, pgroups=["p16371", "p22233"])
return jwt.encode(token_data.model_dump(), "ABC123")
# Single call: Kerberos SPNEGO through Apache, which proxies to the DAQ server.
# Apache injects X-Remote-User; the DAQ server reads it from the localhost-proxied request.
url = f"{base_url}/token"
cacert = f"{cert_path}"
try:
token_result = subprocess.run(
["curl", "-s", "--cacert", cacert, "--negotiate", "-u", ":", url, "-XPOST"],
capture_output=True,
text=True,
timeout=120.0,
check=False,
)
except subprocess.TimeoutExpired as e:
logger.error(f"Token request curl timed out: {e}")
raise RuntimeError(
"Cannot reach AareDAQ server (timeout). "
"Please check the server is running and your connection."
) from e
except FileNotFoundError as e:
logger.error(f"curl not found: {e}")
raise RuntimeError("curl not found on this system.") from e
except OSError as e:
logger.error(f"Token request curl OS error: {e}")
raise RuntimeError(
"Cannot reach AareDAQ server (OS error). "
"Please check the server is running and your connection."
) from e
except Exception as e:
logger.error(f"Token request curl error: {e}")
raise RuntimeError("Cannot reach AareDAQ server (unknown error). ") from e
if token_result.returncode != 0:
logger.error(
f"Token curl exited {token_result.returncode}. stderr: {token_result.stderr[:500]}"
)
raise RuntimeError(
f"Token request failed (curl exit {token_result.returncode}). "
"Check Kerberos ticket is valid (kinit) and server is reachable."
)
try:
response_json = json.loads(token_result.stdout)
except json.JSONDecodeError as e:
logger.error(f"Token response not JSON. stdout: {token_result.stdout[:500]}")
raise RuntimeError(
"Authentication failed (invalid server response). "
"The server may be starting up or misconfigured."
) from e
token = response_json.get("access_token")
if not token or not isinstance(token, str):
logger.error(
f"Missing access_token. Keys: {list(response_json.keys())}. Server response {response_json}"
)
raise RuntimeError(
"Authentication failed (missing token in server response). "
"The server may be starting up."
)
return token
-10
View File
@@ -1,10 +0,0 @@
import getpass
import socket
def _try_clean_hostname(raw_name: str) -> str:
return raw_name.removesuffix(".psi.ch")
CLEAN_HOSTNAME = _try_clean_hostname(socket.gethostname())
LOGGER_NAME = f"AareGUI: {CLEAN_HOSTNAME} - {getpass.getuser()}"
View File
Whitespace-only changes.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

-25
View File
@@ -1,25 +0,0 @@
<svg version="1.2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 468 274" width="468" height="274">
<defs>
<image width="132" height="134" id="img1" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIQAAACGCAYAAAAcjCKsAAAAAXNSR0IB2cksfwAAWS9JREFUeJyVvWd0Fce2Ltqcc895d4x93xj3vbv19t7H2zbGgEW0TZaEkAjGxgFnbCNHQIAINjmzlEgmB4HIIMAgENEEY8AGGxtMNEHkIDIskTNihXpzVnV1zaquxb73R2m1evXqVF/N+c1Qs5xIJOzIFo5EHPo/b2HYH47AdyG+LfZFfMdo2+7/4TD9PiL+D9PzWn7vu34o9neW+w3La/HrRZwQtNv3Hzrnr990jgavOcWXSp095y4520+fd349ca7cL8fPinbinPPboZPOjuLjzr7jJc5B+P7kxStO8MYt51FZGbn/iPdO6LPyewmrZ9XfSUR7bus7Nt+f8a7wM0rOFbY+t3ENODbK31GEvG/1zqLm+4PvY3SC0elh42a1YyPey/E9lHfBkHbjEhjhcCjmw4tOVd+pFxAxGgEAbJ+/fsv56WhJufl/HCg38sdt5QZ9v6Vcz2Uby7VftO7fv1iw5n+kzV9dpdWcVV3emrl8+RvTlxW/NrWItzdnr1qY3Gf0h836jvr/Wgwa999eHzyh3DtZk8p9NnxquS7j5pTrOXnhf4z4bnXckk3b4rYfOhF368FD71nki45GIv6XrL3DiL/TLe817HX+kwaKalF5HyY4LO80avSBDtyQ4/3AQ5/5AB661cPwG/ZJBdU5HgItNxSJRshvI94LUDcYcXwvzuh4/Hzs3set+w+cwj2HnR7LNpV/NW9heqPx84ubTVlc3GLa0uJm+UXFKZMK3bb4fGreYtZ0SiFrMlm0ppOXwP9FvKWOKWCV0wexFzKysF2v3DGruGL7zOKK6YOKK7ULFL/QIfNYjS45wZpdcoPV0wcFa7QZUPBqn1FpQwpWxu05cSZOdEKIvGyL9DLAQjsu7A4a/V0Y78AbSJb9dPD5BnTI+4yS63ug876POPaL0H10hHvikqgPbz/pRE18GjdtdHKYqgTtXsgLcL9/9Pixc+nWHefIlWvO1K27//rhzOWvvThi1sKEcQu2AggYNt7RU7BB58tOd/c1cbfFMYv5/01cUFT7ejir0omDgQEYWHzHTBcc2fx/b1+HALRMVqkDfNcphwFogn//uHuw0hd9CtJHzUpbsXV33JEzl5zSm7edMrhfK7C1d0XAYaihsNvEgI14/RGl54T350nSSMh472SQmecmIKAqWD+Q6B6fOLOJGJtK8Yk02/nt51EcQ4he/kJAopTevef8CPp90uZdcW0XrUtuMH5e+6QJC1jz/CUMpIDofOjUJvmi0e1U3hbzYxpPWeweu9j7De5LGD6Ddzx2dGXe6ZneNgJBbGe5/6tjvO0MAZ5KAJZnPu8TrNF+cEG7MbPSJixd72zee8i5A+pFG/2mKvSeO+R2asj3fsPWvgjFkCb0GvqAC1uPUfu8jaj8sdshYRcYMcmKsd+qv2zgsYKJcAJPSkSc4J17Tt6W3f/zi3nft3lz+rKiRhMXBZt4o73Q69RUDQiL+XZjFwDYUt3/m5J93vakRax6zxGuRMgmHZ+ldTq2eG87oAEkHv5X3wlJUrH9YFa5/eC9yT1HjPgka1LK9FU/xd24cxdILu0UStRJB1LJYQOEBRzhGNtP5Cza/yEXECYSbeih3MHyXdjyAFR3RX0goDxBiU+UCo9DYecaSIScdb+2rDlsVl7KpIUXmqEK8ES9FP2iCTAsdUEgJYMCRRNPgqiG+5vlCzA1GDqNVUwPcFUQ39EEgF86oBTgqqSDDhIpVeKJ9PBUCxz/XJtBwf/6uGfBqO9Wp925d88JhcTolu8mbLx7rR8kN7FIVKlqwmFzH+kPc0BbBqz8vXUUR4net7FRGyg8rhBxTTKyj6qCcISAgWwjP9h37rIzcfOuVo0nLSxIyXM7E4Fg6VTZ8U25BFAd3cSTBkVea+x9p45pOhV+P3ERjGJdNUiOIMAQ8KuHDpkuz7BJDtqyfCoIJdBzbQawlzsECkYsXNNg95FTzoNHD3V+Ybxbae7rJrvBCTT1E9KsPRNEURMsZPDiNfx63AaEJ/EGy0M8kXuEqXqIcBF64ELQGbH+t1bvzVw+M2niAq9zUwkQZKeL0U//L+I8Qv9egmGxB47GUxTX4GombxEQySHaSJcAeFJH26SADQCSiFKeEU++ex6AkdJrRGDg9MUNdh89DZIx5GjWFelQZXmY/gwJlohulmtq51/4QAwpoutuOno1EUZv1jRzYkiYsLSNTYKkpEMoHAWiuDPtjSmLC5pABwmroJBIAV3My07WJYbqfPN3TTzJofhFKgfQUvbygHGempASQXAD2vkBT2Jgh8oOpvupyqhMzhWvAcrkJVmeOooHCVWvU3bBiHmr0qg0jcqBaRtomokaciWybsEp34g5aI3+DSsnWzTsqgzvC6q7LOpC/R9SoseiMvzok2ap+P5eWZmz/fSFuKagGhLBWmjmWQmLyUimYCjkPCE1X4l+qQqoBJGgEaYkVSVFhEwCbxg20+2kgCYdUN9zne9JioDX0ZU6BHwdq0AQ8EmMeAke14w1CSpeR4ICj0GJ8VK7QMGmPcVxd+49cDxi7wGCdDjnH6En8r2Y5FGT8IZH1eMQBImmqrCaKbEuFvMGlIo4UXrD+XbD9tpNJy0KotloI3x0W+n/Iq9jkVjS7/ySQakHSizxM2X8AlalSy7hDgY/IM1qYnawA0D9JsvX8SaA9GME6URwVAOOUa3doGDfaYv/hq5z5cmNWDr+CeEDytv+JVB0q0YnMCYSTcJCRn3YQ3BE3bSnZkzfg+AKy/484rSeu7I/mnpNqQPJa4UeR1DqgPIJt4NBAiiTkqoGE1RKVchrVO2swEA7WnSclASudRCjsym3kATzyUDK0s5Hf2uaq3w7ffC15r1Hfjlj1Sbl3PJ5b80ODnnbmkfU4vjTQEV4SThMJETsi8EJwRRkoZAOjLDFY2lhtnhzdx4+cob+8Ftc8sTvfmlmWAamdGjsgiRFkwKFrlQoct3OSyz8wrRC1H48HnlD1a5DtM4TYlsSviyfCakTySxfJ+vAyfIBxE8ss4gpq1/DNHG5o6vdoIXfjJ8bd+PWbe6gC3t8zrQQqLmppErYlRT+IGJEAw6VJrHFvg2BYePikSdbJXjT6GbuuWxTs4bjFwTNUWuKfH270Ps/Nd+uIkwQKY+lbp6mgnlZs88o4UPQyF+mt4+qAepD0PwJPikQ8MBhqgTdQlHgkYRSgkWzUghxld9V/Kp/8KPMie/uPV4C7/ixPvgMV7XkFb6goYUfmgIgTAFhi37ZXaVGcMYmVYiKWH/4pNNqzsqRjSYt9FSCqR5MvuC3Fgo9kqhxCq42TKAUeeqEn2NqEWs4poB7IkEMux0b8KkDO48IsFjSItb/FdMHsfKf9mbPftaHO7viO+r8IZ6Aw65eTL7hAqndQJbwde60RT9u/cu9Bw+JararArTsNEJqG+w+68PlEBqiqFkTKzQdVs4SKwoBDA9A7xXuKo57Y3rRQRTxzYiZKMR9kU9lUN+CxgE4GAp9oPGDRMUw+O+mLuNeSKG/A5o4jyeivBLpeCkRKnfUxb65X/8NSpbBrHLbgaztyJls7Y59vLUZMY290G4Qq5yhYh26L0KpIbrtgSgjS1NT2F7smFkybvGaOARFmFghWoTUBYMeSQ3bJQfpb8n9dLFjqAalIui+iA6KCFUfUQ6G+TsPxoE5GeR8YSoCQEmG1HxlIqoOFm5pGneQhJFu23+rf3IPJoClbmYexhJiEkQ1anWiaB4br41mEzzi2Aowgscs+YGBVASqFYLPEHsMbWThau5noGCkvgjKYxTgKEh0QovnwODZtwu/j7t7/4EXb4pSdWHlGMr1HQ5TN7jfC6qrAk2c0EhaKLb+IUTl2p27zuTNO+LqjJ0fRHHdjFgGJhjkKJccwG8h2Dq80FUXhRpvEDEOIR0ajZvHXuo91lMR+sg3RHV7v8qIRSTjCRA0TgGd9EbfkQxGLIu4DV42///uw0esyddDeFi9siYB7KrKBAUFkUc8OSj6BXtNWRhXcumKTuaNwRymYKCDm0iUsCFFyAmfHPKOme7mfn/z9h3n26U//mej8QuOy5HaLF9n+9R/oAOChq/F/ym+73X1oKsc4X1MGDYdLIlcQhTpS1fmJFUHNhFOweCBKEMniXge5AnPfdabLdy4lYMggi0cdoEhPgdNLyTAy9JMTf3+dOmgWSwZutTgn+mDgu1Hz4rDND9l2YmBHY3oINAcjVLNWAyESDhsZkyp8LemW4iNK1uInLysLOSMXrTWScjNz6NOICkdUqR/wdP7hVoii5ISCjCeJOFJLFIyEP+Dm9jCI5fTlrN6WXnui5d8QUUa1Ygzk1300Sc7zPQZ6NsBVgXO84/P+7Em3Yay3w8eY2WPH7NINEKAAC0qpMTF0ussBUBaETgG5SN+XmLLtyAkk0gLVEMcoOmDgx9nT4y7//ChZ+3ZOZ/dwWjbZ7dPqbVhkw7E2rj36KGT//1G54VO2S05sZssnUv+ULQMVtEOl51sSgMJGKUaqKdS8YwUsGBe7DWap7/FE0lAJYTU96YOp+SRupKplIjvKD+zOCep23UIe2fAOLbil53sEQAhTKQBb1FdQoQBKNdu3WaBmUWsTudc9nx6wDunaXbq5moW8Y0Id7pydWd653i+3cBg2tCpcVeu3XB8uRSE85nuAxoup9/b1UDEbssqnSMY7sOyMid/5UYHxOZfkkfNKVDSwZ6HYOMGflNSbpteTN36wPMnjZrNqn09lJlBKXs4mqoBPZ9BBaL8JiH+5rkvB7DkbsNYv2mL2frt+9mDR484EOBlspt377LVv+5iOw4eVyBwySWXHC44Hjx6yFZv3cPShkxhFb7s58VN6L1R60dvWYba0H0Zz7cZEOw6bm7cxavXVdqdO8Line truncated
</defs>
<style>
tspan { white-space:pre }
.t0 { font-size: 84px;fill: #fcfcfc;font-weight: 400;font-family: "Asap-Regular", "Asap" }
.t1 { font-size: 20px;fill: #ffffff;font-weight: 400;font-family: "Asap-Regular", "Asap" }
</style>
<use id="Layer 1" href="#img1" x="58" y="57"/>
<text id="AARE " transform="translate(203,106)">
<tspan x="0" y="0" class="t0">A</tspan><tspan y="0" class="t0">A</tspan><tspan y="0" class="t0">R</tspan><tspan y="0" class="t0">E</tspan><tspan y="0" class="t0">
</tspan>
</text>
<text id="Advanced softwARE for macromolec" transform="translate(203.9,130.1)">
<tspan x="0" y="0" class="t1">A</tspan><tspan y="0" class="t1">d</tspan><tspan y="0" class="t1">v</tspan><tspan y="0" class="t1">a</tspan><tspan y="0" class="t1">n</tspan><tspan y="0" class="t1">c</tspan><tspan y="0" class="t1">e</tspan><tspan y="0" class="t1">d</tspan><tspan y="0" class="t1"> </tspan><tspan y="0" class="t1">s</tspan><tspan y="0" class="t1">o</tspan><tspan y="0" class="t1">f</tspan><tspan y="0" class="t1">t</tspan><tspan y="0" class="t1">w</tspan><tspan y="0" class="t1">A</tspan><tspan y="0" class="t1">R</tspan><tspan y="0" class="t1">E</tspan><tspan y="0" class="t1"> </tspan><tspan y="0" class="t1">f</tspan><tspan y="0" class="t1">o</tspan><tspan y="0" class="t1">r</tspan><tspan y="0" class="t1">
</tspan>
<tspan x="0" y="24" class="t1">m</tspan><tspan y="24" class="t1">a</tspan><tspan y="24" class="t1">c</tspan><tspan y="24" class="t1">r</tspan><tspan y="24" class="t1">o</tspan><tspan y="24" class="t1">m</tspan><tspan y="24" class="t1">o</tspan><tspan y="24" class="t1">l</tspan><tspan y="24" class="t1">e</tspan><tspan y="24" class="t1">c</tspan><tspan y="24" class="t1">u</tspan><tspan y="24" class="t1">l</tspan><tspan y="24" class="t1">a</tspan><tspan y="24" class="t1">r</tspan><tspan y="24" class="t1">
</tspan>
<tspan x="0" y="48" class="t1">c</tspan><tspan y="48" class="t1">r</tspan><tspan y="48" class="t1">y</tspan><tspan y="48" class="t1">s</tspan><tspan y="48" class="t1">t</tspan><tspan y="48" class="t1">a</tspan><tspan y="48" class="t1">l</tspan><tspan y="48" class="t1">l</tspan><tspan y="48" class="t1">o</tspan><tspan y="48" class="t1">g</tspan><tspan y="48" class="t1">r</tspan><tspan y="48" class="t1">a</tspan><tspan y="48" class="t1">p</tspan><tspan y="48" class="t1">h</tspan><tspan y="48" class="t1">y</tspan><tspan y="48" class="t1"> </tspan><tspan y="48" class="t1">a</tspan><tspan y="48" class="t1">t</tspan><tspan y="48" class="t1">
</tspan>
<tspan x="0" y="72" class="t1">S</tspan><tspan y="72" class="t1">w</tspan><tspan y="72" class="t1">i</tspan><tspan y="72" class="t1">s</tspan><tspan y="72" class="t1">s</tspan><tspan y="72" class="t1"> </tspan><tspan y="72" class="t1">L</tspan><tspan y="72" class="t1">i</tspan><tspan y="72" class="t1">g</tspan><tspan y="72" class="t1">h</tspan><tspan y="72" class="t1">t</tspan><tspan y="72" class="t1"> </tspan><tspan y="72" class="t1">S</tspan><tspan y="72" class="t1">o</tspan><tspan y="72" class="t1">u</tspan><tspan y="72" class="t1">r</tspan><tspan y="72" class="t1">c</tspan><tspan y="72" class="t1">e</tspan><tspan y="72" class="t1"> </tspan><tspan y="72" class="t1">2</tspan><tspan y="72" class="t1">.</tspan><tspan y="72" class="t1">0</tspan><tspan y="72" class="t1">
</tspan>
</text>
</svg>

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

-1
View File
@@ -1 +0,0 @@
<svg version="1.2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" width="800" height="800"><defs><image width="689" height="692" id="img1" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAArEAAAK0CAMAAAAjyZWsAAAAAXNSR0IB2cksfwAAAfhQTFRFAAAAJmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/Jmh/ykfTawAAAKh0Uk5TAAABAgMEBQcKDQ8QERIVGiEoLzQ2ODk7QEpWYmx1eDw6en6Dj5yqtb3BfDUUCwjEydHZ4eft8D0zKTDz9vn8/42AcWRuz7ggGAwWH+pURysJHi4/UpqJZVMGIk5nmL/MrIJPJR3TWkMxIxtfdpOx3p9ZS5Kj1hwnUNzkEyY+qG9XunMZXLNMjA5eLIauQhctSIhpRmGhJDLHlmvrov3p/vry9KUqRPdtkHY/kAAAR85JREFUeJztnQmcVNWV8N+r6qruapZGEAFZ1Y5sjdCAQENDg4JBRcAVdBARk8kYx2Qyk8/JRKPErMOXxM+YZSZuuIyK+4JoAGWVTZS9AYcYVtmUReiuXqre++q+96reUm9/9771/H+/SHd1dVV11z+3zz3n3PNoCrAGrf9V/sssq7hBQLxdhvqtgBr6v39ARO03JdeRFsh5yVG4JX8HtvAF/jP5g4G2pgBjjVH+jngFaYWOdJGxLC2/D1swlpXaKzcXvDUAjFVB45eCzBMlpIuUVRhbSrPN6musRFiWyf9X7RlB32LAWClav42CjDG6iMKd4so1tqxJIyrIih8zFxzJ/bfn55fQuyUBgxSwVg4YW0D6q5CIyEsX51ztdjyvrMTPAkmTcWyL5OMM999eNL0rZ29WGuZKogWQVgIYKyD8IiR/7oWbuY/77xVULSl8ManQMUei8DkSr1V6g4BwOyXai/7TneaNrdxVCHMpIVhghO8j+rMHCjCWg/81xGI5L2MxubK8sZ8l+A8knhbpaBHeXvTfTse77EOfXLqrsMiif0bQH9V+yDAgrYzIGytunGLx2AR6bf8zX8oWT+Gvf6xUuNGpp8WglZaLZpsZMcxFtw6l19c0xZczWUZia+TFjbKxssA1fu0HE3Muruu/p518h5/kA1j8psrgFlzOWz7MRTcMzhlLt7LsslYU4UrvTO51+J/IGivfWt20g71s6xD6cI8N9MitigCVsKtSxDCX+3DQhlHZktbkO1MPr7oq9SoKcAu7Mndejx+JqrH5IDXGJwJuea1i1PEDtRtqP8196qKieuQ2XucdGbpm5Jrmq9EL2reaQVEDI4QIkXXWB++MB3A/NdpnxS4+yCUCruyQc+JMh7WlMX/9QlimefTp9Ve/03wz/QJ7fsWuEfSai6pe4aWNqLP+eoNcQcgLxPuy31jRlz3AJQKm09vYk/HSmMcvTQ2mmZmwpC62iC0923fXUHpd5dg/TXw3G93wIGLG5n/cWKxfz0EL7nyuL8se5hIBk5fGfOkrIrfQTnof7cQ25DZjF7wx46+DL9opOhs1a6NkbP5nRYFr8nv0saVT/trn2AVfkU8EOIfbkvGbsVtW1e35YNI2uupVJpIbMV+/T1gRftJc7HrNknGDX7rzmZJZb8a6HU/63FUZaDN2yekKtnP9+jPfXvz5JZ8VNmLRkTY475YzCkWtK9bc9wXL9vxL3bHem0vjAfzxmeZsx/FHWbZ7eim9a5S4EYuKtAF8y6wjpLJQUStbtm7UJa+UXlfPXr4yiL4ikLP0ZW/2pOny3EZs4EJJgSEC0gb0TTNPIXjli1oJdt3dx5iVVy3370bLBEwzM+l9pss+tvqCN+55ZOrh8S/sikxQG2pjJc3W8VglKmolMvH1I7dPXuq3vKtlhGaE3Ebshear6e19To+LirQBf+N0KPxk/F5r+PNCUavbqViA9lq68BsxVGCo/vjinLTrF0egPTEk710RYmagX3dur8UmfVnUcgxfYDjSdmlO2sEXzhfbE8PqbMjePwFJZmDM+rr8XsunRS2noAJDKyftzX9TtCeG0drQGVvYaeUzA5vGhmGvpY8gbazLn/n2xCtDXMYNl7HiVkvMDDw1Jhx7LQO4Ui7fnshuGbyNrnolpCFtmN7GwlGtmNDuymcG6BDttXQptCf2umD9mVufC2lIG6J3UtJCeM3jFeHLDJiCa0+sYNme/y8rCWnDpGx43k30k8RK0FGtvpNSh/3Z7uoKfEmsEx/SLr24PmTOhuUdRT8HXfLwgT4b6HV92YPTfdvu6gaoJPYFH9K+P3zN1Je52CAszobCWCGZNbBHgk0d77Ghz7GYn9td3aAQ0v7D3r/vHL0sG6KTNiEwNn+mID55892xs6/kYtdgtRCSggtpB7VuGXH83cp3w+Ns8N9YfsMV79vzVOfq+lT3ZZGMXTVgmmtWTHp92htXr96b24OhW4KvbODfXWHD9YtjKwa3flSzswx8lcIyHfpv7bJiyPZZHe9nsvzoDq9fk0MC/v7mN1zfYNJ/qas8t6IsysGrKmy27uPxR9mWvrEjf5gWhj1YkI2VbrjKK4Lco00ULts14ExjzarqtSHYgwX3LZZtuB6PTwlz34BDUH/Xouw9b18Thj1YUI0tDB2ADZcZWKZ54mL5Hiyozgb0bebi11j8p0nYcJlEsgdreSjItdtAvtG8rwM+n0R37gkbLrMU9mAfFWq3QZQ2eMYK8cAtb9dumjzy0UAfinUbYQ9WveH94WsymYDGBkF7r/Px65VrB15U+T+1m0PdqI0f7oxNNardDnl6+suBdDZYxuZ9jV2x7oGNQxLbI9qd5YR87bZ22fBEIOPZQL3f4n7rpRveumHp+HWwvNqBq91+NYx9qC6IvYgBMla+3zo2eNdpWF/tgfIG79zbWLohiL2IgXnP+YYX2G/hgc02M9lqWS9iUJwNxrsuDM6KT4T9Fi5UehGD4WwgjOVeJB2/du+1F8B+Cx+FXsSOwgDlQCgbhHeeayiMxSvHvnc97LdwItTBxnww6Z2L6rmL5Xr9ikwQAGNptL7Gkzd/MGjLeNhv4YWvg3XetmLk8kwmGMus7999vmM7+Z//eUMr3XUF7Ldwww1QPtm2tGTFoZ0oa+B7Zf3+/nPCXtc0bfHWkdt6Rfh4LEFyzlYN2tj53YmHlwUhmvW3sVwKNl4y+Ys+Pbb37rwMfCVDbgu2pOrUtGOPtmT8v8z62lghIvj+tnOX9TsA8QA5WKZpYO/nB17zo167fb/M+tkC9NpK+t1y/uKdJb1Lz8D6ShKmafzWz0dVp+5r9fsy62NjUY5gxtuz35i4/uLB0AFLGjbb9O29r42s8/0y61dj+aJsSenE2Cc3Vj5eBhEBcVimQ7dVWXGZ9auz/jSBf1XxktLEjB4Lxh2BFKwrFJbZ0X5OGvhSBaHr5a2xIzp/vKkcFli3EJbZNh3erVzk2y5EP8rApwh++qt5Bzt0erwEDh26CLfMvj77T9VCF6IPlfWfDfkxL0cn/PpfHoccgctwrQY3Luz23g9e9ukOzG/G8gEBN+Zl0/XHu0COwHVQq0H/bltWPujTHZjPjOUXWH7MSyoeC+SljgMP14Xo2x2Yv4xAryY+Ze/hsTDmxUukOzDfNSH6yglUMygpGbt5Oox58ZjCDmw114ToJ2X9ZAWNUgTfuGTksu4w5sVrhB3YxA1/+18UzfpIWf8Yy+W0Bl54cPYnXXdBG6z3cDuwo8Oe7fmFv/pmfSMG3wh74Wvjk5uugnMxvgA1IQ5vWXHjF+/4SVm/GMv1aU2MlW1ItYGagV9gmaZMQ3pkE7MsQ/lGWZ+4wfVpvTPjxPBOG7+CmoF/YCo6jfhqU+eF1y30zf7LH8bSfJ9WciM0wvoMpqJ5f2ZEy7Jm37TN+sHY/J5rfI8FUyFH4DOYpvFvzzm0sHWCX4JZ743lXkG8ZO5rk2jo0/IhbLapcfjlJz79MOOPApjnggh12XFtYc/lU9D+69uvtb3MJ+cWvTYkX5d96GvYc/kWLpgdeM2XL+/2Qc7AY2MldVnYc/kX/tzisuufnep9zsBTY/nWbajL+h/+QM0wxgc5Ay+N5ctcy3tAXdb/cO1cvsgZeKgJX+Yqq+r8MdRlA4CQM9jR5HEBzDtj82WuczfCWa5AIOQMvC6AeWYKlLmCh6wA5pWyXhlLQ5krgPAFsBV8A6JHynpjLF+XvfnJWihzBQsumGXX3PWKd8p6Yku+F/b+x6DMFTC4BsR7f/HP3inrhS6FXtibTkGZK3AwFZ3OG/AT75T1wFjohcXDLPos1Y593vXn9VhZ942FJAEW0rffy/372Line truncated

Before

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 261 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 270 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 148 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 137 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 151 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 143 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 103 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 103 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 180 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 176 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 174 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 192 B

-220
View File
@@ -1,220 +0,0 @@
import os
import sys
from aarecommon.config.beamline import cfg_get, mx_beamline
from aarecommon.config.logger import setup_logger
from aarecommon.models.beamline import MXBeamline
from PySide6 import QtGui
from PySide6.QtCore import QCommandLineOption, QCommandLineParser
from PySide6.QtWidgets import QApplication, QMessageBox
from aare.gui.auth import auth
from aare.gui.constants import LOGGER_NAME
from aare.gui.main_window import MainWindow
from aare.gui.widgets.splash_screen import LoadingSplashScreen
logger = setup_logger(LOGGER_NAME)
def main():
"""Wrapped gui as main function to make tests easier"""
try:
basedir = os.path.dirname(__file__)
icon_path = os.path.join(basedir, "graphics/aaregui_logo.svg")
# SVG looks strange on consoles...only show one line
banner_path = os.path.join(basedir, "graphics/aare_banner_blue.png")
except Exception:
logger.exception("Failed to load resources for splash screen")
sys.exit(1)
try:
# define application
app = QApplication(sys.argv)
splash_pix = QtGui.QPixmap(banner_path)
splash = LoadingSplashScreen(splash_pix)
app.setWindowIcon(QtGui.QIcon(icon_path))
app.setApplicationName("AareGUI")
app.setApplicationVersion("0.3.1")
app.setOrganizationName("PSI")
app.setOrganizationDomain("psi.ch")
splash.show()
splash.set_progress(10, "Initializing Application...")
# Create the parser
parser = QCommandLineParser()
parser.setApplicationDescription("PSI AareGUI")
parser.addHelpOption() # Adds --help option
parser.addVersionOption() # Adds --version option
# TODO if zmq and pred stream come from same source, do not need images from both streams, can combine
match mx_beamline():
case MXBeamline.X06DA:
default_url = cfg_get("gui.daq.daq_url", "https://mx-x06da-queue-01.psi.ch")
default_cert_path = cfg_get("gui.daq.cert_path", "/sls/x06da/misc/.cert/6d.crt")
default_zmq_addr = cfg_get(
"gui.cameras.sample_camera_zmq_url", "tcp://x06da-pserv-01:9089"
)
default_pred_zmq_addr = cfg_get(
"gui.cameras.prediction_zmq_url", "tcp://mx-ml:9091"
)
default_beamline_cam_addr = cfg_get(
"gui.cameras.beamline_camera_url", "x06da-axis-1.psi.ch"
)
default_gonio_cam_addr = cfg_get(
"gui.cameras.gonio_camera_url", "axis-accc8ed2972e.psi.ch"
)
default_gonio_camera_id = int(cfg_get("gui.cameras.gonio_camera_id", 3))
case MXBeamline.X10SA:
default_url = cfg_get("gui.daq.daq_url", "https://mx-x10sa-queue-01.psi.ch")
default_cert_path = cfg_get("gui.daq.cert_path", "/sls/x10sa/misc/.cert/10s.crt")
default_zmq_addr = cfg_get(
"gui.cameras.sample_camera_zmq_url", "tcp://x10sa-spark-01:9091"
)
default_pred_zmq_addr = cfg_get(
"gui.cameras.prediction_zmq_url", "tcp://x10sa-spark-01:9091"
)
default_beamline_cam_addr = cfg_get(
"gui.cameras.beamline_camera_url", "axis-accc8eb02488.psi.ch"
)
default_gonio_cam_addr = cfg_get(
"gui.cameras.gonio_camera_url", "axis-accc8ea5e463.psi.ch"
)
default_gonio_camera_id = int(cfg_get("gui.cameras.gonio_camera_id", 1))
case MXBeamline.X06SA:
default_url = cfg_get("gui.daq.daq_url", "https://mx-x06sa-queue-01.psi.ch")
default_cert_path = cfg_get("gui.daq.cert_path", "/sls/x06sa/misc/.cert/6s.crt")
default_zmq_addr = cfg_get("gui.cameras.sample_camera_zmq_url", "")
default_pred_zmq_addr = cfg_get("gui.cameras.prediction_zmq_url", "")
default_beamline_cam_addr = cfg_get("gui.cameras.beamline_camera_url", "")
default_gonio_cam_addr = cfg_get("gui.cameras.gonio_camera_url", "")
default_gonio_camera_id = int(cfg_get("gui.cameras.gonio_camera_id", 1))
case _:
default_url = cfg_get("gui.daq.daq_url", "")
default_cert_path = cfg_get("gui.daq.cert_path", "")
default_zmq_addr = cfg_get("gui.cameras.sample_camera_zmq_url", "")
default_pred_zmq_addr = cfg_get("gui.cameras.prediction_zmq_url", "")
default_beamline_cam_addr = cfg_get("gui.cameras.beamline_camera_url", "")
default_gonio_cam_addr = cfg_get("gui.cameras.gonio_camera_url", "")
default_gonio_camera_id = int(cfg_get("gui.cameras.gonio_camera_id", 1))
# Add custom options as needed
urlOption = QCommandLineOption(["u", "aaredaq-url"], "Base AareDAQ URL", "url", default_url)
parser.addOption(urlOption)
certPath = QCommandLineOption(
["c", "aaredaq-cert-path"],
"Server Certificate Path (for self-signed certificates)",
"cert",
default_cert_path,
)
parser.addOption(certPath)
defaultImage = QCommandLineOption(
["i", "image"], "Default image to display in absence of the ZMQ stream", "image"
)
parser.addOption(defaultImage)
cameraZeroMQ = QCommandLineOption(
["s", "sample-camera-zmq"],
"Sample camera ZeroMQ URL",
"sample-camera-zmq",
default_zmq_addr,
)
parser.addOption(cameraZeroMQ)
predZmqOption = QCommandLineOption(
["p", "pred-zmq"],
"Prediction ZeroMQ URL (PUB) to subscribe to (e.g. tcp://mx-ml:9091)",
"pred-zmq",
default_pred_zmq_addr,
)
parser.addOption(predZmqOption)
splash.set_progress(30, "Parsing Arguments...")
parser.process(app)
base_url = parser.value(urlOption)
if base_url == "" or base_url.lower() == "none":
base_url = None
cert_path = parser.value(certPath)
if cert_path == "" or cert_path.lower() == "none":
cert_path = None
zmq_addr = parser.value(cameraZeroMQ)
if zmq_addr == "":
zmq_addr = None
pred_zmq_addr = parser.value(predZmqOption)
if pred_zmq_addr == "":
pred_zmq_addr = None
if pred_zmq_addr is None:
pred_zmq_addr = zmq_addr
if parser.isSet(defaultImage):
default_image = parser.value(defaultImage)
else:
default_image = None
try:
splash.set_progress(50, f"Connecting to {base_url or 'backend'}...")
token = auth(base_url, cert_path)
if not token or token.count(".") != 2:
raise RuntimeError(
"Authentication did not return a valid token. "
"Please check the server is running (it may still be initialising)."
)
logger.info("Authentication successful")
splash.set_progress(80, "Authentication successful...")
except Exception as e:
splash.finish(None)
logger.exception("Cannot connect to AareDAQ server. Exiting.")
QMessageBox.critical(
None,
"Authentication Error",
f"Cannot connect to AareDAQ server:\n{e!s}\n\n Please check the server is running and your network connection.",
)
sys.exit(1)
splash.set_progress(90, "Loading Main Window...")
win = MainWindow(
base_url=base_url,
token=token,
default_image=default_image,
zmq_addr=zmq_addr,
pred_zmq_addr=pred_zmq_addr,
beamline_cam_addr=default_beamline_cam_addr,
gonio_cam_addr=default_gonio_cam_addr,
gonio_cam_id=default_gonio_camera_id,
)
splash.set_progress(100, "Ready")
splash.finish(win)
# Start windowed (not maximized) at a fraction of the primary screen,
# centered — sized explicitly because the size hint is wider than the
# monitor. Other panels may still enforce a somewhat larger minimum;
# the window then lands on that minimum instead.
unmax_w, unmax_h = 0.5, 0.7
available = app.primaryScreen().availableGeometry()
win.resize(int(available.width() * unmax_w), int(available.height() * unmax_h))
win.move(available.center() - win.rect().center())
win.show()
sys.exit(app.exec())
except Exception as e:
splash.finish(None)
logger.exception("Error starting GUI")
QMessageBox.critical(
None,
"Fatal Error",
f"An error occurred during startup. See console for details."
f"\nPlease check the server is running and your network connection."
f"\n\n{e!s}\n\n",
)
sys.exit(1)
if __name__ == "__main__":
main()
-20
View File
@@ -1,20 +0,0 @@
import logging
from PySide6.QtCore import QObject, Signal
class QtLogEmitter(QObject):
message = Signal(str)
class QtLogHandler(logging.Handler):
def __init__(self, emitter: QtLogEmitter):
super().__init__()
self.emitter = emitter
def emit(self, record: logging.LogRecord):
try:
msg = self.format(record)
self.emitter.message.emit(msg)
except Exception: # noqa: BLE001 - logging here would recurse into this handler
self.handleError(record)
Loaded 100 of 261 files, more files were not shown because too many files have changed in this diff. Show more