diff --git a/docs/cheatsheet.md b/docs/cheatsheet.md deleted file mode 100644 index 924d645e..00000000 --- a/docs/cheatsheet.md +++ /dev/null @@ -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 | diff --git a/docs/index.md b/docs/index.md index 53dfe305..fb97843e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -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 diff --git a/scripts/alc_bkg_comp.py b/scripts/alc_bkg_comp.py deleted file mode 100644 index 1ead13b4..00000000 --- a/scripts/alc_bkg_comp.py +++ /dev/null @@ -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() diff --git a/scripts/camera_stat_thread.py b/scripts/camera_stat_thread.py deleted file mode 100644 index 2d22e451..00000000 --- a/scripts/camera_stat_thread.py +++ /dev/null @@ -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 diff --git a/scripts/gui_desginer.py b/scripts/gui_desginer.py deleted file mode 100644 index ba48ca9a..00000000 --- a/scripts/gui_desginer.py +++ /dev/null @@ -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()) diff --git a/scripts/pshell_client_old.py b/scripts/pshell_client_old.py deleted file mode 100644 index 22c3116b..00000000 --- a/scripts/pshell_client_old.py +++ /dev/null @@ -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=""): - """Returns help or auto-completion strings. - - Args: - input(optional, str): - ":" for control commands - - "" 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)) diff --git a/scripts/redis_dump.py b/scripts/redis_dump.py deleted file mode 100644 index 84148556..00000000 --- a/scripts/redis_dump.py +++ /dev/null @@ -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()) diff --git a/src/aare/beamline_dispatch/__init__.py b/src/aare/beamline_dispatch/__init__.py deleted file mode 100644 index 4d29ae1f..00000000 --- a/src/aare/beamline_dispatch/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""A single API to dispatch functions based on the current beamline""" diff --git a/src/aare/beamline_dispatch/beamline_dispatch.py b/src/aare/beamline_dispatch/beamline_dispatch.py deleted file mode 100644 index 0a0281c9..00000000 --- a/src/aare/beamline_dispatch/beamline_dispatch.py +++ /dev/null @@ -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) diff --git a/src/aare/beamline_dispatch/default/__init__.py b/src/aare/beamline_dispatch/default/__init__.py deleted file mode 100644 index 85788a92..00000000 --- a/src/aare/beamline_dispatch/default/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .beamline_dispatch import DefaultDispatch - -__all__ = ["DefaultDispatch"] diff --git a/src/aare/beamline_dispatch/default/beamline_dispatch.py b/src/aare/beamline_dispatch/default/beamline_dispatch.py deleted file mode 100644 index 45dba3bb..00000000 --- a/src/aare/beamline_dispatch/default/beamline_dispatch.py +++ /dev/null @@ -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} diff --git a/src/aare/beamline_dispatch/protocols.py b/src/aare/beamline_dispatch/protocols.py deleted file mode 100644 index 169fc4b4..00000000 --- a/src/aare/beamline_dispatch/protocols.py +++ /dev/null @@ -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]: ... diff --git a/src/aare/beamline_dispatch/simulated/__init__.py b/src/aare/beamline_dispatch/simulated/__init__.py deleted file mode 100644 index 2f069aaf..00000000 --- a/src/aare/beamline_dispatch/simulated/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .beamline_dispatch import SimulatedDispatch - -__all__ = ["SimulatedDispatch"] diff --git a/src/aare/beamline_dispatch/simulated/beamline_dispatch.py b/src/aare/beamline_dispatch/simulated/beamline_dispatch.py deleted file mode 100644 index fe06ba2f..00000000 --- a/src/aare/beamline_dispatch/simulated/beamline_dispatch.py +++ /dev/null @@ -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 diff --git a/src/aare/beamline_dispatch/x06da/__init__.py b/src/aare/beamline_dispatch/x06da/__init__.py deleted file mode 100644 index 6c356917..00000000 --- a/src/aare/beamline_dispatch/x06da/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .beamline_dispatch import X06daDispatch - -__all__ = ["X06daDispatch"] diff --git a/src/aare/beamline_dispatch/x06da/beamline_dispatch.py b/src/aare/beamline_dispatch/x06da/beamline_dispatch.py deleted file mode 100644 index 0c85000c..00000000 --- a/src/aare/beamline_dispatch/x06da/beamline_dispatch.py +++ /dev/null @@ -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} diff --git a/src/aare/beamline_dispatch/x06sa/__init__.py b/src/aare/beamline_dispatch/x06sa/__init__.py deleted file mode 100644 index 359dbc5a..00000000 --- a/src/aare/beamline_dispatch/x06sa/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .beamline_dispatch import X06saDispatch - -__all__ = ["X06saDispatch"] diff --git a/src/aare/beamline_dispatch/x06sa/beamline_dispatch.py b/src/aare/beamline_dispatch/x06sa/beamline_dispatch.py deleted file mode 100644 index fcae2cec..00000000 --- a/src/aare/beamline_dispatch/x06sa/beamline_dispatch.py +++ /dev/null @@ -1,4 +0,0 @@ -from aare.beamline_dispatch.default.beamline_dispatch import DefaultDispatch - - -class X06saDispatch(DefaultDispatch): ... diff --git a/src/aare/beamline_dispatch/x10sa/__init__.py b/src/aare/beamline_dispatch/x10sa/__init__.py deleted file mode 100644 index 7e56c8b7..00000000 --- a/src/aare/beamline_dispatch/x10sa/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .beamline_dispatch import X10saDispatch - -__all__ = ["X10saDispatch"] diff --git a/src/aare/beamline_dispatch/x10sa/beam_centers.json b/src/aare/beamline_dispatch/x10sa/beam_centers.json deleted file mode 100644 index a67755c1..00000000 --- a/src/aare/beamline_dispatch/x10sa/beam_centers.json +++ /dev/null @@ -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 - ] -} diff --git a/src/aare/beamline_dispatch/x10sa/beamline_dispatch.py b/src/aare/beamline_dispatch/x10sa/beamline_dispatch.py deleted file mode 100644 index 356cbe90..00000000 --- a/src/aare/beamline_dispatch/x10sa/beamline_dispatch.py +++ /dev/null @@ -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} diff --git a/src/aare/daq/autofocus.py b/src/aare/daq/autofocus.py deleted file mode 100644 index 8e405ddd..00000000 --- a/src/aare/daq/autofocus.py +++ /dev/null @@ -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() diff --git a/src/aare/daq/beamcenterfit.py b/src/aare/daq/beamcenterfit.py deleted file mode 100644 index 280a2160..00000000 --- a/src/aare/daq/beamcenterfit.py +++ /dev/null @@ -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 diff --git a/src/aare/daq/config.py b/src/aare/daq/config.py deleted file mode 100644 index eabbc772..00000000 --- a/src/aare/daq/config.py +++ /dev/null @@ -1,1246 +0,0 @@ -import base64 -import io -import json -import time -from dataclasses import asdict, is_dataclass -from datetime import datetime -from typing import Any - -import numpy as np -from aarecommon.config.beamline import cfg_get -from aarecommon.config.config_models import GridscanAnalysisMode -from aarecommon.config.logger import setup_logger -from aarecommon.math.coordinate import AerotechCoordinate, Coordinate -from aarecommon.models.auth import ( - BatonHolderInfo, - BatonRequest, - BatonRequestStatus, - BatonTransferQueue, -) -from aarecommon.models.automation import AutomationProgress -from aarecommon.models.beamline import MXBeamline -from aarecommon.models.models import ( - BeamlineSettingsModel, - BeamlineStateEnum, - BeamMarkCoeffModel, - CryojetSettingsModel, - CrystalSize, - FluorescenceSpectrumOutputModel, - OpenGuiSessionInfo, - SampleCameraSettings, - SampleShortInfo, - SampleShortInfoList, - SessionsStateEnum, - SessionStatus, - SimpleScanParameters, - SimpleStrategyInputModel, - ZoomModeEnum, - ZoomModel, - zoom_manager, -) -from redis.client import PubSub, Redis -from redis.lock import Lock as RedisLock - -from aare.daq.config_model import LocalContactConfigModel - -# TODO WHAT SHOULD THIS BE? This should be in the YAMl file it is beamline specific -ABR_POS_MOUNT = AerotechCoordinate(at_mm=Coordinate(x=0, y=0, z=0), omega_deg=0) - - -# TODO WHAT SHOULD THIS BE? This should be in the YAMl file it is beamline specific -ABR_POS_MOUNT = AerotechCoordinate(at_mm=Coordinate(x=0, y=0, z=0), omega_deg=0) -ABR_OMEGA_MOUNT = 0.0 -DEFAULT_LENS_MAGNIFICATION = 10.0 - -logger = setup_logger("aareDAQ") - - -# Serialize the NumPy array to a Base64 string -def numpy_to_base64(array: np.ndarray) -> str: - buffer = io.BytesIO() # Create an in-memory buffer - # Save the array as a binary file to the buffer - np.save(buffer, array, allow_pickle=False) - # Reset buffer's position to the beginning - buffer.seek(0) - # Base64 encode and convert bytes to string - return base64.b64encode(buffer.read()).decode() - - -# Retrieve and decode the array -def base64_to_numpy(encoded_str: str | None) -> np.ndarray | None: - if encoded_str is None: - return None - decoded = base64.b64decode(encoded_str) # Base64 decode - buffer = io.BytesIO(decoded) # Convert bytes to a buffer - return np.load(buffer) # Load buffer as a NumPy array - - -class BeamlineConfig: - """ - Manages the configuration and state of a beamline system by interacting with a Redis - backend. Provides methods for updating status, settings, and related state details. - - This class encapsulates the logic needed to manage beamline states and corresponding - operations such as setting busy flags, updating or retrieving settings, and handling - different beamline-related data such as background images. By connecting to a Redis - database, it ensures that the beamline's state and configurations are stored and - retrieved efficiently. Each beamline instance is identified by a unique name, and all - operations are performed with atomic safety using Redis locking mechanisms. - - Attributes: - _bl (str): The beamline's unique identifier or name. - redis (redis.Redis): Redis client instance used for interacting with the datastore. - """ - - redis: Redis - GUI_SESSION_EXPIRE_SECONDS = 60 * 10 - - def __init__(self, bl: MXBeamline): - self._mxb = bl - self._bl = bl.value.lower() - if bl is MXBeamline.SIMULATED: - host = "localhost" - else: - host = cfg_get("daq.hardware.redis_url", f"{self._bl}-redis.psi.ch") - self.redis = Redis(host=host, port=6379, db=0, decode_responses=True) - self.hw_lock = RedisLock(self.redis, name=f"{bl}:hardware_busy_lock") - self.simulated_detector = bl is MXBeamline.SIMULATED - self._initialize_optional_yaml_defaults() - - def _initialize_optional_yaml_defaults(self) -> None: - raw_dtz_safe_position = cfg_get("daq.hardware.dtz_safe_position") - - if raw_dtz_safe_position in (None, ""): - return - - if self.dtz_safe_position is not None: - return - - try: - self.dtz_safe_position = float(raw_dtz_safe_position) - logger.info( - f"Initialized dtz_safe_position from beamline config: {self.dtz_safe_position}" - ) - except (TypeError, ValueError) as e: - logger.warning( - f"Ignoring invalid daq.hardware.dtz_safe_position value: " - f"{raw_dtz_safe_position!r} ({e})" - ) - - # GUI session management - - def _gui_sessions_index_key(self) -> str: - return f"{self._bl}:gui_sessions" - - def _gui_session_key(self, session: int) -> str: - return f"{self._bl}:gui_session:{session}" - - def _write_gui_session( - self, payload: OpenGuiSessionInfo, expiry_sec: int | None = None - ) -> None: - expiry = int(expiry_sec or self.GUI_SESSION_EXPIRE_SECONDS) - - pipe = self.redis.pipeline() - pipe.set(self._gui_session_key(payload.session), payload.model_dump_json()) - pipe.expire(self._gui_session_key(payload.session), expiry) - pipe.sadd(self._gui_sessions_index_key(), payload.session) - pipe.execute() - - def _current_gui_session_ttl(self, session: int) -> int | None: - try: - ttl = int(self.redis.ttl(self._gui_session_key(session))) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - except Exception: - logger.debug("Could not read the GUI session TTL", exc_info=True) - return None - - if ttl > 0: - return ttl - return None - - def _read_gui_session(self, session: int) -> OpenGuiSessionInfo | None: - raw = self.redis.get(self._gui_session_key(session)) - if raw is None: - return None - try: - return OpenGuiSessionInfo(**json.loads(raw)) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - except Exception: - logger.warning(f"Failed to parse GUI session info for session {session}", exc_info=True) - return None - - def touch_gui_session( - self, *, session: int, username: str, staff: bool = False, expiry_sec: int - ) -> OpenGuiSessionInfo: - existing = self._read_gui_session(session) - holder = self.baton_holder - holds_baton = bool(holder is not None and holder.session == session) - - payload = OpenGuiSessionInfo( - session=session, - username=username, - staff=staff, - last_seen_ts=time.time(), - last_interaction_ts=existing.last_interaction_ts if existing is not None else None, - close_requested=existing.close_requested if existing is not None else False, - close_requested_by=existing.close_requested_by if existing is not None else None, - close_requested_at=existing.close_requested_at if existing is not None else None, - close_grace_seconds=existing.close_grace_seconds if existing is not None else None, - holds_baton=holds_baton, - ) - - self._write_gui_session(payload, expiry_sec=expiry_sec) - self.purge_expired_gui_sessions() - return payload - - def update_gui_interaction( - self, session: int, last_interaction_ts: float - ) -> OpenGuiSessionInfo | None: - payload = self._read_gui_session(session) - if payload is None: - self.redis.srem(self._gui_sessions_index_key(), session) - return None - - payload.last_interaction_ts = last_interaction_ts - ttl = self._current_gui_session_ttl(session) - self._write_gui_session(payload, expiry_sec=ttl) - return payload - - def request_gui_close( - self, *, session: int, requested_by: str, grace_seconds: int = 60 - ) -> OpenGuiSessionInfo | None: - payload = self._read_gui_session(session) - if payload is None: - self.redis.srem(self._gui_sessions_index_key(), session) - return None - - payload.close_requested = True - payload.close_requested_by = requested_by - payload.close_requested_at = time.time() - payload.close_grace_seconds = grace_seconds - - ttl = self._current_gui_session_ttl(session) - self._write_gui_session(payload, expiry_sec=ttl) - return payload - - def clear_gui_close_request(self, session: int) -> None: - payload = self._read_gui_session(session) - if payload is None: - self.redis.srem(self._gui_sessions_index_key(), session) - return - - payload.close_requested = False - payload.close_requested_by = None - payload.close_requested_at = None - payload.close_grace_seconds = None - - ttl = self._current_gui_session_ttl(session) - self._write_gui_session(payload, expiry_sec=ttl) - - def remove_gui_session(self, session: int) -> None: - pipe = self.redis.pipeline() - pipe.delete(self._gui_session_key(session)) - pipe.srem(self._gui_sessions_index_key(), session) - pipe.execute() - self.purge_expired_gui_sessions() - - def purge_expired_gui_sessions(self) -> None: - session_ids: set[str] = self.redis.smembers(self._gui_sessions_index_key()) # pyright: ignore[reportArgumentType, reportAssignmentType] # using sync client - remove ignore on upgrade to redis v8 - if not session_ids: - return - - expired_ids: list[str] = [] - for session_id in session_ids: - if not self.redis.exists(self._gui_session_key(int(session_id))): - expired_ids.append(session_id) - - if expired_ids: - self.redis.srem(self._gui_sessions_index_key(), *expired_ids) - - def get_open_gui_sessions(self) -> list[OpenGuiSessionInfo]: - self.purge_expired_gui_sessions() - - session_ids = self.redis.smembers(self._gui_sessions_index_key()) - if not session_ids: - return [] - - holder = self.baton_holder - holder_session = holder.session if holder is not None else None - - sessions: list[OpenGuiSessionInfo] = [] - for session_id in sorted(int(s) for s in session_ids): - payload = self._read_gui_session(session_id) - if payload is not None: - payload.holds_baton = payload.session == holder_session - sessions.append(payload) - - return sessions - - def get_gui_session(self, session: int) -> OpenGuiSessionInfo | None: - payload = self._read_gui_session(session) - if payload is None: - self.redis.srem(self._gui_sessions_index_key(), session) - return None - - holder = self.baton_holder - payload.holds_baton = bool(holder is not None and holder.session == payload.session) - return payload - - # Session and authentication management - - @property - def allow_non_staff_request_from_staff(self) -> bool: - raw = self.redis.get(f"{self._bl}:allow_non_staff_request_from_staff") - if raw is None: - return False - return str(raw).strip().lower() in {"1", "true", "yes", "on"} - - @allow_non_staff_request_from_staff.setter - def allow_non_staff_request_from_staff(self, enabled: bool) -> None: - if enabled: - self.redis.set(f"{self._bl}:allow_non_staff_request_from_staff", "1") - else: - self.redis.delete(f"{self._bl}:allow_non_staff_request_from_staff") - - def generate_session(self) -> int: - return int(self.redis.incr(f"{self._bl}:session")) # pyright: ignore[reportArgumentType, reportAssignmentType] # using sync client - remove ignore on upgrade to redis v8 - - @property - def active_session(self) -> int | None: - """ - Read active_session from Redis and convert to int. - - Returns: - int if present and valid, otherwise None. - """ - baton = self.baton_holder - if baton is None: - return None - return baton.session - - def session_status(self, session: int) -> SessionStatus: - return SessionStatus(session=self.session_state(session), current_pgroup=self.pgroup) - - def session_state(self, session: int) -> SessionsStateEnum: - holder = self.baton_holder - pending = self.pending_baton_request - - if holder is None: - return SessionsStateEnum.Vacant - - if holder.session == session: - # You are the holder. Check if someone else requested from you. - if ( - pending - and pending.status == BatonRequestStatus.PENDING - and pending.holder_session == session - ): - return SessionsStateEnum.PendingElseToYou - return SessionsStateEnum.OwnedByYou - else: - # Someone else is the holder. Check if you requested from them. - if ( - pending - and pending.status == BatonRequestStatus.PENDING - and pending.requester_session == session - ): - return SessionsStateEnum.PendingYouToElse - return SessionsStateEnum.OwnedByElse - - def try_set_active_session(self, session: int, expiry_sec: int) -> None: - with RedisLock(self.redis, f"{self._bl}:active_session_lock", timeout=10): - active = self.active_session - if active is None: - self.redis.set(f"{self._bl}:active_session", session) - elif active != session: - raise RuntimeError( - "There is already active session with different id. Try again later." - ) - self.redis.expire(f"{self._bl}:active_session", expiry_sec) - - # TODO finish setting this up! - def try_extend_active_session(self, session: int, expiry_sec: int) -> None: - with RedisLock(self.redis, f"{self._bl}:active_session_lock", timeout=10): - active = self.active_session - if active is None: - raise RuntimeError("There is no active session with given id. Try again later.") - # if active == session: - # self.redis.expire(f"{self._bl}:active_session", expiry_sec, gt=True) - - if active == session: - key = f"{self._bl}:active_session" - current_ttl = self.redis.ttl(key) - - # Redis compatibility: - # some Redis servers do not support EXPIRE with GT option. - # Emulate "extend only if greater" manually while holding the lock. - if current_ttl is None or float(current_ttl) < 0 or float(current_ttl) < expiry_sec: # pyright: ignore[reportArgumentType, reportAssignmentType] # using sync client - remove ignore on upgrade to redis v8 - self.redis.expire(key, expiry_sec) - else: - raise RuntimeError( - "There is already active session with different id. Try again later." - ) - - def end_active_session(self, session: int) -> None: - with RedisLock(self.redis, f"{self._bl}:active_session_lock", timeout=10): - active = self.active_session - if active is None: - return - if active == session: - self.redis.delete(f"{self._bl}:active_session") - self.redis.delete(f"{self._bl}:baton_holder") - - def force_set_active_session(self, session: int, expiry_sec: int) -> None: - # Ensure that there is no active try-set for active session - with RedisLock(self.redis, f"{self._bl}:active_session_lock", timeout=10): - self.redis.set(f"{self._bl}:active_session", session) - self.redis.expire(f"{self._bl}:active_session", expiry_sec) - - # ========== BATON SYSTEM ========== - - @property - def baton_holder(self) -> BatonHolderInfo | None: - """Get information about the current baton holder.""" - tmp = self.redis.get(f"{self._bl}:baton_holder") - if tmp is None: - return None - try: - return BatonHolderInfo(**json.loads(tmp)) - except Exception: - logger.debug("Could not parse the baton holder info", exc_info=True) - return None - - @baton_holder.setter - def baton_holder(self, info: BatonHolderInfo | None) -> None: - if info is None: - self.redis.delete(f"{self._bl}:baton_holder") - else: - self.redis.set(f"{self._bl}:baton_holder", info.model_dump_json()) - - @property - def pending_baton_request(self) -> BatonRequest | None: - """Get the current pending baton request, if any.""" - tmp = self.redis.get(f"{self._bl}:baton_request") - if tmp is None: - return None - try: - return BatonRequest(**json.loads(tmp)) - except Exception: - logger.debug("Could not parse the pending baton request", exc_info=True) - return None - - def set_pending_baton_request( - self, request: BatonRequest | None, timeout_sec: int = 30 - ) -> None: - """Set a pending baton request with auto-expiry for timeout.""" - if request is None: - self.redis.delete(f"{self._bl}:baton_request") - else: - self.redis.set(f"{self._bl}:baton_request", request.model_dump_json()) - # Add a few seconds buffer so we can detect timeout vs expiry - self.redis.expire(f"{self._bl}:baton_request", timeout_sec + 5) - - def clear_pending_baton_request(self) -> None: - self.redis.delete(f"{self._bl}:baton_request") - - @property - def queued_baton_transfer(self) -> BatonTransferQueue | None: - """Get queued transfer waiting for beamline to be available.""" - tmp = self.redis.get(f"{self._bl}:baton_transfer_queue") - if tmp is None: - return None - try: - return BatonTransferQueue(**json.loads(tmp)) - except Exception: - logger.debug("Could not parse the queued baton transfer", exc_info=True) - return None - - @queued_baton_transfer.setter - def queued_baton_transfer(self, transfer: BatonTransferQueue | None) -> None: - if transfer is None: - self.redis.delete(f"{self._bl}:baton_transfer_queue") - else: - self.redis.set(f"{self._bl}:baton_transfer_queue", transfer.model_dump_json()) - - def can_transfer_baton_now(self) -> bool: - """Check if baton can be transferred (beamline not mid-operation).""" - return not self.hw_lock.locked() - - def execute_baton_transfer( - self, - to_session: int, - to_username: str, - to_is_staff: bool, - to_pgroup: str | None, - expiry_sec: int, - ) -> None: - """ - Atomically transfer the baton to a new holder. - Use existing active_session_lock for consistency. - """ - with RedisLock(self.redis, f"{self._bl}:active_session_lock", timeout=10): - self.redis.set(f"{self._bl}:active_session", to_session) - self.redis.expire(f"{self._bl}:active_session", expiry_sec) - self.baton_holder = BatonHolderInfo( - username=to_username, session=to_session, is_staff=to_is_staff, pgroup=to_pgroup - ) - # Clear any pending request or queued transfer - self.clear_pending_baton_request() - self.queued_baton_transfer = None - - def process_queued_transfer_if_ready(self, expiry_sec: int) -> bool: - """ - Check if there's a queued transfer and beamline is now available. - Returns True if transfer was executed. - """ - queued = self.queued_baton_transfer - if queued is None: - return False - - if not self.can_transfer_baton_now(): - return False - - self.execute_baton_transfer( - to_session=queued.target_session, - to_username=queued.target_username, - to_is_staff=queued.target_is_staff, - to_pgroup=queued.target_pgroup, - expiry_sec=expiry_sec, - ) - return True - - @property - def pgroup(self) -> str | None: - return self.redis.get(f"{self._bl}:pgroup") # pyright: ignore[reportReturnType] # using sync client - remove ignore on upgrade to redis v8 - - @pgroup.setter - def pgroup(self, pgroup: str | None) -> None: - if pgroup is None: - self.redis.delete(f"{self._bl}:pgroup") - else: - self.redis.set(f"{self._bl}:pgroup", pgroup) - - @property - def commissioning_mode(self) -> bool: - return self.redis.get(f"{self._bl}:commissioning_mode") is not None - - @commissioning_mode.setter - def commissioning_mode(self, commisioning_mode: bool) -> None: - if commisioning_mode: - self.redis.set(f"{self._bl}:commissioning_mode", "1") - else: - self.redis.delete(f"{self._bl}:commissioning_mode") - - def start_moving( - self, target: BeamlineStateEnum, timeout: int | None = None - ) -> BeamlineStateEnum: - curr_state = self.state - if target != curr_state: - self.state = BeamlineStateEnum.Moving - return curr_state - - @property - def state(self) -> BeamlineStateEnum: - raw_value = self.redis.get(f"{self._bl}:state") - - if raw_value is None: - return BeamlineStateEnum.Maintenance - try: - int_value = int(raw_value) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - return BeamlineStateEnum(int_value) - except (ValueError, KeyError): - raise ValueError( - f"Invalid 'mx_state' value: {raw_value}. Expected integer corresponding to a BeamlineStateEnum." - ) - - @state.setter - def state(self, state: BeamlineStateEnum): - self.redis.set(f"{self._bl}:state", state.value) - - @property - def tell_mount_count(self) -> int: - return int(self.redis.incr(f"{self._bl}:tell_mount_count")) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - - def pixel_to_mm(self, zoom: float) -> float: - cfg = self.settings - base_pixel_in_mm = 1.0 / ( - cfg.camera_translation_factor_b * np.exp(cfg.camera_translation_factor_a * zoom) # pyright: ignore[reportOptionalOperand] - ) - # Apply lens magnification correction relative to the default 10x lens. - # A lower magnification lens (e.g. 5x) makes each pixel cover more physical space. - lens_magnification = cfg_get("daq.hardware.lens_magnification", DEFAULT_LENS_MAGNIFICATION) - try: - lens_magnification = float(lens_magnification) - except (TypeError, ValueError): - lens_magnification = DEFAULT_LENS_MAGNIFICATION - if lens_magnification <= 0: - lens_magnification = DEFAULT_LENS_MAGNIFICATION - return base_pixel_in_mm * (DEFAULT_LENS_MAGNIFICATION / lens_magnification) - - def zoom_for_pixel_to_mm(self, target_pixel_in_mm: float) -> float: - """Inverse of :meth:`pixel_to_mm`: the zoom at which one pixel covers - ``target_pixel_in_mm`` millimetres. - - pixel_to_mm(z) = lens_factor / (b * exp(a*z)) => - z = ln(lens_factor / (b * target)) / a - """ - if target_pixel_in_mm <= 0: - raise ValueError(f"target_pixel_in_mm must be > 0, got {target_pixel_in_mm}") - cfg = self.settings - a = cfg.camera_translation_factor_a - b = cfg.camera_translation_factor_b - lens_magnification = cfg_get("daq.hardware.lens_magnification", DEFAULT_LENS_MAGNIFICATION) - try: - lens_magnification = float(lens_magnification) - except (TypeError, ValueError): - lens_magnification = DEFAULT_LENS_MAGNIFICATION - if lens_magnification <= 0: - lens_magnification = DEFAULT_LENS_MAGNIFICATION - lens_factor = DEFAULT_LENS_MAGNIFICATION / lens_magnification - return float(np.log(lens_factor / (b * target_pixel_in_mm)) / a) - - @property - def beam_size_mm(self) -> Coordinate: - x = float(self.redis.get(f"{self._bl}:beam_size_x") or 0.4) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - y = float(self.redis.get(f"{self._bl}:beam_size_y") or 0.4) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - return Coordinate(x=x, y=y) - - @beam_size_mm.setter - def beam_size_mm(self, data: Coordinate): - self.redis.set(f"{self._bl}:beam_size_x", data.x) - self.redis.set(f"{self._bl}:beam_size_y", data.y) - - @property - def gridscan_analysis_mode(self) -> GridscanAnalysisMode: - data = self.redis.get(f"{self._bl}:gridscan_analysis_mode") - return GridscanAnalysisMode(data) if data is not None else GridscanAnalysisMode.FindXtal - - @gridscan_analysis_mode.setter - def gridscan_analysis_mode(self, val: GridscanAnalysisMode) -> None: - self.redis.set(f"{self._bl}:gridscan_analysis_mode", str(val)) - - @property - def current_zoom_level(self) -> float | None: - data = self.redis.get(f"{self._bl}:current_zoom_level") - return float(data) if data is not None else None - - @current_zoom_level.setter - def current_zoom_level(self, val: float) -> None: - self.redis.set(f"{self._bl}:current_zoom_level", str(val)) - - def _get_settings(self) -> BeamlineSettingsModel: - tmp = self.redis.get(f"{self._bl}:settings") - if tmp is None: - return BeamlineSettingsModel() - - data_dict = json.loads(tmp) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - model = BeamlineSettingsModel(**data_dict) - return model - - @property - def settings(self) -> BeamlineSettingsModel: - with RedisLock(self.redis, f"{self._bl}:settings_lock", timeout=10): - return self._get_settings() - - @settings.setter - def settings(self, data: BeamlineSettingsModel): - with RedisLock(self.redis, f"{self._bl}:settings_lock", timeout=10): - current = self._get_settings() - updated_data = current.model_copy(update=data.model_dump(exclude_unset=True)) - self.redis.set(f"{self._bl}:settings", updated_data.model_dump_json()) - - @property - def cryojet_settings(self) -> CryojetSettingsModel: - tmp = self.redis.get(f"{self._bl}:cryojet_settings") - if tmp is None: - return CryojetSettingsModel() - - data_dict = json.loads(tmp) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - return CryojetSettingsModel(**data_dict) - - @cryojet_settings.setter - def cryojet_settings(self, data: CryojetSettingsModel): - self.redis.set(f"{self._bl}:cryojet_settings", data.model_dump_json()) - - def get_alc_bkg(self, zoom: float, exp: float, gain: float) -> np.ndarray | None: - return base64_to_numpy(self.redis.get(f"{self._bl}:bkg{zoom:.1f}_{exp:.2f}_{gain:.1f}")) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - - def put_alc_bkg(self, zoom: float, exp: float, gain: float, data: np.ndarray): - self.redis.set(f"{self._bl}:bkg{zoom:.1f}_{exp:.2f}_{gain:.1f}", numpy_to_base64(data)) - - @property - def spreadsheet(self) -> SampleShortInfoList: - tmp = self.redis.get(f"{self._bl}:sample_spreadsheet") - if tmp is None: - return SampleShortInfoList(s=[]) - - data_dict = json.loads(tmp) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - return SampleShortInfoList(**data_dict) - - def spreadsheet_pgroup(self, pgroups: list[str]) -> SampleShortInfoList: - sample = self.spreadsheet - sample.s = list(filter(lambda x: x.user in pgroups, sample.s)) - return sample - - @spreadsheet.setter - def spreadsheet(self, data: SampleShortInfoList): - self.redis.set(f"{self._bl}:sample_spreadsheet", data.model_dump_json()) - - def listen_changes_spreadsheet(self) -> PubSub: - self.redis.config_set("notify-keyspace-events", "KEA") - pubsub = self.redis.pubsub() - pubsub.psubscribe(f"__keyspace@0__:{self._bl}:sample_spreadsheet") - return pubsub - - @property - def reference_tools(self) -> SampleShortInfoList: - tmp = self.redis.get(f"{self._bl}:reference-tools") - if tmp is None: - return SampleShortInfoList(s=[]) - - data_dict = json.loads(tmp) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - return SampleShortInfoList(**data_dict) - - @reference_tools.setter - def reference_tools(self, data: SampleShortInfoList): - self.redis.set(f"{self._bl}:reference-tools", data.model_dump_json()) - - def listen_changes_reference_tools(self) -> PubSub: - self.redis.config_set("notify-keyspace-events", "KEA") - pubsub = self.redis.pubsub() - pubsub.psubscribe(f"__keyspace@0__:{self._bl}:reference-tools") - return pubsub - - @property - def current_sample(self) -> SampleShortInfo | None: - tmp = self.redis.get(f"{self._bl}:current_sample") - if tmp is None: - return None - - data_dict = json.loads(tmp) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - return SampleShortInfo(**data_dict) - - @current_sample.setter - def current_sample(self, sample: SampleShortInfo | None): - if sample is None: - self.redis.delete(f"{self._bl}:current_sample") - else: - self.redis.set(f"{self._bl}:current_sample", sample.model_dump_json()) - - @property - def beam_mark_coeff(self) -> BeamMarkCoeffModel: - tmp = self.redis.get(f"{self._bl}:beam_center_camera") - if tmp is None: - return BeamMarkCoeffModel() - - data_dict = json.loads(tmp) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - return BeamMarkCoeffModel(**data_dict) - - @beam_mark_coeff.setter - def beam_mark_coeff(self, data: BeamMarkCoeffModel): - self.redis.set(f"{self._bl}:beam_center_camera", data.model_dump_json()) - - # TODO tidy up zoom functions - @property - def zoom_mode(self) -> ZoomModeEnum: - raw_value = self.redis.get(f"{self._bl}:zoom_mode") - if raw_value is None: - print("no zoom mode given, defaulting to user mode") - return ZoomModeEnum.User - try: - int_value = int(raw_value) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - return ZoomModeEnum(int_value) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - except (ValueError, KeyError): - raise ValueError( - f"Invalid 'mx_zoom_mode' value: {raw_value}. Expected integer corresponding to a ZoomModeEnum." - ) - - @zoom_mode.setter - def zoom_mode(self, mode: ZoomModeEnum): - self.redis.set(f"{self._bl}:zoom_mode", mode.value) - - @staticmethod - def zoom_setting_string(mode: ZoomModeEnum = ZoomModeEnum.User) -> str: - if mode == ZoomModeEnum.BeamLocation: - setting_string = "bl_zoom_settings" - elif mode == ZoomModeEnum.LoopCenter: - setting_string = "alc_zoom_settings" - elif mode == ZoomModeEnum.User: - setting_string = "zoom_settings" - else: - print("invalid zoom_settings mode using manual user settings") - setting_string = "zoom_settings" - return setting_string - - @property - def zoom_settings(self) -> ZoomModel: - mode = self.zoom_mode - if not mode or not isinstance(mode, ZoomModeEnum): - raise ValueError("incorrect zoom settings mode used") - tmp = self.redis.get(f"{self._bl}:{self.zoom_setting_string(mode)}") - if tmp is None: - return zoom_manager(mode, self._mxb) - data_dict = json.loads(tmp) - return ZoomModel(**data_dict) - - @zoom_settings.setter - def zoom_settings(self, data: ZoomModel): - mode = self.zoom_mode - if not mode or not isinstance(mode, ZoomModeEnum): - raise ValueError("incorrect zoom settings mode used") - self.redis.set(f"{self._bl}:{self.zoom_setting_string(mode)}", data.model_dump_json()) - - def save_zoom_camera_setting( - self, zoom_value: float, settings: SampleCameraSettings, mode: ZoomModeEnum | None = None - ) -> None: - """Insert/replace the camera settings for a single zoom stop in a given - mode's table (persisted to Redis under that mode's key). Defaults to the - active zoom mode; pass ``mode`` to target a specific one explicitly.""" - mode = mode or self.zoom_mode - key = f"{self._bl}:{self.zoom_setting_string(mode)}" - tmp = self.redis.get(key) - model = ZoomModel(**json.loads(tmp)) if tmp is not None else zoom_manager(mode, self._mxb) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - model.z[zoom_value] = settings # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - self.redis.set(key, model.model_dump_json()) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - - @property - def abr_meas_pos(self) -> AerotechCoordinate: - tmp = self.redis.get(f"{self._bl}:abr_meas_pos") - if tmp is None: - return ABR_POS_MOUNT - - data_dict = json.loads(tmp) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - return AerotechCoordinate(**data_dict) - - @abr_meas_pos.setter - def abr_meas_pos(self, data: AerotechCoordinate): - self.redis.set(f"{self._bl}:abr_meas_pos", data.model_dump_json()) - - @property - def dtz(self) -> float | None: - tmp = self.redis.get(f"{self._bl}:dtz") - if tmp is None: - return None - return float(tmp) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - - @dtz.setter - def dtz(self, dtz: float): - self.redis.set(f"{self._bl}:dtz", dtz) - - @property - def dtz_safe_position(self) -> float | None: - tmp = self.redis.get(f"{self._bl}:dtz_safe_position") - if tmp is None: - return None - return float(tmp) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - - @dtz_safe_position.setter - def dtz_safe_position(self, dtz: float): - self.redis.set(f"{self._bl}:dtz_safe_position", dtz) - - @property - def xrf(self) -> FluorescenceSpectrumOutputModel | None: - tmp = self.redis.get(f"{self._bl}:xrf") - if tmp is None: - return None - data_dict = json.loads(tmp) - return FluorescenceSpectrumOutputModel(**data_dict) - - @xrf.setter - def xrf(self, data: FluorescenceSpectrumOutputModel | None): - if data is None: - self.redis.delete(f"{self._bl}:xrf") - else: - self.redis.set(f"{self._bl}:xrf", data.model_dump_json()) - - def clear_mark_beam(self): - self.redis.delete(f"{self._bl}:beam_mark") - - def mark_beam(self, x_pxl: float, y_pxl: float, zoom: float): - self.redis.hset( - f"{self._bl}:beam_mark", mapping={f"{zoom}": json.dumps({"x": x_pxl, "y": y_pxl})} - ) - vals = self.redis.hgetall(f"{self._bl}:beam_mark") - - if len(vals) >= 3: # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - zooms = [] - x_pxls = [] - y_pxls = [] - for k, v in vals.items(): # pyright: ignore[reportArgumentType,reportAttributeAccessIssue] # using sync client - remove ignore on upgrade to redis v8 - zooms.append(float(k)) - x_pxls.append(float(json.loads(v)["x"])) - y_pxls.append(float(json.loads(v)["y"])) - - model = BeamMarkCoeffModel( - coeff_x=tuple(np.polyfit(zooms, x_pxls, deg=2)), - coeff_y=tuple(np.polyfit(zooms, y_pxls, deg=2)), - ) - self.beam_mark_coeff = model - - def get_beam_mark(self, zoom: float) -> tuple[float, float]: - model = self.beam_mark_coeff - x_pxl = np.polyval(model.coeff_x, zoom) - y_pxl = np.polyval(model.coeff_y, zoom) - return float(x_pxl), float(y_pxl) - - @property - def crystal_size(self) -> CrystalSize: - tmp = self.redis.get(f"{self._bl}:crystal_size") - if tmp is None: - return CrystalSize(x=0, y=0, z=0) - data_dict = json.loads(tmp) - return CrystalSize(**data_dict) - - @crystal_size.setter - def crystal_size(self, xtal_size: CrystalSize): - self.redis.set(f"{self._bl}:crystal_size", xtal_size.model_dump_json()) - - @property - def last_best_res(self) -> float | None: - tmp = self.redis.get(f"{self._bl}:last_best_res") - if tmp is None: - return None - return float(tmp) - - @last_best_res.setter - def last_best_res(self, best_res: float | None): - if best_res is None: - self.redis.delete(f"{self._bl}:last_best_res") - else: - self.redis.set(f"{self._bl}:last_best_res", best_res) - - @property - def last_best_b_factor(self) -> float | None: - tmp = self.redis.get(f"{self._bl}:last_best_b_factor") - if tmp is None: - return None - return float(tmp) - - @last_best_b_factor.setter - def last_best_b_factor(self, last_best_b_factor: float | None): - if last_best_b_factor is None: - self.redis.delete(f"{self._bl}:last_best_b_factor") - else: - self.redis.set(f"{self._bl}:last_best_b_factor", last_best_b_factor) - - def _mount_failure_streak_key(self) -> str: - return f"{self._bl}:mount_fail_count" - - def get_mount_failure_streak(self) -> int: - value = self.redis.get(self._mount_failure_streak_key()) - return int(value) if value else 0 # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - - def increment_mount_failure_streak(self) -> int: - return int(self.redis.incr(self._mount_failure_streak_key())) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - - def reset_mount_failure_streak(self) -> None: - self.redis.delete(self._mount_failure_streak_key()) - - def get_mount_fail_count(self) -> int: - return self.get_mount_failure_streak() - - def record_mount_failure(self) -> int: - return self.increment_mount_failure_streak() - - def record_mount_success(self): - self.reset_mount_failure_streak() - - @property - def simple_input_parameters(self) -> SimpleStrategyInputModel | None: - tmp = self.redis.get(f"{self._bl}:simple_input_params") - if tmp is None: - return None - data_dict = json.loads(tmp) - return SimpleStrategyInputModel(**data_dict) - - @simple_input_parameters.setter - def simple_input_parameters(self, input_params: SimpleStrategyInputModel | None): - if input_params is None: - self.redis.delete(f"{self._bl}:simple_input_params") - else: - self.redis.set(f"{self._bl}:simple_input_params", input_params.model_dump_json()) - - @property - def auto_params(self) -> SimpleScanParameters | None: - tmp = self.redis.get(f"{self._bl}:auto_params") - if tmp is None: - logger.debug(f"auto_params missing in redis key {self._bl}:auto_params") - return None - try: - data_dict = json.loads(tmp) - return SimpleScanParameters(**data_dict) - except Exception: - logger.exception(f"failed to parse auto_params from redis; raw={tmp}") - return None - - @auto_params.setter - def auto_params(self, params: SimpleScanParameters | None): - if params is None: - self.redis.delete(f"{self._bl}:auto_params") - else: - self.redis.set(f"{self._bl}:auto_params", params.model_dump_json()) - - def _automation_progress_key(self) -> str: - return f"{self._bl}:automation_progress" - - def _automation_progress_seq_key(self) -> str: - return f"{self._bl}:automation_progress_seq" - - def reset_automation_progress(self) -> None: - self.redis.set(self._automation_progress_seq_key(), 0) - self.redis.delete(self._automation_progress_key()) - - def get_automation_progress_state(self) -> dict[str, Any]: - seq_raw = self.redis.get(self._automation_progress_seq_key()) - payload_raw = self.redis.get(self._automation_progress_key()) - - seq = int(seq_raw) if seq_raw is not None else 0 # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - progress = json.loads(payload_raw) if payload_raw else None # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - - return {"seq": seq, "progress": progress} - - def set_automation_progress_state( - self, progress: AutomationProgress | dict[str, Any] - ) -> dict[str, Any]: - def _json_default(value): - if isinstance(value, datetime): - return value.isoformat() - raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable") - - if isinstance(progress, dict): - payload = dict(progress) - elif hasattr(progress, "model_dump"): - payload = progress.model_dump() - elif is_dataclass(progress): - payload = asdict(progress) - else: - raise TypeError(f"Unsupported automation progress type: {type(progress).__name__}") - - next_seq = int(self.redis.incr(self._automation_progress_seq_key())) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - self.redis.set( - self._automation_progress_key(), - json.dumps(payload, separators=(",", ":"), default=_json_default), - ) - - return {"seq": next_seq, "progress": payload} - - @property - def failed_mount_count(self) -> int: - tmp = self.redis.get(f"{self._bl}:failed_mount_count") - if tmp is None: - return 0 - try: - return int(tmp) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - except (TypeError, ValueError): - logger.warning( - "Failed Mount Count is not an integer, resetting to 0.", - extra={"beamline": self._bl, "tmp": tmp}, - ) - return 0 - - @failed_mount_count.setter - def failed_mount_count(self, count: int): - if count == 0: - self.redis.delete(f"{self._bl}:failed_mount_count") - else: - self.redis.set(f"{self._bl}:failed_mount_count", count) - - def increment_failed_mount_count(self) -> int: - return int(self.redis.incr(f"{self._bl}:failed_mount_count")) # pyright: ignore[reportArgumentType] # using sync client - remove ignore on upgrade to redis v8 - - def _runtime_sim_key(self, name: str) -> str: - return f"{self._bl}:runtime:simulate:{name}" - - def get_runtime_simulated(self, name: str, default: bool = False) -> bool: - raw = self.redis.get(self._runtime_sim_key(name)) - if raw is None: - return default - return str(raw).strip().lower() in {"1", "true", "yes", "on"} - - def set_runtime_simulated(self, name: str, enabled: bool) -> None: - key = self._runtime_sim_key(name) - if enabled: - self.redis.set(key, "1") - else: - self.redis.delete(key) - - @property - def simulate_bec(self) -> bool: - return self.get_runtime_simulated("bec", default=False) - - @simulate_bec.setter - def simulate_bec(self, enabled: bool) -> None: - self.set_runtime_simulated("bec", enabled) - - @property - def simulate_tell(self) -> bool: - return self.get_runtime_simulated("tell", default=False) - - @simulate_tell.setter - def simulate_tell(self, enabled: bool) -> None: - self.set_runtime_simulated("tell", enabled) - - @property - def simulate_aerotech(self) -> bool: - return self.get_runtime_simulated("aerotech", default=False) - - @simulate_aerotech.setter - def simulate_aerotech(self, enabled: bool) -> None: - self.set_runtime_simulated("aerotech", enabled) - - @property - def simulate_smargon(self) -> bool: - return self.get_runtime_simulated("smargon", default=False) - - @simulate_smargon.setter - def simulate_smargon(self, enabled: bool) -> None: - self.set_runtime_simulated("smargon", enabled) - - @property - def runtime_simulation_state(self) -> dict[str, bool]: - return { - "bec": self.simulate_bec, - "detector": bool(self.simulated_detector), - "tell": self.simulate_tell, - "aerotech": self.simulate_aerotech, - "smargon": self.simulate_smargon, - } - - @staticmethod - def _coerce_optional_float(value) -> float | None: - if value is None: - return None - - if isinstance(value, np.ndarray): - if value.size == 0: - return None - value = value.flatten().tolist() - - if isinstance(value, (list, tuple)): - if len(value) == 0: - return None - value = value[0] - - try: - return float(value) - except (TypeError, ValueError): - logger.warning(f"Failed to coerce cached numeric value to float: {value!r}") - return None - - def _detector_metadata_key(self) -> str: - return f"{self._bl}:detector_metadata" - - def get_detector_metadata(self) -> dict: - try: - raw = self.redis.get(self._detector_metadata_key()) - if raw in (None, "", b""): - return {} - - if isinstance(raw, bytes): - raw = raw.decode("utf-8") - - payload = json.loads(str(raw)) - return payload if isinstance(payload, dict) else {} - except Exception as e: - logger.warning(f"Failed to read detector metadata from Redis: {e}", exc_info=True) - return {} - - def set_detector_metadata(self, payload: dict[str, Any]) -> dict[str, Any]: - safe_payload = dict(payload or {}) - safe_payload["dtz_low"] = self._coerce_optional_float(safe_payload.get("dtz_low")) - safe_payload["dtz_high"] = self._coerce_optional_float(safe_payload.get("dtz_high")) - safe_payload["pixel_size_mm"] = self._coerce_optional_float( - safe_payload.get("pixel_size_mm") - ) - safe_payload["updated_at"] = datetime.now().isoformat(timespec="seconds") - self.redis.set(self._detector_metadata_key(), json.dumps(safe_payload)) - return safe_payload - - @property - def cached_detector_metadata(self) -> dict[str, Any]: - return self.get_detector_metadata() - - @property - def cached_dtz_low(self) -> float | None: - value = self.get_detector_metadata().get("dtz_low") - return self._coerce_optional_float(value) - - @property - def cached_dtz_high(self) -> float | None: - value = self.get_detector_metadata().get("dtz_high") - return self._coerce_optional_float(value) - - @property - def local_contact_links(self) -> dict[str, str | None]: - detector_frontend = None - smargon_frontend = cfg_get( - "daq.hardware.smargon_frontend_url", - f"http://{self._mxb.name.lower()}-smargopolo.psi.ch:8080/", - ) - aerotech_frontend = cfg_get( - "daq.hardware.aerotech_url", f"http://mx-{self._mxb.name.lower()}-queue-01.psi.ch:5234/" - ) - tell_hint = "Please check TELL status via Remmina / VNC." - - if self._mxb is MXBeamline.X06DA: - detector_frontend = "http://sls-gpu-001:8080/frontend" - elif self._mxb is MXBeamline.X10SA: - detector_frontend = "http://sls-gpu-002:8080/frontend" - elif self._mxb is MXBeamline.SIMULATED: - detector_frontend = None - smargon_frontend = None - aerotech_frontend = None - - return { - "aerotech": aerotech_frontend, - "detector": detector_frontend, - "smargon": smargon_frontend, - "tell_hint": tell_hint, - } - - def get_local_contact_config(self) -> LocalContactConfigModel: - default = LocalContactConfigModel() - - try: - redis_key = f"{self._bl}:local_contact_config" - raw_value = self.redis.get(redis_key) - - if raw_value in (None, "", b""): - return default - - if isinstance(raw_value, bytes): - raw_value = raw_value.decode("utf-8") - - return LocalContactConfigModel.model_validate_json(str(raw_value)) - except Exception as e: - logger.warning(f"Failed to read Local Contact config from Redis: {e}", exc_info=True) - return default - - def set_local_contact_config( - self, config: LocalContactConfigModel | dict - ) -> LocalContactConfigModel: - validated = LocalContactConfigModel.model_validate(config) - try: - redis_key = f"{self._bl}:local_contact_config" - self.redis.set(redis_key, validated.model_dump_json()) - logger.info(f"Saved Local Contact config to Redis: {redis_key}") - except Exception as e: - logger.error(f"Failed to write Local Contact config to Redis: {e}") - raise - - return validated - - @property - def local_contact_config(self) -> LocalContactConfigModel: - return self.get_local_contact_config() - - @local_contact_config.setter - def local_contact_config(self, value: LocalContactConfigModel | dict) -> None: - self.set_local_contact_config(value) - - -if __name__ == "__main__": - from aarecommon.config.beamline import mx_beamline - - cfg = BeamlineConfig(bl=mx_beamline()) - # cfg.allow_non_staff_request_from_staff = True - # fg.abr_meas_pos = AerotechCoordinate(at_mm=Coordinate(x=0.0,y=0.0,z=0.0)) - cfg.dtz_safe_position = 300.0 diff --git a/src/aare/daq/config_model.py b/src/aare/daq/config_model.py deleted file mode 100644 index 3882d5eb..00000000 --- a/src/aare/daq/config_model.py +++ /dev/null @@ -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." - ), - ) diff --git a/src/aare/daq/daq.py b/src/aare/daq/daq.py deleted file mode 100644 index 7c587159..00000000 --- a/src/aare/daq/daq.py +++ /dev/null @@ -1,3308 +0,0 @@ -import copy -import json -import secrets -import time -from collections.abc import Callable -from datetime import UTC, datetime -from pathlib import Path -from typing import Any - -from aarecommon.config.beamline import cfg_get -from aarecommon.config.logger import setup_logger -from aarecommon.config.logger_events import ( - log_timing, - merge_log_context, - raster_request_log_context, - rotation_request_log_context, - sample_log_context, -) -from aarecommon.errors.exception_handler import ( - AareException, - AerotechCommunicationError, - AutoRasterSampleSkipped, - BeamlineBusyException, - BeamlineBusyTimeoutException, - BECCommunicationError, - CriticalTellException, - DataCollectionException, - JFJochCommunicationError, - LoopCenteringFailed, - MagnetPositionSensorError, - MaintenanceStateException, - MountingFailed, - RasterScanException, - SmargonCommunicationError, - StateTransitionFailed, - TellCommunicationError, - TransformationInvalidException, - UnmountingFailed, - WarningTellException, -) -from aarecommon.math.coordinate import AerotechCoordinate, Coordinate, SmargonCoordinate -from aarecommon.math.diffraction_geometry import DiffractionGeometry -from aarecommon.math.find_xtal import CenterOfMassModel -from aarecommon.math.sample_geometry import SampleGeometryModel -from aarecommon.models.automation import ( - AutomationProgress, - StepState, - StepStatus, - WorkflowStateKind, -) -from aarecommon.models.beamline import MXBeamline -from aarecommon.models.models import ( - AutofocusSettings, - BeamlineStatus, - DAQOperation, - DAQStatusModel, - FluorescenceSpectrumOutputModel, - FluorescenceSpectrumParameterModel, - PuckLoadedInfo, - SampleCameraSettings, - SampleShortInfo, - SampleShortInfoList, - SessionStatus, - SimpleScanParameters, - ZoomModeEnum, -) -from aarecommon.models.raster_grid import CompletedRasterGrid, GridScanDecision, RasterGridRequest -from aarecommon.models.rotation_scan import CompletedRotationScan, RotationScanRequest -from aarecommon.models.tell import TellPhaseEnum, TellStateModel -from aareDB import SampleEventType -from jfjoch_client import ScanResult -from redis.lock import Lock as RedisLock - -from aare.beamline_dispatch.protocols import BeamlineDispatch -from aare.daq import workflows -from aare.daq.aaredb import AareWrapper -from aare.daq.config import ABR_POS_MOUNT, BeamlineConfig, BeamlineStateEnum -from aare.daq.config_model import LocalContactConfigModel -from aare.daq.devices import BeamlineDevices -from aare.daq.mlbox import MlBox -from aare.daq.operations.common.ml_bounding_box import get_ml_bounding_box -from aare.daq.operations.common.runtime import DAQRuntimeState -from aare.daq.operations.common.services import ( - DataCollectionPreparer, - FaceDetectionProgressEmitter, - OperationServices, - PredictionProvider, - SampleEventPublisher, - ScanIngestionService, - StateController, - TraceWriter, -) -from aare.daq.operations.common.simulate_scan_result import build_fake_rotation_result -from aare.daq.operations.face_detection import ( - FaceDetectionContext, - FaceDetectionResult, - FaceDetectionService, -) -from aare.daq.operations.face_detection.models import ( - FaceDetectionDependencies, - FaceDetectionSettings, -) -from aare.daq.operations.loop_centering import LoopCenteringContext, LoopCenteringService -from aare.daq.operations.loop_centering.models import ( - LoopCenteringDependencies, - LoopCenteringSettings, -) -from aare.daq.operations.mounting.models import ( - MountingContext, - MountingDependencies, - MountingResult, - MountingSettings, -) -from aare.daq.operations.mounting.service import MountingService -from aare.daq.operations.raster.models import RasterContext, RasterDependencies, RasterSettings -from aare.daq.operations.raster.service import RasterService -from aare.daq.operations.rotation.models import ( - RotationContext, - RotationDependencies, - RotationSettings, -) -from aare.daq.operations.rotation.service import RotationService -from aare.daq.operations.screenshot.service import ScreenshotService -from aare.devices.area_detector import AutoEnum -from aare.devices.jfjoch import JFJochWrapper - -logger = setup_logger("aareDAQ") - - -class _DAQSampleProvider: - def __init__(self, daq: "AareDAQ"): - self._daq = daq - - @property - def sample(self) -> SampleShortInfo | None: - return self._daq.sample - - -class _DAQSampleGeometryProvider: - def __init__(self, daq: "AareDAQ"): - self._daq = daq - - @property - def sample_geometry(self) -> SampleGeometryModel: - return self._daq.sample_geometry - - -class _DAQNonCriticalRunner: - def __init__(self, daq: "AareDAQ"): - self._daq = daq - - def __call__( - self, action, *, description: str, sample: SampleShortInfo | None = None - ) -> object | None: - return self._daq._run_noncritical(action, description=description, sample=sample) - - -class _DAQScreenshotSampleProvider: - def __init__(self, daq: "AareDAQ"): - self._daq = daq - - @property - def sample(self) -> SampleShortInfo | None: - return self._daq.sample - - -class _DAQPGroupProvider: - def __init__(self, daq: "AareDAQ"): - self._daq = daq - - @property - def pgroup(self) -> str | None: - return self._daq._cfg.pgroup - - -class _DAQStatusProvider: - def __init__(self, daq: "AareDAQ"): - self._daq = daq - - @property - def status(self) -> DAQStatusModel: - return self._daq.status - - -class _DAQStateSetter: - def __init__(self, daq: "AareDAQ"): - self._daq = daq - - def set_state(self, target: BeamlineStateEnum) -> None: - self._daq._set_state(target) - - -class _DAQTraceAppender: - def __init__(self, daq: "AareDAQ"): - self._daq = daq - - def append_smargon_trace(self, *, sample_id: int | None, event: str) -> None: - self._daq._append_smargon_trace(sample_id=sample_id, event=event) - - -class _DAQSampleEventSender: - def __init__(self, daq: "AareDAQ"): - self._daq = daq - - def send_sample_event(self, sample_id: int, event_type, comment: str | None = None) -> None: - self._daq._aare.send_sample_event(sample_id, event_type, comment) - - -class _DAQScanIngestor: - def __init__(self, daq: "AareDAQ"): - self._daq = daq - - def ingest_scan(self, *, sample, result, geom, beam_mark_pxl) -> None: - self._daq._aare.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._daq._aare.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, - ) - - -class _DAQDatacollectionSetupRunner: - def __init__(self, daq: "AareDAQ"): - self._daq = daq - - def prepare(self, request, screening: bool = False) -> None: - self._daq._setup_datacollection(request=request, screening=screening) - - -class _LoopCenteringPredictionGetter: - def __init__(self, daq: "AareDAQ", settings: LoopCenteringSettings): - self._daq = daq - self._settings = settings - - def get_predictions(self): - return self._daq._mlbox.predict_all_best( - overlap_with_pin=self._settings.overlap_with_pin, - confidence_min=self._settings.confidence_min, - return_image=True, - return_bundle_meta=True, - ) - - -class _FaceDetectionProgressReporter: - def __init__(self, daq: "AareDAQ"): - self._daq = daq - - def emit_progress(self, payload: dict) -> None: - self._daq._emit_face_detection_progress(payload) - - -class AareDAQ: - """ - Main Data Acquisition class for the Aare system. - - This class orchestrates interactions between various beamline devices, - the Aare database, ML services, and data collection workflows. - """ - - MIN_SPOTS_LOW_RES_THRESHOLD = 10.0 - AUTOMATION_BUSY_TIMEOUT_S = 600 - MANUAL_RASTER_BUSY_TIMEOUT_S = 600 - AUTO_RASTER_MAX_IMAGES = 4500 - AUTO_RASTER_MIN_CELL_SIZE_MM = 0.005 - AUTO_RASTER_SKIP_IF_EXCEED_MAX_IMAGE_THRESHOLD = True - - def __init__( - self, cfg: BeamlineConfig, bl: MXBeamline, dispatch: BeamlineDispatch, hw_lock: RedisLock - ): - self._hw_lock = hw_lock - self.last_time = 0.0 - self._dispatch = dispatch - self._cfg = cfg - self._devs = BeamlineDevices(bl, dispatch, cfg) - self._mlbox = MlBox(bl) - self._jfjoch = JFJochWrapper(bl) - self._bl = bl.value.upper() - self._beamline = bl - self._aare = AareWrapper(bl) - self._saved_box = None - self._smargon_trace_path = Path("/sls/mx/applications/logs") / "smargon_trace.csv" - self._face_detection_progress_cb: Callable[[dict], None] | None = None - self._automation_progress_cb: Callable[[AutomationProgress], None] | None = None - self._last_sample_sync_ts = 0.0 - self._sample_sync_min_interval_s = 2.0 - self._automation_completed_samples = 0 - self._automation_total_sample_time_s = 0.0 - self._automation_last_sample_name = "" - self._automation_samples_in_queue = 0 - self._last_mount_error_message = "" - - self._screenshot_service = ScreenshotService( - mlbox=self._mlbox, - aare=self._aare, - logger=logger, - run_noncritical=_DAQNonCriticalRunner(self), - sample_provider=_DAQScreenshotSampleProvider(self), - pgroup_provider=_DAQPGroupProvider(self), - ) - - @property - def busy(self) -> bool: - return self._hw_lock.locked() - - def shutdown(self): - self._devs.bec_worker.shutdown() - - def _cached_detector_metadata(self) -> dict[str, Any]: - return self._cfg.cached_detector_metadata - - def refresh_detector_metadata_cache(self) -> dict[str, Any]: - det_cfg = self._jfjoch.detector() - dtz_low = self._cfg._coerce_optional_float(self._devs.dtz_low) - dtz_high = self._cfg._coerce_optional_float(self._devs.dtz_high) - - payload = self._cfg.set_detector_metadata( - { - "detector_description": det_cfg.description, - "detector_serial_number": det_cfg.serial_number, - "detector_width": det_cfg.width, - "detector_height": det_cfg.height, - "pixel_size_mm": det_cfg.pixel_size_mm, - "dtz_low": dtz_low, - "dtz_high": dtz_high, - } - ) - logger.info( - "Refreshed hardware metadata cache", - extra={ - "detector_description": payload.get("detector_description"), - "detector_serial_number": payload.get("detector_serial_number"), - "dtz_low": payload.get("dtz_low"), - "dtz_high": payload.get("dtz_high"), - }, - ) - return payload - - def get_runtime_simulation_state(self) -> dict[str, bool]: - return self._cfg.runtime_simulation_state - - def get_local_contact_links(self) -> dict[str, str | None]: - return self._cfg.local_contact_links - - def get_local_contact_device_state(self) -> dict[str, dict[str, str | bool | None]]: - status = self.status - sim = self.get_runtime_simulation_state() - - return { - "bec": {"mode": "simulated" if sim.get("bec") else "live", "error": None}, - "detector": {"mode": "simulated" if sim.get("detector") else "live", "error": None}, - "tell": { - "mode": "simulated" if sim.get("tell") else "live", - "error": getattr(status, "tell_error", None), - }, - "aerotech": { - "mode": "simulated" if sim.get("aerotech") else "live", - "error": getattr(status, "aerotech_error", None), - }, - "smargon": { - "mode": "simulated" if sim.get("smargon") else "live", - "error": getattr(status, "smargon_error", None), - }, - } - - def read_current_state_from_bec(self): - return self._devs.read_current_state_from_bec() - - def restart_bec_worker(self) -> dict[str, object]: - self._devs.restart_bec_worker(simulated=self._cfg.simulate_bec) - return {"ok": True, "device": "bec", "simulated": self._cfg.simulate_bec} - - def restart_detector(self) -> dict[str, object]: - beamline = MXBeamline.SIMULATED if self._cfg.simulated_detector else self._beamline - logger.info(f"Restarting JFJoch wrapper with simulated={self._cfg.simulated_detector}") - self._jfjoch = JFJochWrapper(beamline) - return {"ok": True, "device": "detector", "simulated": bool(self._cfg.simulated_detector)} - - def restart_tell(self) -> dict[str, object]: - self._devs.restart_tell(simulated=self._cfg.simulate_tell) - return {"ok": True, "device": "tell", "simulated": self._cfg.simulate_tell} - - def restart_aerotech(self) -> dict[str, object]: - self._devs.restart_aerotech(simulated=self._cfg.simulate_aerotech) - return {"ok": True, "device": "aerotech", "simulated": self._cfg.simulate_aerotech} - - def restart_smargon(self) -> dict[str, object]: - self._devs.restart_smargon(simulated=self._cfg.simulate_smargon) - return {"ok": True, "device": "smargon", "simulated": self._cfg.simulate_smargon} - - def set_runtime_simulation(self, device: str, enabled: bool) -> dict[str, object]: - device = str(device).strip().lower() - - if device == "bec": - self._cfg.simulate_bec = enabled - return self.restart_bec_worker() - elif device == "detector": - self._cfg.simulated_detector = enabled - return self.restart_detector() - elif device == "tell": - self._cfg.simulate_tell = enabled - return self.restart_tell() - elif device == "aerotech": - self._cfg.simulate_aerotech = enabled - return self.restart_aerotech() - elif device == "smargon": - self._cfg.simulate_smargon = enabled - return self.restart_smargon() - - raise ValueError( - "Unknown simulation device. Expected one of: bec, detector, tell, aerotech, smargon" - ) - - def _is_hardware_failure(self, error: Exception) -> bool: - return isinstance( - error, - ( - CriticalTellException, - TellCommunicationError, - BECCommunicationError, - SmargonCommunicationError, - AerotechCommunicationError, - JFJochCommunicationError, - MountingFailed, - UnmountingFailed, - MagnetPositionSensorError, - TransformationInvalidException, - StateTransitionFailed, - MaintenanceStateException, - DataCollectionException, - RasterScanException, - ), - ) - - @staticmethod - def _is_jfjoch_detector_state_error(message: str | None) -> bool: - text = str(message or "").lower() - return ( - "daq state error" in text - or "must be idle to start measurement" in text - or "must be idle" in text - ) - - def _raise_if_critical_jfjoch_detector_error(self, error: Exception, *, command: str) -> None: - if not isinstance(error, JFJochCommunicationError): - return - - if getattr(error, "status_code", None) != 500 and not self._is_jfjoch_detector_state_error( - str(error) - ): - return - - message = ( - f"Critical detector error while running JFJoch command '{command}'. " - f"Automation has been stopped. " - f"There is an error with the detector. Please call your local contact. " - f"Original error: {error}" - ) - logger.critical(message) - raise JFJochCommunicationError( - message, - operation=getattr(error, "operation", None), - endpoint=getattr(error, "endpoint", None), - base_url=getattr(error, "base_url", None), - status_code=getattr(error, "status_code", None), - critical=True, - ) from error - - def _raise_if_critical_bec_error(self, error: Exception, *, command: str) -> None: - if not isinstance(error, BECCommunicationError): - return - - message = ( - f"Critical BEC error while running '{command}'. " - f"Automation has been stopped because the beamline state may be inconsistent. " - f"Original error: {error}" - ) - logger.critical(message) - raise BECCommunicationError( - message, - operation=getattr(error, "operation", None), - endpoint=getattr(error, "endpoint", None), - base_url=getattr(error, "base_url", None), - exception=getattr(error, "exception", None), - critical=True, - ) from error - - def _ensure_not_in_maintenance(self, *, context: str) -> None: - if self._cfg.state == BeamlineStateEnum.Maintenance: - raise MaintenanceStateException( - f"Automation cannot continue because beamline is in Maintenance during {context}" - ) - - def _validate_automation_state(self, *, context: str) -> None: - self._ensure_not_in_maintenance(context=context) - if self._cfg.state == BeamlineStateEnum.Moving: - raise StateTransitionFailed( - f"Automation cannot continue because beamline is still in Moving state during {context}" - ) - logger.debug(f"Automation state validated with context: {context}") - - def _run_noncritical( - self, - action: Callable[[], object], - *, - description: str, - sample: SampleShortInfo | None = None, - ) -> object | None: - try: - return action() - except Exception as e: - logger.warning( - f"Non-critical failure during {description}: {e}", - extra={ - "sample_name": getattr(sample, "sample_name", None), - "sample_id": getattr(sample, "db_id", None), - }, - exc_info=True, - ) - return None - - def _run_critical( - self, - action: Callable[[], object], - *, - description: str, - sample: SampleShortInfo | None = None, - ) -> object: - try: - return action() - except Exception as e: - if isinstance(e, WarningTellException): - logger.warning( - f"Non-critical warning during {description}: {e}", - extra={ - "sample_name": getattr(sample, "sample_name", None), - "sample_id": getattr(sample, "db_id", None), - }, - exc_info=True, - ) - return None - raise - - @staticmethod - def _parse_iso_timestamp(value: str | None) -> datetime | None: - if not value: - return None - try: - return datetime.fromisoformat(value) - except ValueError: - return None - - def _get_tell_events_from_redis(self) -> list[dict]: - try: - redis_client = getattr(self._cfg, "_client", None) - beamline_key = getattr(self._cfg, "_bl", None) - - if redis_client is None or beamline_key is None: - return [] - - redis_key = f"{beamline_key}:tell_events" - raw_value = redis_client.get(redis_key) - if raw_value in (None, "", b""): - return [] - - if isinstance(raw_value, bytes): - raw_value = raw_value.decode("utf-8") - - parsed = json.loads(str(raw_value)) - return parsed if isinstance(parsed, list) else [] - except Exception as e: - logger.debug(f"Failed to read tell_events from Redis: {e}", exc_info=True) - return [] - - @staticmethod - def _tell_phase_confirms_previous_sample_unmounted(phase: TellPhaseEnum | None) -> bool: - return phase in { - TellPhaseEnum.OLD_SAMPLE_RETURNED, - TellPhaseEnum.PICKING_NEW_SAMPLE, - TellPhaseEnum.PLACING_NEW_SAMPLE, - TellPhaseEnum.FINALIZING, - TellPhaseEnum.COMPLETE, - } - - def _was_previous_sample_unmounted_since(self, started_at: datetime) -> bool: - tell_state = self._safe_tell_state() - if tell_state is not None: - state_ts = self._parse_iso_timestamp(tell_state.last_update_ts) - if ( - state_ts is not None - and state_ts >= started_at - and tell_state.operation == "mount" - and self._tell_phase_confirms_previous_sample_unmounted(tell_state.phase) - ): - return True - - if ( - ( - tell_state.last_event_class == "Motion Sync" - and tell_state.last_event_value == "Sample put on Puck" - ) - and state_ts is not None - and state_ts >= started_at - ): - return True - - for event in reversed(self._get_tell_events_from_redis()): - if event.get("class") == "Motion Sync" and event.get("event") == "Sample put on Puck": - event_ts = self._parse_iso_timestamp(event.get("timestamp")) - if event_ts is not None and event_ts >= started_at: - return True - - return False - - def set_face_detection_progress_callback(self, cb: Callable[[dict], None] | None) -> None: - self._face_detection_progress_cb = cb - - def set_automation_progress_callback( - self, cb: Callable[[AutomationProgress], None] | None - ) -> None: - self._automation_progress_cb = cb - - def _emit_face_detection_progress(self, payload: dict) -> None: - if self._face_detection_progress_cb is None: - return - try: - self._face_detection_progress_cb(payload) - except Exception as e: - logger.warning(f"Failed to emit face detection progress: {e}", exc_info=True) - - def _emit_automation_progress(self, progress: AutomationProgress) -> None: - if self._automation_progress_cb is None: - return - try: - self._automation_progress_cb(progress) - except Exception as e: - logger.warning(f"Failed to emit automation progress: {e}", exc_info=True) - - def _record_best_effort_step_failure( - self, - *, - progress: AutomationProgress, - step: WorkflowStateKind, - error: Exception, - sample: SampleShortInfo | None, - code: str, - ) -> None: - reason = str(error) - event_context = merge_log_context( - sample_log_context(sample), - { - "step": step.value, - "code": code, - "exception_class": error.__class__.__name__, - "reason": reason, - }, - ) - - self._set_progress_step(progress, step, StepStatus.FAILED, reason) - progress.append_event( - level="WARNING", - code=code, - exception_class=error.__class__.__name__, - message=reason, - sample_id=getattr(sample, "db_id", None), - context=event_context, - ) - logger.warning( - "Best-effort automation step failed; continuing workflow", extra=event_context - ) - - def _new_automation_progress(self) -> AutomationProgress: - return AutomationProgress( - current_step=None, - steps=[ - StepState(step=WorkflowStateKind.MOUNT, status=StepStatus.PENDING), - StepState(step=WorkflowStateKind.LOOP_CENTRE, status=StepStatus.PENDING), - StepState(step=WorkflowStateKind.RASTER, status=StepStatus.PENDING), - StepState(step=WorkflowStateKind.DATA_COLLECTION, status=StepStatus.PENDING), - StepState(step=WorkflowStateKind.FINAL, status=StepStatus.PENDING), - ], - finished=False, - success=None, - samples_in_queue=self._automation_samples_in_queue, - avg_time_per_sample=( - self._automation_total_sample_time_s / self._automation_completed_samples - if self._automation_completed_samples > 0 - else 0.0 - ), - current_sample_name=self._automation_last_sample_name, - ) - - @staticmethod - def _step_display_name(step: WorkflowStateKind) -> str: - labels = { - WorkflowStateKind.MOUNT: "Mount", - WorkflowStateKind.LOOP_CENTRE: "Center", - WorkflowStateKind.RASTER: "Raster", - WorkflowStateKind.DATA_COLLECTION: "Collect", - WorkflowStateKind.FINAL: "Paused/Finished", - } - return labels.get(step, str(step.value)) - - def _get_progress_step( - self, progress: AutomationProgress, step: WorkflowStateKind - ) -> StepState | None: - for item in progress.steps: - if item.step == step: - return item - return None - - def _set_progress_context( - self, - progress: AutomationProgress, - *, - current_sample_name: str | None = None, - samples_in_queue: int | None = None, - ) -> None: - if current_sample_name is not None: - safe_name = str(current_sample_name or "") - progress.current_sample_name = safe_name - self._automation_last_sample_name = safe_name - - if samples_in_queue is not None: - safe_count = max(0, int(samples_in_queue)) - progress.samples_in_queue = safe_count - self._automation_samples_in_queue = safe_count - else: - progress.samples_in_queue = max(0, int(self._automation_samples_in_queue)) - - if self._automation_completed_samples > 0: - progress.avg_time_per_sample = ( - self._automation_total_sample_time_s / self._automation_completed_samples - ) - else: - progress.avg_time_per_sample = 0.0 - - def _record_completed_sample_time(self, progress: AutomationProgress, elapsed_s: float) -> None: - if elapsed_s <= 0: - return - self._automation_completed_samples += 1 - self._automation_total_sample_time_s += float(elapsed_s) - progress.avg_time_per_sample = ( - self._automation_total_sample_time_s / self._automation_completed_samples - ) - - def _set_progress_step( - self, - progress: AutomationProgress, - step: WorkflowStateKind, - status: StepStatus, - message: str = "", - *, - make_current: bool = False, - error_code: str | None = None, - ) -> None: - now = time.time() - - for item in progress.steps: - if item.step == step: - item.status = status - item.message = message - item.error_code = error_code - - if status == StepStatus.RUNNING: - if item.started_at is None: - item.started_at = now - item.completed_at = None - elif status in { - StepStatus.SUCCESS, - StepStatus.FAILED, - StepStatus.SKIPPED, - StepStatus.PAUSED, - }: - if item.started_at is None: - item.started_at = now - item.completed_at = now - break - - if make_current: - progress.current_step = self._step_display_name(step) - - self._emit_automation_progress(progress) - - def _mark_progress_running( - self, progress: AutomationProgress, step: WorkflowStateKind, message: str = "" - ) -> None: - self._set_progress_step(progress, step, StepStatus.RUNNING, message, make_current=True) - - def _mark_progress_success( - self, progress: AutomationProgress, step: WorkflowStateKind, message: str = "" - ) -> None: - self._set_progress_step(progress, step, StepStatus.SUCCESS, message) - - def _mark_progress_failed( - self, progress: AutomationProgress, step: WorkflowStateKind, message: str = "" - ) -> None: - self._set_progress_step( - progress, - step, - StepStatus.FAILED, - message, - make_current=True, - error_code=message or None, - ) - self._set_progress_step( - progress, - WorkflowStateKind.FINAL, - StepStatus.FAILED, - message, - error_code=message or None, - ) - progress.current_step = self._step_display_name(WorkflowStateKind.FINAL) - progress.finished = True - progress.success = False - self._emit_automation_progress(progress) - - def _mark_progress_finished( - self, progress: AutomationProgress, success: bool, message: str = "" - ) -> None: - final_status = StepStatus.SUCCESS if success else StepStatus.FAILED - self._set_progress_step(progress, WorkflowStateKind.FINAL, final_status, message) - progress.current_step = self._step_display_name(WorkflowStateKind.FINAL) - progress.finished = True - progress.success = success - self._emit_automation_progress(progress) - - # -------------------------------------------- - # Operation Services - # -------------------------------------------- - - def _build_runtime_state(self) -> DAQRuntimeState: - return DAQRuntimeState( - sample_provider=_DAQSampleProvider(self), - sample_geometry_provider=_DAQSampleGeometryProvider(self), - status_provider=_DAQStatusProvider(self), - ) - - def _build_operation_services(self) -> OperationServices: - return OperationServices( - screenshots=self._screenshot_service, - state=StateController(setter=_DAQStateSetter(self)), - traces=TraceWriter(appender=_DAQTraceAppender(self)), - events=SampleEventPublisher(sender=_DAQSampleEventSender(self)), - ingestion=ScanIngestionService(ingestor=_DAQScanIngestor(self)), - datacollection=DataCollectionPreparer(runner=_DAQDatacollectionSetupRunner(self)), - ) - - def _create_loop_centering_settings(self) -> LoopCenteringSettings: - return LoopCenteringSettings() - - def _create_loop_centering_service(self) -> LoopCenteringService: - settings = self._create_loop_centering_settings() - services = self._build_operation_services() - services.predictions = PredictionProvider( - getter=_LoopCenteringPredictionGetter(self, settings) - ) - - return LoopCenteringService( - context=LoopCenteringContext( - deps=LoopCenteringDependencies(cfg=self._cfg, devs=self._devs, mlbox=self._mlbox), - runtime=self._build_runtime_state(), - services=services, - settings=settings, - ), - logger=logger, - ) - - def _create_face_detection_service(self) -> FaceDetectionService: - services = self._build_operation_services() - services.face_detection_progress = FaceDetectionProgressEmitter( - reporter=_FaceDetectionProgressReporter(self) - ) - - return FaceDetectionService( - context=FaceDetectionContext( - deps=FaceDetectionDependencies(cfg=self._cfg, devs=self._devs, mlbox=self._mlbox), - runtime=self._build_runtime_state(), - services=services, - settings=FaceDetectionSettings(), - ), - logger=logger, - ) - - def _create_mounting_service(self) -> MountingService: - return MountingService( - context=MountingContext( - deps=MountingDependencies(cfg=self._cfg, devs=self._devs), - settings=MountingSettings(mount_position=ABR_POS_MOUNT), - ), - logger=logger, - ) - - def _create_raster_service(self) -> RasterService: - return RasterService( - context=RasterContext( - deps=RasterDependencies( - cfg=self._cfg, - devs=self._devs, - mlbox=self._mlbox, - jfjoch=self._jfjoch, - aare=self._aare, - ), - runtime=self._build_runtime_state(), - services=self._build_operation_services(), - settings=RasterSettings( - auto_raster_max_images=self.AUTO_RASTER_MAX_IMAGES, - auto_raster_min_cell_size_mm=self.AUTO_RASTER_MIN_CELL_SIZE_MM, - auto_raster_skip_if_exceed_max_image_threshold=self.AUTO_RASTER_SKIP_IF_EXCEED_MAX_IMAGE_THRESHOLD, - ), - ), - logger=logger, - ) - - def _create_rotation_service(self) -> RotationService: - return RotationService( - context=RotationContext( - deps=RotationDependencies( - cfg=self._cfg, devs=self._devs, jfjoch=self._jfjoch, aare=self._aare - ), - runtime=self._build_runtime_state(), - services=self._build_operation_services(), - settings=RotationSettings(), - ), - logger=logger, - ) - - # -------------------------------------------- - # Operation Handlers - # -------------------------------------------- - # TODO make sure this is implemented currectly - def _handle_operation_error( - self, - operation: DAQOperation, - sample: SampleShortInfo | None, - error: Exception, - event_type: SampleEventType = SampleEventType.FAILED, - additional_comment: str | None = None, - ) -> None: - """ - Centralized databse maessage error handling for all operations. - - Args: - operation: Name of the operation that failed (e.g., "mount", "alc", "raster") - sample: The sample being processed - error: The exception that occurred - event_type: Type of event to send to database - "mount", "alc", "axc", or "generic" - """ - sample_name = getattr(sample, "sample_name", None) - sample_id = getattr(sample, "db_id", None) - - logger.exception( - f"Operation {operation.value} failed with error {error}", - extra={ - "operation": operation.value, - "event_type": str(event_type), - "sample_name": sample_name, - "sample_id": sample_id, - "additional_comment": additional_comment, - }, - ) - logger.warning("cleaning up detector state after failed operation...") - try: - self._jfjoch.cancel() - except JFJochCommunicationError as e: - logger.error(f"Failure sending cancellation to jfjoch: {e}") - - if sample is None or sample_id is None: - logger.error(f"Error in {operation.value}: {error}") - return - - comment = f"Error in {operation.value}: {error}" - if additional_comment is not None: - comment += f" Additional comment: {additional_comment}" - - try: - self._aare.send_sample_event( - sample_id=sample_id, event_type=event_type, comment=comment - ) - except Exception: - logger.exception( - "Failed to report operation error to database", - extra={ - "operation": operation.value, - "sample_name": sample_name, - "sample_id": sample_id, - }, - ) - - # todo make sure these functions are correctly implemented! - # Operation handlers should handle database communication and beamline state changes, - # where possible/between operations. For example in raster, we may use XtalSnapshot to take a screenshot, then - # return to Datacollection. - # Busy stats are handled by the public function call i.e. sample() or by automation i.e. measure() - def _execute_mount_and_prepare(self, sample: SampleShortInfo | None) -> bool: - """ - Operation handler for executing mounting and take screenshot. - - Returns: - True if successful, False otherwise - """ - previous_sample = None - mount_started_at = datetime.now(UTC) - self._last_mount_error_message = "" - logger.info("clearing statistics for previous sample") - self._cfg.last_best_res = None - self._cfg.last_best_b_factor = None - try: - previous_sample = self.sample - if previous_sample is None or previous_sample.db_id is None: - try: - previous_sample = self.sync_current_sample_from_tell( - force=True, clear_cached_on_empty=False - ) - except Exception as sync_error: - logger.warning( - f"Failed to reconcile previous sample from TELL before mount: {sync_error}", - exc_info=True, - ) - - if previous_sample is not None and previous_sample.db_id is not None: - self._aare.send_sample_event(previous_sample.db_id, SampleEventType.UNMOUNTING) - - self._set_state(BeamlineStateEnum.RobotSampleExchange) - - if sample is not None and sample.db_id is not None: - self._aare.send_sample_event(sample.db_id, SampleEventType.MOUNTING) - - self._devs.tell.blower_on() - mounting_result: MountingResult = self._create_mounting_service().execute(target=sample) - - if not mounting_result.success: - raise mounting_result.error or MountingFailed( - mounting_result.comment or "Mount failed" - ) - - previous_sample = mounting_result.previous_sample or previous_sample - mounted_sample = mounting_result.mounted_sample or sample - - if ( - mounting_result.did_unmount_previous - and previous_sample is not None - and previous_sample.db_id is not None - ): - self._aare.send_sample_event(previous_sample.db_id, SampleEventType.UNMOUNTED) - - self._set_state(BeamlineStateEnum.SampleAlignment) - - if mounted_sample is not None and mounted_sample.db_id is not None: - self._aare.send_sample_event(mounted_sample.db_id, SampleEventType.MOUNTED) - self.save_screenshot_db(mounted_sample.db_id, f"{mounted_sample.db_id}_mounted") - - return True - - except TransformationInvalidException as e: - self._last_mount_error_message = str(e) or "Mount failed" - logger.error(f"Mount failed due to invalid transformation: {e}") - self._handle_operation_error( - operation=DAQOperation.MOUNT if sample is not None else DAQOperation.UNMOUNT, - sample=sample, - error=e, - event_type=SampleEventType.MOUNTFAILED, - ) - raise - - except TellCommunicationError as e: - self._last_mount_error_message = str(e) or "Mount failed" - logger.error(f"Tell communication error occured: {e}") - self._handle_operation_error( - operation=DAQOperation.MOUNT if sample is not None else DAQOperation.UNMOUNT, - sample=sample, - error=e, - event_type=SampleEventType.MOUNTFAILED, - ) - raise - - except Exception as e: - self._last_mount_error_message = str(e) or "Mount failed" - logger.exception("Mount failed") - - previous_sample_unmounted = ( - previous_sample is not None - and previous_sample.db_id is not None - and self._was_previous_sample_unmounted_since(mount_started_at) - ) - - if previous_sample_unmounted: - logger.info( - "Mount failed after TELL confirmed previous sample was unmounted; " - "marking previous sample as unmounted and clearing cached current_sample" - ) - self._cfg.current_sample = None - self._aare.send_sample_event( - previous_sample.db_id, - SampleEventType.UNMOUNTED, - comment="Auto-unmount succeeded before mount failed", - ) - - try: - self._set_state(BeamlineStateEnum.SampleAlignment) - except Exception: - logger.exception("Failed to set state to SampleAlignment") - finally: - self._handle_operation_error( - operation=DAQOperation.MOUNT if sample is not None else DAQOperation.UNMOUNT, - sample=sample, - error=e, - event_type=SampleEventType.MOUNTFAILED, - ) - - return False - - def _execute_loop_centering(self, sample: SampleShortInfo) -> bool: - """ - Execute loop centering sequence. - - Returns: - True if successful, False otherwise - """ - result = None - additional_comment = None - - if sample is None or sample.db_id is None or sample.db_id < 0: - logger.error("Loop centering failed: no sample provided") - return False - - self._set_state(BeamlineStateEnum.SampleAlignment) - self._devs.lamp_light = 2.5 - - try: - self._aare.send_sample_event(sample.db_id, SampleEventType.CENTERING) - - service = self._create_loop_centering_service() - result = service.run(sample_id=sample.db_id) - - if not result.success: - self._handle_operation_error( - operation=DAQOperation.LOOP_CENTERING, - sample=sample, - error=result.error or Exception("Loop centering failed"), - event_type=SampleEventType.ALCFAILED, - additional_comment=result.comment if result.comment is not None else "", - ) - return False - - self.save_screenshot_db(sample.db_id, "loop_centering") - self._aare.send_sample_event(sample.db_id, SampleEventType.CENTERED) - return True - - except Exception as e: - logger.exception("Loop centering failed") - if result is not None and result.error is not None: - additional_comment = result.comment if result.comment is not None else "" - self._handle_operation_error( - operation=DAQOperation.LOOP_CENTERING, - sample=sample, - error=e, - event_type=SampleEventType.ALCFAILED, - additional_comment=additional_comment, - ) - return False - - def _execute_face_detection( - self, - steps: int = 14, - step_size: int = 15, - face_min_ratio: float = 0.3, - report_error: bool = True, - sample: SampleShortInfo | None = None, - ) -> FaceDetectionResult: - """ - Execute face detection sequence through the face detection service. - - Returns: - FaceDetectionResult - """ - self._set_state(BeamlineStateEnum.SampleAlignment) - result: FaceDetectionResult | None = None - - try: - if sample is None: - try: - sample = self.sample - logger.debug(f"No sample provided, using current sample from DAQ {sample}") - except Exception: - logger.exception("Failed to get current sample") - sample = None - - aare = getattr(self, "_aare", None) - if aare is not None and sample is not None and sample.db_id is not None: - aare.send_sample_event(sample.db_id, SampleEventType.LOOPFACEDETECTING) - - result = self._create_face_detection_service().run( - steps=steps, step_size=step_size, face_min_ratio=face_min_ratio - ) - - if not result.success: - if report_error: - self._handle_operation_error( - operation=DAQOperation.FACE_CENTERING, - sample=sample, - error=result.error or Exception("Face detection failed"), - event_type=SampleEventType.LOOPFACEDETECTFAILED, - additional_comment=result.comment, - ) - return result - - if aare is not None: - aare.send_sample_event(sample.db_id, SampleEventType.LOOPFACEDETECTED) - return result - - except Exception as e: - logger.exception("Face detection failed") - additional_comment = f"{e}" if e is not None else "" - - try: - sample = self.sample - except Exception: - logger.debug("Could not read the current sample for face detection", exc_info=True) - sample = None - - if report_error: - self._handle_operation_error( - operation=DAQOperation.FACE_CENTERING, - sample=sample, - error=e, - event_type=SampleEventType.LOOPFACEDETECTFAILED, - additional_comment=additional_comment, - ) - - payload = ( - result.payload - if result is not None - else {"running": False, "samples": [], "height_fit": {}, "area_fit": {}} - ) - return FaceDetectionResult( - success=False, payload=payload, error=e, comment=additional_comment - ) - - def _validate_grid_params(self, request: RasterGridRequest): - self._devs.aerotech.validate_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_sec=request.exp_time_s, - ) - - def _execute_raster_sequence( - self, grid_request: RasterGridRequest, auto_center: bool = False - ) -> CompletedRasterGrid | None: - """ - Execute raster scan with optional auto-centering. - - Args: - grid_request: Raster grid parameters - auto_center: If True, use auto-centering; if False, use direct raster - - Returns: - CompletedRasterGrid result or None if failed - """ - if self.sample is None: - raise RasterScanException( - "Please load a sample before running a raster scan. If you have manually mounted a sample, create its record in the 'Manual sample' panel." - ) - try: - logger.info( - "Starting raster sequence", - extra=merge_log_context( - sample_log_context(self.sample), - raster_request_log_context(grid_request), - {"auto_center": auto_center}, - ), - ) - - raster_service = self._create_raster_service() - - if auto_center: - self.zoom = 300 - setup_request = copy.deepcopy(grid_request) - setup_request.smargon_top_left = None - self._setup_datacollection(request=setup_request) - result = raster_service.execute_auto_center(grid_request) - if result is None: - logger.error( - "Raster sequence returned no result after auto-centering", - extra=merge_log_context( - sample_log_context(self.sample), - raster_request_log_context(grid_request), - ), - ) - else: - # Resolve + validate the requested dtz (sets cfg.dtz, requires - # request.dtz) BEFORE configuring JFJoch, so JFJoch receives the - # commanded target rather than the live, still-in-transit position. - self._setup_datacollection(request=grid_request) - logger.debug(f"Is detector simulated? {self._cfg.simulated_detector}") - if not self._cfg.simulated_detector: - logger.info("initialise detector for raster") - status = self.status - self._jfjoch.measure_raster(grid_request, status) - logger.info("detector initialised") - else: - logger.info("Simulated detector mode enabled; using fake raster result.") - - self._set_state(BeamlineStateEnum.DataCollection) - raster_result = raster_service.execute(grid_request) - result = CompletedRasterGrid(r=[raster_result]) - self._set_state(BeamlineStateEnum.SampleAlignment) - - if result is not None: - logger.info( - "Raster sequence completed", - extra=merge_log_context( - sample_log_context(self.sample), - raster_request_log_context(grid_request), - { - "auto_center": auto_center, - "result_count": len(result.r) - if hasattr(result, "r") and result.r is not None - else None, - }, - ), - ) - else: - if self.sample is not None and self.sample.db_id is not None: - self._aare.send_sample_event(self.sample.db_id, SampleEventType.RASTERINGFAILED) - logger.error( - "Raster sequence returned no result", - extra=merge_log_context( - sample_log_context(self.sample), raster_request_log_context(grid_request) - ), - ) - return result - - except JFJochCommunicationError as e: - logger.exception( - "Raster sequence failed due to JFJoch communication error", - extra=merge_log_context( - sample_log_context(self.sample), raster_request_log_context(grid_request) - ), - ) - self._handle_operation_error( - operation=DAQOperation.RASTER, - sample=self.sample, - error=e, - event_type=SampleEventType.RASTERINGFAILED, - additional_comment=f"JFJoch communication error: {e}", - ) - raise - - except BeamlineBusyTimeoutException as e: - logger.exception( - "Raster sequence failed because the beamline busy state timed out", - extra=merge_log_context( - sample_log_context(self.sample), - raster_request_log_context(grid_request), - {"auto_center": auto_center}, - ), - ) - self._handle_operation_error( - operation=DAQOperation.RASTER, - sample=self.sample, - error=e, - event_type=SampleEventType.RASTERINGFAILED, - additional_comment=( - "Beamline busy timeout during raster sequence. " - "The operation exceeded the configured busy-state TTL." - ), - ) - raise - - except AutoRasterSampleSkipped: - raise - - except Exception as e: - logger.exception( - "Raster sequence failed", - extra=merge_log_context( - sample_log_context(self.sample), - raster_request_log_context(grid_request), - {"auto_center": auto_center}, - ), - ) - self._handle_operation_error( - operation=DAQOperation.RASTER, - sample=self.sample, - error=e, - event_type=SampleEventType.RASTERINGFAILED, - additional_comment=f"Raster sequence failed: {e}", - ) - return None - - def _validate_rotation_params(self, request: RotationScanRequest): - total_time = request.exp_time_s * request.steps - logger.debug("Validating rotation parameters with AareScan") - if request.screening: - if request.wedge_omega_deg is None: - raise ValueError("Must supply a wedge angle for screening requests") - self._devs.aerotech.validate_screening_scan( - rotation_deg=request.incr_omega_deg, - wedge_deg=request.wedge_omega_deg, - time_sec=total_time, - steps=request.steps, - run_async=True, - ) - else: - self._devs.aerotech.validate_rotation_scan( - rotation_deg=request.steps * request.incr_omega_deg, - time_sec=total_time, - start_pos_deg=request.start_omega_deg, - run_async=True, - ) - - def _execute_rotation_sequence( - self, rotation_request: RotationScanRequest - ) -> CompletedRotationScan | None: - """ - Execute rotation scan. - - Args: - rotation_request: Rotation scan parameters - - Returns: - CompletedRotationScan result or None if failed - """ - min_exp_time = 0.0011 - if rotation_request.exp_time_s < min_exp_time: - logger.warning(f"Exposure shorter than default of {min_exp_time} s! Adjusting.") - rotation_request.exp_time_s = min_exp_time - try: - self._validate_rotation_params(rotation_request) - return self._create_rotation_service().run(rotation_request) - except JFJochCommunicationError as e: - logger.error(f"Rotation sequence failed due to JFJoch Communication error: {e}") - self._handle_operation_error( - operation=DAQOperation.ROTATION, - sample=self.sample, - error=e, - event_type=SampleEventType.COLLECTIONFAILED, - additional_comment=f"JFJoch communication error: {e}", - ) - raise - except Exception as e: - logger.error(f"Rotation sequence failed: {e}") - self._handle_operation_error( - operation=DAQOperation.ROTATION, - sample=self.sample, - error=e, - event_type=SampleEventType.COLLECTIONFAILED, - ) - raise - - def _append_smargon_trace(self, *, sample_id: int | None, event: str) -> None: - try: - path = self._smargon_trace_path - path.parent.mkdir(parents=True, exist_ok=True) - - is_new_file = not path.exists() or path.stat().st_size == 0 - pos = self.smargon - sh = pos.sh_mm - - with path.open("a", encoding="utf-8", buffering=1) as f: - if is_new_file: - f.write( - "timestamp,event,sample_id,omega_deg,zoom," - "shx_mm,shy_mm,shz_mm,phi_deg,chi_deg\n" - ) - - f.write( - f"{datetime.now().isoformat(timespec='milliseconds')}," - f"{event}," - f"{'' if sample_id is None else sample_id}," - f"{self.omega:.3f}," - f"{self.zoom:.3f}," - f"{sh.x:.5f}," - f"{sh.y:.5f}," - f"{sh.z:.5f}," - f"{pos.phi_deg:.5f}," - f"{pos.chi_deg:.5f}\n" - ) - f.flush() - - except Exception as e: - logger.warning(f"Failed to append smargon trace: {e}", exc_info=True) - - def _sample_matches_mounted_address( - self, sample: SampleShortInfo | None, mounted_address - ) -> bool: - if sample is None or sample.location is None or mounted_address is None: - return False - return ( - sample.location.segment == mounted_address.puck.segment - and sample.location.pos == mounted_address.puck.pos - and sample.pin == mounted_address.pin - ) - - def _find_sample_by_mounted_address(self, mounted_address) -> SampleShortInfo | None: - for sample in self._cfg.spreadsheet.s: - if self._sample_matches_mounted_address(sample, mounted_address): - return sample - - for sample in self._cfg.reference_tools.s: - if self._sample_matches_mounted_address(sample, mounted_address): - return sample - - return None - - def _placeholder_sample_from_mounted_address(self, mounted_address) -> SampleShortInfo: - return SampleShortInfo( - db_id=-1, - puck_name="", - dewar_name="", - sample_name=f"Mounted sample {mounted_address.puck.segment}{mounted_address.puck.pos}-{mounted_address.pin}", - run_number=0, - user="", - pin=mounted_address.pin, - location=mounted_address.puck, - ) - - @staticmethod - def _sample_mount_display_name(sample: SampleShortInfo | None) -> str: - if sample is None: - return "current sample" - - sample_name = str(getattr(sample, "sample_name", "") or "").strip() - if sample_name: - return sample_name - - return "sample" - - def sync_current_sample_from_tell( - self, force: bool = False, clear_cached_on_empty: bool = True - ) -> SampleShortInfo | None: - current_sample = self._cfg.current_sample - - if current_sample is not None and current_sample.location is None: - return current_sample - - now = time.monotonic() - if not force and (now - self._last_sample_sync_ts) < self._sample_sync_min_interval_s: - return current_sample - - self._last_sample_sync_ts = now - mounted_address = self._devs.tell.get_mounted_sample() - - if mounted_address is None: - if current_sample is not None and current_sample.location is not None: - if clear_cached_on_empty: - logger.warning("TELL reports no mounted sample; clearing cached current_sample") - self._cfg.current_sample = None - else: - logger.warning( - "TELL reports no mounted sample; keeping cached current_sample to avoid losing context" - ) - return self._cfg.current_sample - - if self._sample_matches_mounted_address(current_sample, mounted_address): - return current_sample - - resolved_sample = self._find_sample_by_mounted_address(mounted_address) - if resolved_sample is None: - resolved_sample = self._placeholder_sample_from_mounted_address(mounted_address) - logger.warning( - "Mounted sample from TELL was not found in known sample lists; using placeholder", - extra={"mounted_address": str(mounted_address)}, - ) - else: - logger.info( - f"Reconciled cached sample from TELL to {resolved_sample.sample_name}", - extra={"db_id": resolved_sample.db_id}, - ) - - self._cfg.current_sample = resolved_sample - return resolved_sample - - @property - def state(self) -> BeamlineStateEnum: - return self._cfg.state - - @state.setter - def state(self, target: BeamlineStateEnum): - if target == BeamlineStateEnum.Moving: - logger.error( - "Cannot explicitly move to busy state", - extra={"target": target, "state": self._cfg.state}, - ) - raise RuntimeError("Cannot explicitly move to busy state") - - start = time.perf_counter() - self._set_state(target) - - end = time.perf_counter() - - self.last_time = end - start - - def _expand_macros(self, name: str) -> str: - name = name.replace("{date}", datetime.now().strftime("%Y%m%d")) - name = name.replace("{sample}", self.sample.sample_name) - name = name.replace("{CrystalName}", self.sample.sample_name) - name = name.replace("{puck}", self.sample.puck_name) - name = name.replace("{position}", f"{self.sample.pin:02d}") - name = name.replace("{sample_id}", f"{self.sample.db_id}") - name = name.replace("{beamline}", f"{self._beamline.value.lower()}") - name = name.replace( - "{prefix}", f"{self.sample.puck_name}/{self.sample.pin:02d}/{self.sample.sample_name}" - ) - # TODO work out why clean_filename is removing slahses - # name = clean_filename(name) - return name - - def spreadsheet_params(self) -> tuple[SimpleScanParameters | None, str | None]: - file_prefix = None - - if self.status.sample is None: - return None, file_prefix - - logger.debug(f"generate params for sample: {self.status.sample}") - aaredb_params = ( - self.status.sample.aaredb_params - if hasattr(self.status.sample, "aaredb_params") - else None - ) - if aaredb_params is None: - return None, file_prefix - - if ( - getattr(aaredb_params, "exposure", None) is None - and getattr(aaredb_params, "transmission", None) is None - and getattr(aaredb_params, "oscillation", None) is None - and getattr(aaredb_params, "totalrange", None) is None - and getattr(aaredb_params, "targetresolution", None) is None - ): - return None, file_prefix - - params = SimpleScanParameters(**self._dispatch.default_rotation_parameters) - - if (exp := getattr(aaredb_params, "exposure", None)) is not None: - params.exp_time_s = exp - - if (trans := getattr(aaredb_params, "transmission", None)) is not None: - params.transmission = trans - - if (res := getattr(aaredb_params, "targetresolution", None)) is not None: - logger.debug(f"resolution: {res}") - logger.debug(f"requested dtz: {self.diffraction_geometry.calc_dtz_mm(res)} ") - new_res = 1 / ((1 / res) + 0.01) - corrected_dtz = self.diffraction_geometry.calc_dtz_mm(new_res) - logger.debug(f"corrected dtz: {corrected_dtz}") - params.dtz = round(corrected_dtz) - - if params.dtz < self._devs.dtz_low: - logger.warning( - f"Detector distance based on desired resolution cannot be reached, using minimum of {self._devs.dtz_low}." - ) - params.dtz = self._devs.dtz_low - - osc = getattr(aaredb_params, "oscillation", None) - total = getattr(aaredb_params, "totalrange", None) - - if osc is not None: - osc = abs(osc) - if osc > 0: - params.incr_omega_deg = osc - if total is not None and abs(total) > 0: - params.steps = round(abs(total) / osc) - else: - params.steps = round(360.0 / osc) - elif total is not None and abs(total) > 0: - default_osc = SimpleScanParameters().incr_omega_deg - params.incr_omega_deg = default_osc - params.steps = round(abs(total) / default_osc) - - return params, file_prefix - - @property - def omega(self) -> float: - return self._devs.aerotech_omega - - def _omega(self, val: float): - self._saved_box = None - logger.info(f"Set omega to {val}") - if -2000 < val < 2000: - try: - self._devs.aerotech_omega = val - except Exception: - logger.exception("Omega move timed out") - else: - logger.error("Omega has to be between -2000 and 2000 degrees") - raise ValueError("Omega has to be between -2000 and 2000 degrees (for now)") - - @omega.setter - def omega(self, val: float): - self._omega(val) - - def omega_rel(self, val: float): - curr_omega = self._devs.aerotech_omega - self._omega(curr_omega + val) - - @property - def zoom(self) -> float: - return self._devs.zoom - - @zoom.setter - def zoom(self, val: float): - self._saved_box = None - # Decide off the beamline STATE (persisted in Redis) so it is robust to - # how/when beam-location was entered, rather than a separate flag that - # must be set exactly on the state transition. - beam_location = self._cfg.state == BeamlineStateEnum.BeamLocation - logger.debug( - f"zoom -> {val} (state={self._cfg.state}, beam_location_presets={beam_location})" - ) - if beam_location: - # Auto-exposure is too dark to see the beam at high zoom, so apply - # the preset per-zoom gain/exposure (interpolated between the stored - # zoom stops). Every other state keeps auto-exposure. - if self._cfg.zoom_mode != ZoomModeEnum.BeamLocation: - self._cfg.zoom_mode = ZoomModeEnum.BeamLocation - self._devs.zoom = val - time.sleep(0.2) - settings = self._cfg.zoom_settings.get_camera_settings(val) - self._devs.samcam_settings = settings - logger.debug( - f"applied beam-location preset for zoom {val}: gain={settings.gain}, exposure={settings.exposure}" - ) - else: - self._devs.samcam_auto(AutoEnum.AUTO) - self._devs.zoom = val - time.sleep(0.2) - self._devs.samcam_auto(AutoEnum.ONCE) - self._cfg.current_zoom_level = val - - def save_beam_location_camera_setting(self) -> None: - """Persist the camera's current gain/exposure for the current zoom as - the beam-location preset (Redis), so it is re-applied on future zooms.""" - zoom_value = self.zoom - settings = self.samcam_settings - self._cfg.save_zoom_camera_setting(zoom_value, settings, mode=ZoomModeEnum.BeamLocation) - logger.info( - f"Saved beam-location camera setting for zoom {zoom_value}: " - f"gain={settings.gain}, exposure={settings.exposure}" - ) - - @property - def front_light(self) -> float: - val = self._devs.lamp_light - if val <= 1.0: - return 0 - elif val >= 2.5: - return 100.0 - else: - return (val - 1.0) / 1.5 * 100.0 - - @front_light.setter - def front_light(self, f: float): - conv = (f / 100.0 * 1.5) + 1.0 - logger.info(f"Light {f} -> {conv}") - self._devs.lamp_light = conv - - @property - def back_light(self) -> float: - val = self._devs.back_light - if val <= 0.0: - return 0.0 - elif val <= 3.0: - return val / 3.0 * 100.0 - else: - return 100.0 - - @back_light.setter - def back_light(self, f: float): - conv = f / 100.0 * 3.0 - logger.info(f"Backlight {f} -> {conv}") - self._devs.back_light = conv - - @property - def sample(self) -> SampleShortInfo | None: - return self._cfg.current_sample - - @property - def samcam_settings(self) -> SampleCameraSettings: - return self._devs.samcam_settings - - @samcam_settings.setter - def samcam_settings(self, s: SampleCameraSettings): - self._devs.samcam_settings = s - - def tweak_abr_meas_pos(self, c: AerotechCoordinate): - new_meas_pos = AerotechCoordinate(at_mm=self._cfg.abr_meas_pos.at_mm + c.at_mm) - self._cfg.abr_meas_pos = new_meas_pos - self._devs.aerotech_pos = new_meas_pos - self._saved_box = None - - def save_abr_meas_pos(self): - self._cfg.abr_meas_pos = AerotechCoordinate(at_mm=self._devs.aerotech_pos.at_mm) - self._devs.bec_worker.save_current_aerotech_position() - - def goto_abr_meas_pos(self): - self._devs.aerotech_pos = self._cfg.abr_meas_pos - - def create_sample(self, target: SampleShortInfo): - curr_sample = self._cfg.current_sample - - if curr_sample is not None and curr_sample.location is not None: - raise RuntimeError("Sample from TELL is loaded") - - self._aare.create_manual_sample(target) - self._cfg.current_sample = target - - def check_tell_mount_start_conditions(self) -> None: - self._devs.tell.validate_mount_start_conditions() - - def _execute_dry(self, park: bool = True, unmount: bool = False): - self._create_mounting_service().dry(park=park, unmount=unmount) - - def park_and_dry(self, park=True): - """External API for dry and park only""" - try: - self._execute_dry(park=park, unmount=False) - except Exception as e: - logger.error(f"Failed to park and dry: {e}") - raise - - def tell_toggle_blower(self): - try: - self._devs.tell.toggle_blower() - except Exception: - logger.exception("Failed to turn off blower") - - def initialise_smargon(self): - try: - self._devs.smargon_initialize() - except Exception as e: - logger.error(f"Failed to initialise Smargon: {e}") - raise - - def initialise_detector(self): - try: - self._jfjoch.initialize() - except Exception as e: - logger.error(f"Failed to initialise detector: {e}") - raise - - def recovery_unmount_sample(self) -> None: - self._set_state(BeamlineStateEnum.RobotSampleExchange) - self._devs.tell.check_enable_motion() - self._devs.tell.wait_not_busy() - self._devs.tell.set_in_mount_position(True) - self._devs.tell.unmount(wait=True, timeout=360.0) - self._cfg.current_sample = None - self._set_state(BeamlineStateEnum.SampleAlignment) - - @sample.setter - def sample(self, target: SampleShortInfo | None): - try: - logger.debug(f"Mount target {target}") - - if target is None: - logger.debug("Unmounting sample") - operation_name = "Unmount" - else: - logger.debug(f"Mounting sample: {target}") - operation_name = "Mount" - - if not self._execute_mount_and_prepare(target): - current_sample = target or self._cfg.current_sample - sample_name = self._sample_mount_display_name(current_sample) - if target is None: - raise UnmountingFailed(f"Failed to {operation_name.lower()} {sample_name}") - raise MountingFailed(f"Failed to {operation_name.lower()} {sample_name}") - - logger.info(f"Sample operation completed: {target}") - - except Exception as e: - logger.debug(f"Failed to change mounted sample: {e}") - raise - - def list_loaded_pucks(self) -> list[PuckLoadedInfo]: - return [] - - def _auto_focus(self, settings: AutofocusSettings, settle_time_s: float = 1.0) -> float: - # TODO uses old code change - """ - Scan smargon Z and find the position with maximum focus measure. - - Args: - settings: AutofocusSettings with center, radius, range, and steps - settle_time_s: Time to wait after each move before capturing image - - Returns: - Best Z position (mm) found during the scan - """ - raise NotImplementedError("Autofocus not implemented yet") - - def auto_focus(self, settings: AutofocusSettings) -> float: - """ - Public autofocus method. Only allowed in SampleAlignment state. - - Args: - settings: AutofocusSettings with center, radius, range, and steps - - Returns: - Best Z position (mm) found during the scan - """ - self._cfg.set_busy(BeamlineStateEnum.SampleAlignment) - try: - best_z = self._auto_focus(settings) - return best_z - except Exception as e: - logger.error(f"Autofocus failed: {e}") - raise - - def auto_exposure(self): - self._devs.samcam_auto(AutoEnum.ONCE) - - def _setup_datacollection( - self, request: RasterGridRequest | RotationScanRequest, screening: bool = False - ): - request_omega = getattr(request, "omega_deg", None) - if request_omega is None: - request_omega = getattr(request, "start_omega_deg", None) - - if request_omega is not None: - logger.info(f"requesting omega to move to {request_omega}") - self._devs.aerotech_omega = request_omega - - if request.dtz is not None: - if request.dtz < self._cfg.cached_dtz_low: - raise ValueError( - f"Requested DTZ {request.dtz} is less than low detector limit {self._cfg.cached_dtz_low}" - ) - elif request.dtz > self._cfg.cached_dtz_high: - raise ValueError( - f"Requested DTZ {request.dtz} exceeds high detector limit {self._cfg.cached_dtz_high}" - ) - logger.info(f"requesting dtz to move to {request.dtz}") - self._cfg.dtz = request.dtz - else: - raise ValueError("No DTZ specified") - - if self.sample is not None and self.sample.db_id is not None: - sample_id = self.sample.db_id - if screening: - screenshot_name = f"{sample_id}_before_screening" - elif type(request) is RasterGridRequest: - screenshot_name = f"{sample_id}_before_raster" - else: - screenshot_name = f"{sample_id}_before_data_collection" - self.save_screenshot_db(sample_id, screenshot_name) - - if ( - request.transmission is not None - and abs(request.transmission - self._devs.transmission) > 0.001 - ): - logger.info(f"requesting transmission to move to {request.transmission}") - self._devs.transmission = request.transmission - # FIXME: figure out why IOC goes to error and make sure set() statuses resolve so we can wait - # on completion correctly - logger.debug("Sleeping to ensure transmission set completes due to IOC issues") - time.sleep(2) - if self._devs.transmission == 0: - logger.warning("Transmission move still not completed, sleeping another 2s") - time.sleep(2) - - start_pos = getattr(request, "start", None) - if start_pos is not None: - logger.info(f"requesting smargon to move to {start_pos}") - self._devs.smargon_pos = start_pos - else: - smargon_top_left = getattr(request, "smargon_top_left", None) - has_valid_smargon_target = ( - smargon_top_left is not None - and getattr(smargon_top_left, "sh_mm", None) is not None - ) - - is_zero_placeholder = ( - has_valid_smargon_target - and abs(smargon_top_left.sh_mm.x) < 1e-6 - and abs(smargon_top_left.sh_mm.y) < 1e-6 - and abs(smargon_top_left.sh_mm.z) < 1e-6 - and abs(smargon_top_left.phi_deg) < 1e-6 - and abs(smargon_top_left.chi_deg) < 1e-6 - ) - - if has_valid_smargon_target and not is_zero_placeholder: - logger.info(f"requesting smargon to move to {smargon_top_left}") - self._devs.set_smargon_pos( - SmargonCoordinate( - sh_mm=smargon_top_left.sh_mm, - phi_deg=smargon_top_left.phi_deg, - chi_deg=smargon_top_left.chi_deg, - ) - ) - else: - logger.debug( - "No explicit smargon target in request; skipping pre-datacollection smargon move" - ) - - self._devs.smargon_wait(timeout=180) - - def _build_fake_rotation_result(self, request: RotationScanRequest) -> CompletedRotationScan: - start_angle = 0.0 - try: - start_angle = float(self.omega) - except Exception: - logger.debug("Could not read omega for the fake rotation result", exc_info=True) - - return build_fake_rotation_result(request, start_angle=start_angle) - - def measure_raster(self, request: RasterGridRequest, auto_center: bool) -> CompletedRasterGrid: - """ - Execute a raster scan. - - Args: - request: RasterGridRequest parameters for the scan. - auto_center: Boolean flag indicating if this is part of an automated sequence. - - Returns: - CompletedRasterGrid result. - """ - logger.info( - "Received raster scan request", - extra=merge_log_context( - sample_log_context(self.sample), raster_request_log_context(request) - ), - ) - try: - result = self._execute_raster_sequence(request, auto_center=auto_center) - - if result is None: - raise RasterScanException("Raster scan failed for unknown reason.") - self._set_state(BeamlineStateEnum.SampleAlignment) - return result - except Exception: - self._set_state(BeamlineStateEnum.SampleAlignment) - raise - - def measure_rotation(self, request: RotationScanRequest) -> CompletedRotationScan: - """ - Execute a rotation scan. - - Args: - request: RotationScanRequest parameters. - - Returns: - CompletedRotationScan result. - """ - total_time = request.exp_time_s * request.steps - logger.info( - "Received rotation scan request", - extra=merge_log_context( - sample_log_context(self.sample), - rotation_request_log_context(request, total_time_s=total_time), - ), - ) - - try: - result = self._execute_rotation_sequence(request) - - if result is None: - logger.error("Rotation scan failed, no result returned") - raise DataCollectionException("Rotation scan failed, no result returned") - self._set_state(BeamlineStateEnum.SampleAlignment) - return result - finally: - try: - self._set_state(BeamlineStateEnum.SampleAlignment) - except Exception: - logger.exception("Failed to restore SampleAlignment after rotation") - raise - - @property - def dtz(self) -> float: - tmp = self._cfg.dtz - if tmp is None: - return cfg_get("daq.data_collection_settings.default_raster_scan_settings.dtz", 200) - else: - return tmp - - @dtz.setter - def dtz(self, val: float): - state = self._cfg.state - - dtz_low = self._cfg.cached_dtz_low - dtz_high = self._cfg.cached_dtz_high - - if dtz_low is None or dtz_high is None: - logger.warning("DTZ limits not found in cache, refreshing hardware metadata") - try: - self.refresh_detector_metadata_cache() - except Exception as e: - raise RuntimeError(f"DTZ limits unavailable and refresh failed: {e}") from e - dtz_low = self._cfg.cached_dtz_low - dtz_high = self._cfg.cached_dtz_high - - if dtz_low is None or dtz_high is None: - raise RuntimeError("DTZ limits are unavailable") - - if val < dtz_low or val > dtz_high: - raise RuntimeError(f"dtz={val} outside limits {dtz_low} to {dtz_high}") - - if state == BeamlineStateEnum.DataCollection: - raise RuntimeError("Cannot set dtz during data collection") - elif state == BeamlineStateEnum.SampleAlignment: - self._devs.set_dtz(val, wait=False) - - self._cfg.dtz = val - - @property - def smargon(self) -> SmargonCoordinate: - return self._devs.smargon_pos - - @smargon.setter - def smargon(self, sc: SmargonCoordinate): - self._saved_box = None - self._devs.smargon_pos = sc - self._devs.smargon_wait() - - def mark_beam(self, x_pxl: float, y_pxl: float): - self._cfg.mark_beam(x_pxl, y_pxl, self._devs.zoom) - - def clear_mark_beam(self): - self._cfg.clear_mark_beam() - - @property - def sample_geometry(self) -> SampleGeometryModel: - zoom = self._devs.zoom - aerotech_pos_ref = self._cfg.abr_meas_pos.at_mm - aerotech_pos = self._devs.aerotech_pos.at_mm - sample_geom = SampleGeometryModel( - beam_location_pxl=self._cfg.beam_mark_coeff.apply(zoom), - pixel_in_mm=self._cfg.pixel_to_mm(zoom), - omega_deg=self._devs.aerotech_omega, - smargon=self._devs.smargon_pos, - beam_size_mm=self._cfg.beam_size_mm, - aerotech=aerotech_pos - aerotech_pos_ref, - aerotech_meas=aerotech_pos, - ) - return sample_geom - - @property - def beam_size_mm(self) -> Coordinate: - return self._cfg.beam_size_mm - - @beam_size_mm.setter - def beam_size_mm(self, val: Coordinate): - self._cfg.beam_size_mm = val - - def get_beam_mark(self): - return self._cfg.get_beam_mark(self._devs.zoom) - - def ml_bounding_box( - self, sample_id: int | None = None, filename: str | None = None - ) -> RasterGridRequest | None: - """ - Request an ML-based bounding box for the sample. - - Args: - sample_id: Optional sample ID. - filename: Optional filename for saving/logging. - - Returns: - RasterGridRequest object representing the found bounding box, or None if failed. - """ - return get_ml_bounding_box( - mlbox=self._mlbox, - sample=self.sample, - sample_geometry=self.sample_geometry, - filename=filename, - upload_image=self._aare.upload_image, # pyright: ignore[reportArgumentType] - logger=logger, - max_images=self.AUTO_RASTER_MAX_IMAGES, - min_cell_size_mm=self.AUTO_RASTER_MAX_IMAGES, - skip_if_exceed_max_image_threshold=self.AUTO_RASTER_SKIP_IF_EXCEED_MAX_IMAGE_THRESHOLD, - ) - - def face_detection( - self, steps: int = 14, step_size: int = 15, face_min_ratio: float = 0.3 - ) -> dict: - """ - Perform a face detection sequence by rotating the sample and using ML to find the flat face. - - Args: - steps: Number of rotation steps. Default is 14. - step_size: Size of each rotation step in degrees. Default is 15. - face_min_ratio: Minimum ratio of loopface count to loop_all count to use loop_face over loop_all. - - Returns: - Dictionary containing face detection results, including found samples and fits. - """ - return self._execute_face_detection( - steps=steps, step_size=step_size, face_min_ratio=face_min_ratio, report_error=True - ).payload - - @log_timing(logger, "Auto loop center") - def auto_loop_center(self, sample: SampleShortInfo | None = None) -> float: - """ - Automatically center the loop using ML-based detection. - This performs a multi-step sequence including rotation and centering. - - Args: - sample: the current SampleShortInfo. If None, the current sample (self.sample) is used. - - Returns: - Time taken for the centering process (seconds) - - Raises: - LoopCenteringFailed: If the centering sequence fails - """ - start = time.perf_counter() - try: - if sample is None: - if self.sample is None: - raise LoopCenteringFailed( - "No sample available for loop centering." - "If you have mounted a manual sample," - "please add it in the manual sample panel." - ) - sample = self.sample - - if not self._execute_loop_centering(sample): - raise LoopCenteringFailed - except Exception: - self._cfg.zoom_mode = ZoomModeEnum.User - raise - - finally: - self._cfg.zoom_mode = ZoomModeEnum.User - - end = time.perf_counter() - return end - start - - def _default_screenshot_message(self, sample_id: int) -> str: - omega_value = self.omega - zoom_value = self.zoom - samcam = self.samcam_settings - return ( - f"sample_id: {sample_id} " - f"zoom: {zoom_value} " - f"exp:{samcam.exposure} " - f"gain:{samcam.gain} " - f"omega:{omega_value:.2f}" - ) - - def save_screenshot(self, filename: str, settle_time_s: float = 0.2) -> None: - """ - Capture a screenshot and write it locally. - - Args: - filename: Name to give to the uploaded image. - settle_time_s: float time to wait before taking the screenshot. - """ - self._screenshot_service.save_local(filename, settle_time_s) - - def save_screenshot_db(self, sample_id: int, filename: str, settle_time_s: float = 0.2): - """ - Capture a screenshot and upload it to the database for a specific sample. - - Args: - sample_id: Database ID of the sample. - filename: Name to give to the uploaded image. - settle_time_s: float time to wait before taking the screenshot. - """ - self._screenshot_service.save_to_db(sample_id, filename, settle_time_s) - - def send_screenshot_db(self, filename: str | None = None, message: str | None = None) -> None: - sample = self.sample - if sample is None: - raise ValueError("No sample with a valid sample_id is mounted.") - - self._screenshot_service.send_to_db( - filename=filename, - message=message, - default_message=self._default_screenshot_message(sample.db_id), - ) - - def send_message_db(self, db_id: int, event_type: SampleEventType, comment: str | None = None): - self._aare.send_sample_event(db_id, event_type, comment) - - @property - def sample_spreadsheet(self) -> SampleShortInfoList: - return self._cfg.spreadsheet - - @property - def reference_tools(self) -> SampleShortInfoList: - return self._cfg.reference_tools - - def sample_spreadsheet_user(self, pgroup: str) -> SampleShortInfoList: - # sample = copy.deepcopy(self.sample_spreadsheet) #switch to copy if too heavy! - # sample.s = list(filter(lambda x: x.user == pgroup, sample.s)) - # return sample - return SampleShortInfoList(s=[x for x in self.sample_spreadsheet.s if x.user == pgroup]) - - def get_beamline_default_raster_params(self) -> SimpleScanParameters: - default_exp_time_s = cfg_get( - "daq.data_collection_settings.default_raster_scan_settings.exp_time_s", 0.01 - ) - default_transmission = cfg_get( - "daq.data_collection_settings.default_raster_scan_settings.transmission", 1.0 - ) - default_dtz = cfg_get("daq.data_collection_settings.default_raster_scan_settings.dtz", 250) - return SimpleScanParameters( - dtz=default_dtz, exp_time_s=default_exp_time_s, transmission=default_transmission - ) - - def get_beamline_default_rotation_params(self) -> SimpleScanParameters: - default_exp_time_s = cfg_get( - "daq.data_collection_settings.default_rotation_settings.exp_time_s", 0.01 - ) - default_transmission = cfg_get( - "daq.data_collection_settings.default_rotation_settings.transmission", 1.0 - ) - default_dtz = cfg_get("daq.data_collection_settings.default_rotation_settings.dtz", 250) - default_start_omega_deg = cfg_get( - "daq.data_collection_settings.default_rotation_settings.start_omega_deg", 0.0 - ) - default_increment_omega_deg = cfg_get( - "daq.data_collection_settings.default_rotation_settings.incr_omega_deg", 0.2 - ) - default_steps = cfg_get( - "daq.data_collection_settings.default_rotation_settings.steps", 1800 - ) - return SimpleScanParameters( - dtz=default_dtz, - exp_time_s=default_exp_time_s, - transmission=default_transmission, - start_omega_deg=default_start_omega_deg, - incr_omega_deg=default_increment_omega_deg, - steps=default_steps, - ) - - def get_auto_raster_params(self) -> SimpleScanParameters: - """Raster parameters for the automated measurement sequence. - - Fixed per beamline; spreadsheet parameters only apply to data collection. - """ - return SimpleScanParameters(**self._dispatch.default_auto_raster_parameters) - - def get_collection_params(self, prefer_smart: bool = False) -> tuple[SimpleScanParameters, str]: - spreadsheet_params, _file_prefix = self.spreadsheet_params() - logger.debug(f"spreadsheet_params: {spreadsheet_params}") - smart_params = self._cfg.auto_params - default_params = SimpleScanParameters(**self._dispatch.default_rotation_parameters) - if prefer_smart: - if smart_params: - return smart_params, "smart_params" - if spreadsheet_params: - return spreadsheet_params, "spreadsheet_params" - else: - if spreadsheet_params: - return spreadsheet_params, "spreadsheet_params" - if smart_params: - return smart_params, "smart_params" - - return default_params, "defaults" - - def _end_operation( - self, - start: float, - operation: DAQOperation | None = DAQOperation.AUTOMATION, - error: bool = False, - ) -> float: - """ - End an operation and return elapsed time. - - Returns: - (elapsed_seconds, end_time_perf_counter) - """ - if operation is DAQOperation.AUTOMATION: - msg = "Ended automation operation" - else: - msg = f"Ended automation operation after {operation.value}" - - if error: - msg += "with an error" - logger.error(f"{msg}, time taken {time.perf_counter() - start} seconds.") - try: - self._set_state(BeamlineStateEnum.RobotSampleExchange) - except Exception: - logger.exception( - "Failed to transition to RobotSampleExchange during error recovery" - ) - raise - - else: - msg += " successfully" - logger.info(f"{msg}, time taken {time.perf_counter() - start} seconds.") - end = time.perf_counter() - return end - start - - @log_timing(logger, "Measure Sequence") - def measure(self, sample: SampleShortInfo) -> float: - """ - Main measurement sequence for a given sample. - Includes mounting, loop centering, face detection, auto-raster, and data collection. - - Args: - sample: SampleShortInfo object containing sample details - - Returns: - Total time taken for the measurement (seconds) - """ - start = time.perf_counter() - sample_started_at = time.time() - progress = self._new_automation_progress() - self._set_progress_context( - progress, current_sample_name=getattr(sample, "sample_name", "") or "" - ) - self._emit_automation_progress(progress) - - formatted_date = datetime.now().strftime("%Y%m%d") - sample_prefix = f"{formatted_date}/{sample.puck_name}/{sample.pin:02d}/{sample.sample_name}" - - try: - logger.info("Automation-measure starting sequence") - self._validate_automation_state(context="automation start") - - self._validate_automation_state(context="after acquiring automation busy state") - logger.info("Cancelling any pending jfjoch operations") - self._jfjoch.cancel() - self._set_progress_context( - progress, current_sample_name=getattr(sample, "sample_name", "") or "" - ) - - self._mark_progress_running(progress, WorkflowStateKind.MOUNT, "Mounting sample") - logger.info("Automation-measure initial setup complete") - if not self._execute_mount_and_prepare(sample): - mount_error_message = self._last_mount_error_message or "Mount failed" - self._mark_progress_failed(progress, WorkflowStateKind.MOUNT, mount_error_message) - return self._end_operation(start, DAQOperation.MOUNT, error=True) - self._validate_automation_state(context="after mount") - self._mark_progress_success(progress, WorkflowStateKind.MOUNT, "Mount complete") - self._set_state(BeamlineStateEnum.SampleAlignment) - self._validate_automation_state(context="after transition to SampleAlignment") - logger.info(f"Automation-measure mounting done at {time.perf_counter() - start}") - - self._mark_progress_running(progress, WorkflowStateKind.LOOP_CENTRE, "Centering sample") - - local_contact_config = self.get_local_contact_config() - mount_to_center_sleep_s = float(local_contact_config.mount_to_center_sleep_s) - - if mount_to_center_sleep_s > 0: - logger.info( - f"Sleeping {mount_to_center_sleep_s:.2f}s between mount and loop centering" - ) - sleep_started_at = time.monotonic() - time.sleep(mount_to_center_sleep_s) - logger.info( - "Finished mount-to-center sleep", - extra={ - "requested_sleep_s": mount_to_center_sleep_s, - "actual_sleep_s": time.monotonic() - sleep_started_at, - }, - ) - - centered = False - try: - logger.info("Automation-measure running loop centering") - centered = self._execute_loop_centering(sample) - except LoopCenteringFailed as e: - self._record_best_effort_step_failure( - progress=progress, - step=WorkflowStateKind.LOOP_CENTRE, - error=e, - sample=sample, - code="LOOP_CENTERING_FAILED", - ) - else: - if not centered: - self._record_best_effort_step_failure( - progress=progress, - step=WorkflowStateKind.LOOP_CENTRE, - error=LoopCenteringFailed("Centering returned no result"), - sample=sample, - code="LOOP_CENTERING_FAILED", - ) - self._validate_automation_state(context="after loop centering") - - logger.info( - f"Automation-measure - loop Centering done at {time.perf_counter() - start}" - ) - - face_detection_result = self._execute_face_detection( - steps=7, step_size=30, face_min_ratio=0.3, report_error=True - ) - if not face_detection_result.success: - logger.warning( - "Face detection failed during automation; continuing with latest payload", - extra=merge_log_context( - sample_log_context(sample), {"comment": face_detection_result.comment} - ), - ) - self._validate_automation_state(context="after face detection") - logger.info(f"Face Detection done at {time.perf_counter() - start}") - - self._mark_progress_success( - progress, WorkflowStateKind.LOOP_CENTRE, "Centering complete" - ) - - self._mark_progress_running(progress, WorkflowStateKind.RASTER, "Running raster") - hex_string = secrets.token_hex(3) - # Fixed per-beamline raster settings; spreadsheet values are ignored here - raster_params = self.get_auto_raster_params() - geom = self.sample_geometry - - if raster_params.filename is not None: - logger.info(f"Using filename {raster_params.filename}") - sample_prefix = f"{raster_params.filename}/{sample.sample_name}" - - raster_grid = RasterGridRequest( - exp_time_s=raster_params.exp_time_s, - file_prefix=sample_prefix + f"_{hex_string}", - smargon_top_left=SmargonCoordinate(), - n_x=1, - n_y=1, - dtz=raster_params.dtz, - grid_size_mm=Coordinate(x=geom.beam_size_mm.x * 0.5, y=geom.beam_size_mm.y * 0.5), - omega_deg=self.omega, - transmission=raster_params.transmission, - ) - - try: - raster_result = self._execute_raster_sequence(raster_grid, auto_center=True) - except AutoRasterSampleSkipped as e: - logger.warning( - "Skipping sample during automation because auto-raster grid is too large", - extra=merge_log_context( - sample_log_context(sample), - raster_request_log_context(raster_grid), - {"reason": str(e)}, - ), - ) - self._set_progress_step( - progress, WorkflowStateKind.RASTER, StepStatus.SKIPPED, str(e) - ) - self._set_progress_step( - progress, - WorkflowStateKind.DATA_COLLECTION, - StepStatus.SKIPPED, - "Data collection skipped because auto-raster was too large", - ) - self._mark_progress_finished( - progress, True, "Sample skipped: auto-raster too large" - ) - return self._end_operation(start, DAQOperation.AUTOMATION, error=False) - - if raster_result is None: - logger.error( - "Raster result was None during automation", - extra=merge_log_context( - sample_log_context(sample), raster_request_log_context(raster_grid) - ), - ) - self._mark_progress_failed(progress, WorkflowStateKind.RASTER, "Raster failed") - return self._end_operation(start, DAQOperation.RASTER, error=True) - - time.sleep(2) - - self._validate_automation_state(context="after raster") - self._mark_progress_success(progress, WorkflowStateKind.RASTER, "Raster complete") - self._set_state(BeamlineStateEnum.DataCollection) - self._validate_automation_state(context="after transition to DataCollection") - - logger.info(f"Raster scans completed at {time.perf_counter() - start}") - - self._mark_progress_running( - progress, WorkflowStateKind.DATA_COLLECTION, "Collecting data" - ) - params, source = self.get_collection_params(prefer_smart=False) - logger.info(f"Using {source} for data collection: {params}") - - self._devs.dtz = params.dtz - start_omega = self.omega - - update_sample = self.sample - if ( - update_sample is not None - and update_sample.db_id is not None - and update_sample.db_id == sample.db_id - ): - logger.info( - f"Updating sample info {sample.db_id} old run_number" - f" sample.run_number {sample.run_number} new run_number {update_sample.run_number}" - ) - - if params.filename is not None: - logger.info(f"Using filename {params.filename}") - sample_prefix = f"{params.filename}/{sample.sample_name}" - - rotation_request = RotationScanRequest( - start_omega_deg=start_omega, - dtz=params.dtz, - file_prefix="data/" + sample_prefix + f"_{hex_string}", - exp_time_s=params.exp_time_s, - incr_omega_deg=params.incr_omega_deg, - steps=params.steps, - transmission=params.transmission, - ) - - rotation_result = self._execute_rotation_sequence(rotation_request) - if rotation_result is None: - logger.error("Rotation result was None") - self._mark_progress_failed( - progress, WorkflowStateKind.DATA_COLLECTION, "Collection failed" - ) - return self._end_operation(start, DAQOperation.ROTATION, error=True) - - self._validate_automation_state(context="after data collection") - self._mark_progress_success( - progress, WorkflowStateKind.DATA_COLLECTION, "Collection complete" - ) - logger.info(f"Rotation scan done at {time.perf_counter() - start}") - - self._validate_automation_state(context="automation end") - - except BECCommunicationError as e: - self._end_operation(start, operation=DAQOperation.AUTOMATION, error=True) - self._raise_if_critical_bec_error(e, command=getattr(e, "operation", None) or "bec") - - except JFJochCommunicationError as e: - self._end_operation(start, operation=DAQOperation.AUTOMATION, error=True) - self._raise_if_critical_jfjoch_detector_error(e, command=e.endpoint or "unknown") - raise - - except ( - TransformationInvalidException, - StateTransitionFailed, - MaintenanceStateException, - ) as e: - logger.error(f"Critical automation state error: {e}") - if progress.current_step is not None: - current_kind = next( - ( - item.step - for item in progress.steps - if self._step_display_name(item.step) == progress.current_step - ), - WorkflowStateKind.FINAL, - ) - self._mark_progress_failed(progress, current_kind, str(e)) - else: - self._mark_progress_finished(progress, False, str(e)) - - self._handle_operation_error( - operation=DAQOperation.AUTOMATION, - sample=sample, - error=e, - event_type=SampleEventType.FAILED, - ) - self._end_operation(start, operation=DAQOperation.AUTOMATION, error=True) - raise - - except (BeamlineBusyTimeoutException, BeamlineBusyException) as e: - time_of_measure = abs(time.perf_counter() - start) - - if time_of_measure > self.AUTOMATION_BUSY_TIMEOUT_S: - logger.error( - f"Error in measure due to Beamline Busy State timeout:" - f"Time of: {time_of_measure} is greater than timeout duration {self.AUTOMATION_BUSY_TIMEOUT_S}" - f"Error thrown: {e}" - ) - - else: - logger.error(f"Error in measure due to Beamline Busy State: {e}") - - if progress.current_step is not None: - current_kind = next( - ( - item.step - for item in progress.steps - if self._step_display_name(item.step) == progress.current_step - ), - WorkflowStateKind.FINAL, - ) - self._mark_progress_failed(progress, current_kind, str(e)) - else: - self._mark_progress_finished(progress, False, str(e)) - - self._handle_operation_error( - operation=DAQOperation.AUTOMATION, - sample=sample, - error=e, - event_type=SampleEventType.FAILED, - ) - self._end_operation(start, operation=DAQOperation.AUTOMATION, error=True) - raise - - except MountingFailed as e: - logger.error(f"Failed to mount sample: {e}") - if e.critical: - self._end_operation(start, operation=DAQOperation.AUTOMATION, error=True) - raise - else: - pass - - except Exception as e: - logger.error(f"Error in measure: {e}") - if progress.current_step is not None: - current_kind = next( - ( - item.step - for item in progress.steps - if self._step_display_name(item.step) == progress.current_step - ), - WorkflowStateKind.FINAL, - ) - self._mark_progress_failed(progress, current_kind, str(e)) - else: - self._mark_progress_finished(progress, False, str(e)) - - self._handle_operation_error( - operation=DAQOperation.AUTOMATION, - sample=sample, - error=e, - event_type=SampleEventType.FAILED, - ) - self._end_operation(start, operation=DAQOperation.AUTOMATION, error=True) - raise RuntimeError(f"Critical Error in automation: {e}") from e - - self._record_completed_sample_time(progress, time.time() - sample_started_at) - self._mark_progress_finished(progress, True, "Automation complete") - return self._end_operation(start, DAQOperation.AUTOMATION, error=False) - - @log_timing(logger, "Changing Beamline State") - def _set_state(self, target: BeamlineStateEnum): - """__set_state assumes that beamline is already in busy state - it will apply a proper transformation and change state afterward - specifically: - 1. If target state is maintenance, just go there - 2. If target state is same as current, nothing will happen - 3. If target state cannot be reached, exception is raised and current state is kept - 4. If exception is raised during transformation, state is set to maintenance - 5. If transformation goes OK, target state is set - - Busy state will be cleared only, if exception is raised.""" - - curr_state = self._cfg.state - - if hasattr(curr_state, "value") and hasattr(target, "value"): - logger.info( - f"State transition requested: {curr_state} -> {target}", - extra={"from_state": curr_state, "to_state": target}, - ) - - # TODO: CHECK BUSY LOCK - - if target == BeamlineStateEnum.Maintenance: - self._cfg.state = BeamlineStateEnum.Maintenance - logger.warning("Beamline entered Maintenance state during state transition request.") - return - elif target == curr_state: - logger.debug( - f"State already set to {target}", - extra={"from_state": curr_state, "to_state": target}, - ) - # TODO unify BeamlineStateEnum and BeamlineState and allow transition from same state to same state to recover motor positions! - # TODO or just allow BEC thingy - return - elif target != curr_state: - self._cfg.state = BeamlineStateEnum.Moving - try: - match curr_state: - case BeamlineStateEnum.Maintenance: - if target == BeamlineStateEnum.SampleExchange: - workflows.m2se(self._devs, self._cfg) - elif target == BeamlineStateEnum.SampleAlignment: - workflows.m2sa(self._devs, self._cfg) - else: - raise TransformationInvalidException( - f"Cannot go from {curr_state} to {target}, not implemented" - ) - case BeamlineStateEnum.SampleExchange: - if target == BeamlineStateEnum.SampleAlignment: - workflows.se2sa(self._devs, self._cfg) - elif target == BeamlineStateEnum.BeamLocation: - workflows.se2sa(self._devs, self._cfg) - workflows.sa2bl(self._devs, self._cfg) - elif target == BeamlineStateEnum.DewarTransfer: - workflows.common2dh(self._devs, self._cfg) - elif target == BeamlineStateEnum.RobotSampleExchange: - workflows.common_2rse(self._devs, self._cfg) - else: - raise TransformationInvalidException( - f"Cannot go from {curr_state} to {target}, not implemented" - ) - case BeamlineStateEnum.DewarTransfer: - if target == BeamlineStateEnum.SampleAlignment: - workflows.dh2sa(self._devs, self._cfg) - elif target == BeamlineStateEnum.RobotSampleExchange: - workflows.dh2sa(self._devs, self._cfg) - workflows.sa2rse(self._devs, self._cfg) - elif target == BeamlineStateEnum.SampleExchange: - workflows.dh2sa(self._devs, self._cfg) - workflows.sa2se(self._devs, self._cfg) - else: - raise TransformationInvalidException( - f"Cannot go from {curr_state} to {target}, not implemented" - ) - case BeamlineStateEnum.DataCollection: - if target == BeamlineStateEnum.SampleAlignment: - workflows.dc2sa(self._devs, self._cfg) - elif target == BeamlineStateEnum.RobotSampleExchange: - workflows.dc2rse(self._devs, self._cfg) - elif target == BeamlineStateEnum.XtalSnapshot: - workflows.sa2xtal_snapshot(self._devs, self._cfg) - else: - raise TransformationInvalidException( - f"Cannot go from {curr_state} to {target}, not implemented" - ) - case BeamlineStateEnum.BeamLocation: - if target == BeamlineStateEnum.SampleAlignment: - workflows.bl2sa(self._devs, self._cfg) - elif target == BeamlineStateEnum.SampleExchange: - workflows.bl2sa(self._devs, self._cfg) - workflows.sa2se(self._devs, self._cfg) - elif target == BeamlineStateEnum.BeamstopAlignment: - workflows.bl2ba(self._devs, self._cfg) - elif target == BeamlineStateEnum.FluxMeasurement: - workflows.bl2flux_measurement(self._devs, self._cfg) - else: - raise TransformationInvalidException( - f"Cannot go from {curr_state} to {target}, not implemented" - ) - case BeamlineStateEnum.BeamstopAlignment: - if target == BeamlineStateEnum.SampleAlignment: - workflows.ba2sa(self._devs, self._cfg) - elif target == BeamlineStateEnum.SampleExchange: - workflows.ba2sa(self._devs, self._cfg) - workflows.sa2se(self._devs, self._cfg) - elif target == BeamlineStateEnum.FluxMeasurement: - workflows.ba2flux_measurement(self._devs, self._cfg) - elif target == BeamlineStateEnum.BeamLocation: - workflows.ba2bl(self._devs, self._cfg) - elif target == BeamlineStateEnum.SampleExchange: - workflows.bl2sa(self._devs, self._cfg) - workflows.sa2se(self._devs, self._cfg) - else: - raise TransformationInvalidException( - f"Cannot go from {curr_state} to {target}, not implemented" - ) - case BeamlineStateEnum.FluxMeasurement: - if target == BeamlineStateEnum.SampleAlignment: - workflows.flux_measurement2sa(self._devs, self._cfg) - elif target == BeamlineStateEnum.SampleExchange: - workflows.flux_measurement2sa(self._devs, self._cfg) - workflows.sa2se(self._devs, self._cfg) - elif target == BeamlineStateEnum.BeamLocation: - workflows.flux_measurement2bl(self._devs, self._cfg) - elif target == BeamlineStateEnum.BeamstopAlignment: - workflows.flux_measurement2ba(self._devs, self._cfg) - else: - raise TransformationInvalidException( - f"Cannot go from {curr_state} to {target}, not implemented" - ) - case BeamlineStateEnum.SampleAlignment: - if target == BeamlineStateEnum.DewarTransfer: - workflows.sa2dh(self._devs, self._cfg) - elif target == BeamlineStateEnum.SampleExchange: - workflows.sa2se(self._devs, self._cfg) - elif target == BeamlineStateEnum.RobotSampleExchange: - workflows.sa2rse(self._devs, self._cfg) - elif target == BeamlineStateEnum.DataCollection: - workflows.sa2dc(self._devs, self._cfg) - elif target == BeamlineStateEnum.XrayFluorescence: - workflows.sa2xrf(self._devs, self._cfg) - elif target == BeamlineStateEnum.BeamLocation: - workflows.sa2bl(self._devs, self._cfg) - elif target == BeamlineStateEnum.BeamstopAlignment: - workflows.sa2ba(self._devs, self._cfg) - elif target == BeamlineStateEnum.FluxMeasurement: - workflows.sa2flux_measurement(self._devs, self._cfg) - elif target == BeamlineStateEnum.XtalSnapshot: - workflows.sa2xtal_snapshot(self._devs, self._cfg) - else: - raise TransformationInvalidException( - f"Cannot go from {curr_state} to {target}, not implemented" - ) - case BeamlineStateEnum.XrayFluorescence: - if target == BeamlineStateEnum.SampleAlignment: - workflows.xrf2sa(self._devs, self._cfg) - else: - raise TransformationInvalidException( - f"Cannot go from {curr_state} to {target}, not implemented" - ) - case BeamlineStateEnum.RobotSampleExchange: - if target == BeamlineStateEnum.SampleAlignment: - workflows.rse2sa(self._devs, self._cfg) - elif target == BeamlineStateEnum.SampleExchange: - workflows.rse2se(self._devs, self._cfg) - elif target == BeamlineStateEnum.DewarTransfer: - workflows.common2dh(self._devs, self._cfg) - else: - raise TransformationInvalidException( - f"Cannot go from {curr_state} to {target}, not implemented" - ) - case BeamlineStateEnum.XtalSnapshot: - if target == BeamlineStateEnum.SampleAlignment: - workflows.xtal_snapshot2sa(self._devs, self._cfg) - elif target == BeamlineStateEnum.SampleExchange: - workflows.xtal_snapshot2se(self._devs, self._cfg) - elif target == BeamlineStateEnum.RobotSampleExchange: - workflows.xtal_snapshot2rse(self._devs, self._cfg) - elif target == BeamlineStateEnum.DataCollection: - workflows.xtal_snapshot2dc(self._devs, self._cfg) - elif target == BeamlineStateEnum.XrayFluorescence: - workflows.xtal_snapshot2xrf(self._devs, self._cfg) - elif target == BeamlineStateEnum.DewarTransfer: - workflows.xtal_snapshot2dh(self._devs, self._cfg) - elif target == BeamlineStateEnum.BeamLocation: - workflows.xtal_snapshot2bl(self._devs, self._cfg) - else: - raise TransformationInvalidException( - f"Cannot go from {curr_state} to {target}, not implemented" - ) - self._cfg.state = target - # Beam-location mode uses preset per-zoom camera settings; any - # other state goes back to auto-exposure (User zoom mode). Apply - # the preset for the current zoom on entry. - if target == BeamlineStateEnum.BeamLocation: - self._cfg.zoom_mode = ZoomModeEnum.BeamLocation - self._devs.samcam_settings = self._cfg.zoom_settings.get_camera_settings( - self._devs.zoom - ) - elif self._cfg.zoom_mode == ZoomModeEnum.BeamLocation: - self._cfg.zoom_mode = ZoomModeEnum.User - logger.info( - f"State transition completed: {curr_state} -> {target}", - extra={"from_state": curr_state, "to_state": target}, - ) - except TransformationInvalidException as e: - logger.error( - f"State transition invali: {curr_state} -> {target}: {e}", - extra={"from_state": curr_state, "to_state": target}, - ) - self._cfg.state = curr_state - raise - except Exception as e: - logger.exception( - f"Exception during state transition : {curr_state} -> {target}. " - "Changing state to maintenance due to error.", - extra={"from_state": curr_state, "to_state": target}, - ) - self._cfg.state = BeamlineStateEnum.Maintenance - raise StateTransitionFailed( - f"State transition failed: {curr_state} -> {target}. " - f"Beamline moved to Maintenance. Original error: {e}" - ) from e - - @property - def shutter(self) -> bool: - return self._devs.shutter - - @shutter.setter - def shutter(self, v: bool): - self._devs.shutter = v - - @property - def diffraction_geometry(self) -> DiffractionGeometry: - metadata = self._cached_detector_metadata() - width = int(metadata.get("detector_width", 1)) - height = int(metadata.get("detector_height", 1)) - pixel_size_mm = float(metadata.get("pixel_size_mm", 0.15)) - detector_description = str(metadata.get("detector_description", "unavailable")) - detector_serial_number = str(metadata.get("detector_serial_number", "unavailable")) - energy = self._devs.energy_kev - dtz = self._devs.dtz - poni_rot1_rad, poni_rot2_rad = self._dispatch.geo.detector_tilt - return DiffractionGeometry( - energy_keV=energy, - dtz_mm=dtz, - detector_size_pxl=(width, height), - pixel_size_mm=pixel_size_mm, - beam_center_pxl=self._devs.detector_beam_centre_px, - detector_description=detector_description, - detector_serial_number=detector_serial_number, - poni_rot1_rad=poni_rot1_rad, - poni_rot2_rad=poni_rot2_rad, - ) - - @property - def beamline_status(self) -> BeamlineStatus: - try: - ring_current = self._devs.ring_current - front_light = self.front_light - back_light = self.back_light - cryojet_temp = self._devs.cryojet_temp - shutter_open = self._devs.shutter - exp_shutter_open = self._devs.exp_shutter.state() - pss_prohibited = self._devs.pss.is_prohibited() - pss_alarm = self._devs.pss.alarm_active() - flux = self._devs.full_flux - samcam_settings = self._devs.samcam_settings - bl = self._bl - transmission = self._devs.transmission - zoom = self._devs.zoom - commisioning_mode = self._cfg.commissioning_mode - - dtz_min = self._cfg.cached_dtz_low - dtz_max = self._cfg.cached_dtz_high - - if ( - dtz_min is None - or dtz_max is None - or (dtz_min > dtz_max) - or (dtz_min == dtz_max) - or (dtz_min == 0 and dtz_max == 0) - ): - logger.warning( - "DTZ limits missing from cache, using conservative defaults in beamline_status" - ) - dtz_min = cfg_get("daq.hardware.default_detector_distance_minimum", 100) - dtz_max = cfg_get("daq.hardware.default_detector_distance_maximum", 1000) - logger.warning(f"using dtz_min {dtz_min} and dtz_max {dtz_max}") - - return BeamlineStatus( - ring_current_mA=ring_current, - front_light=front_light, - back_light=back_light, - cryojet_K=cryojet_temp, - shutter_open=shutter_open, - exp_shutter_open=exp_shutter_open, - flux_ph_s=flux, - sample_camera=samcam_settings, - name=bl, - transmission=transmission, - zoom=zoom, - commissioning_mode=commisioning_mode, - dtz_min=dtz_min, - dtz_max=dtz_max, - pss_prohibited=pss_prohibited, - pss_alarm=pss_alarm, - ) - - except Exception: - logger.exception("Failed to retrieve beamline status") - raise - - def _safe_sample(self) -> tuple[SampleShortInfo | None, bool, str | None]: - """ - Return (sample, tell_connected, tell_error) without raising. - """ - sample = self._cfg.current_sample - try: - self._devs.tell.get_state() - tell_connected, tell_error = True, None - except TellCommunicationError as e: - tell_connected, tell_error = False, f"TELL unavailable: {e}" - return sample, tell_connected, tell_error - - def _aerotech_status(self) -> tuple[bool, str | None]: - aerotech_ok = True - aerotech_err: str | None = None - try: - _ = self._devs.aerotech.status() - except Exception as e: - logger.warning(f"Aerotech error in _aerotech_status: {e}", exc_info=True) - aerotech_ok = False - aerotech_err = f"Cannot connect to Aerotech: {e}" - return aerotech_ok, aerotech_err - - def _safe_geom(self) -> tuple[SampleGeometryModel, bool, str | None, bool, str | None]: - """ - Return (geom, smargon_connected, smargon_error, aerotech_connected, aerotech_error) without raising. - Uses a conservative fallback geometry if Smargon access fails. - """ - aerotech_connected, smargon_connected = True, True - aerotech_error, smargon_error = None, None - try: - return ( - self.sample_geometry, - smargon_connected, - smargon_error, - aerotech_connected, - aerotech_error, - ) - except SmargonCommunicationError as e: - logger.warning(f"Smargon error in _safe_geom: {e}") - smargon_error = f"Cannot connect to Smargon: {e}" - smargon_connected = False - except AerotechCommunicationError as e: - logger.warning(f"Aeroetch error in _safe_geom: {e}") - aerotech_error = f"Cannot connect to Aerotech: {e}" - self._devs.exp_shutter.close() - aerotech_connected = False - except Exception as e: - logger.warning(f"Unexpected error in _safe_geom: {e}", exc_info=True) - smargon_error = f"Safe geometry failed: {e}" - aerotech_error = f"Safe geometry failed: {e}" - aerotech_connected = False - smargon_connected = False - zoom = self._devs.zoom - logger.warning("Safe geometry failed: falling back to default settings") - fallback = SampleGeometryModel( - beam_location_pxl=self._cfg.beam_mark_coeff.apply(zoom), - pixel_in_mm=self._cfg.pixel_to_mm(zoom), - omega_deg=0.0, - smargon=SmargonCoordinate( - sh_mm=Coordinate(x=0.0, y=0.0, z=0.0), phi_deg=0.0, chi_deg=0.0 - ), - beam_size_mm=self._cfg.beam_size_mm, - aerotech=Coordinate(x=0.0, y=0.0, z=0.0), - aerotech_meas=Coordinate(x=0.0, y=0.0, z=0.0), - ) - return (fallback, smargon_connected, smargon_error, aerotech_connected, aerotech_error) - - def _safe_beamline_status(self) -> BeamlineStatus: - try: - return self.beamline_status - except Exception as e: - # TODO add error message to send to GUI to say problem - logger.error(f"Failed to retrieve beamline status: {e!s}") - raise - - def _safe_tell_state(self) -> TellStateModel | None: - try: - redis_client = getattr(self._cfg, "_client", None) - beamline_key = getattr(self._cfg, "_bl", None) - - if redis_client is None or beamline_key is None: - return None - - redis_key = f"{beamline_key}:tell_state" - raw_value = redis_client.get(redis_key) - if raw_value in (None, "", b""): - return None - - if isinstance(raw_value, bytes): - raw_value = raw_value.decode("utf-8") - - return TellStateModel.model_validate_json(str(raw_value)) - except Exception as e: - logger.warning(f"Failed to read tell_state from Redis: {e}", exc_info=True) - return None - - def _safe_diffraction_geometry(self) -> DiffractionGeometry: - try: - return self.diffraction_geometry - except Exception as e: - logger.warning(f"Failed to retrieve diffraction geomtrey: {e!s}", exc_info=True) - # Must satisfy pydantic constraints in DiffractionGeometry - return DiffractionGeometry( - energy_keV=12.4, - dtz_mm=150.0, - detector_size_pxl=(1, 1), - pixel_size_mm=0.15, - beam_center_pxl=(0.0, 0.0), - detector_description="unavailable", - detector_serial_number="unavailable", - poni_rot1_rad=0.0, - poni_rot2_rad=0.0, - ) - - @property - def status(self) -> DAQStatusModel: - try: - # og_start = time.perf_counter() - safe_sample, tell_ok, tell_err = self._safe_sample() - # logger.debug(f"Safe sample info call took {time.perf_counter() - og_start:.3f}s") - # start = time.perf_counter() - safe_geom, smargon_ok, smargon_err, aerotech_ok, aerotech_err = self._safe_geom() - # logger.debug(f"safe geom call took {time.perf_counter() - start:.3f}s") - # start = time.perf_counter() - safe_tell_state = self._safe_tell_state() - # logger.debug(f"Safe tell call call took {time.perf_counter() - start:.3f}s") - # start = time.perf_counter() - safe_beamline_status = self._safe_beamline_status() - # logger.debug(f"Safe beamline status call took {time.perf_counter() - start:.3f}s") - # start = time.perf_counter() - safe_diffraction_geom = self._safe_diffraction_geometry() - # logger.debug(f"Safe diffraction geometry call took {time.perf_counter() - start:.3f}s") - # start = time.perf_counter() - session_status = SessionStatus( - current_pgroup=self._cfg.pgroup, - session=self._cfg.session_state(0), # 0 is dummy session - staff=False, - ) - # logger.debug(f"Safe session status call took {time.perf_counter() - start:.3f}s") - # start = time.perf_counter() - status = DAQStatusModel( - state=self.state, - busy=self.busy, - geom=safe_geom, - bl=safe_beamline_status, - sample=safe_sample, - session=session_status, - diffraction=safe_diffraction_geom, - box=self._saved_box, - last_best_res=self._cfg.last_best_res, - last_best_b_factor=self._cfg.last_best_b_factor, - crystal_size=self._cfg.crystal_size, - tell_connected=tell_ok, - tell_error=tell_err, - tell_state=safe_tell_state, - smargon_connected=smargon_ok, - smargon_error=smargon_err, - aerotech_connected=aerotech_ok, - aerotech_error=aerotech_err, - ) - # logger.debug(f"Creating DAQStatusModel took {time.perf_counter() - start:.3f}s") - # logger.debug(f"returning status call took {time.perf_counter() - og_start:.3f}s") - return status - - except Exception as e: - logger.error(f"Failed to retrieve DAQ status: {e}") - raise - - def cancel(self): - if self._cfg.state == BeamlineStateEnum.DataCollection: - self._devs.aerotech.cancel() - self._jfjoch.cancel() - - def anneal(self, time_s: float): - self._devs.anneal(time_s) - - def mono_pitch_scan(self, plot: bool = False) -> None: - self._devs.bec_worker.mono_pitch_scan_runner(plot=plot) - - def change_energy(self, value: float, plot: bool = False) -> None: - self._devs.bec_worker.change_energy(value=value, plot=plot) - - def bec_load_user_macros(self) -> None: - self._devs.bec_worker.load_user_macros() - - def bec_list_all_user_macros(self) -> list[str]: - macros = self._devs.bec_worker.list_all_user_macros() - if macros is None: - return [] - return [str(item) for item in macros] - - def bec_list_all_devices(self) -> list[str]: - devices = self._devs.bec_worker.list_position_devices() - if devices is None: - return [] - return [str(item) for item in devices] - - def bec_reinitialise_planner_and_position_devices(self, method: str = "auto") -> list[str]: - self._devs.bec_worker.load_user_macros() - return self._devs.bec_worker.reinitialise_planner_and_position_devices(method=method) - - def bec_save_current_bs_pos(self) -> None: - self._devs.bec_worker.save_current_bs_pos() - - def bec_save_current_collimator_pos(self) -> None: - self._devs.bec_worker.save_current_collimator_pos() - - def bec_save_current_aerotech_position(self) -> None: - self._devs.bec_worker.save_current_aerotech_position() - - def steer_beam_available(self) -> bool: - return "beam_steering" in self._devs.bec_worker.dev - - def steer_beam(self, x: int | None, y: int | None): - """Run the routine to move the beam to the sample location. Update the location if provided.""" - if "beam_steering" not in self._devs.bec_worker.dev: - raise BECCommunicationError("Beam steering device does not exist in the BEC config.") - if not self.shutter: - raise AareException( - "Shutter not open! Please open the shutter before running beam steering." - ) - self._dispatch.bec_macros.auto_exposure() - if x is not None: - self._devs.bec_worker.dev.beam_steering.sample_loc_x_px.set(x).wait() - if y is not None: - self._devs.bec_worker.dev.beam_steering.sample_loc_y_px.set(y).wait() - self._devs.bec_worker.dev.beam_steering.trigger().wait() - - def fluorimeter_take_spectrum( - self, fm: FluorescenceSpectrumParameterModel - ) -> FluorescenceSpectrumOutputModel: - try: - self._set_state(BeamlineStateEnum.XrayFluorescence) - - if fm.transmission is not None: - self._devs.transmission = fm.transmission - - # TODO: Fill - - self._set_state(BeamlineStateEnum.SampleAlignment) - return None - except Exception: - self._set_state(BeamlineStateEnum.SampleAlignment) - raise - - def get_local_contact_config(self) -> LocalContactConfigModel: - return self._cfg.get_local_contact_config() - - def set_local_contact_config(self, config: LocalContactConfigModel) -> LocalContactConfigModel: - return self._cfg.set_local_contact_config(config) diff --git a/src/aare/daq/devices.py b/src/aare/daq/devices.py deleted file mode 100644 index dbc645f5..00000000 --- a/src/aare/daq/devices.py +++ /dev/null @@ -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() diff --git a/src/aare/daq/mlbox.py b/src/aare/daq/mlbox.py deleted file mode 100644 index 60916a4e..00000000 --- a/src/aare/daq/mlbox.py +++ /dev/null @@ -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 '_' -> [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 diff --git a/src/aare/daq/operations/__init__.py b/src/aare/daq/operations/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/aare/daq/operations/common/__init__.py b/src/aare/daq/operations/common/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/aare/daq/operations/common/ml_bounding_box.py b/src/aare/daq/operations/common/ml_bounding_box.py deleted file mode 100644 index 11dcccae..00000000 --- a/src/aare/daq/operations/common/ml_bounding_box.py +++ /dev/null @@ -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, - ) diff --git a/src/aare/daq/operations/common/models.py b/src/aare/daq/operations/common/models.py deleted file mode 100644 index da6605ee..00000000 --- a/src/aare/daq/operations/common/models.py +++ /dev/null @@ -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 diff --git a/src/aare/daq/operations/common/runtime.py b/src/aare/daq/operations/common/runtime.py deleted file mode 100644 index 417a3bc6..00000000 --- a/src/aare/daq/operations/common/runtime.py +++ /dev/null @@ -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 diff --git a/src/aare/daq/operations/common/services.py b/src/aare/daq/operations/common/services.py deleted file mode 100644 index 20baf241..00000000 --- a/src/aare/daq/operations/common/services.py +++ /dev/null @@ -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 diff --git a/src/aare/daq/operations/common/simulate_scan_result.py b/src/aare/daq/operations/common/simulate_scan_result.py deleted file mode 100644 index 73e6f343..00000000 --- a/src/aare/daq/operations/common/simulate_scan_result.py +++ /dev/null @@ -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 - ) diff --git a/src/aare/daq/operations/face_detection/__init__.py b/src/aare/daq/operations/face_detection/__init__.py deleted file mode 100644 index f43927cf..00000000 --- a/src/aare/daq/operations/face_detection/__init__.py +++ /dev/null @@ -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"] diff --git a/src/aare/daq/operations/face_detection/models.py b/src/aare/daq/operations/face_detection/models.py deleted file mode 100644 index 283c20c9..00000000 --- a/src/aare/daq/operations/face_detection/models.py +++ /dev/null @@ -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 diff --git a/src/aare/daq/operations/face_detection/service.py b/src/aare/daq/operations/face_detection/service.py deleted file mode 100644 index d75776ed..00000000 --- a/src/aare/daq/operations/face_detection/service.py +++ /dev/null @@ -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 diff --git a/src/aare/daq/operations/face_detection/utils.py b/src/aare/daq/operations/face_detection/utils.py deleted file mode 100644 index 6aec307f..00000000 --- a/src/aare/daq/operations/face_detection/utils.py +++ /dev/null @@ -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 diff --git a/src/aare/daq/operations/loop_centering/__init__.py b/src/aare/daq/operations/loop_centering/__init__.py deleted file mode 100644 index f6d0c2be..00000000 --- a/src/aare/daq/operations/loop_centering/__init__.py +++ /dev/null @@ -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", -] diff --git a/src/aare/daq/operations/loop_centering/analyzer.py b/src/aare/daq/operations/loop_centering/analyzer.py deleted file mode 100644 index d28d94a3..00000000 --- a/src/aare/daq/operations/loop_centering/analyzer.py +++ /dev/null @@ -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 diff --git a/src/aare/daq/operations/loop_centering/models.py b/src/aare/daq/operations/loop_centering/models.py deleted file mode 100644 index fbc86702..00000000 --- a/src/aare/daq/operations/loop_centering/models.py +++ /dev/null @@ -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 diff --git a/src/aare/daq/operations/loop_centering/service.py b/src/aare/daq/operations/loop_centering/service.py deleted file mode 100644 index e1f586c8..00000000 --- a/src/aare/daq/operations/loop_centering/service.py +++ /dev/null @@ -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) diff --git a/src/aare/daq/operations/mounting/__init__.py b/src/aare/daq/operations/mounting/__init__.py deleted file mode 100644 index ff65a562..00000000 --- a/src/aare/daq/operations/mounting/__init__.py +++ /dev/null @@ -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"] diff --git a/src/aare/daq/operations/mounting/models.py b/src/aare/daq/operations/mounting/models.py deleted file mode 100644 index 252da7d7..00000000 --- a/src/aare/daq/operations/mounting/models.py +++ /dev/null @@ -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 diff --git a/src/aare/daq/operations/mounting/service.py b/src/aare/daq/operations/mounting/service.py deleted file mode 100644 index b97ec726..00000000 --- a/src/aare/daq/operations/mounting/service.py +++ /dev/null @@ -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), - ) diff --git a/src/aare/daq/operations/raster/__init__.py b/src/aare/daq/operations/raster/__init__.py deleted file mode 100644 index 06414f52..00000000 --- a/src/aare/daq/operations/raster/__init__.py +++ /dev/null @@ -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"] diff --git a/src/aare/daq/operations/raster/models.py b/src/aare/daq/operations/raster/models.py deleted file mode 100644 index 2220649d..00000000 --- a/src/aare/daq/operations/raster/models.py +++ /dev/null @@ -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 diff --git a/src/aare/daq/operations/raster/service.py b/src/aare/daq/operations/raster/service.py deleted file mode 100644 index 62ebba26..00000000 --- a/src/aare/daq/operations/raster/service.py +++ /dev/null @@ -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]) diff --git a/src/aare/daq/operations/rotation/__init__.py b/src/aare/daq/operations/rotation/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/aare/daq/operations/rotation/models.py b/src/aare/daq/operations/rotation/models.py deleted file mode 100644 index 532cc5b3..00000000 --- a/src/aare/daq/operations/rotation/models.py +++ /dev/null @@ -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 diff --git a/src/aare/daq/operations/rotation/service.py b/src/aare/daq/operations/rotation/service.py deleted file mode 100644 index 2c9049cb..00000000 --- a/src/aare/daq/operations/rotation/service.py +++ /dev/null @@ -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 diff --git a/src/aare/daq/operations/screenshot/__init__.py b/src/aare/daq/operations/screenshot/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/aare/daq/operations/screenshot/service.py b/src/aare/daq/operations/screenshot/service.py deleted file mode 100644 index 13d20dac..00000000 --- a/src/aare/daq/operations/screenshot/service.py +++ /dev/null @@ -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) diff --git a/src/aare/daq/server.py b/src/aare/daq/server.py index 5525b715..1b745f00 100644 --- a/src/aare/daq/server.py +++ b/src/aare/daq/server.py @@ -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") diff --git a/src/aare/daq/spreadsheetupdater.py b/src/aare/daq/spreadsheetupdater.py deleted file mode 100644 index 4f7efd34..00000000 --- a/src/aare/daq/spreadsheetupdater.py +++ /dev/null @@ -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() diff --git a/src/aare/daq/tell_state_machine.py b/src/aare/daq/tell_state_machine.py deleted file mode 100644 index 9de7e8d0..00000000 --- a/src/aare/daq/tell_state_machine.py +++ /dev/null @@ -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) diff --git a/src/aare/daq/tellupdater.py b/src/aare/daq/tellupdater.py deleted file mode 100644 index 6facf01a..00000000 --- a/src/aare/daq/tellupdater.py +++ /dev/null @@ -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() diff --git a/src/aare/daq/workflows.py b/src/aare/daq/workflows.py deleted file mode 100644 index 441d974c..00000000 --- a/src/aare/daq/workflows.py +++ /dev/null @@ -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) diff --git a/src/aare/devices/__init__.py b/src/aare/devices/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/aare/devices/aerotech.py b/src/aare/devices/aerotech.py deleted file mode 100644 index d26efab0..00000000 --- a/src/aare/devices/aerotech.py +++ /dev/null @@ -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() diff --git a/src/aare/devices/area_detector.py b/src/aare/devices/area_detector.py deleted file mode 100644 index 74e67076..00000000 --- a/src/aare/devices/area_detector.py +++ /dev/null @@ -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) diff --git a/src/aare/devices/bec_worker.py b/src/aare/devices/bec_worker.py deleted file mode 100644 index 983882b6..00000000 --- a/src/aare/devices/bec_worker.py +++ /dev/null @@ -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() diff --git a/src/aare/devices/enum_pv.py b/src/aare/devices/enum_pv.py deleted file mode 100644 index fd725e17..00000000 --- a/src/aare/devices/enum_pv.py +++ /dev/null @@ -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__}") diff --git a/src/aare/devices/experimental_hutch_shutter.py b/src/aare/devices/experimental_hutch_shutter.py deleted file mode 100644 index 1510c9b3..00000000 --- a/src/aare/devices/experimental_hutch_shutter.py +++ /dev/null @@ -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) diff --git a/src/aare/devices/filter_transmission.py b/src/aare/devices/filter_transmission.py deleted file mode 100644 index 2eadb4c0..00000000 --- a/src/aare/devices/filter_transmission.py +++ /dev/null @@ -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"" - - 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.") diff --git a/src/aare/devices/fluorimeter.py b/src/aare/devices/fluorimeter.py deleted file mode 100644 index 4e6eb823..00000000 --- a/src/aare/devices/fluorimeter.py +++ /dev/null @@ -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) diff --git a/src/aare/devices/jfjoch.py b/src/aare/devices/jfjoch.py deleted file mode 100644 index d3ea6388..00000000 --- a/src/aare/devices/jfjoch.py +++ /dev/null @@ -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() diff --git a/src/aare/devices/mx_lib.py b/src/aare/devices/mx_lib.py deleted file mode 100644 index c0807eda..00000000 --- a/src/aare/devices/mx_lib.py +++ /dev/null @@ -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 diff --git a/src/aare/devices/my_motor.py b/src/aare/devices/my_motor.py deleted file mode 100644 index 7878f38c..00000000 --- a/src/aare/devices/my_motor.py +++ /dev/null @@ -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") diff --git a/src/aare/devices/pss_state.py b/src/aare/devices/pss_state.py deleted file mode 100644 index c00e608d..00000000 --- a/src/aare/devices/pss_state.py +++ /dev/null @@ -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 diff --git a/src/aare/devices/set_get_pv.py b/src/aare/devices/set_get_pv.py deleted file mode 100644 index fa849073..00000000 --- a/src/aare/devices/set_get_pv.py +++ /dev/null @@ -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) diff --git a/src/aare/devices/smargon.py b/src/aare/devices/smargon.py deleted file mode 100644 index 6fc9abad..00000000 --- a/src/aare/devices/smargon.py +++ /dev/null @@ -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) diff --git a/src/aare/devices/tell_backend.py b/src/aare/devices/tell_backend.py deleted file mode 100644 index 8b7f25c1..00000000 --- a/src/aare/devices/tell_backend.py +++ /dev/null @@ -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() diff --git a/src/aare/devices/tell_client.py b/src/aare/devices/tell_client.py deleted file mode 100644 index baccfd14..00000000 --- a/src/aare/devices/tell_client.py +++ /dev/null @@ -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() diff --git a/src/aare/devices/workflow_tools.py b/src/aare/devices/workflow_tools.py deleted file mode 100644 index a75eea0b..00000000 --- a/src/aare/devices/workflow_tools.py +++ /dev/null @@ -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) diff --git a/src/aare/devices/zmq_client.py b/src/aare/devices/zmq_client.py deleted file mode 100644 index da8d389b..00000000 --- a/src/aare/devices/zmq_client.py +++ /dev/null @@ -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" diff --git a/src/aare/gui/__init__.py b/src/aare/gui/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/aare/gui/about.py b/src/aare/gui/about.py deleted file mode 100644 index 8152fdee..00000000 --- a/src/aare/gui/about.py +++ /dev/null @@ -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} -""" diff --git a/src/aare/gui/auth.py b/src/aare/gui/auth.py deleted file mode 100644 index 92201ca6..00000000 --- a/src/aare/gui/auth.py +++ /dev/null @@ -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 diff --git a/src/aare/gui/constants.py b/src/aare/gui/constants.py deleted file mode 100644 index 9697a10f..00000000 --- a/src/aare/gui/constants.py +++ /dev/null @@ -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()}" diff --git a/src/aare/gui/graphics/__init__.py b/src/aare/gui/graphics/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/aare/gui/graphics/aare_banner.png b/src/aare/gui/graphics/aare_banner.png deleted file mode 100644 index 759a2b2f..00000000 Binary files a/src/aare/gui/graphics/aare_banner.png and /dev/null differ diff --git a/src/aare/gui/graphics/aare_banner.svg b/src/aare/gui/graphics/aare_banner.svg deleted file mode 100644 index eccb1b1a..00000000 --- a/src/aare/gui/graphics/aare_banner.svg +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - AARE - - - - Advanced softwARE for - - macromolecular - - crystallography at - - Swiss Light Source 2.0 - - - \ No newline at end of file diff --git a/src/aare/gui/graphics/aare_banner_blue.png b/src/aare/gui/graphics/aare_banner_blue.png deleted file mode 100644 index 39dfa9c5..00000000 Binary files a/src/aare/gui/graphics/aare_banner_blue.png and /dev/null differ diff --git a/src/aare/gui/graphics/aaregui_logo.svg b/src/aare/gui/graphics/aaregui_logo.svg deleted file mode 100644 index 8709c36e..00000000 --- a/src/aare/gui/graphics/aaregui_logo.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/src/aare/gui/graphics/check_mark_dark.png b/src/aare/gui/graphics/check_mark_dark.png deleted file mode 100644 index bbc73327..00000000 Binary files a/src/aare/gui/graphics/check_mark_dark.png and /dev/null differ diff --git a/src/aare/gui/graphics/check_mark_light.png b/src/aare/gui/graphics/check_mark_light.png deleted file mode 100644 index e9fe4c70..00000000 Binary files a/src/aare/gui/graphics/check_mark_light.png and /dev/null differ diff --git a/src/aare/gui/graphics/resize_grip_h_idle_dark.png b/src/aare/gui/graphics/resize_grip_h_idle_dark.png deleted file mode 100644 index d3e9696d..00000000 Binary files a/src/aare/gui/graphics/resize_grip_h_idle_dark.png and /dev/null differ diff --git a/src/aare/gui/graphics/resize_grip_h_idle_light.png b/src/aare/gui/graphics/resize_grip_h_idle_light.png deleted file mode 100644 index ed9bffc9..00000000 Binary files a/src/aare/gui/graphics/resize_grip_h_idle_light.png and /dev/null differ diff --git a/src/aare/gui/graphics/resize_grip_v_idle_dark.png b/src/aare/gui/graphics/resize_grip_v_idle_dark.png deleted file mode 100644 index 3f125af8..00000000 Binary files a/src/aare/gui/graphics/resize_grip_v_idle_dark.png and /dev/null differ diff --git a/src/aare/gui/graphics/resize_grip_v_idle_light.png b/src/aare/gui/graphics/resize_grip_v_idle_light.png deleted file mode 100644 index ddef85aa..00000000 Binary files a/src/aare/gui/graphics/resize_grip_v_idle_light.png and /dev/null differ diff --git a/src/aare/gui/graphics/slider_grip_dark.png b/src/aare/gui/graphics/slider_grip_dark.png deleted file mode 100644 index ef6d413f..00000000 Binary files a/src/aare/gui/graphics/slider_grip_dark.png and /dev/null differ diff --git a/src/aare/gui/graphics/slider_grip_light.png b/src/aare/gui/graphics/slider_grip_light.png deleted file mode 100644 index 81008622..00000000 Binary files a/src/aare/gui/graphics/slider_grip_light.png and /dev/null differ diff --git a/src/aare/gui/graphics/spin_arrow_down_dark.png b/src/aare/gui/graphics/spin_arrow_down_dark.png deleted file mode 100644 index 645f0076..00000000 Binary files a/src/aare/gui/graphics/spin_arrow_down_dark.png and /dev/null differ diff --git a/src/aare/gui/graphics/spin_arrow_down_light.png b/src/aare/gui/graphics/spin_arrow_down_light.png deleted file mode 100644 index 2335ba1d..00000000 Binary files a/src/aare/gui/graphics/spin_arrow_down_light.png and /dev/null differ diff --git a/src/aare/gui/graphics/spin_arrow_up_dark.png b/src/aare/gui/graphics/spin_arrow_up_dark.png deleted file mode 100644 index f9a6ca7f..00000000 Binary files a/src/aare/gui/graphics/spin_arrow_up_dark.png and /dev/null differ diff --git a/src/aare/gui/graphics/spin_arrow_up_light.png b/src/aare/gui/graphics/spin_arrow_up_light.png deleted file mode 100644 index 25533140..00000000 Binary files a/src/aare/gui/graphics/spin_arrow_up_light.png and /dev/null differ diff --git a/src/aare/gui/gui.py b/src/aare/gui/gui.py deleted file mode 100644 index 6559b148..00000000 --- a/src/aare/gui/gui.py +++ /dev/null @@ -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() diff --git a/src/aare/gui/log.py b/src/aare/gui/log.py deleted file mode 100644 index 815b007e..00000000 --- a/src/aare/gui/log.py +++ /dev/null @@ -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) diff --git a/src/aare/gui/main_window.py b/src/aare/gui/main_window.py deleted file mode 100644 index 729e5e70..00000000 --- a/src/aare/gui/main_window.py +++ /dev/null @@ -1,3187 +0,0 @@ -import time - -import jwt -from aarecommon.config.logger import setup_logger -from aarecommon.math.coordinate import Coordinate, SmargonCoordinate -from aarecommon.math.diffraction_geometry import DiffractionGeometry -from aarecommon.math.sample_geometry import SampleGeometryModel - -# Common imports -from aarecommon.models.auth import BatonStatus -from aarecommon.models.models import ( - BeamlineStateEnum, - DAQStatusModel, - SampleShortInfoList, - SessionsStateEnum, - TokenData, -) -from PySide6.QtCore import ( - QByteArray, - QEvent, - QObject, - QPropertyAnimation, - QSettings, - Qt, - QTimer, - Signal, - Slot, -) -from PySide6.QtGui import ( - QAction, - QActionGroup, - QColor, - QCursor, - QFont, - QImage, - QKeySequence, - QPalette, - QPixmap, -) -from PySide6.QtWidgets import ( - QAbstractButton, - QApplication, - QCheckBox, - QComboBox, - QDockWidget, - QFrame, - QGraphicsColorizeEffect, - QGraphicsOpacityEffect, - QHBoxLayout, - QLabel, - QMainWindow, - QMessageBox, - QPushButton, - QScrollArea, - QSizePolicy, - QSlider, - QTabWidget, - QToolBar, - QToolTip, - QVBoxLayout, - QWidget, -) - -from aare.gui.about import about_text -from aare.gui.constants import LOGGER_NAME - -# Gui Models -from aare.gui.models.gui_state_manager import UIStateManager -from aare.gui.panels.abr_tweak_panel import AbrTweakWidget -from aare.gui.panels.automation_panel import AutomationProgressWidget -from aare.gui.panels.axis_video_panel import AxisVideoPanel -from aare.gui.panels.beamline_controls import BeamConfigPanel, BeamlineControls -from aare.gui.panels.beamline_recovery_panel import BeamlineRecoveryDialog -from aare.gui.panels.beamline_state_panel import BeamlineStatePanel -from aare.gui.panels.data_collection_settings import DataCollectionSettings -from aare.gui.panels.developer_help_dialog import DeveloperHelpDialog -from aare.gui.panels.face_detection_panel import FaceDetectionPanel -from aare.gui.panels.fluorescence_panel import FluorescencePanel -from aare.gui.panels.local_contact_panel import LocalContactDialog - -# panels -from aare.gui.panels.log_panel import LogPanel -from aare.gui.panels.monochromator_panel import MonochromatorPanel -from aare.gui.panels.prediction_metrics_panel import PredictionMetricsPanel -from aare.gui.panels.reference_tools_panel import ReferenceToolsPanel -from aare.gui.panels.samcam_panel import SamcamPanel -from aare.gui.panels.sample_queue_panel import SampleQueuePanel -from aare.gui.panels.smargon_trace_panel import SmargonTracePanel -from aare.gui.panels.target_stability_panel import TargetStabilityPanel -from aare.gui.panels.tell_sample_panel import TellSamplePanel - -# Scan Logic -from aare.gui.scan_logic.raster_grid_manager import RasterGridManager -from aare.gui.scan_logic.rotation_scan_manager import RotationScanManager -from aare.gui.scan_logic.sample_mount_logic import SampleMountLogic -from aare.gui.styles import ( - APP_BACKGROUND, - DARK_TEXT, - DOCK_CONTENT_LEFT_PAD, - FONT_SCALE_LADDER, - SEPARATOR_HINT_DELAY_MS, - THEME_BLUEBIRD, - THEME_FADE_MS, - THEME_SUNRISE, - THEME_SUNSET, - admin_tip_qss, - build_app_stylesheet, - font_scale, - qcolor, - set_font_scale, -) - -# Threads -from aare.gui.threads.axis_video_thread import VideoThread -from aare.gui.threads.daq_worker import DAQWorker -from aare.gui.threads.jfjoch_viewer import JFJochDBusClient -from aare.gui.threads.prediction_subscriber import PredictionSubscriber -from aare.gui.tutorials.controls_help_dialog import ControlsHelpDialog - -# Tutorials -from aare.gui.tutorials.tutorial_actions import TutorialActionExecutor -from aare.gui.tutorials.tutorial_manager import TutorialManager -from aare.gui.tutorials.tutorial_registration import register_tutorials -from aare.gui.tutorials.tutorial_runtime import DictionaryTextResolver, TutorialEventBus -from aare.gui.tutorials.tutorial_targets import MainWindowTutorialTargetResolver -from aare.gui.tutorials.tutroial_texts import MANUAL_MOUNT_TUTORIAL - -# Widgets -from aare.gui.widgets.alert_banner import AlertBanner -from aare.gui.widgets.baton_request_dialog import BatonPendingDialog, BatonRequestDialog -from aare.gui.widgets.busy_overlay import build_busy_overlay_style -from aare.gui.widgets.camera_image import SampleCameraImageLabel -from aare.gui.widgets.message_box import precondition_check -from aare.gui.widgets.no_wheel_scroll_area import NoWheelScrollArea -from aare.gui.widgets.popout_window import DockTitleBar, PopoutWindow -from aare.gui.widgets.status_bar import StatusBar -from aare.gui.widgets.title_label import TitleLabel, tighten_column -from aare.gui.widgets.video_image import VideoGraphicsView -from aare.gui.widgets.wheel_value_guard import WheelValueGuard - -logger = setup_logger(LOGGER_NAME) - - -class ClickableCursorFilter(QObject): - """App-wide pointing-hand cursor on every button/combo/slider, present - and future. QSS cannot set cursors, and per-widget setCursor calls are - forgotten whenever a new widget is added — the Polish event fires once - for each widget when its style is applied, so this catches them all. - Widgets that manage their own cursor afterwards (beamline state strip's - forbidden cursor) still win: they set it later.""" - - def eventFilter(self, obj, event): - # Same PySide 6.9 quirk as WheelValueGuard: an app-level filter can be - # handed a QWidgetItem instead of a QEvent during layout teardown. - if not isinstance(event, QEvent): - return False - if event.type() == QEvent.Type.Polish and isinstance( - obj, (QAbstractButton, QComboBox, QSlider) - ): - obj.setCursor(Qt.CursorShape.PointingHandCursor) - return False - - -class _AlertBannerHost(QWidget): - """Content root that repositions the floating alert banners on resize. - A plain resizeEvent override instead of event filters: filters firing - during widget teardown corrupted PySide in the test suite.""" - - def resizeEvent(self, event): - super().resizeEvent(event) - for banner in self.findChildren(AlertBanner): - banner.reposition() - - -class MainWindow(QMainWindow): - sample_geometry = Signal(SampleGeometryModel) - - # Class-level defaults: Qt can call overrides (showEvent, closeEvent) - # before __init__ finishes, so these must be readable without a getattr - # guard; also typed for the basedpyright gate. - _session_operations_enabled: bool | None = None - _default_dock_split_done: bool = False - _cleanup_done: bool = False - _pre_watch_dock_state: QByteArray | None = None - _pre_watch_visibility: list[tuple[QWidget, bool]] | None = None - - def __init__( - self, - base_url: str | None, - token: str, - default_image: str | None, - zmq_addr: str | None, - pred_zmq_addr: str | None, - beamline_cam_addr: str | None, - gonio_cam_addr: str | None, - gonio_cam_id: int | None, - ): - super().__init__() - - # Banners open before a baton-vacancy fold; in __init__ (not a class - # default) so the mutable list is per-instance (RUF012). - self._pre_vacancy_open_banners: list[TitleLabel] = [] - - self._theme_mode = THEME_BLUEBIRD - self._theme_action_group = None - self._use_legacy_theme_action = None - self._use_portrait_theme_action = None - - self._base_url = base_url - self._token = token - self._watching_motion = False - self._samcam_feed_banner_active = False - self._samcam_feed_banner_message = "Sample camera feed unavailable" - - self._automation_critical_banner_active = False - self._dev_help_dialog = None - self._beamline_recovery_dialog = None - self._local_contact_dialog = None - self._controls_help_dialog = None - self._default_window_state = None - - self._beamline_cam_addr = beamline_cam_addr - self._gonio_cam_addr = gonio_cam_addr - self._gonio_cam_id = gonio_cam_id - self._axis_camera_refresh_interval_ms = 60 * 60 * 1000 - self.beamline_camera_thread = None - self.gonio_camera_thread = None - - self._waiting_for_baton_response: bool = False - self._baton_request_dialog: BatonRequestDialog | None = None - self._baton_pending_dialog: BatonPendingDialog | None = None - - self._last_user_interaction_ts = time.time() - self._last_interaction_report_ts = 0.0 - self._interaction_report_min_interval_s = 15.0 - self._idle_close_timeout_s = 60 * 60 * 8 - self._remote_close_deadline_ts: float | None = None - self._remote_close_reason: str | None = None - self._remote_close_banner_active: bool = False - self._latest_daq_status: DAQStatusModel | None = None - # Queue head awaiting removal: popped only once /status shows it is no - # longer on the gonio, so a failed unmount never loses a sample. - self._pending_unmount_pop: int | None = None - - self._tutorial_event_bus = TutorialEventBus(self) - self._tutorial_text_resolver = DictionaryTextResolver(MANUAL_MOUNT_TUTORIAL) - self.state_manager = UIStateManager("PSI", "AareGUI") - - # App-level, not window-level: dialogs and pop-outs get it too. - # Installed once per process and parented to the app, NOT the window: - # the old per-window copies stacked up (one per MainWindow the test - # suite builds) and kept filtering every process event after their - # parent window died — stale wrappers in the hottest Qt→Python path. - app = QApplication.instance() - assert app is not None - if not app.property("_aare_app_filters_installed"): - app.setProperty("_aare_app_filters_installed", True) - app.installEventFilter(ClickableCursorFilter(app)) - # Wheel safety: sliders/spin boxes/combos only react to the wheel - # while the right mouse button is held; a bare wheel just scrolls - # the page — it can never nudge a value or move a motor. - app.installEventFilter(WheelValueGuard(app)) - self.viewer = JFJochDBusClient() - - try: - token_str = (token or "").strip() - if token_str.count(".") != 2: - raise ValueError( - "Invalid authentication token received (not a JWT). " - "This usually happens when the server is not running or still starting." - ) - - payload = jwt.decode(token_str, options={"verify_signature": False}) - self._decoded_token = TokenData(**payload) - except Exception: - logger.exception("Failed to decode authentication token") - QMessageBox.critical( - None, - "Authentication Error", - "Could not start the GUI because authentication data was invalid.\n\n" - "Most commonly the server is not running yet (or is still initialising).\n" - "Please start/restart the server and try again.", - ) - raise - - self.setStyleSheet(f"background-color: {APP_BACKGROUND};") - - # Resize-line hint (see SEPARATOR_HINT in styles.py): WA_Hover gives - # us HoverMove without a button held; the single-shot timer implements - # the "rested for 1s" gate. The QSS ::separator:hover rule does the - # hit-testing, so event() never needs to know where separators are. - self.setAttribute(Qt.WidgetAttribute.WA_Hover, True) - self._separator_hint_timer = QTimer(self) - self._separator_hint_timer.setSingleShot(True) - self._separator_hint_timer.setInterval(SEPARATOR_HINT_DELAY_MS) - self._separator_hint_timer.timeout.connect(lambda: self._set_separator_hint(True)) - - root_widget = _AlertBannerHost(parent=self) - root_widget.setObjectName("mainContentRoot") - root_layout = QVBoxLayout(root_widget) - root_layout.setContentsMargins(0, 0, 0, 0) - root_layout.setSpacing(0) - - # Banners float over the content instead of sitting in root_layout, so - # messages (e.g. "Baton acquired!") no longer shift the whole UI. - self.alert_banner = AlertBanner(parent=root_widget) - self.alert_banner.float_over(root_widget) - - self.alert_banner_secondary = AlertBanner(parent=root_widget) - self.alert_banner_secondary.float_over(root_widget) - - top_widget = QWidget(parent=root_widget) - top_widget.setObjectName("standardMainPage") - top_widget_layout = QHBoxLayout(top_widget) - top_widget.setLayout(top_widget_layout) - - diffraction = DiffractionGeometry( - energy_keV=12.4, - dtz_mm=100, - detector_size_pxl=(1553, 1630), - pixel_size_mm=0.150, # PILATUS 4 - beam_center_pxl=(750, 750), - detector_description="PILATUS 4", - detector_serial_number="1", - poni_rot1_rad=-0, - poni_rot2_rad=-0, - ) - - geom = SampleGeometryModel( - beam_location_pxl=Coordinate(x=1000, y=1000), - pixel_in_mm=0.001, - aerotech=Coordinate(), - smargon=SmargonCoordinate(sh_mm=Coordinate(), phi_deg=0, chi_deg=0), - omega_deg=0, - beam_size_mm=Coordinate(x=0.01, y=0.01), - aerotech_meas=Coordinate(), - ) - - self.raster = RasterGridManager(geom=geom) - self.rotation = RotationScanManager() - - self.collection_controls_scroll = NoWheelScrollArea(top_widget) - - self.left_column = QWidget(parent=top_widget) - self.left_column_layout = QVBoxLayout(self.left_column) - self.left_column_layout.setContentsMargins(0, 0, 0, 0) - - self.data_collection = DataCollectionSettings( - s=geom, parent=self.left_column, raster_mgr=self.raster, diffraction=diffraction - ) - - # The beamline state strip lives in a bottom toolbar row (created - # after the docks), not in the left column. Always visible. - self.beamline_state_panel = BeamlineStatePanel(staff=self._decoded_token.staff, parent=self) - - # Anchor for _show_admin_tip: QToolTip inherits QSS from the widget - # it is shown for, so this hidden label carries the red warning wash - # without reddening any other tooltip. Eager, not lazy — basedpyright - # requires instance attributes to exist after __init__. - self._admin_tip_anchor = QLabel(self) - self._admin_tip_anchor.hide() - - # Beamline / Experiment as tabs (like the Dewar samples dock) instead - # of two stacked banner groups; the pages keep their banner children. - # documentMode: no pane frame, so the fixed-width panels aren't inset. - self.left_column_tabs = QTabWidget(self.left_column) - self.left_column_tabs.setDocumentMode(True) - # documentMode draws a grey base line across the bar's full width. - self.left_column_tabs.tabBar().setDrawBase(False) - - beamline_page = QWidget() - beamline_layout = QVBoxLayout(beamline_page) - beamline_layout.setContentsMargins(0, 0, 0, 0) - self.samcam = SamcamPanel(beamline_page) - # Non-staff keep the staff-only banners visible (locked stand-ins, a - # click explains the gate) so the Beamline tab reads the same for - # every role instead of looking amputated. - self._locked_beamline_banners: list[TitleLabel] = [] - if self._decoded_token.staff: - self.monochromator_panel = MonochromatorPanel(beamline_page) - self.abr_tweak = AbrTweakWidget(beamline_page) - self.beam_config = BeamConfigPanel(beamline_page) - self.beam_mark = self.beam_config.beam_mark - self.beam_center = self.beam_config.beam_center - self.beam_size = self.beam_config.beam_size - beamline_layout.addWidget(self.monochromator_panel) - beamline_layout.addWidget(self.abr_tweak) - beamline_layout.addWidget(self.beam_config) - else: - for title in ("Beamline setup", "ABR meas. pos.", "Beam configuration"): - # Holder with default layout margins so the banner aligns with - # the real panels' banners (same trick as BeamConfigPanel). - holder = QWidget(beamline_page) - holder_layout = QVBoxLayout(holder) - holder_layout.setSpacing(0) - banner = TitleLabel(title, holder) - banner.setCursor(Qt.CursorShape.PointingHandCursor) - banner.setToolTip("Only accessible for beamline scientists") - # eventFilter install happens LATE in __init__ (next to - # installEventFilter(self)) — see the comment there. - holder_layout.addWidget(banner) - beamline_layout.addWidget(holder) - self._locked_beamline_banners.append(banner) - # Samcam last: the beam panels are the ones tweaked most. - beamline_layout.addWidget(self.samcam) - beamline_layout.addStretch() - tighten_column(beamline_layout) - - experiment_page = QWidget() - experiment_layout = QVBoxLayout(experiment_page) - experiment_layout.setContentsMargins(0, 0, 0, 0) - experiment_layout.addWidget(self.data_collection) - experiment_layout.addStretch() - tighten_column(experiment_layout) - - self.left_column_tabs.addTab(beamline_page, "Beamline") - self.left_column_tabs.addTab(experiment_page, "Experiment") - - # Only the visible page counts toward the height — same trick as the - # content stack below, else the taller page pads the other tab. - def _only_current_left_tab_counts(index: int) -> None: - for i in range(self.left_column_tabs.count()): - page = self.left_column_tabs.widget(i) - vertical = ( - QSizePolicy.Policy.Preferred if i == index else QSizePolicy.Policy.Ignored - ) - page.setSizePolicy(QSizePolicy.Policy.Preferred, vertical) - - self.left_column_tabs.currentChanged.connect(_only_current_left_tab_counts) - _only_current_left_tab_counts(self.left_column_tabs.currentIndex()) - - # Dewar-tabs look: first banner flush under the tab bar (no top - # margin) and the tab row starting at the banners' left edge. The - # Experiment side needs two levels: the frame AND its first panel. - beamline_first = ( - self.monochromator_panel - if self._decoded_token.staff - # Non-staff: the first locked banner's holder is the column's - # first widget now, not samcam. - else self._locked_beamline_banners[0].parentWidget() - ) - assert beamline_first is not None # the locked banner always has its holder - for first in (beamline_first, self.data_collection, self.data_collection.file_path_panel): - first_layout = first.layout() - assert first_layout is not None # panels build their layouts in __init__ - m = first_layout.contentsMargins() - first_layout.setContentsMargins(m.left(), 0, m.right(), m.bottom()) - samcam_layout = self.samcam.layout() - assert samcam_layout is not None - self.left_column_tabs.setStyleSheet( - f"QTabWidget::tab-bar {{ left: {samcam_layout.contentsMargins().left()}px; }}" - ) - - self.left_column_layout.addWidget(self.left_column_tabs) - self.left_column_layout.addStretch() - - # Plain HBox, no splitter: drag-resizing the side columns was tried - # and rejected (user: the panels don't need resizing — the View-menu - # toggles collapse them, and the camera takes whatever is left). - top_widget_layout.addWidget(self.collection_controls_scroll) - self.collection_controls_scroll.setWidget(self.left_column) - self.collection_controls_scroll.setHorizontalScrollBarPolicy( - Qt.ScrollBarPolicy.ScrollBarAlwaysOff - ) - self.collection_controls_scroll.setWidgetResizable(True) - # No frame: its border drew a line above the tab bar (Dewar tabs have - # none). Freeze the inner column width: widgetResizable makes it track - # the viewport, so the scrollbar appearing used to re-flow every - # banner. Fixed inner width + a 10px scrollbar gutter means the - # scrollbar pops into spare space and nothing moves; the widths are - # zoom-dependent and live in _apply_zoom_widths. - - self.video_tab = QTabWidget(parent=top_widget) - - self.sample_camera = SampleCameraImageLabel( - geom=geom, raster=self.raster, parent=top_widget, default_image=default_image - ) - # Baton toasts sit as a compact pill under the camera view instead of - # a full-width bar at the top of the window. - self.alert_banner.anchor_to(self.sample_camera) - - self.beamline_view = VideoGraphicsView() - self.beamline_view_panel = AxisVideoPanel( - "Beamline view", self.beamline_view, parent=top_widget - ) - self.beamline_view_panel.refresh_requested.connect(self.refresh_axis_cameras) - - self.gonio_view = VideoGraphicsView() - self.gonio_view_panel = AxisVideoPanel("Gonio camera", self.gonio_view, parent=top_widget) - self.gonio_view_panel.refresh_requested.connect(self.refresh_axis_cameras) - - self.beamline_view_container = QWidget(parent=top_widget) - self.beamline_view_layout = QVBoxLayout(self.beamline_view_container) - self.beamline_view_layout.setContentsMargins(0, 0, 0, 0) - self.beamline_view_layout.setSpacing(6) - - self.beamline_view_1_combined = VideoGraphicsView() - self.beamline_view_2_combined = VideoGraphicsView() - self.beamline_view_layout.addWidget(self.beamline_view_1_combined) - self.beamline_view_layout.addWidget(self.beamline_view_2_combined) - - self.beamline_combined_panel = AxisVideoPanel( - "Beamline combined view", self.beamline_view_container, parent=top_widget - ) - self.beamline_combined_panel.refresh_requested.connect(self.refresh_axis_cameras) - - self.video_tab.addTab(self.sample_camera, "Sample camera") - self.video_tab.addTab(self.gonio_view_panel, "Gonio camera") - self.video_tab.addTab(self.beamline_view_panel, "Beamline view") - self.video_tab.addTab(self.beamline_combined_panel, "Beamline combined view") - - # The camera region's natural minimum (~284px) came from the widest - # page's controls row (title + refresh button) and the tab labels — - # not from the video views, which rescale freely like they do in - # height. Clamp to 1/3 so a narrow window can shrink all four camera - # views that far; past the natural width the tab bar scrolls and the - # controls rows clip. - self.video_tab.setMinimumWidth(self.video_tab.minimumSizeHint().width() // 3) - - # if cfg_get("gui.cameras.secondary_beamline_camera_url", None): - # self.secondary_beamline_view = VideoGraphicsView() - # self.secondary_beamline_view_panel = AxisVideoPanel("Secondary view", self.secondary_beamline_view, - # parent=top_widget) - # self.secondary_beamline_view_panel.refresh_requested.connect(self.refresh_axis_cameras) - # self.video_tab.addTab(self.secondary_beamline_view_panel, "Secondary view") - - top_widget_layout.addWidget(self.video_tab, 1) - self._start_axis_camera_threads() - - self.beamline_controls_scroll = NoWheelScrollArea(top_widget) - - self.beamline = BeamlineControls(self.beamline_controls_scroll) - top_widget_layout.addWidget(self.beamline_controls_scroll) - self.beamline_controls_scroll.setWidget(self.beamline) - # Resizable so the column shrinks when panels collapse; without it the - # scrollbar keeps dead range below the collapsed panels. - self.beamline_controls_scroll.setWidgetResizable(True) - self.beamline_controls_scroll.setHorizontalScrollBarPolicy( - Qt.ScrollBarPolicy.ScrollBarAlwaysOff - ) - # Gutter math per column (10px scrollbar + frame) lives here. - self._apply_zoom_widths() - - self.tell_samples = TellSamplePanel(samples=SampleShortInfoList(s=[])) - self.ref_tools_panel = ReferenceToolsPanel(samples=SampleShortInfoList(s=[])) - self.job_list_panel = SampleQueuePanel(show_user=self._decoded_token.staff) - - # One dock for both lists: the old tabified Reference Tools dock was - # staff-only and hid behind the Sample List tab, so it "sometimes" - # showed. aaregui2 concept: one panel, Dewar + Auxiliary-puck tabs - # that always travel together, and the dewar table doubles as the - # queue view (status tints), so the automation controls sit under it - # and the Automation list dock is gone. SampleQueuePanel stays alive, - # hidden, as the queue engine; its buttons are reparented here so all - # their existing wiring keeps working. - dewar_tab = QWidget() - dewar_tab.setObjectName("dewarTab") - dewar_layout = QVBoxLayout(dewar_tab) - dewar_layout.setContentsMargins(0, 0, 0, 0) - dewar_layout.setSpacing(2) - dewar_layout.addWidget(self.tell_samples) - - self.quick_unmount_button = QPushButton("⏏ Unmount", dewar_tab) - self.quick_unmount_button.clicked.connect(lambda: self._on_manual_unmount_requested()) - - # Was parented to dewar_tab but never added to a layout, so Qt - # painted it at (0, 0) — on top of the TELL banner. It lives in the - # automation row, left of Unmount, like the pop-out clone below. - self.mount_next_button = QPushButton("⏭ Mount next", dewar_tab) - self.mount_next_button.clicked.connect(self._mount_next_from_queue) - - automation_row = QHBoxLayout() - for w in ( - self.job_list_panel.play_button, - self.job_list_panel.remove_button, - self.job_list_panel.clear_button, - self.mount_next_button, - self.quick_unmount_button, - self.job_list_panel.park_and_dry_when_cleared, - self.job_list_panel.pause_on_conditions_cb, - ): - automation_row.addWidget(w) - # Trailing stretch: without it every widget shares the spare width - # and the buttons balloon; five buttons plus two long checkboxes need - # them at their natural size. - automation_row.addStretch(1) - # Host widget with Ignored horizontal policy: the row's ~1000px - # natural minimum used to propagate dock -> window and pin the whole - # window wider than small screens (unshrinkable). Now the row clips - # from the right instead. - automation_row_host = QWidget(dewar_tab) - automation_row_host.setLayout(automation_row) - automation_row_host.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Fixed) - dewar_layout.addWidget(automation_row_host) - - # "Remove selected" now unqueues the dewar-table selection — the - # queue's own table is no longer displayed. - self.job_list_panel.remove_button.clicked.disconnect( - self.job_list_panel.remove_selected_samples - ) - self.job_list_panel.remove_button.clicked.connect(self._remove_selected_from_queue) - self.job_list_panel.hide() - - # Queue controls act on the queue, whose order only the Queued chip - # view shows — so they are live there and greyed out elsewhere. The - # pop-out clones register themselves in _clone_automation_row. "run" - # kind stays enabled while automation runs: pausing is always allowed. - self._queue_action_buttons: list[tuple[QPushButton, str]] = [ - (self.job_list_panel.play_button, "run"), - (self.job_list_panel.remove_button, "queue"), - (self.job_list_panel.clear_button, "queue"), - (self.mount_next_button, "queue"), - ] - self.tell_samples.status_chips.buttonClicked.connect( - lambda _chip: self._update_queue_buttons_enabled() - ) - self.job_list_panel.automation_running_changed.connect( - lambda _running: self._update_queue_buttons_enabled() - ) - self._update_queue_buttons_enabled() - - self.sample_lists_tabs = QTabWidget() - self.sample_lists_tabs.addTab(dewar_tab, "Dewar samples") - self.sample_lists_tabs.addTab(self.ref_tools_panel, "Auxiliary puck") - # Non-staff never get reference-tools data (the DAQ connect below is - # staff-gated). Grey the tab out instead of hiding it: every role sees - # the same view, and clicking the locked tab says why it is locked. - if not self._decoded_token.staff: - self.sample_lists_tabs.setTabEnabled(1, False) - self.sample_lists_tabs.setTabToolTip(1, "Staff only") - # Disabled tabs are skipped by tabBarClicked's hit-test, so the - # click is caught in eventFilter via the geometric tabAt() instead. - self.sample_lists_tabs.tabBar().installEventFilter(self) - - # Tracks beamline-state TRANSITIONS for the default sample-tab switch - # (see _apply_default_sample_tab). - self._last_beamline_state: BeamlineStateEnum | None = None - # None = not yet evaluated, so the first status tick always applies - # the gate (the GUI may start while a visitor pgroup is active). - self._beamline_tab_gated: bool | None = None - - # Wrapper for the left inset: QTabWidget ignores its own contents - # margins for the tab bar, so the padding lives one level up. Aligns - # the panel's left edge with the left column above (Loop centering). - sample_lists_wrap = QWidget() - sample_lists_wrap_layout = QVBoxLayout(sample_lists_wrap) - sample_lists_wrap_layout.setContentsMargins(DOCK_CONTENT_LEFT_PAD, 0, 0, 0) - sample_lists_wrap_layout.setSpacing(0) - sample_lists_wrap_layout.addWidget(self.sample_lists_tabs) - - self.tell_samples_dock = QDockWidget("Sample List", self) - self.tell_samples_dock.setObjectName("tell_samples_dock") - self.tell_samples_dock.setWidget(sample_lists_wrap) - self.tell_samples_dock.setAllowedAreas(Qt.DockWidgetArea.BottomDockWidgetArea) - self.addDockWidget(Qt.DockWidgetArea.BottomDockWidgetArea, self.tell_samples_dock) - - # No floating: popping the dock out ripped the panel from the row and - # reshuffled the rest. The ⤢ button (in the title bar, next to ✕) - # opens an ADDITIONAL fully-wired window; closing it changes nothing. - self.tell_samples_dock.setFeatures( - QDockWidget.DockWidgetFeature.DockWidgetMovable - | QDockWidget.DockWidgetFeature.DockWidgetClosable - ) - self._sample_popout: PopoutWindow | None = None - self.tell_samples_dock.setTitleBarWidget( - DockTitleBar(self.tell_samples_dock, self._open_sample_popout) - ) - - self.sample_logic = SampleMountLogic() - - # Manual sample lives in the left column (DataCollectionSettings) - # between Dataset path and Exp. Config., collapsible like its - # neighbors — it is no longer a bottom dock. - self.manual_sample_panel = self.data_collection.manual_sample_panel - - self.automation_progress_panel = AutomationProgressWidget() - # Scroll host: the panel's ~420px minimum otherwise dictates the whole - # bottom row's height and squeezes the Beamline column into a scrollbar. - automation_scroll = NoWheelScrollArea() - automation_scroll.setWidget(self.automation_progress_panel) - automation_scroll.setWidgetResizable(True) - automation_scroll.setFrameShape(QFrame.Shape.NoFrame) - - # One "Information" dock with Automation progress + Console log tabs, - # mirroring the Sample List dock's Dewar/Auxiliary layout — replaces - # the two tabified docks whose switcher tabs sat at the window bottom. - self.log_panel = LogPanel() - self.log_panel.attach_logger("") - self.log_panel.attach_logger("aareGUI") - self.log_panel.reveal_requested.connect(self._reveal_console_log) - - self.information_tabs = QTabWidget() - self.information_tabs.addTab(automation_scroll, "Automation progress") - self.information_tabs.addTab(self.log_panel, "Console log") - - # Same wrapper trick as the Sample List dock: QTabWidget ignores its - # own contents margins for the tab bar, so the inset lives one level up. - information_wrap = QWidget() - information_wrap_layout = QVBoxLayout(information_wrap) - information_wrap_layout.setContentsMargins(DOCK_CONTENT_LEFT_PAD, 0, 0, 0) - information_wrap_layout.setSpacing(0) - information_wrap_layout.addWidget(self.information_tabs) - - self.information_dock = QDockWidget("Information", self) - self.information_dock.setObjectName("information_dock") - self.information_dock.setWidget(information_wrap) - self.information_dock.setAllowedAreas(Qt.DockWidgetArea.BottomDockWidgetArea) - self.addDockWidget(Qt.DockWidgetArea.BottomDockWidgetArea, self.information_dock) - self.information_dock.setFeatures( - QDockWidget.DockWidgetFeature.DockWidgetMovable - | QDockWidget.DockWidgetFeature.DockWidgetClosable - ) - # Same title-bar icons (⤢ pop-out + ✕) as Sample List. - self._information_popout: PopoutWindow | None = None - self.information_dock.setTitleBarWidget( - DockTitleBar(self.information_dock, self._open_information_popout) - ) - - self.face_panel = FaceDetectionPanel() - self.face_panel_dock = QDockWidget("Face detection", self) - self.face_panel_dock.setObjectName("face_panel_dock") - self.face_panel_dock.setWidget(self.face_panel) - self.face_panel_dock.setAllowedAreas( - Qt.DockWidgetArea.RightDockWidgetArea | Qt.DockWidgetArea.LeftDockWidgetArea - ) - self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.face_panel_dock) - self.face_panel_dock.hide() - - self.fluor_panel = FluorescencePanel() - self.fluor_panel_dock = QDockWidget("Fluorescence", self) - self.fluor_panel_dock.setObjectName("fluor_panel_dock") - self.fluor_panel_dock.setWidget(self.fluor_panel) - self.fluor_panel_dock.setAllowedAreas( - Qt.DockWidgetArea.TopDockWidgetArea - | Qt.DockWidgetArea.BottomDockWidgetArea - | Qt.DockWidgetArea.RightDockWidgetArea - ) - self.addDockWidget(Qt.DockWidgetArea.BottomDockWidgetArea, self.fluor_panel_dock) - self.fluor_panel_dock.hide() - - self.job_list_panel.samples_in_queue_changed.connect( - self.automation_progress_panel.set_samples_in_queue - ) - self.job_list_panel.automation_running_changed.connect( - self.automation_progress_panel.set_running - ) - self.job_list_panel.automation_running_changed.connect(self._on_automation_running_changed) - self.job_list_panel.automation_running_changed.connect( - self.data_collection.set_automation_running - ) - - self.automation_progress_panel.set_samples_in_queue( - len(self.job_list_panel.table_model.samples) - ) - self.automation_progress_panel.set_running(self.job_list_panel.is_running()) - - # smargon trace panel - self.smargon_trace_panel = SmargonTracePanel() - self.smargon_trace_dock = QDockWidget("Smargon trace", self) - self.smargon_trace_dock.setObjectName("smargon_trace_dock") - self.smargon_trace_dock.setWidget(self.smargon_trace_panel) - self.smargon_trace_dock.setAllowedAreas( - Qt.DockWidgetArea.RightDockWidgetArea - | Qt.DockWidgetArea.LeftDockWidgetArea - | Qt.DockWidgetArea.BottomDockWidgetArea - ) - self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.smargon_trace_dock) - self.smargon_trace_dock.hide() - - # Target stability panel - self.target_stability_panel = TargetStabilityPanel() - self.target_stability_dock = QDockWidget("Target stability", self) - self.target_stability_dock.setObjectName("target_stability_dock") - self.target_stability_dock.setWidget(self.target_stability_panel) - self.target_stability_dock.setAllowedAreas( - Qt.DockWidgetArea.RightDockWidgetArea - | Qt.DockWidgetArea.LeftDockWidgetArea - | Qt.DockWidgetArea.BottomDockWidgetArea - ) - self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.target_stability_dock) - self.target_stability_dock.hide() - - # Prediction Metrics Panel - self.prediction_metrics_panel = PredictionMetricsPanel() - self.prediction_metrics_dock = QDockWidget("Prediction Metrics", self) - self.prediction_metrics_dock.setObjectName("prediction_metrics_dock") - self.prediction_metrics_dock.setWidget(self.prediction_metrics_panel) - self.prediction_metrics_dock.setAllowedAreas( - Qt.DockWidgetArea.RightDockWidgetArea - | Qt.DockWidgetArea.LeftDockWidgetArea - | Qt.DockWidgetArea.BottomDockWidgetArea - ) - self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.prediction_metrics_dock) - self.prediction_metrics_dock.hide() - - # Full-width state strip directly above the status bar: the bottom - # toolbar area is guaranteed to sit below the bottom dock area (a - # bottom dock would land beside the existing docks instead). - self.beamline_state_toolbar = QToolBar("Beamline state", self) - self.beamline_state_toolbar.setObjectName("beamline_state_toolbar") - self.beamline_state_toolbar.setMovable(False) - self.beamline_state_toolbar.setFloatable(False) - self.beamline_state_toolbar.setAllowedAreas(Qt.ToolBarArea.BottomToolBarArea) - self.beamline_state_panel.setSizePolicy( - QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred - ) - self.beamline_state_toolbar.addWidget(self.beamline_state_panel) - self.addToolBar(Qt.ToolBarArea.BottomToolBarArea, self.beamline_state_toolbar) - - # The standard page's combined panel minimum (~1400x1200) exceeds many - # monitors, which pushed the status bar off-screen. Scrolling instead of - # clamping lets the window shrink to any screen; scrollbars only appear - # when the monitor is actually smaller than the panels. - standard_page_scroll = QScrollArea(parent=root_widget) - standard_page_scroll.setWidgetResizable(True) - standard_page_scroll.setFrameShape(QFrame.Shape.NoFrame) - standard_page_scroll.setWidget(top_widget) - root_layout.addWidget(standard_page_scroll, 1) - - self.setCentralWidget(root_widget) - - # Qt auto-pins a top-level window's minimum size to its layout - # minimum, which the bottom dock row pushed past small monitors. - # An explicit minimum disables that auto-pin: the window shrinks to - # this floor and the dock contents clip/scroll instead. - self.setMinimumSize(320, 240) - - self.setWindowTitle("AareGUI") - self._restore_theme_settings() - self._apply_theme() - self.create_menu_bar() - self._setup_global_shortcuts() - # Default bottom-dock height: the sample list used to grab ~40% of the - # window and squeeze the Beamline column behind a scrollbar. Before - # the default-state capture so "reset layout" gets it too; a saved - # user layout (restored below) still wins. - self.resizeDocks( - [self.tell_samples_dock, self.information_dock], [240, 240], Qt.Orientation.Vertical - ) - # Equal oversized requests -> Qt distributes proportionally = 50/50. - self.resizeDocks( - [self.tell_samples_dock, self.information_dock], - [10000, 10000], - Qt.Orientation.Horizontal, - ) - self._capture_default_window_state() - self._restore_window_state() - - # Define tutorials now that the UI exists - self._tutorial_target_resolver = MainWindowTutorialTargetResolver(self) - self._tutorial_action_executor = TutorialActionExecutor(self) - - self.tutorial_manager = TutorialManager( - self, - target_resolver=self._tutorial_target_resolver, - text_resolver=self._tutorial_text_resolver, - action_executor=self._tutorial_action_executor, - event_bus=self._tutorial_event_bus, - ) - - self.status_bar = StatusBar(self._decoded_token, parent=self) - # Created after the first _apply_theme, so hand it the theme directly. - self.status_bar.set_theme(self._theme_mode) - self.setStatusBar(self.status_bar) - - self.daq = DAQWorker(base_url=self._base_url, token=self._token) - - self.installEventFilter(self) - # These share MainWindow.eventFilter, which reads sample_lists_tabs - # and left_column_tabs on every event — so they must install only - # HERE, after every attribute the filter touches exists. Installing - # them at widget-construction time made each early event raise - # AttributeError inside the filter ("Error calling Python override - # of QObject::eventFilter()" spam that poisoned CI teardowns). - self.left_column_tabs.tabBar().installEventFilter(self) - for locked_banner in self._locked_beamline_banners: - locked_banner.installEventFilter(self) - - self._remote_close_timer = QTimer(self) - self._remote_close_timer.setInterval(1000) - self._remote_close_timer.timeout.connect(self._check_remote_close_deadline) - - self._axis_camera_refresh_timer = QTimer(self) - self._axis_camera_refresh_timer.setInterval(self._axis_camera_refresh_interval_ms) - self._axis_camera_refresh_timer.timeout.connect(self.refresh_axis_cameras) - self._axis_camera_refresh_timer.start() - - self.daq.polled_devices_status.connect(self._runtime_alert_primary) - self.daq.detector_error.connect(self._runtime_alert_secondary) - - if hasattr(self, "monochromator_panel"): - self.daq.steer_beam_available.connect( - self.monochromator_panel.update_beam_steering_available - ) - - self.daq.baton_status_changed.connect(self.status_bar.update_baton_status) - self.daq.baton_status_changed.connect(self._on_baton_status_changed) - self.daq.baton_request_result.connect(self._on_baton_request_result) - self.daq.baton_response_result.connect(self._on_baton_response_result) - self.daq.baton_timeout_checked.connect(self._on_baton_timeout_checked) - self.daq.automation_progress.connect(self.automation_progress_panel.set_progress) - - self.status_bar.baton_request_received.connect(self._show_baton_request_dialog) - self.status_bar.baton_request_accepted.connect(self._accept_baton_request) - self.status_bar.baton_request_refused.connect(self._refuse_baton_request) - - self.daq.spreadsheet.connect(self.tell_samples.new_sample_list) - if self._decoded_token.staff: - self.daq.reference_tools.connect(self.ref_tools_panel.new_list) - - self.samcam.changed.connect(self.daq.samcam_settings) - self.samcam.screenshot_requested.connect(self.daq.send_screenshot_db) - self.samcam.save_beam_location_setting.connect(self.daq.save_beam_location_camera_setting) - self.data_collection.find_tip.clicked.connect(self.daq.center_loop) - self.data_collection.bounding_box.clicked.connect(self.daq.ml_bounding_box) - self.daq.raster_generated_by_ml.connect(self.raster.update_active_grid_request) - - # Clicking the big session badge (SESSION VACANT / Guest Mode) opens - # the grab/request menu right at the cursor. - self.sample_camera.session_badge_clicked.connect( - lambda: self.status_bar.show_session_menu(QCursor.pos()) - ) - self.sample_camera.smargon.connect(self.daq.move_smargon) - self.beamline.smargon_panel.smargon.connect(self.daq.move_smargon) - self.sample_camera.samcam_updated.connect(self.daq.samcam_settings) - self.sample_camera.open_full_help.connect(self.show_controls_help) - - self.raster.omega.connect(self.daq.set_omega) - self.raster.smargon.connect(self.daq.move_smargon) - - self.beamline.omega_panel.set_omega_rel.connect(self.daq.set_omega_rel) - self.beamline.omega_panel.set_omega.connect(self.daq.set_omega) - self.sample_camera.set_omega.connect(self.daq.set_omega) - self.beamline.zoom_panel.zoom.connect(self.daq.zoom) - self.beamline.illumination_panel.front_light.connect(self.daq.front_light) - self.beamline.illumination_panel.back_light.connect(self.daq.back_light) - - # Energy row inside Exp. Config. — not staff-gated like the - # Beamline setup copy; the server enforces write permission anyway. - self.data_collection.change_energy.connect(self.daq.change_energy) - - if self._decoded_token.staff: - self.monochromator_panel.mono_pitch_scan.connect(self.daq.mono_pitch_scan) - self.monochromator_panel.move_beam_to_box.connect(self.daq.steer_beam) - self.monochromator_panel.change_energy.connect(self.daq.change_energy) - self.monochromator_panel.open_shutter.connect(self.daq.open_shutter) - self.monochromator_panel.close_shutter.connect(self.daq.close_shutter) - self.abr_tweak.abr_tweak.connect(self.daq.abr_tweak) - self.abr_tweak.abr_save.connect(self.daq.abr_save) - self.abr_tweak.abr_goto_meas.connect(self.daq.abr_goto_meas) - - self.beam_mark.beam_mark_clear.connect(self.daq.beam_mark_clear) - self.sample_camera.update_beam_mark.connect(self.daq.beam_mark_add) - self.beam_center.beam_center.connect(self.daq.beam_center) - self.beam_size.beam_size.connect(self.daq.beam_size_mm) - - self.sample_camera.load_image.connect(self.raster.load_image) - self.sample_camera.switch_raster_grid.connect(self.data_collection.switch_to_raster) - self.samcam.show_detections_changed.connect(self.sample_camera.set_show_detections) - self.samcam.show_detection_polygons_changed.connect( - self.sample_camera.set_show_detection_polygons - ) - self.samcam.show_target_point_changed.connect(self.sample_camera.set_show_target_point) - self.samcam.show_target_coordinates_changed.connect( - self.sample_camera.set_show_target_coordinates - ) - self.samcam.show_overlay_legend_changed.connect(self.sample_camera.set_show_overlay_legend) - self.samcam.compact_overlay_legend_changed.connect( - self.sample_camera.set_compact_overlay_legend - ) - self.samcam.target_color_changed.connect(self.sample_camera.set_target_color) - self._restore_samcam_overlay_settings() - - sample_feed_addr = pred_zmq_addr or zmq_addr - - if sample_feed_addr is not None: - logger.debug(f"Starting prediction subscriber thread {sample_feed_addr}") - self.prediction_thread = PredictionSubscriber(pred_zmq_url=sample_feed_addr, topic=b"") - self.prediction_thread.image.connect(self._on_sample_camera_frame) - self.prediction_thread.prediction.connect(self.sample_camera.update_detections) - self.prediction_thread.prediction.connect( - self.prediction_metrics_panel.update_from_prediction - ) - self.prediction_thread.target_point.connect(self.sample_camera.update_target_point) - self.prediction_thread.target_point.connect( - self.target_stability_panel.update_target_point - ) - self.prediction_thread.focus_measure.connect(self.status_bar.update_sharpness) - self.prediction_thread.fps_measure.connect(self.status_bar.update_samcam_fps) - self.prediction_thread.camera_availability_changed.connect( - self.sample_camera.set_camera_available - ) - self.prediction_thread.camera_availability_changed.connect( - self._on_sample_camera_availability_changed - ) - self.prediction_thread.camera_error.connect(self._on_sample_camera_error) - self.prediction_thread.start() - else: - self.prediction_thread = None - self.sample_camera.set_camera_available(False) - self._show_samcam_feed_banner("Sample camera feed unavailable: no stream configured") - - # - # self.data_collection.helical.helical_scan.connect(self.worker.helical_scan) - # self.data_collection.helical.update_bookmarks.connect( - # self.camera_image.update_bookmarks - # ) - # - - self.sample_camera.autofocus.connect(self.daq.autofocus) - - # Context-menu "Evaluate grid" presses the panel button so it gets the - # same file-exists guard, and stays inert while the button is disabled. - self.sample_camera.evaluate_grid.connect(self.data_collection.raster.start_button.click) - self.data_collection.raster.evaluate_grid.connect(self.raster.run_grid_scan) - self.data_collection.raster.evaluate_grid_auto.connect(self.raster.run_grid_scan_auto) - - self.sample_camera.clear_evaluated_grids.connect(self.raster.clear_completed_grids) - self.sample_camera.clear_grid.connect(self.raster.clear_active_grid) - self.daq.run_number_incremented.connect( - self.data_collection.file_path_panel.increment_run_number - ) - - self.job_list_panel.auto_scan.connect(self.daq.automated_scan) - - self.job_list_panel.unmount.connect(self.daq.unmount) - self.job_list_panel.unmount_then_park_and_dry.connect(self.daq.unmount_then_park_and_dry) - - # Gate manual mounts/unmounts on the hutch PSS state so the user gets an - # immediate pop-up instead of the robot failing to move server-side. - self.tell_samples.mount.connect(self._on_manual_mount_requested) - self.tell_samples.unmount.connect(self._on_manual_unmount_requested) - self.ref_tools_panel.mount.connect(self._on_manual_mount_requested) - self.ref_tools_panel.unmount.connect(self._on_manual_unmount_requested) - - # Dewar table doubles as the queue view: right-click edits queue - # membership, and every queue change repaints the status tints. - self.tell_samples.add_to_queue.connect( - lambda lst: self.job_list_panel.queue_samples(lst.s, replace=False) - ) - self.tell_samples.remove_from_queue.connect( - lambda lst: self.job_list_panel.remove_samples([s.db_id for s in lst.s]) - ) - self.job_list_panel.table_model.modelReset.connect(self._sync_queue_row_tints) - - self.data_collection.raster.grid_size_updated.connect(self.raster.update_grid_size) - self.data_collection.raster.exp_time_updated.connect(self.raster.update_exposure_time) - self.data_collection.raster.transmission_updated.connect(self.raster.update_transmission) - self.data_collection.raster.dtz_updated.connect(self.raster.update_dtz) - self.data_collection.raster.grid_metric_updated.connect(self.raster.metric) - self.data_collection.raster.raster_alpha_changed.connect(self.sample_camera.raster_alpha) - self.data_collection.cancel.connect(self.daq.cancel) - - self.raster.grid_scan.connect(self.daq.raster_scan) - self.raster.grid_scan_auto.connect(self.daq.raster_scan_auto) - self.data_collection.screening.rotation_scan.connect(self.daq.standard_scan) - self.data_collection.simple.rotation_scan.connect(self._on_simple_rotation_requested) - self.data_collection.simple.parameters_changed.connect(self.daq.smart_params) - - self.raster.grid_scan_size_changed.connect( - self.data_collection.raster.grid_scan_size_change - ) - - self.status_bar.set_pgroup.connect(self.daq.set_pgroup) - self.status_bar.end_session.connect(self.daq.end_session) - self.status_bar.force_session.connect(self.daq.force_session) - - self.status_bar.request_baton.connect(self.daq.request_baton) - self.status_bar.cancel_baton_request.connect(self.daq.cancel_baton_request) - self.status_bar.release_baton.connect(self.daq.release_baton) - self.status_bar.baton_request_accepted.connect( - lambda: self.daq.respond_to_baton_request(True) - ) - self.status_bar.baton_request_refused.connect( - lambda: self.daq.respond_to_baton_request(False) - ) - - self.status_bar.dewar_exchange.connect(self.daq.dewar_exchange) - self.status_bar.sample_exchange.connect(self.daq.sample_exchange) - self.status_bar.sample_alignment.connect(self.daq.sample_alignment) - self.status_bar.beam_location.connect(self.daq.beam_location) - - self.status_bar.close_shutter.connect(self.daq.close_shutter) - self.status_bar.open_shutter.connect(self.daq.open_shutter) - - self.beamline_state_panel.dewar_exchange.connect(self.daq.dewar_exchange) - self.beamline_state_panel.sample_exchange.connect(self.daq.sample_exchange) - self.beamline_state_panel.sample_alignment.connect(self.daq.sample_alignment) - self.beamline_state_panel.beam_location.connect(self.daq.beam_location) - self.beamline_state_panel.beamstop_alignment.connect(self.daq.beamstop_alignment) - self.beamline_state_panel.flux_measurement.connect(self.daq.flux_measurement) - self.beamline_state_panel.data_collection.connect(self.daq.data_collection) - self.beamline_state_panel.xtal_snapshot.connect(self.daq.xtal_snapshot) - self.beamline_state_panel.xray_fluorescence.connect(self.daq.xray_fluorescence) - self.beamline_state_panel.robot_sample_exchange.connect(self.daq.robot_sample_exchange) - self.rotation.file_ready.connect(self.viewer.load_image) - self.raster.image_selected.connect(self.viewer.load_image) - - self.raster.viewer_track_online.connect(self.viewer.load_online) - self.data_collection.screening.viewer_track_online.connect(self.viewer.load_online) - self.job_list_panel.viewer_track_online.connect(self.viewer.load_online) - - self.sample_logic.sample_changed.connect(self.data_collection.file_path_panel.update_sample) - self.sample_logic.sample_changed.connect(self._on_mounted_sample_changed) - - self.daq.update.connect(self.beamline.omega_panel.update_daq_status) - self.daq.update.connect(self.beamline.smargon_panel.update_daq_status) - self.daq.update.connect(self.job_list_panel.update_daq_status) - self.daq.update.connect(self.data_collection.file_path_panel.update_daq_status) - - self.daq.update.connect(self.data_collection.update_daq_status) - self.daq.update.connect(self.beamline.illumination_panel.update_daq_status) - self.daq.update.connect(self.raster.update_daq_status) - self.daq.update.connect(self.sample_camera.update_daq_status) - self.daq.auto_centering.connect(self.sample_camera.set_auto_centering) - self.daq.update.connect(self.tell_samples.update_daq_status) - self.daq.update.connect(self.ref_tools_panel.update_daq_status) - if self.prediction_thread is not None: - self.daq.update.connect(self.prediction_thread.update_daq_status) - - if self._decoded_token.staff: - self.daq.update.connect(self.monochromator_panel.update_daq_status) - self.daq.update.connect(self.beam_size.update_daq_status) - self.daq.update.connect(self.beam_center.update_daq_status) - self.daq.update.connect(self.abr_tweak.update_daq_status) - self.daq.update.connect(self.beam_mark.update_daq_status) - self.daq.update.connect(self.status_bar.update_daq_status) - self.daq.update.connect(self.samcam.update_daq_status) - self.daq.update.connect(self.beamline.zoom_panel.update_daq_status) - - self.daq.update.connect(self.sample_logic.update_daq_status) - self.daq.update.connect(self.manual_sample_panel.update_daq_status) - self.daq.update.connect(self.fluor_panel.update_daq_status) - self.daq.update.connect(self.beamline_state_panel.update_daq_status) - self.daq.update.connect(self.update_daq_status) - - self.daq.sample_missing.connect(self.show_sample_missing_dialog) - # Generic/background HTTP errors -> non-modal runtime alert; failed - # user operations (mount/unmount/...) -> modal pop-up. - self.daq.http_error.connect(self._on_http_error) - self.daq.operation_failed.connect(self._on_operation_failed) - self.daq.pss_alarm_changed.connect(self._on_pss_alarm_changed) - - self.daq.standard_scan_completed.connect(self.rotation.scan_completed) - self.daq.raster_scan_completed.connect(self.raster.grid_scan_completed) - - self.daq.automated_scan_done.connect(self.job_list_panel.automated_scan_done) - self.daq.automated_scan_done.connect(self._mark_scan_result) - self.daq.automation_critical_failure.connect(self._on_automation_critical_failure) - self.daq.manual_collection_critical_failure.connect( - self._on_manual_collection_critical_failure - ) - self.daq.recovery_action_completed.connect( - lambda _msg: self._clear_automation_critical_banner() - ) - - self.manual_sample_panel.sample_manual.connect(self.daq.sample_manual) - self.face_panel.face_detection.connect(self.daq.face_detection) - self.daq.face_detection_result.connect(self.face_panel.update_plot) - - self.status_bar.get_all_pgroups.connect(self.daq.get_all_pgroups) - self.daq.staff_pgroups_loaded.connect(self.status_bar.staff_pgroups_loaded) - - self.data_collection.fluo.fluo_scan.connect(self._on_fluo_scan_requested) - self.daq.fluorimeter_spectrum_update.connect(self.fluor_panel.update_plot) - self.daq.fluorimeter_spectrum_update.connect(lambda: self.fluor_panel_dock.setVisible(True)) - - # === Alert/Status Message Routing === - # Status bar: General status messages (not device connection status) - self.daq.status_message.connect(self.status_bar.show_connection_message) - - register_tutorials(self, self.tutorial_manager) - - # Every dock: closing its popped-out window brings it back into the - # layout instead of hiding it (eventFilter), and popping out opens - # an enlarged window (2x width, 3x height, clamped to the screen). - for dock in self.findChildren(QDockWidget): - dock.installEventFilter(self) - dock.topLevelChanged.connect(self._on_dock_top_level_changed) - - self.prompt_init_state() - - def prompt_init_state(self): - self.daq.update_steer_beam_available() - - def _setup_global_shortcuts(self) -> None: - self._shortcut_manual_sample = QAction("Expand Manual Sample", self) - self._shortcut_manual_sample.setShortcut(QKeySequence("Ctrl+M")) - self._shortcut_manual_sample.triggered.connect( - lambda: self.manual_sample_panel.title.expand() - ) - self.addAction(self._shortcut_manual_sample) - - self._shortcut_raise_sample_list = QAction("Raise sample list", self) - self._shortcut_raise_sample_list.setShortcut(QKeySequence("Ctrl+L")) - self._shortcut_raise_sample_list.triggered.connect( - lambda: ( - self.tell_samples_dock.setVisible(True), - self.tell_samples_dock.raise_(), - self.sample_lists_tabs.setCurrentIndex(0), - ) - ) - self.addAction(self._shortcut_raise_sample_list) - - # Reference tools now live inside the Sample List dock as the - # Auxiliary-puck tab — Ctrl+R raises the dock on that tab. - self._shortcut_raise_reference_tools_list = QAction("Raise reference tools", self) - self._shortcut_raise_reference_tools_list.setShortcut(QKeySequence("Ctrl+R")) - self._shortcut_raise_reference_tools_list.triggered.connect(self._raise_reference_tools) - self.addAction(self._shortcut_raise_reference_tools_list) - - # The automation controls live under the Dewar samples tab now. - self._shortcut_raise_job_list = QAction("Raise automation list", self) - self._shortcut_raise_job_list.setShortcut(QKeySequence("Ctrl+J")) - self._shortcut_raise_job_list.triggered.connect( - lambda: ( - self.tell_samples_dock.setVisible(True), - self.tell_samples_dock.raise_(), - self.sample_lists_tabs.setCurrentIndex(0), - ) - ) - self.addAction(self._shortcut_raise_job_list) - - self._shortcut_toggle_target_stability = QAction("Toggle target stability panel", self) - self._shortcut_toggle_target_stability.setShortcut(QKeySequence("Ctrl+Shift+T")) - self._shortcut_toggle_target_stability.triggered.connect( - lambda: self.target_stability_dock.setVisible( - not self.target_stability_dock.isVisible() - ) - ) - self.addAction(self._shortcut_toggle_target_stability) - - self._shortcut_toggle_prediction_metrics = QAction("Toggle prediction metrics panel", self) - self._shortcut_toggle_prediction_metrics.setShortcut(QKeySequence("Ctrl+Shift+P")) - self._shortcut_toggle_prediction_metrics.triggered.connect( - lambda: self.prediction_metrics_dock.setVisible( - not self.prediction_metrics_dock.isVisible() - ) - ) - self.addAction(self._shortcut_toggle_prediction_metrics) - - self._shortcut_toggle_smargon_trace = QAction("Toggle smargon trace panel", self) - self._shortcut_toggle_smargon_trace.setShortcut(QKeySequence("Ctrl+Shift+S")) - self._shortcut_toggle_smargon_trace.triggered.connect( - lambda: self.smargon_trace_dock.setVisible(not self.smargon_trace_dock.isVisible()) - ) - self.addAction(self._shortcut_toggle_smargon_trace) - - self._shortcut_console_log = QAction("Show Console log", self) - self._shortcut_console_log.setShortcut(QKeySequence("Ctrl+Shift+L")) - self._shortcut_console_log.triggered.connect(self._reveal_console_log) - self.addAction(self._shortcut_console_log) - - @Slot() - def _sync_queue_row_tints(self) -> None: - self.tell_samples.table_model.set_queued_ids( - sample.db_id for sample in self.job_list_panel.table_model.samples - ) - - @Slot() - def _update_queue_buttons_enabled(self) -> None: - queued_view = self.tell_samples.table_model.status_filter == "queued" - running = self.job_list_panel.is_running() - tip = "Active in the Queued view — click the Queued chip above the table" - for button, kind in self._queue_action_buttons: - enabled = queued_view or (kind == "run" and running) - button.setEnabled(enabled) - button.setToolTip("" if enabled else tip) - - @Slot() - def _remove_selected_from_queue(self) -> None: - self._unqueue_panel_selection(self.tell_samples) - - def _unqueue_panel_selection(self, panel: TellSamplePanel) -> None: - rows = panel.table_view.selectionModel().selectedRows() - db_ids = [panel.table_model.get_id(index.row()).db_id for index in rows] - if db_ids: - self.job_list_panel.remove_samples(db_ids) - - @Slot(int, bool, str) - def _mark_scan_result(self, db_id: int, success: bool, reply: str) -> None: - # Display only: a failed run tints the row pale red until a later - # success clears it. Auth errors are not the sample's fault — skip. - if reply == "Authentication Error": - return - self.tell_samples.table_model.set_flagged(db_id, not success) - - @Slot() - def _open_sample_popout(self) -> None: - if self._sample_popout is None: - # Fully operational duplicate of the Sample List tab: second panel - # instances SHARING the docked panels' models, wired to the same - # slots — mounts, queue edits, chips and filters all work here. - dewar_panel = TellSamplePanel(model=self.tell_samples.table_model) - aux_panel = ReferenceToolsPanel(model=self.ref_tools_panel.table_model) - dewar_panel.mount.connect(self._on_manual_mount_requested) - dewar_panel.unmount.connect(self._on_manual_unmount_requested) - dewar_panel.add_to_queue.connect( - lambda lst: self.job_list_panel.queue_samples(lst.s, replace=False) - ) - dewar_panel.remove_from_queue.connect( - lambda lst: self.job_list_panel.remove_samples([s.db_id for s in lst.s]) - ) - aux_panel.mount.connect(self._on_manual_mount_requested) - aux_panel.unmount.connect(self._on_manual_unmount_requested) - - # One shared filter state → keep the two chip rows visually in sync. - self.tell_samples.status_chips.buttonClicked.connect( - lambda chip: dewar_panel.set_status_chip(chip.property("status_key")) - ) - dewar_panel.status_chips.buttonClicked.connect( - lambda chip: self.tell_samples.set_status_chip(chip.property("status_key")) - ) - # Pop-out chips drive the same shared filter — regate the queue - # buttons from here too. - dewar_panel.status_chips.buttonClicked.connect( - lambda _chip: self._update_queue_buttons_enabled() - ) - dewar_panel.set_status_chip(self.tell_samples.table_model.status_filter) - - dewar_tab = QWidget() - dewar_tab.setObjectName("dewarTab") - dewar_layout = QVBoxLayout(dewar_tab) - dewar_layout.setContentsMargins(0, 0, 0, 0) - dewar_layout.setSpacing(2) - dewar_layout.addWidget(dewar_panel) - dewar_layout.addLayout(self._clone_automation_row(dewar_panel)) - - tabs = QTabWidget() - tabs.addTab(dewar_tab, "Dewar samples") - tabs.addTab(aux_panel, "Auxiliary puck") - if not self._decoded_token.staff: - tabs.setTabEnabled(1, False) - tabs.setTabToolTip(1, "Staff only") - self._sample_popout = PopoutWindow("Sample List", tabs, parent=self) - self._sample_popout.resize(1200, 500) - self._sample_popout.show() - self._sample_popout.raise_() - self._sample_popout.activateWindow() - - def _open_information_popout(self) -> None: - if self._information_popout is None: - # Automation mirror wired to the same feeds as the docked panel. - panel = AutomationProgressWidget() - self.job_list_panel.samples_in_queue_changed.connect(panel.set_samples_in_queue) - self.job_list_panel.automation_running_changed.connect(panel.set_running) - self.daq.automation_progress.connect(panel.set_progress) - panel.set_samples_in_queue(len(self.job_list_panel.table_model.samples)) - panel.set_running(self.job_list_panel.is_running()) - - tabs = QTabWidget() - tabs.addTab(panel, "Automation progress") - tabs.addTab(self.log_panel.make_mirror_view(), "Console log") - self._information_popout = PopoutWindow("Information", tabs, parent=self) - self._information_popout.resize(1000, 520) - self._information_popout.show() - self._information_popout.raise_() - self._information_popout.activateWindow() - - @Slot() - def _reveal_console_log(self) -> None: - """Show the Information dock with the Console log tab on top — the - one entry point for 'the user must see the log now' (notifications, - Ctrl+Shift+L).""" - self.information_dock.setVisible(True) - self.information_dock.raise_() - self.information_tabs.setCurrentWidget(self.log_panel) - - def _clone_automation_row(self, dewar_panel: TellSamplePanel) -> QHBoxLayout: - """Pop-out copy of the automation controls, driving the same queue - engine. Run/Pause text and checkbox states stay mirrored; 'Remove - selected' acts on the pop-out's own table selection.""" - jl = self.job_list_panel - run_button = QPushButton(jl.play_button.text()) - run_button.clicked.connect(jl.run) - jl.automation_running_changed.connect( - lambda running: run_button.setText("⏸ Pause" if running else "▶ Run") - ) - remove_button = QPushButton("🗑 Remove selected") - remove_button.clicked.connect(lambda: self._unqueue_panel_selection(dewar_panel)) - clear_button = QPushButton("✖ Clear list") - clear_button.clicked.connect(jl.clear) - mount_next_button = QPushButton("⏭ Mount next") - mount_next_button.clicked.connect(self._mount_next_from_queue) - unmount_button = QPushButton("⏏ Unmount") - unmount_button.clicked.connect(lambda: self._on_manual_unmount_requested()) - - # Same Queued-view gating as the docked buttons. - self._queue_action_buttons += [ - (run_button, "run"), - (remove_button, "queue"), - (clear_button, "queue"), - (mount_next_button, "queue"), - ] - self._update_queue_buttons_enabled() - - row = QHBoxLayout() - for button in (run_button, remove_button, clear_button, mount_next_button, unmount_button): - row.addWidget(button) - for source in (jl.park_and_dry_when_cleared, jl.pause_on_conditions_cb): - clone = QCheckBox(source.text()) - clone.setToolTip(source.toolTip()) - clone.setChecked(source.isChecked()) - # setChecked with an unchanged value emits nothing, so the - # cross-connection cannot loop. - clone.toggled.connect(source.setChecked) - source.toggled.connect(clone.setChecked) - row.addWidget(clone) - row.addStretch(1) # natural button widths, see the docked row - return row - - def _show_admin_tip(self, message: str) -> None: - # "Not admin" denials are passive red tips, not QMessageBoxes: - # nothing to click away. Styled at show time so it always matches - # the theme. - self._admin_tip_anchor.setStyleSheet(admin_tip_qss(self._theme_mode)) - QToolTip.showText(QCursor.pos(), message, self._admin_tip_anchor) - - def _show_reference_tools_staff_only_popup(self) -> None: - self._show_admin_tip( - "The Auxiliary puck (reference tools) view is available to staff accounts only." - ) - - def _show_beamline_staff_only_popup(self) -> None: - self._show_admin_tip( - "Beamline configuration is available to staff accounts only.\n" - "Log in with a staff account or contact your local contact " - "to configure the beamline." - ) - - def _show_beamline_tab_gated_popup(self) -> None: - # The tab is only ever disabled by the pgroup gate; staff hitting it - # are running a visitor's pgroup, users simply lack the rights. - if self._decoded_token.staff: - QMessageBox.information( - self, - "Beamline tab disabled", - "The active pgroup is not one of yours, so the Beamline tab " - "is disabled while running a visitor's experiment. Switch " - "back to your own pgroup to configure the beamline.", - ) - else: - self._show_beamline_staff_only_popup() - - @Slot() - def _raise_reference_tools(self) -> None: - if not self._decoded_token.staff: - self._show_reference_tools_staff_only_popup() - return - self.tell_samples_dock.setVisible(True) - self.tell_samples_dock.raise_() - self.sample_lists_tabs.setCurrentIndex(1) - - def _restore_samcam_overlay_settings(self) -> None: - settings = QSettings("PSI", "AareGUI") - # bool()/str() wraps: QSettings.value is typed "object" even with - # type=..., so the wraps are runtime no-ops for the pyright gate. - show_detections = bool(settings.value("samcam/show_detections", False, type=bool)) - show_detection_polygons = bool( - settings.value("samcam/show_detection_polygons", True, type=bool) - ) - show_target_point = bool(settings.value("samcam/show_target_point", True, type=bool)) - show_target_coordinates = bool( - settings.value("samcam/show_target_coordinates", True, type=bool) - ) - # Legend defaults off — it covers the camera image; users opt in and - # the choice persists via QSettings. - show_overlay_legend = bool(settings.value("samcam/show_overlay_legend", False, type=bool)) - compact_overlay_legend = bool( - settings.value("samcam/compact_overlay_legend", False, type=bool) - ) - target_color = str(settings.value("samcam/target_color", "Cyan", type=str)) - - self.samcam.apply_overlay_settings( - show_detections=show_detections, - show_detection_polygons=show_detection_polygons, - show_target_point=show_target_point, - show_target_coordinates=show_target_coordinates, - show_overlay_legend=show_overlay_legend, - compact_overlay_legend=compact_overlay_legend, - target_color=target_color, - ) - self.sample_camera.set_show_detections(show_detections) - self.sample_camera.set_show_detection_polygons(show_detection_polygons) - self.sample_camera.set_show_target_point(show_target_point) - self.sample_camera.set_show_target_coordinates(show_target_coordinates) - self.sample_camera.set_show_overlay_legend(show_overlay_legend) - self.sample_camera.set_compact_overlay_legend(compact_overlay_legend) - self.sample_camera.set_target_color(target_color) - - def _save_samcam_overlay_settings(self) -> None: - settings = QSettings("PSI", "AareGUI") - overlay = self.sample_camera.target_overlay_settings() - settings.setValue("samcam/show_detections", overlay["show_detections"]) - settings.setValue( - "samcam/show_detection_polygons", overlay["show_detection_polygons"] - ) # NEW - settings.setValue("samcam/show_target_point", overlay["show_target_point"]) - settings.setValue("samcam/show_target_coordinates", overlay["show_target_coordinates"]) - settings.setValue("samcam/show_overlay_legend", overlay["show_overlay_legend"]) - settings.setValue("samcam/compact_overlay_legend", overlay["compact_overlay_legend"]) - settings.setValue("samcam/target_color", overlay["target_color"]) - - @Slot(QImage) - def _on_sample_camera_frame(self, image: QImage) -> None: - """Hand one frame to whichever sample camera view is on screen. - - The subscriber emits from its own thread, so this runs queued on the - GUI thread. Painting only the visible view costs one repaint per frame - instead of three, and the acknowledgement at the end is what paces the - subscriber to the rate the GUI can actually keep up with. - - The subscriber sends a QImage: QPixmap is a GUI-thread-only class, so - it is built here rather than in the worker. - """ - try: - pixmap = QPixmap.fromImage(image) - if self.sample_camera.isVisible(): - self.sample_camera.update_pixmap(pixmap) - finally: - # The slot is only connected once the subscriber exists, but the - # attribute is Optional so the guard is what the type checker needs. - if self.prediction_thread is not None: - self.prediction_thread.notify_frame_displayed() - - @Slot(bool) - def _on_sample_camera_availability_changed(self, available: bool) -> None: - if available: - self._clear_samcam_feed_banner() - return - - self._show_samcam_feed_banner("Sample camera feed unavailable") - - @Slot(str) - def _on_sample_camera_error(self, message: str) -> None: - logger.warning(message) - self._show_samcam_feed_banner(message or "Sample camera feed unavailable") - # The camera overlays show the reason too, not just the boolean. - self.sample_camera.set_camera_error_message(message or "Sample camera feed unavailable") - - def _show_samcam_feed_banner(self, message: str) -> None: - self._samcam_feed_banner_message = message - self._show_runtime_notification( - title="Sample camera", message=message, level="warning", sticky=True - ) - self._samcam_feed_banner_active = True - - def _clear_samcam_feed_banner(self) -> None: - if not self._samcam_feed_banner_active: - return - self._clear_runtime_notification() - self._samcam_feed_banner_active = False - - def _stop_axis_camera_threads(self) -> None: - for attr_name in ("beamline_camera_thread", "gonio_camera_thread"): - thread = getattr(self, attr_name, None) - if thread is None: - continue - - try: - thread.stop() - except Exception as e: - logger.warning(f"Failed to stop {attr_name}: {e}", exc_info=True) - - setattr(self, attr_name, None) - - @staticmethod - def _axis_busy_text_from_status(s: DAQStatusModel) -> str: - tell_state = getattr(s, "tell_state", None) - if tell_state is None: - return "BEAMLINE BUSY" - - activity_value = str(getattr(tell_state.activity, "value", "") or "").lower() - if activity_value not in {"mounting", "unmounting", "drying", "cooling"}: - return "BEAMLINE BUSY" - - try: - activity_name = tell_state.activity.display_name() - except Exception: - logger.debug("Could not derive the axis busy text from status", exc_info=True) - activity_name = activity_value.capitalize() if activity_value else "Busy" - - return f"TELL {activity_name}".upper() - - def _start_axis_camera_threads(self) -> None: - self._stop_axis_camera_threads() - - if self._beamline_cam_addr: - self.beamline_camera_thread = VideoThread(ip=self._beamline_cam_addr) - self.beamline_camera_thread.frame_ready.connect(self.beamline_view.update_frame) - self.beamline_camera_thread.frame_ready.connect( - self.beamline_view_2_combined.update_frame - ) - self.beamline_camera_thread.start() - - if self._gonio_cam_addr and self._gonio_cam_id: - self.gonio_camera_thread = VideoThread( - ip=self._gonio_cam_addr, camera=self._gonio_cam_id - ) - self.gonio_camera_thread.frame_ready.connect(self.gonio_view.update_frame) - self.gonio_camera_thread.frame_ready.connect(self.beamline_view_1_combined.update_frame) - self.gonio_camera_thread.start() - - def _all_tell_samples_in_default_order(self) -> list: - samples = list(getattr(self.tell_samples.table_model, "samples", [])) - return sorted( - [sample for sample in samples if sample.location is not None], - key=lambda sample: sample.loc_str_sort(), - ) - - @Slot(str, bool) - def _runtime_alert_primary(self, msg: str, is_error: bool) -> None: - """Route primary alerts into the runtime dock.""" - self._show_runtime_notification( - title="Runtime alert" if is_error else "Runtime update", - message=msg, - level="error" if is_error else "success", - sticky=is_error, - auto_clear_ms=None if is_error else 4000, - ) - - @Slot(str, bool) - def _runtime_alert_secondary(self, msg: str, is_error: bool) -> None: - """Route secondary alerts into the runtime dock.""" - self._show_runtime_notification( - title="Device alert" if is_error else "Device update", - message=msg, - level="warning" if is_error else "info", - sticky=is_error, - auto_clear_ms=None if is_error else 4000, - ) - - @staticmethod - def _annotation_token(annotation: str) -> str: - mapping = { - "Heart": "❤️", - "Thumbs Up": "👍", - "Thumbs Down": "👎", - "Eyes": "👀", - "Scan Again": "scan again", - } - return mapping.get(annotation, str(annotation).strip()) - - @staticmethod - def _append_annotation_to_comment(existing_comment: str | None, annotation: str) -> str: - token = MainWindow._annotation_token(annotation) - current = str(existing_comment or "").strip() - - if not current: - return token - - current_tokens = [part.strip() for part in current.split(" | ") if part.strip()] - if token in current_tokens: - return current - - return f"{current} | {token}" - - @Slot() - def refresh_axis_cameras(self) -> None: - logger.info("Refreshing Axis camera threads") - self._stop_axis_camera_threads() - self._start_axis_camera_threads() - - def start_text_tutorial(self) -> None: - self.tutorial_manager.start("manual_workflow_demo") - - def start_interactive_tutorial(self) -> None: - self.tutorial_manager.start("manual_workflow_demo") - - def _apply_theme(self) -> None: - # Screenshot cross-fade (THEME_FADE_MS in styles.py): freeze the old - # look in a click-through overlay, restyle beneath it in one normal - # repolish, fade the overlay out. QSS has no transitions, and - # animating the palette would re-polish every widget per frame. - old_look = self.grab() if self.isVisible() else None - # Native primitives QSS can't recolor (spin/combo arrow glyphs) draw - # from the app palette — flip its text roles with the theme. - app = QApplication.instance() - assert isinstance(app, QApplication) # palette() lives on QApplication - if not hasattr(self, "_default_palette"): - self._default_palette = app.palette() - if self._theme_mode == THEME_SUNSET: - palette = QPalette(self._default_palette) - for role in ( - QPalette.ColorRole.ButtonText, - QPalette.ColorRole.Text, - QPalette.ColorRole.WindowText, - ): - palette.setColor(role, qcolor(DARK_TEXT)) - app.setPalette(palette) - else: - app.setPalette(self._default_palette) - # Text zoom, part 2: the QSS FONT_* ladder only reaches widgets the app - # sheet names — everything else renders in the app default font, so - # scale that too or body text ignores Ctrl+plus/minus. - if not hasattr(self, "_default_app_font"): - self._default_app_font = app.font() - font = QFont(self._default_app_font) - if font_scale() != 1.0: - font.setPointSizeF(self._default_app_font.pointSizeF() * font_scale()) - app.setFont(font) - self.setStyleSheet(build_app_stylesheet(self._theme_mode)) - # State colors are painted in code per DAQ tick — QSS can't reach them. - self.beamline_state_panel.set_theme(self._theme_mode) - # Status bar flags likewise; it is created after the first - # _apply_theme call in __init__, hence the guard. - if hasattr(self, "status_bar"): - self.status_bar.set_theme(self._theme_mode) - # Shutter flag in Beamline setup — staff-only panel, hence the guard. - if hasattr(self, "monochromator_panel"): - self.monochromator_panel.set_theme(self._theme_mode) - self.sample_camera.set_theme(self._theme_mode) - if old_look is None: - return - overlay = QLabel(self) - overlay.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True) - overlay.setPixmap(old_look) - overlay.setGeometry(self.rect()) - overlay.raise_() - overlay.show() - effect = QGraphicsOpacityEffect(overlay) - overlay.setGraphicsEffect(effect) - fade = QPropertyAnimation(effect, QByteArray(b"opacity"), overlay) - fade.setDuration(THEME_FADE_MS) - fade.setStartValue(1.0) - fade.setEndValue(0.0) - fade.finished.connect(overlay.deleteLater) - fade.start(QPropertyAnimation.DeletionPolicy.DeleteWhenStopped) - - def _restore_theme_settings(self) -> None: - settings = QSettings("PSI", "AareGUI") - # str() wrap: settings.value is typed object even with type=str. - saved = str(settings.value("appearance/theme", THEME_SUNRISE, type=str)) - # Migrate the pre-rename tokens so a saved theme survives the value - # change (styles.py: "original"->"sunrise", "portrait"->"sunset"). - saved = {"original": THEME_SUNRISE, "portrait": THEME_SUNSET}.get(saved, saved) - self._theme_mode = saved - set_font_scale(float(settings.value("appearance/font_scale", 1.0, type=float))) - - def _save_theme_settings(self) -> None: - settings = QSettings("PSI", "AareGUI") - settings.setValue("appearance/theme", self._theme_mode) - settings.setValue("appearance/font_scale", font_scale()) - - def _change_font_zoom(self, direction: int) -> None: - """Ctrl+plus / Ctrl+minus / Ctrl+0 accessibility zoom: walk the - 100/125/150% ladder and rebuild the app stylesheet (same repolish - path as a theme switch, so the whole UI rescales in one pass).""" - # index() is safe: set_font_scale snaps every value onto the ladder. - i = FONT_SCALE_LADDER.index(font_scale()) - i = 0 if direction == 0 else max(0, min(len(FONT_SCALE_LADDER) - 1, i + direction)) - set_font_scale(FONT_SCALE_LADDER[i]) - self._save_theme_settings() - self._apply_theme() - self._apply_zoom_widths() - - def _apply_zoom_widths(self) -> None: - # The side columns are fixed-width designs; when the ladder scales the - # text, the boxes must widen with it or the zoomed text clips. Runs - # once at construction and again on every zoom change. - s = font_scale() - left = round(self.data_collection.set_width * s) - self.data_collection.setFixedWidth(left) - self.left_column.setFixedWidth(left) - self.collection_controls_scroll.setFixedWidth(left + 10) - right = round(self.beamline.set_width * s) - self.beamline.setFixedWidth(right) - self.beamline_controls_scroll.setFixedWidth(right + 12) - - @Slot() - def use_legacy_theme(self) -> None: - self._theme_mode = THEME_SUNRISE - self._apply_theme() - - @Slot() - def use_portrait_theme(self) -> None: - self._theme_mode = THEME_SUNSET - self._apply_theme() - - @Slot() - def use_bluebird_theme(self) -> None: - self._theme_mode = THEME_BLUEBIRD - self._apply_theme() - - def create_menu_bar(self): - """Create a menu bar with File->Quit and Help->About.""" - menu_bar = self.menuBar() - - file_menu = menu_bar.addMenu("File") - quit_action = QAction("&Quit", self) - quit_action.setShortcut(QKeySequence.StandardKey.Quit) - quit_action.triggered.connect(self.close) - file_menu.addAction(quit_action) - - view_menu = menu_bar.addMenu("View") - - self._theme_action_group = QActionGroup(self) - self._theme_action_group.setExclusive(True) - - self._use_legacy_theme_action = QAction("Sunrise Theme", self) - self._use_legacy_theme_action.setCheckable(True) - self._use_legacy_theme_action.setChecked(self._theme_mode == THEME_SUNRISE) - self._use_legacy_theme_action.triggered.connect(self.use_legacy_theme) - self._theme_action_group.addAction(self._use_legacy_theme_action) - - self._use_portrait_theme_action = QAction("Sunset Theme (work in progress)", self) - self._use_portrait_theme_action.setCheckable(True) - self._use_portrait_theme_action.setChecked(self._theme_mode == THEME_SUNSET) - self._use_portrait_theme_action.triggered.connect(self.use_portrait_theme) - self._theme_action_group.addAction(self._use_portrait_theme_action) - - self._use_bluebird_theme_action = QAction("Bluebird Theme (default)", self) - self._use_bluebird_theme_action.setCheckable(True) - self._use_bluebird_theme_action.setChecked(self._theme_mode == THEME_BLUEBIRD) - self._use_bluebird_theme_action.triggered.connect(self.use_bluebird_theme) - self._theme_action_group.addAction(self._use_bluebird_theme_action) - - view_menu.addAction(self._use_legacy_theme_action) - view_menu.addAction(self._use_bluebird_theme_action) - view_menu.addAction(self._use_portrait_theme_action) - view_menu.addSeparator() - - # Accessibility text zoom. Ctrl+= alias: StandardKey.ZoomIn is - # Ctrl+Shift+= on some platforms and users expect plain Ctrl+plus. - bigger_text_action = QAction("Bigger Text", self) - bigger_text_action.setShortcuts( - [*QKeySequence.keyBindings(QKeySequence.StandardKey.ZoomIn), QKeySequence("Ctrl+=")] - ) - bigger_text_action.triggered.connect(lambda: self._change_font_zoom(1)) - view_menu.addAction(bigger_text_action) - smaller_text_action = QAction("Smaller Text", self) - smaller_text_action.setShortcuts(QKeySequence.StandardKey.ZoomOut) - smaller_text_action.triggered.connect(lambda: self._change_font_zoom(-1)) - view_menu.addAction(smaller_text_action) - reset_text_action = QAction("Reset Text Size", self) - reset_text_action.setShortcut(QKeySequence("Ctrl+0")) - reset_text_action.triggered.connect(lambda: self._change_font_zoom(0)) - view_menu.addAction(reset_text_action) - view_menu.addSeparator() - - # Side-panel collapse lives here, not as on-screen buttons. - self._show_left_panel_action = QAction("Show Left Panel", self) - self._show_left_panel_action.setCheckable(True) - self._show_left_panel_action.setChecked(True) - self._show_left_panel_action.toggled.connect(self.collection_controls_scroll.setVisible) - view_menu.addAction(self._show_left_panel_action) - self._show_right_panel_action = QAction("Show Right Panel", self) - self._show_right_panel_action.setCheckable(True) - self._show_right_panel_action.setChecked(True) - self._show_right_panel_action.toggled.connect(self.beamline_controls_scroll.setVisible) - view_menu.addAction(self._show_right_panel_action) - view_menu.addSeparator() - - show_samples_action = QAction("Show Sample List", self) - show_samples_action.setCheckable(True) - show_samples_action.setChecked(True) - show_samples_action.triggered.connect( - lambda checked: self.tell_samples_dock.setVisible(checked) - ) - self.tell_samples_dock.visibilityChanged.connect(show_samples_action.setChecked) - view_menu.addAction(show_samples_action) - - show_face_panel_action = QAction("Show face detection", self) - show_face_panel_action.setCheckable(True) - show_face_panel_action.setChecked(False) - show_face_panel_action.triggered.connect( - lambda checked: self.face_panel_dock.setVisible(checked) - ) - self.face_panel_dock.visibilityChanged.connect(show_face_panel_action.setChecked) - view_menu.addAction(show_face_panel_action) - - show_fluor_panel_action = QAction("Show fluorescence", self) - show_fluor_panel_action.setCheckable(True) - show_fluor_panel_action.setChecked(False) - show_fluor_panel_action.triggered.connect( - lambda checked: self.fluor_panel_dock.setVisible(checked) - ) - self.fluor_panel_dock.visibilityChanged.connect(show_fluor_panel_action.setChecked) - view_menu.addAction(show_fluor_panel_action) - - show_smargon_trace_action = QAction("Show Smargon trace", self) - show_smargon_trace_action.setCheckable(True) - show_smargon_trace_action.setChecked(False) - show_smargon_trace_action.triggered.connect( - lambda checked: self.smargon_trace_dock.setVisible(checked) - ) - self.smargon_trace_dock.visibilityChanged.connect(show_smargon_trace_action.setChecked) - self.smargon_trace_dock.visibilityChanged.connect( - lambda visible: self.smargon_trace_panel.refresh_plot(force=True) if visible else None - ) - view_menu.addAction(show_smargon_trace_action) - - show_target_stability_action = QAction("Show Target stability", self) - show_target_stability_action.setCheckable(True) - show_target_stability_action.setChecked(False) - show_target_stability_action.triggered.connect( - lambda checked: self.target_stability_dock.setVisible(checked) - ) - self.target_stability_dock.visibilityChanged.connect( - show_target_stability_action.setChecked - ) - view_menu.addAction(show_target_stability_action) - - show_prediction_metrics_action = QAction("Show Prediction Metrics", self) - show_prediction_metrics_action.setCheckable(True) - show_prediction_metrics_action.setChecked(False) - show_prediction_metrics_action.triggered.connect( - lambda checked: self.prediction_metrics_dock.setVisible(checked) - ) - self.prediction_metrics_dock.visibilityChanged.connect( - show_prediction_metrics_action.setChecked - ) - view_menu.addAction(show_prediction_metrics_action) - - show_information_action = QAction("Show Information", self) - show_information_action.setCheckable(True) - show_information_action.setChecked(False) - show_information_action.triggered.connect( - lambda checked: self.information_dock.setVisible(checked) - ) - self.information_dock.visibilityChanged.connect(show_information_action.setChecked) - view_menu.addAction(show_information_action) - - view_menu.addSeparator() - - sample_camera_tab_action = QAction("Sample camera tab", self) - sample_camera_tab_action.setShortcut(QKeySequence("Ctrl+1")) - sample_camera_tab_action.triggered.connect(lambda: self.video_tab.setCurrentIndex(0)) - view_menu.addAction(sample_camera_tab_action) - - gonio_camera_tab_action = QAction("Gonio camera tab", self) - gonio_camera_tab_action.setShortcut(QKeySequence("Ctrl+2")) - gonio_camera_tab_action.triggered.connect(lambda: self.video_tab.setCurrentIndex(1)) - view_menu.addAction(gonio_camera_tab_action) - - beamline_view_tab_action = QAction("Beamline view tab", self) - beamline_view_tab_action.setShortcut(QKeySequence("Ctrl+3")) - beamline_view_tab_action.triggered.connect(lambda: self.video_tab.setCurrentIndex(2)) - view_menu.addAction(beamline_view_tab_action) - - beamline_combined_tab_action = QAction("Beamline combined view tab", self) - beamline_combined_tab_action.setShortcut(QKeySequence("Ctrl+4")) - beamline_combined_tab_action.triggered.connect(lambda: self.video_tab.setCurrentIndex(3)) - view_menu.addAction(beamline_combined_tab_action) - - view_menu.addSeparator() - - restore_default_view_action = QAction("Restore Default View", self) - restore_default_view_action.setShortcut(QKeySequence("Ctrl+Shift+R")) - restore_default_view_action.triggered.connect(self.restore_default_view) - view_menu.addAction(restore_default_view_action) - - help_menu = menu_bar.addMenu("Help") - about_action = QAction("About", self) - about_action.triggered.connect(self.show_about_dialog) - help_menu.addAction(about_action) - - controls_help_action = QAction("Mouse / Keyboard Controls", self) - controls_help_action.setShortcut(QKeySequence(Qt.Key.Key_F1)) - controls_help_action.triggered.connect(self.show_controls_help) - help_menu.addAction(controls_help_action) - - dev_help_action = QAction("Developer / Help", self) - dev_help_action.triggered.connect(self.show_developer_help) - help_menu.addAction(dev_help_action) - - help_menu.addSeparator() - - refresh_axis_cameras_action = QAction("Refresh Axis Cameras", self) - refresh_axis_cameras_action.triggered.connect(self.refresh_axis_cameras) - help_menu.addAction(refresh_axis_cameras_action) - - if self._decoded_token.staff: - local_contact_action = QAction("Local Contact", self) - local_contact_action.triggered.connect(self.show_local_contact) - help_menu.addAction(local_contact_action) - - # Tutorial entries hidden 2026-08-10: content is out of date. The - # tutorial machinery stays wired — restore the two QActions here - # (Start Tutorial (Text)/(Interactive)) once the content is refreshed. - - def _capture_default_window_state(self) -> None: - self._default_window_state = self.saveState() - - @Slot() - def restore_default_view(self) -> None: - if self._default_window_state is not None: - self.restoreState(self._default_window_state) - - self.collection_controls_scroll.setVisible(True) - self.beamline_controls_scroll.setVisible(True) - - self.tell_samples_dock.setVisible(True) - - self.face_panel_dock.setVisible(False) - self.fluor_panel_dock.setVisible(False) - self.smargon_trace_dock.setVisible(False) - self.target_stability_dock.setVisible(False) - self.prediction_metrics_dock.setVisible(False) - # Default look: Information dock open on the Automation progress tab - # (the old automation dock was visible by default, the log hidden). - self.information_dock.setVisible(True) - self.information_tabs.setCurrentIndex(0) - - self.tell_samples_dock.raise_() - - self.video_tab.setCurrentIndex(0) - - def show_about_dialog(self): - QMessageBox.about(self, "About", about_text(self.daq)) - - def show_controls_help(self) -> None: - if self._controls_help_dialog is None: - self._controls_help_dialog = ControlsHelpDialog(parent=self) - self._controls_help_dialog.show() - self._controls_help_dialog.raise_() - self._controls_help_dialog.activateWindow() - - def show_developer_help(self) -> None: - if self._dev_help_dialog is None: - self._dev_help_dialog = DeveloperHelpDialog( - daq=self.daq, - is_staff=bool(getattr(self._decoded_token, "staff", False)), - parent=self, - ) - self._dev_help_dialog.refresh() - self._dev_help_dialog.show() - self._dev_help_dialog.raise_() - self._dev_help_dialog.activateWindow() - - def _show_runtime_notification( - self, - *, - title: str, - message: str, - level: str = "error", - sticky: bool = True, - auto_clear_ms: int | None = None, - ) -> None: - self.log_panel.show_notification( - title=title, message=message, level=level, sticky=sticky, auto_clear_ms=auto_clear_ms - ) - - def _show_runtime_waiting_notification(self, *, title: str, message: str) -> None: - self.log_panel.show_waiting_notification(title=title, message=message) - - def _clear_runtime_notification(self) -> None: - self.log_panel.clear_notification() - - def _clear_automation_critical_banner(self) -> None: - if not self._automation_critical_banner_active: - return - self._clear_runtime_notification() - self._automation_critical_banner_active = False - - @Slot(bool) - def _on_automation_running_changed(self, running: bool) -> None: - if running: - self._clear_automation_critical_banner() - self._show_runtime_notification( - title="Automation running", - message="Automation resumed.", - level="success", - sticky=False, - auto_clear_ms=3500, - ) - - def _is_detector_critical_failure(self, message: str) -> bool: - text = (message or "").lower() - return "detector" in text or "jfjoch" in text - - @staticmethod - def _is_detector_state_error(message: str) -> bool: - text = (message or "").lower() - return ( - "daq state error" in text - or "must be idle to start measurement" in text - or "must be idle" in text - ) - - def _detector_error_dialog_title(self, message: str) -> str: - if self._is_detector_state_error(message): - return "Detector state error" - return "Detector error" - - def _detector_error_banner_text(self, *, automation: bool, message: str) -> str: - if self._is_detector_state_error(message): - prefix = "Automation halted" if automation else "Manual collection stopped" - return f"{prefix}: detector state error." - return ( - "Automation halted: detector error." - if automation - else "Manual collection stopped: detector error." - ) - - @Slot(str) - @Slot(str) - def _on_http_error(self, message: str) -> None: - """Surface generic/background HTTP errors as a non-modal runtime alert. - - These come from polling, resync and other background requests; a modal - pop-up would be too intrusive, so they go to the runtime dock/banner. - """ - self._runtime_alert_primary(message, True) - - @Slot(bool) - def _on_pss_alarm_changed(self, active: bool) -> None: - """Non-modal warning banner for the hutch PSS alarm (ALARM-STATE != 0). - - Edge-triggered from /status: shows a sticky warning while active and a - brief confirmation when it clears. - """ - if active: - self._show_runtime_notification( - title="Hutch safety alarm", - message=( - "The hutch personnel-safety system reports an active alarm " - "(ALARM-STATE != 0). Mounting is blocked until it clears — " - "check the hutch / call your local contact." - ), - level="warning", - sticky=True, - ) - else: - self._show_runtime_notification( - title="Hutch safety alarm cleared", - message="The hutch safety alarm has cleared.", - level="success", - sticky=False, - auto_clear_ms=4000, - ) - - @Slot(str, str, bool) - def _on_operation_failed(self, title: str, message: str, critical: bool) -> None: - """Modal pop-up for a failed user-triggered operation (mount, unmount, ...). - - Critical failures (e.g. door safety could not be activated) also pause - the automation queue defensively, so we never keep dispatching samples. - """ - logger.error(f"Operation failed [{title}] (critical={critical}): {message}") - - if critical: - try: - if self.job_list_panel is not None and self.job_list_panel.is_running(): - self.job_list_panel.pause_automation() - except Exception: - logger.exception("Failed to pause automation after operation failure") - - try: - show = QMessageBox.critical if critical else QMessageBox.warning - show(self, title, message) - except Exception: - logger.exception("Failed to show operation failure popup") - - def _hutch_blocks_mount(self) -> str | None: - """Reason the hutch PSS currently blocks a mount, or None if OK. - - Uses the latest ``/status``; if no status has arrived yet we defer to - the authoritative server-side gate rather than guess. - """ - bl = getattr(self._latest_daq_status, "bl", None) - if bl is None: - return None - if getattr(bl, "pss_prohibited", True) is False: - return ( - "Door safety could not be activated: close the hutch doors and " - "complete the safety search before mounting." - ) - if getattr(bl, "pss_alarm", False): - return "The hutch safety alarm is active. Mounting is blocked until it clears." - return None - - def _mount_next_from_queue(self) -> None: - """Manual step-through: mount queue head; if head already on gonio, mount the following one. - - The mounted head stays in the queue until /status confirms it left the - gonio (see ``_on_mounted_sample_changed``): a failed unmount must not - drop the sample that is still physically mounted. - """ - queue = self.job_list_panel.table_model.samples - mounted = getattr(self._latest_daq_status, "sample", None) - head_mounted = bool(queue) and mounted is not None and mounted.db_id == queue[0].db_id - target = queue[1] if head_mounted else (queue[0] if queue else None) - if target is None: - sent = self._on_manual_unmount_requested() - else: - sent = self._on_manual_mount_requested(target) - if sent and head_mounted: - self._pending_unmount_pop = queue[0].db_id - - @Slot(object) - def _on_mounted_sample_changed(self, sample) -> None: - """Pop the pending queue head once /status shows it is off the gonio. - - Intentionally not cleared on ``operation_failed``: a busy/duplicate - POST error must not cancel the pop for an exchange still in flight. - """ - pending = self._pending_unmount_pop - if pending is None: - return - if sample is not None and sample.db_id == pending: - return - self._pending_unmount_pop = None - self.job_list_panel.remove_samples([pending]) - - def _on_manual_mount_requested(self, sample, reference: bool = False) -> bool: - """Pre-check the hutch before sending a manual mount to the server. - - Gives the user an immediate pop-up if the door is open / alarm active, - instead of the robot silently failing to move server-side. - """ - reason = self._hutch_blocks_mount() - if reason is not None: - logger.warning(f"Manual mount blocked by hutch PSS: {reason}") - try: - QMessageBox.critical(self, "Mounting Failed", reason) - except Exception: - logger.exception("Failed to show mount-blocked popup") - return False - self.daq.mount(sample, reference) - return True - - def _on_manual_unmount_requested(self) -> bool: - """Block a manual unmount if the hutch isn't ready (robot can't move).""" - reason = self._hutch_blocks_mount() - if reason is not None: - logger.warning(f"Manual unmount blocked by hutch PSS: {reason}") - try: - QMessageBox.critical(self, "Unmounting Failed", reason) - except Exception: - logger.exception("Failed to show unmount-blocked popup") - return False - self.daq.unmount() - return True - - def _precondition_ok(self) -> bool: - """Run the shared ring-current / shutter / door 'continue?' check. - - Uses the latest ``/status``; defers (returns True) if no status yet. - """ - bl = getattr(self._latest_daq_status, "bl", None) - if bl is None: - return True - return precondition_check( - self, - ring_current=getattr(bl, "ring_current_mA", None), - shutter_open=getattr(bl, "exp_shutter_open", None), - door_prohibited=getattr(bl, "pss_prohibited", None), - ) - - def _on_fluo_scan_requested(self, params) -> None: - if self._precondition_ok(): - self.daq.fluorimeter_spectrum(params) - - def _on_simple_rotation_requested(self, request) -> None: - if self._precondition_ok(): - self.daq.standard_scan(request) - - def _on_manual_collection_critical_failure(self, message: str) -> None: - logger.critical(f"Manual collection critical detector failure: {message}") - - self._show_runtime_notification( - title="Collection paused", message=message, level="error", sticky=True - ) - - try: - QMessageBox.critical( - self, - self._detector_error_dialog_title(message), - ( - "The manual collection has stopped because there is an error with the detector.\n\n" - "Please call your local contact.\n\n" - f"Details:\n{message}" - ), - ) - except Exception: - logger.exception("Failed to show manual collection detector popup") - - @Slot(str) - def _on_automation_critical_failure(self, message: str) -> None: - """ - Hard-stop handler for fatal automation failures coming from the server - (transformation errors, busy-flag corruption, unhandled 500s on /scan/auto). - - Stops the queue, marks the progress widget as failed and surfaces the - beamline recovery dialog (staff) or a critical error message (users). - """ - logger.critical(f"Automation critical failure: {message}") - - is_detector_failure = self._is_detector_critical_failure(message) - ( - self._detector_error_banner_text(automation=True, message=message) - if is_detector_failure - else f"Automation halted: {message}" - ) - - # 1. Stop the sample queue so we don't keep dispatching new samples - try: - if self.job_list_panel is not None and self.job_list_panel.is_running(): - self.job_list_panel.pause_automation() - if self.daq is not None: - self.daq.send_status_request() - except Exception: - logger.exception("Failed to pause automation queue after critical failure") - - # 2. Mark the automation progress widget as finished-with-error so - # _is_automation_active() returns False and idle/close timers behave. - try: - from aarecommon.models.automation import ( - AutomationProgress, - StepState, - StepStatus, - WorkflowStateKind, - ) - - progress = getattr(self.automation_progress_panel, "_progress", None) - if progress is None: - progress = AutomationProgress( - current_step=None, - steps=[ - StepState(step=WorkflowStateKind.MOUNT, status=StepStatus.PENDING), - StepState(step=WorkflowStateKind.LOOP_CENTRE, status=StepStatus.PENDING), - StepState(step=WorkflowStateKind.RASTER, status=StepStatus.PENDING), - StepState( - step=WorkflowStateKind.DATA_COLLECTION, status=StepStatus.PENDING - ), - StepState(step=WorkflowStateKind.FINAL, status=StepStatus.PENDING), - ], - finished=False, - success=None, - ) - for step in progress.steps: - if step.status == StepStatus.RUNNING: - step.status = StepStatus.FAILED - step.message = message - if step.step == WorkflowStateKind.FINAL: - step.status = StepStatus.FAILED - step.message = message - progress.finished = True - progress.success = False - self.automation_progress_panel.set_progress(progress) - except Exception: - logger.exception("Failed to update automation progress after critical failure") - - self._show_runtime_notification( - title="Automation paused", message=message, level="error", sticky=True - ) - - # 4. Surface recovery UI - try: - if bool(getattr(self._decoded_token, "staff", False)): - if is_detector_failure: - QMessageBox.critical( - self, - self._detector_error_dialog_title(message), - ( - "Automation has been stopped because there is an error with the detector.\n\n" - f"Details:\n{message}" - ), - ) - else: - QMessageBox.critical( - self, - "Automation halted", - ( - "A critical error occurred during automation and the " - "beamline could not recover automatically:\n\n" - f"{message}\n\n" - ), - ) - else: - if is_detector_failure: - QMessageBox.critical( - self, - self._detector_error_dialog_title(message), - ( - "Automation has been stopped because there is an error with the detector.\n\n" - "Please call your local contact.\n\n" - f"Details:\n{message}" - ), - ) - else: - QMessageBox.critical( - self, - "Automation halted", - ( - "A critical error occurred during automation and the " - "beamline could not recover automatically:\n\n" - f"{message}\n\n" - "Please contact your local contact to recover the beamline." - ), - ) - except Exception: - logger.exception("Failed to surface recovery UI after critical failure") - - def show_beamline_recovery(self) -> None: - if not bool(getattr(self._decoded_token, "staff", False)): - return - if self._beamline_recovery_dialog is None: - self._beamline_recovery_dialog = BeamlineRecoveryDialog(daq=self.daq, parent=self) - self._beamline_recovery_dialog.show() - self._beamline_recovery_dialog.raise_() - self._beamline_recovery_dialog.activateWindow() - - def show_local_contact(self, tab_name: str = "Status") -> None: - if not bool(getattr(self._decoded_token, "staff", False)): - return - if self._local_contact_dialog is None: - self._local_contact_dialog = LocalContactDialog(daq=self.daq, parent=self) - self._local_contact_dialog.set_active_tab(tab_name) - self._local_contact_dialog.show() - self._local_contact_dialog.raise_() - self._local_contact_dialog.activateWindow() - - @Slot(str) - def show_sample_missing_dialog(self, msg: str): - if self.job_list_panel.is_running(): - logger.warning(f"Automation: Sample missing: {msg}") - return - QMessageBox.warning(self, "No Sample", f"{msg}") - - # TODO tidy up mount and sampel view fucntions - @Slot() - def mount_view(self): - self.video_tab.setCurrentWidget(self.beamline_combined_panel) - - @Slot() - def sample_view(self): - self.video_tab.setCurrentWidget(self.sample_camera) - - def _apply_session_gate(self, session_state) -> None: - # No baton -> watching only: camera views stay live, every operating - # surface is greyed. The SESSION VACANT badge (and the status bar - # session menu) remain the way back in. - owned = session_state in (SessionsStateEnum.OwnedByYou, SessionsStateEnum.PendingElseToYou) - if owned == getattr(self, "_session_operations_enabled", None): - return - self._session_operations_enabled = owned - for widget in (self.left_column_tabs, self.beamline, self.tell_samples_dock.widget()): - widget.setEnabled(owned) - if owned: - # None clears the effect (Qt API contract); the PySide6 stub - # signature misses the Optional. - widget.setGraphicsEffect(None) # pyright: ignore[reportArgumentType] - else: - # Full grayscale, banners included — QSS :disabled alone - # can't reach the custom-painted TitleLabels/inline styles. - effect = QGraphicsColorizeEffect(widget) - effect.setColor(QColor("#808080")) - widget.setGraphicsEffect(effect) - self.sample_camera.set_operations_enabled(owned) - - # Vacant folds every panel shut; grabbing reopens exactly the ones - # that were open before. Transient (persist=False) so the fold never - # overwrites the user's saved per-panel choices. - banners = self.left_column_tabs.findChildren(TitleLabel) + self.beamline.findChildren( - TitleLabel - ) - if owned: - for banner in getattr(self, "_pre_vacancy_open_banners", []): - banner.set_collapsed(False, persist=False) - else: - self._pre_vacancy_open_banners = [b for b in banners if not b.is_collapsed()] - for banner in banners: - banner.set_collapsed(True, persist=False) - - # Watch-only shows ONLY the camera stream: every other operating - # surface is hidden outright (not just greyed), and regaining the - # baton restores exactly the visibility each one had before. The - # status bar and its SESSION VACANT badge stay — they are the way - # back in. To later hide the camera streams as well, add - # self.video_tab to this list. - # findChildren instead of a hand list: hand-listing missed docks - # (Console Log, Fluorescence, ...) and would again for future ones. - # Covers the pop-out mirrors too — they are operating surfaces. - hide_in_watch_mode = [ - self.left_column_tabs, - self.beamline, - self.beamline_state_panel, - *self.findChildren(PopoutWindow), - ] - if owned: - for widget, was_visible in self._pre_watch_visibility or []: - widget.setVisible(was_visible) - # Docks restore via restoreState, not per-dock setVisible: a dock - # TABBED BEHIND another is isHidden() at snapshot time, so a - # visibility snapshot mistakes it for user-closed and loses it - # (the vanished Sample List). restoreState also brings back - # tab order, the active tab and dock sizes. Needs objectNames - # on every dock. - state = self._pre_watch_dock_state - if state is not None: - self.restoreState(state) - else: - # not isHidden(), NOT isVisible(): the vacant gate first runs - # before the window is shown, where isVisible() is False for - # everything and the restore would then "restore" all-hidden. - self._pre_watch_dock_state = self.saveState() - self._pre_watch_visibility = [(w, not w.isHidden()) for w in hide_in_watch_mode] - for widget in hide_in_watch_mode + self.findChildren(QDockWidget): - widget.hide() - - # Alignment/maintenance states mount reference pins, so the sample dock - # defaults to the Auxiliary puck there; every other state defaults back - # to the Dewar list. - _AUX_PUCK_STATES = frozenset( - { - BeamlineStateEnum.Maintenance, - BeamlineStateEnum.BeamLocation, - BeamlineStateEnum.BeamstopAlignment, - BeamlineStateEnum.FluxMeasurement, - } - ) - - def _apply_default_sample_tab(self, state: BeamlineStateEnum | None) -> None: - # Index 1 = Auxiliary puck; disabled for non-staff, never force it. - if state in self._AUX_PUCK_STATES and self.sample_lists_tabs.isTabEnabled(1): - self.sample_lists_tabs.setCurrentIndex(1) - else: - self.sample_lists_tabs.setCurrentIndex(0) - - def _apply_pgroup_gate(self, pgroup: str | None) -> None: - # Switching to a pgroup outside the token's own (admin) pgroups means - # running a visitor's experiment: the Beamline tab is then off-limits, - # and the Experiment tab comes up with Dataset path + Exp. Config. - # open. Applied only on gate TRANSITIONS so a manual tab choice - # survives the 1 Hz status ticks. - gated = pgroup is not None and pgroup not in (self._decoded_token.pgroups or []) - if gated == self._beamline_tab_gated: - return - self._beamline_tab_gated = gated - self.left_column_tabs.setTabEnabled(0, not gated) - self.left_column_tabs.setTabToolTip( - 0, "Only accessible for beamline scientists" if gated else "" - ) - if gated: - self.left_column_tabs.setCurrentIndex(1) - # persist=False: programmatic open must not overwrite the user's - # saved per-panel collapse choice (same rule as the session gate). - for banner in self.data_collection.findChildren(TitleLabel): - if banner.text() in ("Dataset path", "Experiment configuration"): - banner.set_collapsed(False, persist=False) - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - self._latest_daq_status = s - self._apply_session_gate(getattr(getattr(s, "session", None), "session", None)) - self._apply_pgroup_gate(getattr(getattr(s, "session", None), "current_pgroup", None)) - - # No login-default state: the GUI adopts whatever state the server - # reports and never posts a transition on startup — a state POST can - # move motors, and merely logging in must not move hardware. - - # Default tab only on state TRANSITIONS — a manual tab choice - # survives while the state stays put. - new_beamline_state = getattr(s, "state", None) - if new_beamline_state != self._last_beamline_state: - self._last_beamline_state = new_beamline_state - self._apply_default_sample_tab(new_beamline_state) - - if self._is_automation_active(): - self._refresh_idle_activity(report_backend=False) - - if hasattr(self, "beamline_camera_thread") and self.beamline_camera_thread is not None: - self.beamline_camera_thread.set_busy(s.busy) - - if hasattr(self, "gonio_camera_thread") and self.gonio_camera_thread is not None: - self.gonio_camera_thread.set_busy(s.busy) - - # Sample alignment busy is the alignment itself (same exception as - # the motion watch below) — no BEAMLINE BUSY curtain on any view. - busy_style = build_busy_overlay_style( - is_busy=bool(s.busy) and s.state != BeamlineStateEnum.SampleAlignment, - tell_state=s.tell_state, - session_state=getattr(getattr(s, "session", None), "session", None), - ) - - if hasattr(self, "beamline_view_panel") and self.beamline_view_panel is not None: - self.beamline_view_panel.set_busy_style(busy_style) - if hasattr(self, "gonio_view_panel") and self.gonio_view_panel is not None: - self.gonio_view_panel.set_busy_style(busy_style) - if hasattr(self, "beamline_combined_panel") and self.beamline_combined_panel is not None: - self.beamline_combined_panel.set_busy_style(busy_style) - - self.target_stability_panel.set_beam_center( - s.geom.beam_location_pxl.x, s.geom.beam_location_pxl.y - ) - - current_session = int(getattr(self._decoded_token, "session", -1)) - for gui in getattr(s, "open_guis", []) or []: - try: - if int(gui.session) == current_session and bool(gui.close_requested): - if self._remote_close_deadline_ts is None: - self._start_remote_close_countdown( - requested_by=gui.close_requested_by, - grace_seconds=gui.close_grace_seconds, - ) - break - except Exception: - logger.debug("Skipping an unreadable GUI session entry", exc_info=True) - continue - else: - if self._remote_close_deadline_ts is not None: - self._clear_remote_close_request() - - # Only the robot station flips to the Beamline combined view. Moving - # no longer triggers it (short gonio moves kept stealing the sample - # camera), and busy alone never did — Sample alignment, Beam - # location, Beamstop alignment, Flux measurement etc. run busy while - # the user watches the sample camera itself. - # Edge-triggered so a manual tab choice survives between transitions. - moving = s.state == BeamlineStateEnum.RobotSampleExchange - if moving and not self._watching_motion: - self._watching_motion = True - self.video_tab.setCurrentWidget(self.beamline_combined_panel) - elif not moving and self._watching_motion: - self._watching_motion = False - self.video_tab.setCurrentWidget(self.sample_camera) - - # ========== BATON DIALOG HANDLING ========== - - @Slot(dict) - def _show_baton_request_dialog(self, payload: dict): - logger.info(f"Showing baton request dialog with payload: {payload}") - requester = str(payload.get("requester") or "Another user") - timeout = int(payload.get("timeout") or 30) - - if self._baton_request_dialog is not None: - if self._baton_request_dialog.isVisible(): - logger.debug("Baton request dialog already visible, skipping") - return - else: - logger.debug("Baton request dialog exists but not visible, recreating") - self._baton_request_dialog.close() - self._baton_request_dialog = None - - self._baton_request_dialog = BatonRequestDialog( - requester=requester, timeout_seconds=timeout, parent=self - ) - self._baton_request_dialog.accepted_signal.connect( - self.status_bar._on_baton_dialog_accepted - ) - self._baton_request_dialog.refused_signal.connect(self.status_bar._on_baton_dialog_refused) - self._baton_request_dialog.show() - self._baton_request_dialog.raise_() - self._baton_request_dialog.activateWindow() - logger.info("Baton request dialog shown") - - @Slot() - def _accept_baton_request(self): - self.daq.respond_to_baton_request(True) - - @Slot() - def _refuse_baton_request(self): - self.daq.respond_to_baton_request(False) - - @Slot(BatonStatus) - def _on_baton_status_changed(self, status: BatonStatus): - """ - Update waiting UI based on SSE status. - StatusBar handles baton-granted p-group selection automatically. - """ - if self._waiting_for_baton_response and not status.you_have_pending_request: - self._waiting_for_baton_response = False - self._close_baton_pending_dialog() - - if status.you_are_holder: - self.alert_banner.show_message("Baton acquired!", False, auto_clear_ms=4000) - else: - self.alert_banner.show_message( - "Request declined or cancelled", False, auto_clear_ms=4000 - ) - - # Manage incoming request dialog (when someone requests from us) - if not status.incoming_request and self._baton_request_dialog is not None: - logger.info("Incoming baton request no longer active, closing request dialog") - self._close_baton_dialog() - - @Slot(dict) - def _on_baton_request_result(self, result: dict): - """ - Handle result of our baton request. - - Show success/pending/error banners - - Manage pending dialog lifecycle - - StatusBar handles p-group selection automatically via update_baton_status - """ - if result.get("granted"): - self._waiting_for_baton_response = False - self.alert_banner.show_message("Baton acquired!", False, auto_clear_ms=4000) - logger.info("Baton acquired") - # Close pending dialog; StatusBar will trigger p-group selection via SSE - self._close_baton_pending_dialog() - - elif result.get("pending"): - self._waiting_for_baton_response = True - timeout = result.get("timeout_seconds", 30) - holder = result.get("message", "Waiting for response...") - is_busy = result.get("beamline_busy", False) - - if getattr(self, "_baton_pending_dialog", None) is None: - target_user = holder.replace("Request sent to ", "").replace( - " (Note: beamline is currently busy, transfer will be queued if accepted)", "" - ) - self._baton_pending_dialog = BatonPendingDialog( - target_user=target_user, timeout_seconds=timeout, parent=self - ) - self._baton_pending_dialog.cancelled_signal.connect(self.daq.cancel_baton_request) - self._baton_pending_dialog.show() - else: - self._baton_pending_dialog.update_remaining(timeout) - - self.alert_banner.show_waiting(f"Requesting control - {holder}", timeout) - logger.info(f"Baton request pending - {timeout}s timeout (busy={is_busy})") - - elif result.get("queued"): - self._waiting_for_baton_response = True - self.alert_banner.show_waiting("Control transfer queued - waiting for beamline") - logger.info("Baton transfer queued") - - if getattr(self, "_baton_pending_dialog", None) is None: - self._baton_pending_dialog = BatonPendingDialog( - target_user="Current Holder", timeout_seconds=0, parent=self - ) - self._baton_pending_dialog.cancelled_signal.connect(self.daq.cancel_baton_request) - self._baton_pending_dialog.show() - self._baton_pending_dialog.set_queued_state() - - elif result.get("already_holder"): - self._waiting_for_baton_response = False - logger.debug("Already baton holder") - self._close_baton_pending_dialog() - - elif result.get("error"): - self._waiting_for_baton_response = False - self.alert_banner.show_message( - result.get("message", "Request failed"), True, auto_clear_ms=15000 - ) - logger.warning(f"Baton request failed: {result.get('message')}") - self._close_baton_pending_dialog() - - @Slot(dict) - def _on_baton_response_result(self, result: dict): - """ - Handle response after someone requests from us. - Just update UI banners; StatusBar handles session display. - """ - logger.debug(f"Baton response result: {result}") - if result.get("accepted"): - self._waiting_for_baton_response = False - self.alert_banner.show_message("Control transferred", False, auto_clear_ms=4000) - self._close_baton_dialog() - self.status_bar.update_baton_status(self.status_bar._baton_status) - elif result.get("refused"): - self._waiting_for_baton_response = False - self.alert_banner.show_message("Request declined", False, auto_clear_ms=4000) - self._close_baton_dialog() - self.status_bar.update_baton_status(self.status_bar._baton_status) - else: - logger.debug(f"replied with {result}") - - @Slot(dict) - def _on_baton_timeout_checked(self, result: dict): - """Refresh waiting UI when backend confirms timeout state.""" - logger.debug(f"Baton timeout checked: {result}") - if result.get("pending"): - remaining = int(result.get("remaining_seconds", 0)) - if self._waiting_for_baton_response: - self.alert_banner.show_waiting("Requesting control", remaining) - if getattr(self, "_baton_pending_dialog", None) is not None: - self._baton_pending_dialog.update_remaining(remaining) - - elif result.get("granted"): - self._waiting_for_baton_response = False - self.alert_banner.show_message("Baton acquired!", False, auto_clear_ms=4000) - self._close_baton_pending_dialog() - - elif result.get("queued"): - self._waiting_for_baton_response = True - self.alert_banner.show_waiting("Control transfer queued - waiting for beamline") - - if getattr(self, "_baton_pending_dialog", None) is not None: - self._baton_pending_dialog.set_queued_state() - else: - self._baton_pending_dialog = BatonPendingDialog( - target_user="Current Holder", timeout_seconds=0, parent=self - ) - self._baton_pending_dialog.cancelled_signal.connect(self.daq.cancel_baton_request) - self._baton_pending_dialog.show() - self._baton_pending_dialog.set_queued_state() - - elif result.get("refused"): - self._waiting_for_baton_response = False - self.alert_banner.show_message("Request declined", False, auto_clear_ms=4000) - self._close_baton_pending_dialog() - - else: - logger.debug(f"replied with {result}") - self.alert_banner.clear_message() - self._close_baton_pending_dialog() - - def _close_baton_dialog(self) -> None: - """Close the incoming-request dialog (when someone requests from us).""" - if getattr(self, "_baton_request_dialog", None) is not None: - try: - self._baton_request_dialog.close() - finally: - self._baton_request_dialog = None - - def _close_baton_pending_dialog(self) -> None: - if getattr(self, "_baton_pending_dialog", None) is not None: - try: - if hasattr(self._baton_pending_dialog, "_timer"): - self._baton_pending_dialog._timer.stop() - self._baton_pending_dialog.close() - finally: - self._baton_pending_dialog = None - - def _save_panel_visibility_settings(self) -> None: - """Save visibility state for developer/diagnostic panels.""" - settings = QSettings("PSI", "AareGUI") - settings.beginGroup("panel_visibility") - settings.setValue("smargon_trace", self.smargon_trace_dock.isVisible()) - settings.setValue("target_stability", self.target_stability_dock.isVisible()) - settings.setValue("prediction_metrics", self.prediction_metrics_dock.isVisible()) - settings.setValue("face_detection", self.face_panel_dock.isVisible()) - settings.setValue("fluorescence", self.fluor_panel_dock.isVisible()) - settings.setValue("information", self.information_dock.isVisible()) - settings.endGroup() - - def _restore_panel_visibility_settings(self) -> None: - """Restore visibility state for developer/diagnostic panels.""" - settings = QSettings("PSI", "AareGUI") - settings.beginGroup("panel_visibility") - - if settings.contains("smargon_trace"): - self.smargon_trace_dock.setVisible(settings.value("smargon_trace", False, type=bool)) - if settings.contains("target_stability"): - self.target_stability_dock.setVisible( - settings.value("target_stability", False, type=bool) - ) - if settings.contains("prediction_metrics"): - self.prediction_metrics_dock.setVisible( - settings.value("prediction_metrics", False, type=bool) - ) - if settings.contains("face_detection"): - self.face_panel_dock.setVisible(settings.value("face_detection", False, type=bool)) - if settings.contains("fluorescence"): - self.fluor_panel_dock.setVisible(settings.value("fluorescence", False, type=bool)) - # New key: the old "log" flag described a dock that defaulted hidden; - # the merged Information dock defaults visible, so old values would - # wrongly hide it. - if settings.contains("information"): - # bool() wrap: settings.value is typed object even with type=bool. - self.information_dock.setVisible(bool(settings.value("information", True, type=bool))) - - settings.endGroup() - - def _restore_window_state(self) -> None: - # TODO put all setting related handlign into state_manager - self.state_manager.restore_window(self) - # Heal a poisoned layout: a state saved while watch-only mode had - # everything folded away comes back as "every dock hidden" — a user - # hides docks selectively, only the watch-mode fold hides ALL of - # them. Fall back to the default layout instead of resurrecting it - # (the vanished-Sample-List-on-restart bug). - docks = self.findChildren(QDockWidget) - if docks and all(d.isHidden() for d in docks) and self._default_window_state is not None: - self.restoreState(self._default_window_state) - self._restore_panel_visibility_settings() - - def showEvent(self, event): - super().showEvent(event) - # First show only, and only without a saved layout: re-apply the - # default dock split AFTER the real (maximized) geometry exists — - # the __init__ resizeDocks ran on the pre-show size and Qt hands the - # scale-up surplus to the sample list, skewing 50/50 into ~80/20. - if not self._default_dock_split_done: - self._default_dock_split_done = True - if not self.state_manager.settings.value("main_window/state"): - QTimer.singleShot(0, self, self._apply_default_dock_split) - - def _apply_default_dock_split(self) -> None: - self.resizeDocks( - [self.tell_samples_dock, self.information_dock], [240, 240], Qt.Orientation.Vertical - ) - self.resizeDocks( - [self.tell_samples_dock, self.information_dock], - [10000, 10000], - Qt.Orientation.Horizontal, - ) - - def closeEvent(self, event) -> None: - try: - # Closing while watch-only would persist the all-hidden fold and - # poison every future start — put the pre-watch layout back first. - if self._session_operations_enabled is False and self._pre_watch_dock_state is not None: - self.restoreState(self._pre_watch_dock_state) - # TODO put all setting related handling into state_manager - self.state_manager.save_window(self) - self._save_samcam_overlay_settings() - self._save_panel_visibility_settings() - self._save_theme_settings() - - except Exception as e: - logger.warning(f"Failed to save main window state: {e}", exc_info=True) - - # End session before closing so the backend removes this GUI from Redis immediately - try: - self.daq.end_session_on_close() - except Exception as e: - logger.warning(f"Failed to end session on close: {e}", exc_info=True) - - try: - self.cleanup() - except Exception as e: - logger.warning(f"Cleanup during closeEvent failed: {e}", exc_info=True) - - super().closeEvent(event) - - def cleanup(self): - if self._cleanup_done: - return - - self._cleanup_done = True - - try: - if hasattr(self, "_samcam_source_timer") and self._samcam_source_timer is not None: - self._samcam_source_timer.stop() - except Exception as e: - logger.warning(f"Failed to stop _samcam_source_timer: {e}", exc_info=True) - - try: - if hasattr(self, "_idle_timer") and self._idle_timer is not None: - self._idle_timer.stop() - except Exception as e: - logger.warning(f"Failed to stop _idle_timer: {e}", exc_info=True) - - try: - if hasattr(self, "_remote_close_timer") and self._remote_close_timer is not None: - self._remote_close_timer.stop() - except Exception as e: - logger.warning(f"Failed to stop _remote_close_timer: {e}", exc_info=True) - - try: - if ( - hasattr(self, "_axis_camera_refresh_timer") - and self._axis_camera_refresh_timer is not None - ): - self._axis_camera_refresh_timer.stop() - except Exception as e: - logger.warning(f"Failed to stop _axis_camera_refresh_timer: {e}", exc_info=True) - - try: - if hasattr(self, "daq") and self.daq is not None: - self.daq.cleanup() - except Exception as e: - logger.warning(f"Failed to clean up DAQ worker: {e}", exc_info=True) - - self._stop_axis_camera_threads() - - for attr_name in ("prediction_thread",): - thread = getattr(self, attr_name, None) - if thread is None: - continue - - logger.debug(f"Stopping {attr_name}") - - try: - thread.stop() - except Exception as e: - logger.warning(f"Failed to stop {attr_name}: {e}", exc_info=True) - - setattr(self, attr_name, None) - - def _is_automation_active(self) -> bool: - try: - if hasattr(self, "job_list_panel") and self.job_list_panel is not None: - return bool(self.job_list_panel.is_running()) - except Exception: - logger.debug("Could not read the job list panel running state", exc_info=True) - - try: - progress = getattr(self.automation_progress_panel, "_progress", None) - if progress is not None and not bool(getattr(progress, "finished", False)): - return True - except Exception: - logger.debug("Could not read the automation progress state", exc_info=True) - - return False - - def _refresh_idle_activity(self, *, report_backend: bool = False) -> None: - self._last_user_interaction_ts = time.time() - - if not report_backend: - return - - now = time.monotonic() - if now - self._last_interaction_report_ts < self._interaction_report_min_interval_s: - return - - self._last_interaction_report_ts = now - try: - self.daq.report_gui_interaction(int(self._decoded_token.session)) - except Exception as e: - logger.debug(f"Failed to report GUI interaction: {e}", exc_info=True) - - def _mark_user_interaction(self) -> None: - self._refresh_idle_activity(report_backend=True) - - @Slot(bool) - def _on_dock_top_level_changed(self, floating: bool) -> None: - dock = self.sender() - if not isinstance(dock, QDockWidget): - return - # Floating = top-level: a transparent top-level renders black on the - # container's non-composited X11, so the QDockWidget[floating="true"] - # QSS rule gives it an opaque face; docked it goes transparent again - # so the main-window gradient stays continuous. - dock.setProperty("floating", floating) - dock.style().unpolish(dock) - dock.style().polish(dock) - dock.update() - if floating: - # Pop-outs open enlarged instead of keeping the cramped docked - # size. Deferred: the window is mid-reparent while the signal - # fires. - QTimer.singleShot(0, dock, lambda d=dock: self._enlarge_floating_dock(d)) - - def _enlarge_floating_dock(self, dock: QDockWidget) -> None: - if not dock.isFloating(): - return - screen = dock.screen().availableGeometry() - dock.resize( - min(dock.width() * 2, int(screen.width() * 0.9)), - min(dock.height() * 3, int(screen.height() * 0.9)), - ) - # Keep the enlarged window fully on screen. - geo = dock.frameGeometry() - dx = min(0, screen.right() - geo.right()) - dy = min(0, screen.bottom() - geo.bottom()) - if dx or dy: - dock.move(geo.x() + dx, geo.y() + dy) - - def _set_separator_hint(self, on: bool) -> None: - if self.property("separatorHint") == on: - return - self.setProperty("separatorHint", on) - # Property selectors are only re-evaluated on repolish. - self.style().unpolish(self) - self.style().polish(self) - self.update() - - def event(self, event): - # Separator press/drag never reaches mousePressEvent — QMainWindow - # eats it inside event() to start the separator move — so the hint - # gate must sit here, before super() dispatches. - t = event.type() - if t in (QEvent.Type.HoverEnter, QEvent.Type.HoverMove): - # Any move restarts the 1s countdown ("hover and rest"); during a - # drag (button held) the hint stays on instead. - if QApplication.mouseButtons() == Qt.MouseButton.NoButton: - self._set_separator_hint(False) - self._separator_hint_timer.start() - elif t == QEvent.Type.HoverLeave: - self._separator_hint_timer.stop() - self._set_separator_hint(False) - elif t == QEvent.Type.MouseButtonPress: - # Press shows the line immediately, no 1s wait. - self._separator_hint_timer.stop() - self._set_separator_hint(True) - elif t == QEvent.Type.MouseButtonRelease: - self._set_separator_hint(False) - self._separator_hint_timer.start() - return super().event(event) - - def eventFilter(self, obj, event): - # Closing a floated (popped-out) dock re-docks it instead of hiding — - # otherwise the panel silently disappears and has to be restored via - # the View menu. - if event.type() == QEvent.Type.Close and isinstance(obj, QDockWidget) and obj.isFloating(): - obj.setFloating(False) - event.ignore() - return True - # No try/except: every attribute this touches exists before the first - # install, and the one risky call (backend report) guards itself in - # _refresh_idle_activity. - if event.type() in { - QEvent.Type.MouseButtonPress, - QEvent.Type.MouseButtonRelease, - QEvent.Type.MouseMove, - QEvent.Type.Wheel, - QEvent.Type.KeyPress, - QEvent.Type.KeyRelease, - QEvent.Type.FocusIn, - QEvent.Type.TouchBegin, - QEvent.Type.TouchUpdate, - }: - self._mark_user_interaction() - # getattr defaults: this filter also runs for events delivered while - # __init__ is still building (or teardown is tearing down) the very - # widgets it inspects — a raise here spams every event and breaks - # widget cleanup, so missing attributes must mean "not my click". - if event.type() == QEvent.Type.MouseButtonPress: - # Non-staff click on the greyed-out Auxiliary-puck tab: only - # installed for non-staff, and tabAt() is geometric so it still - # sees the disabled tab — explain the lock instead of silently - # eating the click. - sample_tabs = getattr(self, "sample_lists_tabs", None) - sample_tab_bar = sample_tabs.tabBar() if sample_tabs is not None else None - if ( - sample_tab_bar is not None - and obj is sample_tab_bar - and sample_tab_bar.tabAt(event.position().toPoint()) == 1 - ): - self._show_reference_tools_staff_only_popup() - return True - # Non-staff click on a locked Beamline banner: same treatment as - # the Auxiliary-puck tab — explain the gate, don't eat the click. - if obj in getattr(self, "_locked_beamline_banners", ()): - self._show_beamline_staff_only_popup() - return True - # Click on the pgroup-gated (disabled) Beamline tab: tabAt() is - # geometric, so it still sees the disabled tab under the cursor. - left_tabs = getattr(self, "left_column_tabs", None) - if left_tabs is not None: - left_tab_bar = left_tabs.tabBar() - if ( - left_tab_bar is not None - and obj is left_tab_bar - and left_tab_bar.tabAt(event.position().toPoint()) == 0 - and not left_tabs.isTabEnabled(0) - ): - self._show_beamline_tab_gated_popup() - return True - return super().eventFilter(obj, event) - - def _start_remote_close_countdown( - self, requested_by: str | None, grace_seconds: int | None - ) -> None: - grace = max(1, int(grace_seconds or 60)) - self._remote_close_deadline_ts = time.time() + grace - self._remote_close_reason = requested_by or "staff" - self._remote_close_timer.start() - - self.alert_banner_secondary.show_message( - f"GUI close requested by {self._remote_close_reason}. Closing in {grace}s when safe.", - True, - ) - self._remote_close_banner_active = True - - def _clear_remote_close_request(self) -> None: - self._remote_close_deadline_ts = None - self._remote_close_reason = None - self._remote_close_timer.stop() - if self._remote_close_banner_active: - self.alert_banner_secondary.clear_message() - self._remote_close_banner_active = False - - def _can_close_for_idle_or_remote(self) -> bool: - status = self._latest_daq_status - if status is not None and bool(status.busy): - return False - return not self._is_automation_active() - - @Slot() - def _check_remote_close_deadline(self) -> None: - if self._remote_close_deadline_ts is None: - return - - remaining = round(self._remote_close_deadline_ts - time.time()) - if remaining > 0: - if self._remote_close_banner_active: - self.alert_banner_secondary.show_message( - f"GUI close requested by {self._remote_close_reason or 'staff'}. Closing in {remaining}s when safe.", - True, - ) - return - - if not self._can_close_for_idle_or_remote(): - if self._remote_close_banner_active: - self.alert_banner_secondary.show_message( - "GUI close requested, waiting for beamline/automation to become idle.", True - ) - return - - logger.warning("Closing GUI due to remote close request.") - self.close() diff --git a/src/aare/gui/models/__init__.py b/src/aare/gui/models/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/aare/gui/models/bookmark.py b/src/aare/gui/models/bookmark.py deleted file mode 100644 index 54fc5f60..00000000 --- a/src/aare/gui/models/bookmark.py +++ /dev/null @@ -1,20 +0,0 @@ -from typing import Literal - -from aarecommon.math.coordinate import SmargonCoordinate -from PySide6.QtGui import QColor - -from aare.gui.styles import BOOKMARK_COLORS, qcolor - - -class SmargonBookmark: - coord: SmargonCoordinate - color: Literal["red", "green", "blue", "indigo", "lime"] # Restrict to specific colors - - def qt_color(self) -> QColor: - """Convert the color property to a QColor.""" - color_map = {name: qcolor(hex_str) for name, hex_str in BOOKMARK_COLORS.items()} - return color_map[self.color] # Map the color string to QColor - - -class SmargonBookmarkList: - b: list[SmargonBookmark] diff --git a/src/aare/gui/models/gui_state_manager.py b/src/aare/gui/models/gui_state_manager.py deleted file mode 100644 index 07131a6d..00000000 --- a/src/aare/gui/models/gui_state_manager.py +++ /dev/null @@ -1,53 +0,0 @@ -import json - -from aarecommon.config.logger import setup_logger -from PySide6.QtCore import QSettings - -from aare.gui.constants import LOGGER_NAME - -logger = setup_logger(LOGGER_NAME) - - -class UIStateManager: - def __init__(self, organization="PSI", app="AareGUI"): - self.settings = QSettings(organization, app) - - def save_window(self, window): - self.settings.setValue("main_window/geometry", window.saveGeometry()) - self.settings.setValue("main_window/state", window.saveState()) - - def restore_window(self, window): - geometry = self.settings.value("main_window/geometry") - if geometry: - window.restoreGeometry(geometry) - - state = self.settings.value("main_window/state") - if state: - window.restoreState(state) - - def save_model(self, key: str, model): - try: - data = model.to_list() - self.settings.setValue(key, json.dumps(data)) - - except Exception: - logger.warning(f"Failed to save model {key}", exc_info=True) - - def restore_model(self, key: str, model): - try: - raw = self.settings.value(key) - if not raw: - return - - data = json.loads(raw) - - model.from_list(data) - - except Exception: - logger.warning(f"Failed to restore model {key}", exc_info=True) - - def save_value(self, key: str, value): - self.settings.setValue(key, value) - - def load_value(self, key: str, default=None, value_type=None): - return self.settings.value(key, default, type=value_type) diff --git a/src/aare/gui/models/sample_queue_model.py b/src/aare/gui/models/sample_queue_model.py deleted file mode 100644 index f6a1c3c7..00000000 --- a/src/aare/gui/models/sample_queue_model.py +++ /dev/null @@ -1,156 +0,0 @@ -from aarecommon.config.logger import setup_logger -from aarecommon.models.models import SampleShortInfo, SampleShortInfoList -from PySide6.QtCore import QAbstractTableModel, Qt -from PySide6.QtGui import QBrush - -from aare.gui.constants import LOGGER_NAME -from aare.gui.styles import SAMPLE_ROW_ACTIVE_BG, SAMPLE_ROW_QUEUED_BG, SAMPLE_STATUS_TEXT, qcolor - -logger = setup_logger(LOGGER_NAME) - - -def get_entry(sample: SampleShortInfo, column: int, *, show_user: bool = False): - if show_user: - if column == 0: - return sample.user - elif column == 1: - return sample.dewar_name - elif column == 2: - return sample.puck_name - elif column == 3: - return sample.sample_name - else: - if column == 0: - return sample.dewar_name - elif column == 1: - return sample.puck_name - elif column == 2: - return sample.sample_name - return "" - - -class SampleQueueSpreadsheet(QAbstractTableModel): - def __init__( - self, parent=None, samples: list[SampleShortInfo] | None = None, show_user: bool = False - ): - super().__init__(parent) - if samples is None: - samples = [] - self._running = False - self._show_user = bool(show_user) - self.samples: list[SampleShortInfo] = samples - self.header = ( - ["User", "Dewar", "Puck", "Sample"] if self._show_user else ["Dewar", "Puck", "Sample"] - ) - - def flags(self, index): - default_flags = super().flags(index) - return Qt.ItemFlag.ItemIsDropEnabled | default_flags - - def rowCount(self, parent=None): - return len(self.samples) - - def columnCount(self, parent=None): - return len(self.header) - - def data(self, index, role=None): - if role == Qt.ItemDataRole.DisplayRole: - return get_entry(self.samples[index.row()], index.column(), show_user=self._show_user) - elif role == Qt.ItemDataRole.TextAlignmentRole: - return Qt.AlignmentFlag.AlignCenter - elif role == Qt.ItemDataRole.BackgroundRole: - # Tint only the head-of-queue row; plain rows return None so the - # theme QSS paints them (hardcoded WHITE fills broke dark mode). - if index.row() == 0: - if self._running: - return QBrush(qcolor(SAMPLE_ROW_ACTIVE_BG)) - else: - return QBrush(qcolor(SAMPLE_ROW_QUEUED_BG)) - elif role == Qt.ItemDataRole.ForegroundRole and index.row() == 0: - # Fixed dark ink on the tint so dark-theme white text stays legible. - return QBrush(qcolor(SAMPLE_STATUS_TEXT)) - return None - - def headerData(self, section, orientation, role=None): - if role == Qt.ItemDataRole.DisplayRole: - if orientation == Qt.Orientation.Horizontal: - return self.header[section] if self.header else f"Column {section + 1}" - if orientation == Qt.Orientation.Vertical: - return str(section + 1) - return None - - def updateData(self, samples: list[SampleShortInfo]): - self.beginResetModel() - self.samples = list(samples) - self.endResetModel() - - def mimeTypes(self): - return ["text/plain"] - - def canDropMimeData(self, data, action, row, column, parent): - return bool(data.hasText()) - - def dropMimeData(self, data, action, row, column, parent): - if not self.canDropMimeData(data, action, row, column, parent): - return False - - if parent.isValid(): - row = parent.row() - - try: - sample_data = SampleShortInfoList.model_validate_json(data.text()) - self.beginResetModel() - for sample in sample_data.s: - updated_row = row - updated_samples = [] - for i in range(len(self.samples)): - if sample != self.samples[i]: - updated_samples.append(self.samples[i]) - else: - if 0 < row < i: - updated_row -= 1 - if updated_row == -1: - updated_samples.append(sample) - else: - updated_samples.insert(updated_row, sample) - self.samples = updated_samples - self.endResetModel() - except Exception: - logger.warning("Failed to handle dropped sample queue rows", exc_info=True) - return False - return True - - def set_running(self, running: bool): - self._running = running - self.layoutChanged.emit() - - def remove_sample(self, db_id: int): - self.beginResetModel() - self.samples = list(filter(lambda x: x.db_id != db_id, self.samples)) - self.endResetModel() - - def clearSamples(self): - self.beginResetModel() - self.samples = [] - self.endResetModel() - - def annotate_sample(self, db_id: int, comment: str) -> None: - self.beginResetModel() - updated_samples: list[SampleShortInfo] = [] - for sample in self.samples: - if sample.db_id == db_id: - updated_samples.append(sample.model_copy(update={"comment": comment})) - else: - updated_samples.append(sample) - self.samples = updated_samples - self.endResetModel() - - def to_state(self) -> dict: - return {"samples": [s.model_dump() for s in self.samples]} - - def from_state(self, state: dict): - self.beginResetModel() - - self.samples = [SampleShortInfo.model_validate(d) for d in state.get("samples", [])] - - self.endResetModel() diff --git a/src/aare/gui/models/user_sample_model.py b/src/aare/gui/models/user_sample_model.py deleted file mode 100644 index 866cd6c2..00000000 --- a/src/aare/gui/models/user_sample_model.py +++ /dev/null @@ -1,510 +0,0 @@ -import re -from typing import ClassVar - -from aarecommon.config.logger import setup_logger -from aarecommon.models.models import SampleShortInfo, SampleShortInfoList -from PySide6.QtCore import QAbstractTableModel, QMimeData, Qt -from PySide6.QtGui import QBrush - -from aare.gui.constants import LOGGER_NAME -from aare.gui.styles import ( - SAMPLE_ROW_QUEUED_BG, - SAMPLE_STATUS_FLAGGED_BG, - SAMPLE_STATUS_MEASURED_BG, - SAMPLE_STATUS_QUEUED_BG, - SAMPLE_STATUS_TEXT, - qcolor, -) - -logger = setup_logger(LOGGER_NAME) - -# Column 0 is display-only: the row position ("#") drawn over the status -# color fill. Data attributes start at column 1. -COL_STATUS = 0 - - -def get_entry(sample: SampleShortInfo, column: int): - if column == 1: - return sample.sample_name - elif column == 2: - return sample.puck_name - elif column == 3: - return sample.dewar_name - elif column == 4: - return sample.loc_str() - elif column == 5: - return sample.priority - elif column == 6: - return sample.user - elif column == 7: - return sample.mount_count - elif column == 8: - return sample.raster_count - elif column == 9: - return sample.screening_count - elif column == 10: - return sample.rotation_count - # Data-collection params straight from the AareDB spreadsheet (filled by - # spreadsheetupdater). Nullable: samples without params show blank. - elif column == 11: - return sample.comment - elif column == 12: - return sample.aaredb_params.oscillation if sample.aaredb_params else None - elif column == 13: - return sample.aaredb_params.exposure if sample.aaredb_params else None - elif column == 14: - return sample.aaredb_params.totalangle if sample.aaredb_params else None - elif column == 15: - # Model holds a 0-1 fraction; users think in spreadsheet percent. - t = sample.aaredb_params.transmission if sample.aaredb_params else None - return None if t is None else t - return "" - - -class UserSampleSpreadsheet(QAbstractTableModel): - def __init__( - self, - parent=None, - samples: list[SampleShortInfo] | None = None, - current_puck: str | None = None, - current_sample: int | None = None, - ): - super().__init__(parent) - if samples is None: - samples = [] - self.samples: list[SampleShortInfo] = samples - self.header = [ - "#", - "Sample name", - "Puck", - "Dewar", - "Location", - "Priority", - "User", - "⧂", # Mount count - "▦", # Raster count - # Workflow order: a sample is screened before rotation data is - # collected, so Screening sits left of Rotation. - "⌕", # Screening count - "↻", # Rotation count - "Comment", - "Oscillation (°)", - "Exposure (s)", - "Total range (°)", - "Transmission", - ] - self.current_sample = current_sample - self.current_puck = current_puck - self._sort_col = 4 # Location - self._sort_order = Qt.SortOrder.AscendingOrder - - self._filters: dict[int, str] = {} - self._filter_col: int | None = 6 # User - self._filter_value: str | None = None - self.current_pgroup: str | None = None - self.show_all_pgroups: bool = False - - # Display-only status tints (aaregui2 concept: the dewar table doubles - # as the queue view). Fed from outside; the queue itself stays in the - # SampleQueueSpreadsheet. - self.queued_ids: set[int] = set() - # Queue order as the engine holds it (Run pops its head): the Queued - # chip view displays THIS order, not the header sort. - self.queued_order: list[int] = [] - self.flagged_ids: set[int] = set() - # None = All; otherwise "queued" | "flagged" | "measured" | - # "unmeasured" (chip row). - self.status_filter: str | None = None - - self._sort() - - def to_list(self) -> list[dict]: - return [sample.to_dict() for sample in self.samples] - - def from_list(self, data: list[dict]): - self.beginResetModel() - self.samples = [SampleShortInfo.from_dict(d) for d in data] - self.endResetModel() - - def rowCount(self, parent=None): - return len(self._sorted_samples) - - def columnCount(self, parent=None): - return len(self.header) - - def data(self, index, role=None): - if role == Qt.ItemDataRole.DisplayRole: - if index.column() == COL_STATUS: - return index.row() + 1 - return get_entry(self._sorted_samples[index.row()], index.column()) - elif role == Qt.ItemDataRole.BackgroundRole: - # Status lives in the "#" column, as a full cell fill under the - # row number — rows themselves alternate grey/white (view-level) - # and selection stays the pale blue tint. Exception: the mounted - # sample paints the WHOLE row blue so it is findable at a glance. - sample = self._sorted_samples[index.row()] - if sample.db_id == self.current_sample: - return QBrush(qcolor(SAMPLE_ROW_QUEUED_BG)) - if index.column() == COL_STATUS: - color = self._status_color(sample) - if color is not None: - return QBrush(qcolor(color)) - elif role == Qt.ItemDataRole.ForegroundRole: - # Pastel-tinted "#" cells get fixed dark ink: the tints stay light - # in BOTH themes, so Sunset's white theme text would vanish on - # them. The mounted-row blue is mid-tone and readable with the - # theme's own text color, so it keeps the default ink. - sample = self._sorted_samples[index.row()] - if ( - index.column() == COL_STATUS - and sample.db_id != self.current_sample - and self._status_color(sample) is not None - ): - return QBrush(qcolor(SAMPLE_STATUS_TEXT)) - elif role == Qt.ItemDataRole.TextAlignmentRole: # Align text to center - return Qt.AlignmentFlag.AlignCenter - return None # For other roles, return None - - def _status_color(self, sample: SampleShortInfo) -> str | None: - # Mounted always wins; below that the dot depends on the active chip: - # inside a filtered view every row carries that status, so its own - # color is redundant — only cross-status marks show (queued view: - # red = also flagged; flagged view: orange = put back in the queue). - # The All view keeps the full priority queued > flagged > measured. - if sample.db_id == self.current_sample: - return SAMPLE_ROW_QUEUED_BG - queued = sample.db_id in self.queued_ids - flagged = sample.db_id in self.flagged_ids - if self.status_filter == "queued": - return SAMPLE_STATUS_FLAGGED_BG if flagged else None - if self.status_filter == "flagged": - return SAMPLE_STATUS_QUEUED_BG if queued else None - if self.status_filter in ("measured", "unmeasured"): - if queued: - return SAMPLE_STATUS_QUEUED_BG - return SAMPLE_STATUS_FLAGGED_BG if flagged else None - if queued: - return SAMPLE_STATUS_QUEUED_BG - if flagged: - return SAMPLE_STATUS_FLAGGED_BG - if self._measured(sample): - return SAMPLE_STATUS_MEASURED_BG - return None - - @staticmethod - def _measured(sample: SampleShortInfo) -> bool: - # Automatic status, never relabelled by hand: any rotation data - # counts as measured (>= 1); unmeasured is exactly rotation count 0. - return isinstance(sample.rotation_count, (int, float)) and sample.rotation_count >= 1 - - def set_queued_ids(self, db_ids) -> None: - # Callers pass the ids in queue order (main_window feeds them straight - # from the queue model) — keep it for the Queued view's row order. - self.queued_order = list(db_ids) - self.queued_ids = set(self.queued_order) - self._status_sets_changed() - - def set_flagged(self, db_id: int, flagged: bool) -> None: - if flagged: - self.flagged_ids.add(db_id) - else: - self.flagged_ids.discard(db_id) - self._status_sets_changed() - - def set_status_filter(self, status: str | None) -> None: - self.layoutAboutToBeChanged.emit() - self.status_filter = status - self._sort() - self.layoutChanged.emit() - - def _status_sets_changed(self) -> None: - # With a status chip active the row SET depends on the sets, not just - # the tint — refilter; otherwise a background repaint is enough. - if self.status_filter: - self.layoutAboutToBeChanged.emit() - self._sort() - self.layoutChanged.emit() - else: - self._emit_tints_changed() - - def _emit_tints_changed(self) -> None: - if self.rowCount() > 0: - # Whole span: the mounted row tints every column, not just "#". - self.dataChanged.emit( - self.index(0, COL_STATUS), - self.index(self.rowCount() - 1, self.columnCount() - 1), - [Qt.ItemDataRole.BackgroundRole, Qt.ItemDataRole.ForegroundRole], - ) - - # Hover tooltips for the glyph-only count columns — the icons save header - # width but don't explain themselves. - HEADER_TOOLTIPS: ClassVar[dict[str, str]] = { - "⧂": "Mount count", - "▦": "Gridscan count", - "⌕": "Screening count", - "↻": "Rotation count", - } - - def headerData(self, section, orientation, role=None): - if role == Qt.ItemDataRole.DisplayRole: - if orientation == Qt.Orientation.Horizontal: # Column header - return self.header[section] if self.header else f"Column {section + 1}" - if orientation == Qt.Orientation.Vertical: # Row header - return str(section + 1) # Row numbers start from 1 - if role == Qt.ItemDataRole.ToolTipRole and orientation == Qt.Orientation.Horizontal: - return self.HEADER_TOOLTIPS.get(self.header[section]) - return None - - def updateCurrentSample( - self, current_puck: str | None = None, current_sample: int | None = None - ): - self.current_puck = current_puck - self.current_sample = current_sample - self._emit_tints_changed() - - def updateData(self, samples: list[SampleShortInfo]): - if samples != self.samples: - self.beginResetModel() - self.samples = samples - self._sort() - self.endResetModel() - - def sort(self, column, order): - # The "#"/status column is display-only — nothing to sort by. - if column == COL_STATUS: - return - self.layoutAboutToBeChanged.emit() - self._sort_order = order - self._sort_col = column - self._sort() - self.layoutChanged.emit() - - def _sort(self): - filtered = self._apply_filter(self.samples) - if self.status_filter == "queued": - # The Queued view is the run order — row 1 runs next. Header - # clicks still move the indicator but must not reorder it. - position = {db_id: i for i, db_id in enumerate(self.queued_order)} - self._sorted_samples = sorted( - filtered, key=lambda row: position.get(row.db_id, len(position)) - ) - return - if self._sort_col == 4: # Location - self._sorted_samples = sorted( - filtered, - key=lambda row: row.loc_str_sort(), - reverse=( - self._sort_order == Qt.SortOrder.DescendingOrder - ), # Reverse for descending order - ) - else: - # Sort the samples based on the specified column and order. - # Nullable columns (params, comment): None sorts last, never - # compared against a real value (None < float raises). - def _key(row): - v = get_entry(row, self._sort_col) - return (v is None, "" if v is None else v) - - self._sorted_samples = sorted( - filtered, - key=_key, - reverse=( - self._sort_order == Qt.SortOrder.DescendingOrder - ), # Reverse for descending order - ) - - def _apply_filter(self, rows: list[SampleShortInfo]) -> list[SampleShortInfo]: - # Status chip filter first (All/Queued/Flagged/Measured row). - if self.status_filter == "queued": - rows = [r for r in rows if r.db_id in self.queued_ids] - elif self.status_filter == "flagged": - rows = [r for r in rows if r.db_id in self.flagged_ids] - elif self.status_filter == "measured": - rows = [r for r in rows if self._measured(r)] - elif self.status_filter == "unmeasured": - # Everything still to be done — the view to select-all and queue. - rows = [r for r in rows if not self._measured(r)] - - # Default filter by User using current p-group if no explicit filter set - filters: dict[int, str] = { - col: v for col, v in (self._filters or {}).items() if (v or "").strip() - } - - if self._filter_col is not None and (self._filter_value or "").strip(): - filters[self._filter_col] = self._filter_value - - if 6 not in filters and self.current_pgroup and not self.show_all_pgroups: - filters[6] = self.current_pgroup # User - - if not filters: - return rows - - def matches(sample: SampleShortInfo) -> bool: - for col, txt in filters.items(): - val = get_entry(sample, col) - s = "" if val is None else str(val) - if str(txt).strip().lower() not in s.strip().lower(): - return False - return True - - return [r for r in rows if matches(r)] - - def flags(self, index): - default_flags = super().flags(index) - if index.isValid(): - return Qt.ItemFlag.ItemIsDragEnabled | default_flags - return default_flags - - def mimeTypes(self): - return ["text/plain"] - - def mimeData(self, indexes): - mime_data = QMimeData() - - sample_data = SampleShortInfoList(s=[]) - - for i in sorted({index.row() for index in indexes}): - sample_data.s.append(self._sorted_samples[i]) - - mime_data.setText(sample_data.model_dump_json()) - return mime_data - - def get_id(self, row: int) -> SampleShortInfo: - return self._sorted_samples[row] - - def set_filter(self, field: str, text: str | None): - try: - col = self.header.index(field) - except ValueError: - col = None - self.layoutAboutToBeChanged.emit() - self._filter_col = col if text and text.strip() and col is not None else None - self._filter_value = text.strip() if text else None - # mirror into multi-filter map - if col is not None: - if text and text.strip(): - self._filters[col] = text.strip() - else: - self._filters.pop(col, None) - self._sort() - self.layoutChanged.emit() - - def clear_filter(self): - self.layoutAboutToBeChanged.emit() - self._filter_col = None - self._filter_value = None - self._filters.clear() - self._sort() - self.layoutChanged.emit() - - def set_default_user_filter(self, pgroup: str | None): - self.layoutAboutToBeChanged.emit() - self.current_pgroup = (pgroup or "").strip() or None - self._sort() - self.layoutChanged.emit() - - def set_column_filter(self, column: int, text: str | None): - self.layoutAboutToBeChanged.emit() - if text and text.strip(): - self._filters[column] = text.strip() - else: - self._filters.pop(column, None) - self._sort() - self.layoutChanged.emit() - - def clear_all_column_filters(self): - self.clear_filter() - - def set_show_all_pgroups(self, show_all: bool): - self.layoutAboutToBeChanged.emit() - self.show_all_pgroups = bool(show_all) - self._sort() - self.layoutChanged.emit() - - def unique_values_for_column(self, column: int, limit: int = 200) -> list[str]: - """Get unique values for a column from currently filtered samples (excluding this column's filter).""" - # Get currently filtered samples, but exclude the filter for this column - temp_filter = self._filters.pop(column, None) - filtered_samples = self._apply_filter(self.samples) - # Restore the filter - if temp_filter is not None: - self._filters[column] = temp_filter - - seen: set[str] = set() - out: list[str] = [] - for s in filtered_samples: - v = get_entry(s, column) - if v is None: - continue - txt = str(v).strip() - if not txt: - continue - if txt not in seen: - seen.add(txt) - out.append(txt) - if len(out) >= limit: - break - - # Sort appropriately - if column == 6: # User/pgroup column - try: - out.sort( - key=lambda x: ( - int(x[1:]) - if x and x[0].lower() == "p" and x[1:].isdigit() - else float("inf") - ) - ) - except Exception: - logger.debug("Falling back to a plain sort for the column values", exc_info=True) - out.sort() - else: - out.sort() - return out - - def suggested_prefixes_for_sample_name(self, limit: int = 200) -> list[str]: - """Get sample name prefixes from currently filtered samples (excluding column 0 filter).""" - # Get currently filtered samples, excluding the sample name filter - temp_filter = self._filters.pop(1, None) - filtered_samples = self._apply_filter(self.samples) - if temp_filter is not None: - self._filters[1] = temp_filter - - rx = re.compile(r"^([A-Za-z]+)") - counts: dict[str, int] = {} - for s in filtered_samples: - name = (s.sample_name or "").strip() - if not name: - continue - m = rx.match(name) - pref = m.group(1) if m else name.split("_")[0] - pref = pref.strip() - if not pref: - continue - counts[pref] = counts.get(pref, 0) + 1 - # Sort by frequency desc, then alpha - items = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0])) - return [k for k, _ in items[:limit]] - - def suggested_prefixes_for_location(self, limit: int = 200) -> tuple[list[str], list[str]]: - """Get location prefixes from currently filtered samples (excluding column 3 filter).""" - # Get currently filtered samples, excluding the location filter - temp_filter = self._filters.pop(4, None) - filtered_samples = self._apply_filter(self.samples) - if temp_filter is not None: - self._filters[4] = temp_filter - - seg_seen: set[str] = set() - segpos_seen: set[str] = set() - for s in filtered_samples: - loc = s.loc_str() # "-" or like "B3-10" - if loc and loc != "-" and isinstance(loc, str) and "-" in loc: - left = loc.split("-", 1)[0] # e.g., "B3" - if left: - segpos_seen.add(left) - seg = left[0] - if seg: - seg_seen.add(seg) - segs = sorted(seg_seen) - segpos = sorted(segpos_seen, key=lambda x: (x[0], int(x[1:]) if x[1:].isdigit() else 0)) - return (segs[:limit], segpos[:limit]) diff --git a/src/aare/gui/panels/__init__.py b/src/aare/gui/panels/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/aare/gui/panels/abr_tweak_panel.py b/src/aare/gui/panels/abr_tweak_panel.py deleted file mode 100644 index e1deec91..00000000 --- a/src/aare/gui/panels/abr_tweak_panel.py +++ /dev/null @@ -1,181 +0,0 @@ -from aarecommon.math.coordinate import AerotechCoordinate, Coordinate -from aarecommon.models.models import DAQStatusModel -from PySide6.QtCore import Signal, Slot -from PySide6.QtGui import Qt -from PySide6.QtWidgets import QGridLayout, QLabel, QPushButton, QWidget - -from aare.gui.styles import ALERT_TEXT -from aare.gui.widgets.button_with_payload import ButtonWithPayload -from aare.gui.widgets.number_line_edit import NumberLineEdit -from aare.gui.widgets.title_label import TitleLabel - -DEFAULT_ABR_STEP_UM = 5 - - -class AbrTweakButtons(QWidget): - abr_tweak = Signal(AerotechCoordinate) - - def __init__(self, step_mm, parent=None): - super().__init__(parent) - - self._step_mm = step_mm - grid_layout = QGridLayout(self) - # Caption, arrows, and value pack tight to the left; the empty - # trailing column soaks up all dead width. The values keep AlignRight - # in their content-width column so the decimal points line up without - # drifting over next to the Step column. - grid_layout.setColumnStretch(0, 0) - grid_layout.setColumnStretch(1, 0) - grid_layout.setColumnStretch(2, 0) - grid_layout.setColumnStretch(3, 0) - grid_layout.setColumnStretch(4, 1) - - grid_layout.addWidget(QLabel("GMX"), 0, 0) - button_gmx_minus = ButtonWithPayload("←", payload={"x": -1, "y": 0, "z": 0}) - button_gmx_plus = ButtonWithPayload("→", payload={"x": 1, "y": 0, "z": 0}) - grid_layout.addWidget(button_gmx_minus, 0, 1) - grid_layout.addWidget(button_gmx_plus, 0, 2) - - grid_layout.addWidget(QLabel("GMY"), 1, 0) - button_gmy_minus = ButtonWithPayload("←", payload={"x": 0, "y": -1, "z": 0}) - button_gmy_plus = ButtonWithPayload("→", payload={"x": 0, "y": 1, "z": 0}) - grid_layout.addWidget(button_gmy_minus, 1, 1) - grid_layout.addWidget(button_gmy_plus, 1, 2) - - grid_layout.addWidget(QLabel("GMZ"), 2, 0) - button_gmz_minus = ButtonWithPayload("←", payload={"x": 0, "y": 0, "z": -1}) - button_gmz_plus = ButtonWithPayload("→", payload={"x": 0, "y": 0, "z": 1}) - grid_layout.addWidget(button_gmz_minus, 2, 1) - grid_layout.addWidget(button_gmz_plus, 2, 2) - - button_gmx_minus.pressed.connect(self.abr_button) - button_gmx_plus.pressed.connect(self.abr_button) - button_gmy_minus.pressed.connect(self.abr_button) - button_gmy_plus.pressed.connect(self.abr_button) - button_gmz_minus.pressed.connect(self.abr_button) - button_gmz_plus.pressed.connect(self.abr_button) - - button_gmx_minus.setFixedWidth(32) - button_gmy_minus.setFixedWidth(32) - button_gmz_minus.setFixedWidth(32) - button_gmx_plus.setFixedWidth(32) - button_gmy_plus.setFixedWidth(32) - button_gmz_plus.setFixedWidth(32) - self.gmx_label = QLabel("0.000") - grid_layout.addWidget(self.gmx_label, 0, 3) - self.gmx_label.setAlignment(Qt.AlignmentFlag.AlignRight) - self.gmy_label = QLabel("0.000") - self.gmy_label.setAlignment(Qt.AlignmentFlag.AlignRight) - grid_layout.addWidget(self.gmy_label, 1, 3) - self.gmz_label = QLabel("0.000") - self.gmz_label.setAlignment(Qt.AlignmentFlag.AlignRight) - grid_layout.addWidget(self.gmz_label, 2, 3) - - # Reserve room for the sign up front: the column is content-sized, so - # without this it widens whenever a value flips negative and the whole - # row shifts. Right alignment keeps the digits anchored in the gap. - sign_width = self.fontMetrics().horizontalAdvance("-88.888") - for label in (self.gmx_label, self.gmy_label, self.gmz_label): - label.setMinimumWidth(sign_width) - - @Slot(dict) - def abr_button(self, payload: dict): - self.abr_tweak.emit( - AerotechCoordinate( - at_mm=Coordinate( - x=self._step_mm * payload["x"], - y=self._step_mm * payload["y"], - z=self._step_mm * payload["z"], - ) - ) - ) - - @Slot(float) - def set_step(self, val_um: float): - self._step_mm = val_um / 1000.0 - - -class AbrTweakWidget(QWidget): - abr_tweak = Signal(AerotechCoordinate) - abr_save = Signal() - abr_goto_meas = Signal() - - def __init__(self, parent=None): - super().__init__(parent) - - grid_layout = QGridLayout(self) - - grid_layout.addWidget( - TitleLabel("ABR meas. pos.", self, collapsible=True, default_collapsed=False), - 0, - 0, - 1, - 2, - ) - - self._abr_buttons = AbrTweakButtons(DEFAULT_ABR_STEP_UM / 1000, parent=self) - grid_layout.addWidget(self._abr_buttons, 1, 0) - self._abr_buttons.abr_tweak.connect(self.abr_button_pressed) - - # Step + actions as a column BESIDE the GM rows instead of below — - # the rows left plenty of dead width. - side = QWidget(self) - side_grid = QGridLayout(side) - side_grid.setContentsMargins(0, 0, 0, 0) - side_grid.addWidget(QLabel("Step", parent=side), 0, 0) - self._step_um = NumberLineEdit(1, 1000, DEFAULT_ABR_STEP_UM, 0, parent=side) - side_grid.addWidget(self._step_um, 0, 1) - side_grid.addWidget(QLabel("μm", parent=side), 0, 2) - self._step_um.newValue.connect(self._abr_buttons.set_step) - - save_button = QPushButton("Save ABR pos.") - side_grid.addWidget(save_button, 1, 0, 1, 3) - save_button.pressed.connect(self.save_button_pressed) - - goto_button = QPushButton("Go to meas.") - side_grid.addWidget(goto_button, 2, 0, 1, 3) - goto_button.pressed.connect(self.goto_button_pressed) - - # ~80% of the width the grid handed it; the freed space goes to the - # GM rows (column 0 takes all stretch). - side.setMaximumWidth(150) - grid_layout.setColumnStretch(0, 1) - grid_layout.addWidget(side, 1, 1) - - @Slot() - def goto_button_pressed(self): - self.abr_goto_meas.emit() - - @Slot(AerotechCoordinate) - def abr_button_pressed(self, c: AerotechCoordinate): - self.abr_tweak.emit(c) - - @Slot() - def save_button_pressed(self): - self.abr_save.emit() - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - # TODO(confirm intent): labels DISPLAY aerotech_meas (saved measurement - # pos) but the red highlight CHECKS aerotech (live stage pos), so a - # label can read 0.000 and still be red. Guess: red was meant to warn - # "live stage is off the meas pos", i.e. the check should be - # abs(aerotech - aerotech_meas) >= 0.001 per axis; alternative reading - # is it should flag the displayed meas value itself being nonzero. - # Confirm which and re-evaluate before changing the condition. - self._abr_buttons.gmx_label.setText(f"{s.geom.aerotech_meas.x:.3f}") - if abs(s.geom.aerotech.x) >= 0.001: - self._abr_buttons.gmx_label.setStyleSheet(f"color: {ALERT_TEXT};") - else: - self._abr_buttons.gmx_label.setStyleSheet("") - self._abr_buttons.gmy_label.setText(f"{s.geom.aerotech_meas.y:.3f}") - if abs(s.geom.aerotech.y) >= 0.001: - self._abr_buttons.gmy_label.setStyleSheet(f"color: {ALERT_TEXT};") - else: - self._abr_buttons.gmy_label.setStyleSheet("") - - self._abr_buttons.gmz_label.setText(f"{s.geom.aerotech_meas.z:.3f}") - if abs(s.geom.aerotech.z) >= 0.001: - self._abr_buttons.gmz_label.setStyleSheet(f"color: {ALERT_TEXT};") - else: - self._abr_buttons.gmz_label.setStyleSheet("") diff --git a/src/aare/gui/panels/automation_panel.py b/src/aare/gui/panels/automation_panel.py deleted file mode 100644 index fbac3819..00000000 --- a/src/aare/gui/panels/automation_panel.py +++ /dev/null @@ -1,328 +0,0 @@ -from __future__ import annotations - -import time -from datetime import datetime - -from aarecommon.config.logger import setup_logger -from aarecommon.models.automation import AutomationProgress, StepStatus, WorkflowStateKind -from PySide6.QtCore import Qt, QTimer, Slot -from PySide6.QtWidgets import QHBoxLayout, QLabel, QVBoxLayout, QWidget - -from aare.gui.constants import LOGGER_NAME -from aare.gui.styles import ( - AUTOMATION_HINT_TEXT, - CARD_BORDER, - FAINT_TEXT, - FONT_BODY, - FONT_LABEL, - FONT_TITLE, - MUTED_TEXT, - STEP_ACTIVE_BG, - STEP_ACTIVE_BORDER, - STEP_ACTIVE_TEXT, - STEP_DONE_BG, - STEP_DONE_BORDER, - STEP_DONE_TEXT, - STEP_FAILED_BG, - STEP_FAILED_BORDER, - STEP_FAILED_TEXT, - STEP_IDLE_BG, - STEP_IDLE_BORDER, - STEP_PAUSED_BG, - STEP_PAUSED_BORDER, - STEP_PAUSED_TEXT, - SURFACE, -) - -logger = setup_logger(LOGGER_NAME) - - -class AutomationProgressWidget(QWidget): - """Compact fixed-step widget for DAQ automation progress.""" - - DEFAULT_SAMPLE_ESTIMATE_S = 150.0 - - def __init__(self, parent: QWidget | None = None): - super().__init__(parent) - self._progress: AutomationProgress | None = None - self._gui_samples_in_queue: int | None = None - self._labels: dict[WorkflowStateKind, QLabel] = {} - self._stats_label: QLabel | None = None - self._is_paused = False - self._refresh_timer = QTimer(self) - self._refresh_timer.setInterval(1000) - self._refresh_timer.timeout.connect(self._refresh_live_metrics) - self._setup_ui() - self.clear() - - def _setup_ui(self) -> None: - # No title label: the dock's title bar already says it. - layout = QVBoxLayout(self) - layout.setContentsMargins(10, 10, 10, 10) - layout.setSpacing(10) - - self._stats_label = QLabel() - self._stats_label.setStyleSheet( - f"color: {AUTOMATION_HINT_TEXT}; font-size: {FONT_LABEL}; font-weight: 700; " - f"background-color: {SURFACE}; border: 1px solid {CARD_BORDER}; " - "padding: 10px;" - ) - self._stats_label.setWordWrap(True) - - # Stats left, automation run-state card right ("||" paused / "▶" - # running — ASCII bars: fancier pause glyphs are missing from the - # beamline console fonts). - self._state_label = QLabel() - self._state_label.setAlignment(Qt.AlignmentFlag.AlignCenter) - - top_row = QHBoxLayout() - top_row.setSpacing(10) - top_row.addWidget(self._stats_label, 2) - top_row.addWidget(self._state_label, 1) - layout.addLayout(top_row) - self._update_state_label() - - steps_row = QHBoxLayout() - steps_row.setSpacing(6) - for step in ( - WorkflowStateKind.MOUNT, - WorkflowStateKind.LOOP_CENTRE, - WorkflowStateKind.RASTER, - WorkflowStateKind.DATA_COLLECTION, - ): - label = QLabel() - label.setWordWrap(True) - steps_row.addWidget(label, 1) - self._labels[step] = label - layout.addLayout(steps_row) - - layout.addStretch() - - def clear(self) -> None: - self._gui_samples_in_queue = 0 - self._is_paused = False - empty = AutomationProgress( - current_step=None, - steps=[ - self._make_step(WorkflowStateKind.MOUNT, StepStatus.PENDING), - self._make_step(WorkflowStateKind.LOOP_CENTRE, StepStatus.PENDING), - self._make_step(WorkflowStateKind.RASTER, StepStatus.PENDING), - self._make_step(WorkflowStateKind.DATA_COLLECTION, StepStatus.PENDING), - self._make_step(WorkflowStateKind.FINAL, StepStatus.PENDING), - ], - finished=False, - success=None, - samples_in_queue=0, - avg_time_per_sample=0.0, - current_sample_name="", - ) - self.set_progress(empty) - - @staticmethod - def _make_step(step: WorkflowStateKind, status: StepStatus): - from aarecommon.models.automation import StepState - - return StepState(step=step, status=status, message="") - - @staticmethod - def _label_for_step(step: WorkflowStateKind) -> str: - return { - WorkflowStateKind.MOUNT: "Mount", - WorkflowStateKind.LOOP_CENTRE: "Center", - WorkflowStateKind.RASTER: "Raster", - WorkflowStateKind.DATA_COLLECTION: "Collect", - WorkflowStateKind.FINAL: "Status", - }.get(step, str(step.value)) - - @staticmethod - def _icon_for_status(status: StepStatus) -> str: - return { - StepStatus.PENDING: "⚪", - StepStatus.RUNNING: "🔵", - StepStatus.SUCCESS: "✅", - StepStatus.FAILED: "❌", - StepStatus.SKIPPED: "⏭️", - StepStatus.PAUSED: "⏸️", - }.get(status, "⚪") - - @staticmethod - def _style_for_status(status: StepStatus) -> str: - base = f"padding: 10px 12px; font-size: {FONT_BODY}; border: 1px solid transparent;" - - if status == StepStatus.SUCCESS: - return ( - base - + f" background-color: {STEP_DONE_BG}; color: {STEP_DONE_TEXT}; border-color: {STEP_DONE_BORDER};" - ) - if status == StepStatus.RUNNING: - return ( - base - + f" background-color: {STEP_ACTIVE_BG}; color: {STEP_ACTIVE_TEXT}; font-weight: 700; border-color: {STEP_ACTIVE_BORDER};" - ) - if status == StepStatus.FAILED: - return ( - base - + f" background-color: {STEP_FAILED_BG}; color: {STEP_FAILED_TEXT}; font-weight: 700; border-color: {STEP_FAILED_BORDER};" - ) - if status == StepStatus.PAUSED: - return ( - base - + f" background-color: {STEP_PAUSED_BG}; color: {STEP_PAUSED_TEXT}; font-weight: 700; border-color: {STEP_PAUSED_BORDER};" - ) - if status == StepStatus.SKIPPED: - return ( - base - + f" background-color: {STEP_IDLE_BG}; color: {MUTED_TEXT}; border-color: {STEP_IDLE_BORDER};" - ) - return ( - base - + f" background-color: {STEP_IDLE_BG}; color: {FAINT_TEXT}; border-color: {STEP_IDLE_BORDER};" - ) - - @staticmethod - def _format_duration(seconds: float | None) -> str: - if seconds is None or seconds <= 0: - return "0m 00s" - if seconds < 60: - return f"0m {round(seconds):02d}s" - minutes, secs = divmod(round(seconds), 60) - if minutes < 60: - return f"{minutes}m {secs:02d}s" - hours, minutes = divmod(minutes, 60) - return f"{hours}h {minutes:02d}m" - - @staticmethod - def _format_eta_timestamp(epoch_seconds: float | None) -> str: - if epoch_seconds is None: - return "N/A" - return datetime.fromtimestamp(epoch_seconds).strftime("%H:%M:%S") - - def _has_live_timing(self, progress: AutomationProgress) -> bool: - if progress.finished: - return False - return any( - step.status == StepStatus.RUNNING and step.started_at is not None - for step in progress.steps - ) - - def _has_active_sample(self, progress: AutomationProgress) -> bool: - if progress.finished: - return False - if progress.current_sample_name: - return True - return any( - step.status == StepStatus.RUNNING - for step in progress.steps - if step.step != WorkflowStateKind.FINAL - ) - - @Slot() - def _refresh_live_metrics(self) -> None: - if self._progress is None: - return - self.set_progress(self._progress) - - def _update_state_label(self) -> None: - if self._is_paused: - colors = ( - f"background-color: {STEP_PAUSED_BG}; color: {STEP_PAUSED_TEXT}; " - f"border: 1px solid {STEP_PAUSED_BORDER};" - ) - text = "|| paused" - else: - colors = ( - f"background-color: {STEP_ACTIVE_BG}; color: {STEP_ACTIVE_TEXT}; " - f"border: 1px solid {STEP_ACTIVE_BORDER};" - ) - text = "▶ running" - self._state_label.setText(text) - self._state_label.setStyleSheet( - f"font-size: {FONT_TITLE}; font-weight: 700; padding: 10px; " + colors - ) - - @Slot(bool) - def set_running(self, running: bool) -> None: - self._is_paused = not running - self._update_state_label() - - if self._progress is None: - return - - if self._is_paused: - self._refresh_timer.stop() - elif self._has_live_timing(self._progress): - self._refresh_timer.start() - - self.set_progress(self._progress) - - @Slot(int) - def set_samples_in_queue(self, count: int) -> None: - self._gui_samples_in_queue = max(0, int(count)) - if self._progress is not None: - self.set_progress(self._progress) - - @Slot(object) - def set_progress(self, progress: AutomationProgress) -> None: - self._progress = progress - - if self._has_live_timing(progress) and not self._is_paused: - if not self._refresh_timer.isActive(): - self._refresh_timer.start() - else: - self._refresh_timer.stop() - - if self._stats_label: - measured_avg_seconds = ( - progress.avg_time_per_sample if progress.avg_time_per_sample > 0 else None - ) - displayed_avg_seconds = measured_avg_seconds or self.DEFAULT_SAMPLE_ESTIMATE_S - - current_sample = progress.current_sample_name or "None" - samples_left = ( - self._gui_samples_in_queue - if self._gui_samples_in_queue is not None - else max(0, int(progress.samples_in_queue or 0)) - ) - - if progress.finished or self._is_paused or not self._has_active_sample(progress): - queue_remaining = displayed_avg_seconds * samples_left - else: - queue_remaining = displayed_avg_seconds * max(0, samples_left) - - eta_clock = time.time() + queue_remaining if queue_remaining > 0 else None - - stats_lines = [ - f"Current sample: {current_sample}", - f"Samples left: {samples_left}", - f"Avg sample time: {self._format_duration(displayed_avg_seconds)}", - f"Queue remaining: {self._format_duration(queue_remaining)}", - f"Done by: {self._format_eta_timestamp(eta_clock)}", - ] - self._stats_label.setText("
".join(stats_lines)) - - for step_state in progress.steps: - label = self._labels.get(step_state.step) - if label is None: - continue - - title = self._label_for_step(step_state.step) - icon = self._icon_for_status(step_state.status) - - duration_str = "" - if step_state.started_at is not None: - end = step_state.completed_at or time.time() - duration_str = f" ({self._format_duration(end - step_state.started_at)})" - - if step_state.status == StepStatus.FAILED and step_state.message: - message = f" — Failed: {step_state.message}" - else: - message = f" — {step_state.message}" if step_state.message else "" - - error_str = ( - f"
Error: {step_state.error_code}" - if step_state.error_code - else "" - ) - - label.setText(f"{icon} {title}{duration_str}{message}{error_str}") - label.setStyleSheet(self._style_for_status(step_state.status)) diff --git a/src/aare/gui/panels/axis_video_panel.py b/src/aare/gui/panels/axis_video_panel.py deleted file mode 100644 index 4225c65f..00000000 --- a/src/aare/gui/panels/axis_video_panel.py +++ /dev/null @@ -1,58 +0,0 @@ -from dataclasses import replace - -from PySide6.QtCore import Signal -from PySide6.QtWidgets import QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget - -from aare.gui.widgets.busy_overlay import BusyOverlayStyle -from aare.gui.widgets.video_image import VideoGraphicsView - - -class AxisVideoPanel(QWidget): - refresh_requested = Signal() - - # video_view may be a bare VideoGraphicsView or any container holding - # them (the combined view passes a QWidget with two stacked views). - def __init__(self, title: str, video_view: QWidget | None = None, parent=None): - super().__init__(parent) - - self._title_label = QLabel(title, self) - - self._refresh_button = QPushButton("Refresh Axis Cameras", self) - self._refresh_button.clicked.connect(self.refresh_requested.emit) - - self.view = video_view if video_view is not None else VideoGraphicsView() - - controls_layout = QHBoxLayout() - controls_layout.setContentsMargins(0, 0, 0, 0) - controls_layout.addWidget(self._title_label) - controls_layout.addStretch() - controls_layout.addWidget(self._refresh_button) - - root_layout = QVBoxLayout(self) - root_layout.setContentsMargins(0, 0, 0, 0) - root_layout.setSpacing(6) - root_layout.addLayout(controls_layout) - root_layout.addWidget(self.view) - - def _all_video_views(self) -> list[VideoGraphicsView]: - views: list[VideoGraphicsView] = [] - if isinstance(self.view, VideoGraphicsView): - views.append(self.view) - views.extend(self.findChildren(VideoGraphicsView)) - unique_views: list[VideoGraphicsView] = [] - for view in views: - if view not in unique_views: - unique_views.append(view) - return unique_views - - def set_busy_style(self, style: BusyOverlayStyle | None) -> None: - # The hint line invites a click, but only the sample-camera badge is - # a click target — strip it for these passive views. - if style is not None and style.subtext: - style = replace(style, subtext="") - - # Only the first view draws the badge: the combined panel stacks two - # video views and used to show the message once per view. - for index, view in enumerate(self._all_video_views()): - if hasattr(view, "set_busy_overlay_style"): - view.set_busy_overlay_style(style if index == 0 else None) diff --git a/src/aare/gui/panels/beam_center_panel.py b/src/aare/gui/panels/beam_center_panel.py deleted file mode 100644 index 6aaf71ee..00000000 --- a/src/aare/gui/panels/beam_center_panel.py +++ /dev/null @@ -1,30 +0,0 @@ -from aarecommon.models.models import DAQStatusModel -from PySide6.QtCore import Signal, Slot -from PySide6.QtWidgets import QGridLayout, QLabel, QWidget - -from aare.gui.widgets.title_label import section_title - - -class BeamCenterWidget(QWidget): - beam_center = Signal(float, float) - - def __init__(self, parent=None): - super().__init__(parent) - - grid_layout = QGridLayout(self) - - grid_layout.addWidget(section_title("Beam center (detector)", self), 0, 0, 1, 5) - - self._x = QLabel("...") - self._y = QLabel("...") - - grid_layout.addWidget(QLabel("x:"), 1, 0) - grid_layout.addWidget(self._x, 1, 1) - grid_layout.addWidget(QLabel("y:"), 1, 2) - grid_layout.addWidget(self._y, 1, 3) - grid_layout.addWidget(QLabel("px"), 1, 4) - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - self._x.setText(f"{s.diffraction.beam_center_pxl[0]:.1f}") - self._y.setText(f"{s.diffraction.beam_center_pxl[1]:.1f}") diff --git a/src/aare/gui/panels/beam_mark_panel.py b/src/aare/gui/panels/beam_mark_panel.py deleted file mode 100644 index 3a892b3b..00000000 --- a/src/aare/gui/panels/beam_mark_panel.py +++ /dev/null @@ -1,41 +0,0 @@ -from aarecommon.models.models import DAQStatusModel -from PySide6.QtCore import Signal, Slot -from PySide6.QtWidgets import QGridLayout, QLabel, QPushButton, QWidget - -from aare.gui.widgets.title_label import section_title - - -class BeamMarkWidget(QWidget): - beam_mark_clear = Signal() - - def __init__(self, parent=None): - super().__init__(parent) - - grid_layout = QGridLayout(self) - grid_layout.setVerticalSpacing(2) - - grid_layout.addWidget(section_title("Beam mark (image)", self), 0, 0, 1, 6) - - self.x = QLabel("0") - self.y = QLabel("0") - - grid_layout.addWidget(QLabel("x:"), 1, 0) - grid_layout.addWidget(self.x, 1, 1) - grid_layout.addWidget(QLabel("y:"), 1, 2) - grid_layout.addWidget(self.y, 1, 3) - grid_layout.addWidget(QLabel("pxl"), 1, 4) - - # Shares the readings row instead of a full-width row below. - clear_button = QPushButton("Clear marks") - clear_button.setFixedWidth(100) # 100 is needed to see everything - grid_layout.addWidget(clear_button, 1, 5) - clear_button.pressed.connect(self.clear_button_pressed) - - @Slot() - def clear_button_pressed(self): - self.beam_mark_clear.emit() - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - self.x.setText(f"{s.geom.beam_location_pxl.x:.0f}") - self.y.setText(f"{s.geom.beam_location_pxl.y:.0f}") diff --git a/src/aare/gui/panels/beam_size_panel.py b/src/aare/gui/panels/beam_size_panel.py deleted file mode 100644 index 83aa4afd..00000000 --- a/src/aare/gui/panels/beam_size_panel.py +++ /dev/null @@ -1,38 +0,0 @@ -from aarecommon.models.models import DAQStatusModel -from PySide6.QtCore import Signal, Slot -from PySide6.QtWidgets import QGridLayout, QLabel, QWidget - -from aare.gui.widgets.number_line_edit import NumberLineEdit -from aare.gui.widgets.title_label import section_title - - -class BeamSizeWidget(QWidget): - beam_size = Signal(float, float) - - def __init__(self, parent=None): - super().__init__(parent) - - grid_layout = QGridLayout(self) - - grid_layout.addWidget(section_title("Beam size", self), 0, 0, 1, 5) - - self.x = NumberLineEdit(1, 400.0, 10, parent=self) - self.x.newValue.connect(self.beam_size_edited) - - self.y = NumberLineEdit(1, 400.0, 10, parent=self) - self.y.newValue.connect(self.beam_size_edited) - - grid_layout.addWidget(QLabel("x:"), 1, 0) - grid_layout.addWidget(self.x, 1, 1) - grid_layout.addWidget(QLabel("y:"), 1, 2) - grid_layout.addWidget(self.y, 1, 3) - grid_layout.addWidget(QLabel("μm"), 1, 4) - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - self.x.update_value(s.geom.beam_size_mm.x * 1000.0) - self.y.update_value(s.geom.beam_size_mm.y * 1000.0) - - @Slot(float) - def beam_size_edited(self, _: float): - self.beam_size.emit(self.x.value / 1000.0, self.y.value / 1000.0) diff --git a/src/aare/gui/panels/beamline_controls.py b/src/aare/gui/panels/beamline_controls.py deleted file mode 100644 index 01e3d4b1..00000000 --- a/src/aare/gui/panels/beamline_controls.py +++ /dev/null @@ -1,65 +0,0 @@ -from PySide6.QtWidgets import QFrame, QVBoxLayout, QWidget - -from aare.gui.panels.beam_center_panel import BeamCenterWidget -from aare.gui.panels.beam_mark_panel import BeamMarkWidget -from aare.gui.panels.beam_size_panel import BeamSizeWidget -from aare.gui.panels.illumination_panel import IlluminationPanel -from aare.gui.panels.omega_panel import OmegaPanel -from aare.gui.panels.smargon_panel import SmargonPanel -from aare.gui.panels.zoom_panel import ZoomPanel -from aare.gui.widgets.title_label import TitleLabel, tighten_column - - -class BeamConfigPanel(QWidget): - """Beam mark / center / size grouped under one collapsible banner; the - sub-widgets keep their own signals and small section titles.""" - - def __init__(self, parent=None): - super().__init__(parent) - # Default layout margins so the banner aligns with the sibling - # panels' banners in the column. - layout = QVBoxLayout(self) - layout.setSpacing(0) - layout.addWidget( - TitleLabel("Beam configuration", self, collapsible=True, default_collapsed=False) - ) - self.beam_mark = BeamMarkWidget(self) - self.beam_center = BeamCenterWidget(self) - self.beam_size = BeamSizeWidget(self) - for sub in (self.beam_mark, self.beam_center, self.beam_size): - sub_layout = sub.layout() - assert sub_layout is not None # each sub-widget builds its grid in __init__ - # The outer layout already indents; zero the sub-grids' side - # margins so section content isn't double-inset. - sub_layout.setContentsMargins(0, 4, 0, 4) - layout.addWidget(sub) - - -class BeamlineControls(QFrame): - set_width = 250 - - def __init__(self, parent=None): - super().__init__(parent) - self.setObjectName("beamlineControls") - self.setFixedWidth(self.set_width) - self.setFrameShape(QFrame.Shape.StyledPanel) - self.setFrameShadow(QFrame.Shadow.Raised) - - # Samcam / monochromator / ABR / beam config moved to the left - # column's "Beamline" group (main_window builds it). - self.v_layout = QVBoxLayout(self) - self.zoom_panel = ZoomPanel(self) - self.v_layout.addWidget(self.zoom_panel) - - self.illumination_panel = IlluminationPanel(self) - self.v_layout.addWidget(self.illumination_panel) - - self.omega_panel = OmegaPanel(parent=self) - self.v_layout.addWidget(self.omega_panel) - - self.smargon_panel = SmargonPanel(parent=self) - self.v_layout.addWidget(self.smargon_panel) - - self.v_layout.addStretch() - tighten_column(self.v_layout) - self.setLayout(self.v_layout) diff --git a/src/aare/gui/panels/beamline_recovery_panel.py b/src/aare/gui/panels/beamline_recovery_panel.py deleted file mode 100644 index 7e4a5822..00000000 --- a/src/aare/gui/panels/beamline_recovery_panel.py +++ /dev/null @@ -1,318 +0,0 @@ -from __future__ import annotations - -from aarecommon.config.logger import setup_logger -from aarecommon.models.models import DAQStatusModel -from PySide6.QtCore import Slot -from PySide6.QtWidgets import ( - QDialog, - QDialogButtonBox, - QInputDialog, - QLabel, - QLineEdit, - QMessageBox, - QPushButton, - QVBoxLayout, - QWidget, -) - -from aare.gui.constants import LOGGER_NAME -from aare.gui.styles import ( - BAD_CARD_BORDER, - CHIP_BAD_BG, - CHIP_BAD_TEXT, - CHIP_INFO_TEXT, - CHIP_WARN_BG, - CHIP_WARN_TEXT, - FLAT_CARD_RADIUS, - INFO_CARD_BG, - INFO_CARD_BORDER, - PENDING_CARD_BG, - PENDING_CARD_BORDER, - WARN_CARD_BORDER, - card_style, -) -from aare.gui.threads.daq_worker import DAQWorker - -logger = setup_logger(LOGGER_NAME) - - -class RecoveryPanel(QWidget): - def __init__(self, *, daq: DAQWorker, parent=None): - super().__init__(parent) - self._daq = daq - self._last_status: DAQStatusModel | None = None - - layout = QVBoxLayout(self) - layout.setContentsMargins(0, 0, 0, 0) - layout.setSpacing(8) - - self._warning_primary = QLabel( - "⚠ Recovery actions are staff-only and intentionally dangerous.", self - ) - self._warning_primary.setWordWrap(True) - self._warning_primary.setStyleSheet( - card_style( - CHIP_WARN_BG, - WARN_CARD_BORDER, - CHIP_WARN_TEXT, - selector="QLabel", - radius=FLAT_CARD_RADIUS, - extra="padding: 10px; font-weight: 600;", - ) - ) - layout.addWidget(self._warning_primary) - - self._warning_secondary = QLabel( - "Only use these commands when beamline is stuck and certain beamline is unrecoverable through normal operation.", - self, - ) - self._warning_secondary.setWordWrap(True) - self._warning_secondary.setStyleSheet( - card_style( - CHIP_BAD_BG, - BAD_CARD_BORDER, - CHIP_BAD_TEXT, - selector="QLabel", - radius=FLAT_CARD_RADIUS, - extra="padding: 10px; font-weight: 600;", - ) - ) - layout.addWidget(self._warning_secondary) - - self._last_action = QLabel("Last action: -", self) - self._last_action.setWordWrap(True) - self._last_action.setStyleSheet( - card_style( - INFO_CARD_BG, - INFO_CARD_BORDER, - CHIP_INFO_TEXT, - selector="QLabel", - radius=FLAT_CARD_RADIUS, - extra="padding: 10px; font-weight: 600;", - ) - ) - layout.addWidget(self._last_action) - - self._take_over_btn = QPushButton("Take over beamline", self) - self._take_over_btn.setStyleSheet( - card_style( - PENDING_CARD_BG, - PENDING_CARD_BORDER, - selector="QPushButton", - radius=FLAT_CARD_RADIUS, - extra="padding: 10px; font-weight: 600;", - ) - ) - self._take_over_btn.clicked.connect(self._take_over_beamline) - layout.addWidget(self._take_over_btn) - - self._force_clear_busy_btn = QPushButton("Clear busy flag", self) - self._force_clear_busy_btn.setStyleSheet( - card_style( - PENDING_CARD_BG, - PENDING_CARD_BORDER, - selector="QPushButton", - radius=FLAT_CARD_RADIUS, - extra="padding: 10px; font-weight: 600;", - ) - ) - self._force_clear_busy_btn.clicked.connect(self._force_clear_busy) - layout.addWidget(self._force_clear_busy_btn) - - self._force_maintenance_state_btn = QPushButton("Force to maintenance state", self) - self._force_maintenance_state_btn.setStyleSheet( - card_style( - CHIP_BAD_BG, - BAD_CARD_BORDER, - CHIP_BAD_TEXT, - selector="QPushButton", - radius=FLAT_CARD_RADIUS, - extra="padding: 10px; font-weight: 700;", - ) - ) - self._force_maintenance_state_btn.clicked.connect(self._force_maintenance_state) - layout.addWidget(self._force_maintenance_state_btn) - - self._recovery_unmount_btn = QPushButton("Unmount sample (recovery)", self) - self._recovery_unmount_btn.setStyleSheet( - card_style( - CHIP_BAD_BG, - BAD_CARD_BORDER, - CHIP_BAD_TEXT, - selector="QPushButton", - radius=FLAT_CARD_RADIUS, - extra="padding: 10px; font-weight: 700;", - ) - ) - self._recovery_unmount_btn.clicked.connect(self._recovery_unmount_sample) - layout.addWidget(self._recovery_unmount_btn) - - self._resync_sample_btn = QPushButton("Resync sample from TELL", self) - self._resync_sample_btn.setStyleSheet( - card_style( - INFO_CARD_BG, - INFO_CARD_BORDER, - CHIP_INFO_TEXT, - selector="QPushButton", - radius=FLAT_CARD_RADIUS, - extra="padding: 10px; font-weight: 600;", - ) - ) - self._resync_sample_btn.clicked.connect(self._resync_sample) - layout.addWidget(self._resync_sample_btn) - - layout.addStretch(1) - - self._daq.update.connect(self._set_daq_status) - self._daq.sample_resync_completed.connect(self._set_last_action) - self._refresh_buttons() - - def _prompt_recovery_code(self, action_name: str) -> str | None: - code, ok = QInputDialog.getText( - self, action_name, "Enter recovery confirmation code:", QLineEdit.EchoMode.Password - ) - if not ok: - return None - code = code.strip() - return code or None - - def _sample_appears_mounted(self) -> bool: - try: - return self._last_status is not None and self._last_status.sample is not None - except Exception: - logger.debug("Could not determine whether a sample is mounted", exc_info=True) - return False - - def _beamline_appears_busy(self) -> bool: - try: - return self._last_status is not None and bool(self._last_status.busy) - except Exception: - logger.debug("Could not determine whether the beamline is busy", exc_info=True) - return False - - def _refresh_buttons(self) -> None: - sample_mounted = self._sample_appears_mounted() - beamline_busy = self._beamline_appears_busy() - - self._recovery_unmount_btn.setEnabled(sample_mounted) - self._recovery_unmount_btn.setToolTip( - "" - if sample_mounted - else "Disabled because no mounted sample is visible in current status." - ) - - self._force_clear_busy_btn.setEnabled(beamline_busy) - self._force_clear_busy_btn.setToolTip( - "" if beamline_busy else "Disabled because beamline does not currently appear busy." - ) - - self._resync_sample_btn.setEnabled(True) - self._resync_sample_btn.setToolTip("Force a one-shot sample reconciliation against TELL.") - - def _confirm(self, title: str, msg: str) -> bool: - reply = QMessageBox.warning( - self, - title, - msg, - QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, - QMessageBox.StandardButton.No, - ) - return reply == QMessageBox.StandardButton.Yes - - @Slot(DAQStatusModel) - def _set_daq_status(self, s: DAQStatusModel) -> None: - self._last_status = s - self._refresh_buttons() - - @Slot() - def _take_over_beamline(self) -> None: - if not self._confirm( - "Take over beamline", - "This will forcefully grab the active beamline session.\n\nDo you want to continue?", - ): - return - code = self._prompt_recovery_code("Take over beamline") - if not code: - return - self._last_action.setText("Last action: Taking over beamline session...") - self._daq.take_over_beamline(code) - - @Slot() - def _force_clear_busy(self) -> None: - if not self._confirm( - "Clear busy flag", - "This will clear the beamline busy flag.\nAfter this, the server may still report that it is 'moving' if it is not in a defined state. You may then force the server into maintenance mode to recover.\nDo you want to continue?", - ): - return - code = self._prompt_recovery_code("Clear busy flag") - if not code: - return - self._last_action.setText("Last action: Clearing beamline busy flag...") - self._daq.force_clear_busy(code) - - @Slot() - def _force_maintenance_state(self) -> None: - if self._sample_appears_mounted(): - if not self._confirm( - "Force maintenance mode", - "A sample appears to be mounted.\n\n" - "Recovering the beamline may damage the sample or leave hardware in an unsafe state.\n\n" - "Only continue if you are sure this is the correct recovery action.", - ): - return - else: - if not self._confirm( - "Force maintenance mode", - "This will take over the beamline, clear the busy flag, and set the state to Maintenance.\n\n" - "Do you want to continue?", - ): - return - - code = self._prompt_recovery_code("Force maintenance mode") - if not code: - return - self._last_action.setText("Last action: Recovering beamline to Maintenance...") - self._daq.force_maintenance_state(code) - - @Slot() - def _recovery_unmount_sample(self) -> None: - if not self._confirm( - "Unmount sample (recovery)", - "This will force-take the session and attempt a controlled recovery unmount.\n\n" - "Use this only if normal unmount is not possible.", - ): - return - - code = self._prompt_recovery_code("Unmount sample (recovery)") - if not code: - return - self._last_action.setText("Last action: Performing recovery sample unmount...") - self._daq.recovery_unmount_sample(code) - - @Slot() - def _resync_sample(self) -> None: - self._last_action.setText("Last action: Resyncing sample cache from TELL...") - self._daq.resync_sample() - - @Slot(str) - def _set_last_action(self, message: str) -> None: - self._last_action.setText(f"Last action: {message}") - - -class BeamlineRecoveryDialog(QDialog): - def __init__(self, *, daq: DAQWorker, parent=None): - super().__init__(parent) - self.setWindowTitle("Beamline Recovery") - self.setMinimumSize(560, 420) - - layout = QVBoxLayout(self) - layout.setContentsMargins(12, 12, 12, 12) - layout.setSpacing(8) - - self._panel = RecoveryPanel(daq=daq, parent=self) - layout.addWidget(self._panel, 1) - - buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close, parent=self) - buttons.rejected.connect(self.reject) - buttons.accepted.connect(self.accept) - layout.addWidget(buttons) diff --git a/src/aare/gui/panels/beamline_state_panel.py b/src/aare/gui/panels/beamline_state_panel.py deleted file mode 100644 index 3401efaa..00000000 --- a/src/aare/gui/panels/beamline_state_panel.py +++ /dev/null @@ -1,476 +0,0 @@ -from typing import ClassVar - -from aarecommon.models.models import BeamlineStateEnum, DAQStatusModel -from PySide6.QtCore import QByteArray, QPropertyAnimation, Qt, QTimer, Signal, Slot -from PySide6.QtGui import QCursor, QFont, QFontMetrics -from PySide6.QtWidgets import ( - QFrame, - QGraphicsOpacityEffect, - QHBoxLayout, - QLabel, - QMenu, - QPushButton, - QSizePolicy, - QToolTip, -) - -from aare.gui.styles import FONT_VALUE, THEME_SUNRISE, admin_tip_qss, state_colors - -# Shortcut transitions from the "Available transitions" menu in -# widgets/status_bar.py show_state_menu — these come ON TOP of the one-hop -# routes between states (_GRAPH), e.g. Manual sample exchange -> Sample -# alignment skipping the robot station, and Maintenance which sits outside -# the route graph. Keep in sync until the server exposes transitions. -_TO_SAMPLE_ALIGNMENT = frozenset({BeamlineStateEnum.SampleAlignment}) -MENU_TRANSITIONS: dict[BeamlineStateEnum, frozenset[BeamlineStateEnum]] = { - BeamlineStateEnum.RobotSampleExchange: _TO_SAMPLE_ALIGNMENT, - BeamlineStateEnum.SampleExchange: _TO_SAMPLE_ALIGNMENT, - BeamlineStateEnum.DewarTransfer: _TO_SAMPLE_ALIGNMENT, - BeamlineStateEnum.BeamLocation: _TO_SAMPLE_ALIGNMENT, - BeamlineStateEnum.DataCollection: _TO_SAMPLE_ALIGNMENT, - BeamlineStateEnum.XrayFluorescence: _TO_SAMPLE_ALIGNMENT, - BeamlineStateEnum.XtalSnapshot: _TO_SAMPLE_ALIGNMENT, - BeamlineStateEnum.SampleAlignment: frozenset( - { - BeamlineStateEnum.SampleExchange, - BeamlineStateEnum.DewarTransfer, - BeamlineStateEnum.BeamLocation, - } - ), - BeamlineStateEnum.Maintenance: frozenset({BeamlineStateEnum.SampleExchange}), -} - -# One-hop routes between states (the former map's segments). -_SEGMENTS = [ - (BeamlineStateEnum.DewarTransfer, BeamlineStateEnum.SampleExchange), - (BeamlineStateEnum.SampleExchange, BeamlineStateEnum.RobotSampleExchange), - (BeamlineStateEnum.RobotSampleExchange, BeamlineStateEnum.SampleAlignment), - (BeamlineStateEnum.SampleAlignment, BeamlineStateEnum.BeamLocation), - (BeamlineStateEnum.SampleAlignment, BeamlineStateEnum.BeamstopAlignment), - (BeamlineStateEnum.SampleAlignment, BeamlineStateEnum.FluxMeasurement), - (BeamlineStateEnum.SampleAlignment, BeamlineStateEnum.DataCollection), - (BeamlineStateEnum.BeamLocation, BeamlineStateEnum.BeamstopAlignment), - (BeamlineStateEnum.BeamLocation, BeamlineStateEnum.FluxMeasurement), - (BeamlineStateEnum.BeamstopAlignment, BeamlineStateEnum.FluxMeasurement), - (BeamlineStateEnum.DataCollection, BeamlineStateEnum.XtalSnapshot), - (BeamlineStateEnum.DataCollection, BeamlineStateEnum.XrayFluorescence), -] - - -def _build_graph( - segments: list[tuple[BeamlineStateEnum, BeamlineStateEnum]], -) -> dict[BeamlineStateEnum, set[BeamlineStateEnum]]: - graph: dict[BeamlineStateEnum, set[BeamlineStateEnum]] = {} - for a, b in segments: - graph.setdefault(a, set()).add(b) - graph.setdefault(b, set()).add(a) - return graph - - -_GRAPH = _build_graph(_SEGMENTS) - - -class HoverableButton(QPushButton): - hovered = Signal(object) - unhovered = Signal() - - # Set by the panel right after construction; carried in hover signals. - _beamline_state: BeamlineStateEnum | None = None - - def enterEvent(self, event) -> None: - self.hovered.emit(self._beamline_state) - super().enterEvent(event) - - def leaveEvent(self, event) -> None: - self.unhovered.emit() - super().leaveEvent(event) - - -class BeamlineStatePanel(QFrame): - """Slim horizontal state strip shown directly above the status bar. - - Replaces the former vertical station map: two-line entries in beamline - order, colored by availability (blue/red = active, orange = reachable in - one transition, grey = not reachable). - """ - - sample_exchange = Signal() - sample_alignment = Signal() - dewar_exchange = Signal() - beam_location = Signal() - data_collection = Signal() - xtal_snapshot = Signal() - xray_fluorescence = Signal() - robot_sample_exchange = Signal() - beamstop_alignment = Signal() - flux_measurement = Signal() - - # Physical beamline order. Labels are one line when the bar is wide - # enough and wrap at the last space to two lines when it is not. - _ENTRIES: tuple[tuple[BeamlineStateEnum, str], ...] = ( - (BeamlineStateEnum.Maintenance, "Maintenance mode"), - (BeamlineStateEnum.BeamLocation, "Beam location"), - (BeamlineStateEnum.BeamstopAlignment, "Beamstop alignment"), - (BeamlineStateEnum.FluxMeasurement, "Flux measurement"), - (BeamlineStateEnum.SampleAlignment, "Sample alignment"), - (BeamlineStateEnum.SampleExchange, "Manual sample exchange"), - (BeamlineStateEnum.RobotSampleExchange, "Robot sample exchange"), - (BeamlineStateEnum.DewarTransfer, "Dewar transfer"), - (BeamlineStateEnum.DataCollection, "Data collection"), - (BeamlineStateEnum.XtalSnapshot, "Crystal snapshot"), - (BeamlineStateEnum.XrayFluorescence, "X-ray fluorescence"), - ) - - # Beam-optics diagnostic states are admin (staff) only: greyed for - # everyone else, with a red warning tip instead of the routes hint. - _STAFF_ONLY_STATES: ClassVar[frozenset[BeamlineStateEnum]] = frozenset( - { - BeamlineStateEnum.BeamLocation, - BeamlineStateEnum.BeamstopAlignment, - BeamlineStateEnum.FluxMeasurement, - } - ) - - _TOOLTIPS: ClassVar[dict[BeamlineStateEnum, str]] = { - BeamlineStateEnum.DewarTransfer: "Dewar transfer mode", - BeamlineStateEnum.SampleExchange: "Manual sample exchange mode", - BeamlineStateEnum.RobotSampleExchange: "Robot-assisted sample exchange", - BeamlineStateEnum.SampleAlignment: "Sample centring and alignment mode", - BeamlineStateEnum.BeamLocation: "Beam location mode", - BeamlineStateEnum.BeamstopAlignment: "Beamstop alignment mode", - BeamlineStateEnum.FluxMeasurement: "Flux measurement mode", - BeamlineStateEnum.DataCollection: "Measurement / collection mode", - BeamlineStateEnum.XtalSnapshot: "Crystal snapshot mode", - BeamlineStateEnum.XrayFluorescence: "X-ray fluorescence mode", - } - - def __init__(self, staff: bool = False, parent=None): - super().__init__(parent) - self.setObjectName("beamlineStatePanel") - - # Fail-closed: callers must opt in to the staff-only states. - self._staff = staff - self._current_state: BeamlineStateEnum | None = None - self._hovered_state: BeamlineStateEnum | None = None - self._pending_target_state: BeamlineStateEnum | None = None - self._busy = False - self._breathing_button: HoverableButton | None = None - - # After 3 s of hovering an unavailable state, explain which states - # it can be reached from. - self._hover_hint_timer = QTimer(self) - self._hover_hint_timer.setSingleShot(True) - self._hover_hint_timer.setInterval(3000) - self._hover_hint_timer.timeout.connect(self._show_hover_hint) - - # Per-theme colors (MainWindow._apply_theme calls set_theme). - self._theme = THEME_SUNRISE - self._colors = state_colors(THEME_SUNRISE) - self._separators: list[QLabel] = [] - - layout = QHBoxLayout(self) - layout.setContentsMargins(10, 2, 10, 2) - layout.setSpacing(2) - layout.addStretch(1) - - self._buttons: dict[BeamlineStateEnum, HoverableButton] = {} - self._single_line = True - for index, (state, label) in enumerate(self._ENTRIES): - if index: - separator = QLabel("–", self) - self._style_separator(separator) - self._separators.append(separator) - layout.addWidget(separator) - button = HoverableButton(label, self) - button.setFlat(True) - # Fill the bar height so the hover region is the whole entry, - # not just the text line. - button.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Expanding) - button._beamline_state = state - # Transitions only via right-click -> "Go to "; a plain - # left click must not move the beamline. - button.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) - button.customContextMenuRequested.connect( - lambda pos, s=state, b=button: self._show_state_menu(s, b, pos) - ) - button.clicked.connect(lambda _checked=False, s=state: self._on_left_click(s)) - button.hovered.connect(self._set_hovered_state) - button.unhovered.connect(self._clear_hovered_state) - self._buttons[state] = button - layout.addWidget(button) - - layout.addStretch(1) - self._apply_highlight() - - def minimumSizeHint(self): - # The 13-button strip would otherwise impose a ~2000px minimum on the - # whole main window, so an un-maximized window could never fit the - # screen. Width 0: the strip adapts (two-line labels) and, below that, - # clips — the window stays freely resizable. - hint = super().minimumSizeHint() - hint.setWidth(0) - return hint - - def resizeEvent(self, event) -> None: - super().resizeEvent(event) - self._update_label_mode() - - def _update_label_mode(self) -> None: - # One line while it fits, wrapped at the last space otherwise. - # Measured with bold so the mode does not flap when the active - # state (the only bold entry) changes. - font = QFont(self.font()) - font.setPixelSize(18) - font.setWeight(QFont.Weight.Bold) - fm = QFontMetrics(font) - needed = 20 # layout margins - for index, (_state, label) in enumerate(self._ENTRIES): - if index: - needed += fm.horizontalAdvance("–") + 4 - needed += fm.horizontalAdvance(label) + 20 # padding + frame - single_line = needed <= self.width() - if single_line == self._single_line: - return - self._single_line = single_line - for state, label in self._ENTRIES: - text = label if single_line else "\n".join(label.rsplit(" ", 1)) - self._buttons[state].setText(text) - - def _show_state_menu(self, state: BeamlineStateEnum, button: QPushButton, pos) -> None: - if state not in self._available_targets(): - return - menu = QMenu(button) - go_action = menu.addAction(f"Go to {state.display_name()}") - go_action.triggered.connect(lambda: self._emit_for_state(state)) - menu.exec(button.mapToGlobal(pos)) - - def _on_left_click(self, state: BeamlineStateEnum) -> None: - # Left click never moves the beamline: remind about right-click for - # available states, explain unreachability for the rest. - if state == self._current_state: - return - if state in self._available_targets(): - button = self._buttons[state] - QToolTip.showText( - QCursor.pos(), - f"Right-click to go to {state.display_name()}.", - button, - button.rect(), - ) - else: - self._show_unavailable_hint(state) - - def _available_targets(self) -> frozenset[BeamlineStateEnum]: - current = self._current_state - # Busy greys the whole strip like Moving does: a transition posted - # mid-operation would clobber it (same guard as the status-bar menu). - if self._busy or current is None or current == BeamlineStateEnum.Moving: - return frozenset() - # Reachable in one step: the route graph plus the status-bar - # shortcut transitions. - targets = frozenset(_GRAPH.get(current, set())) | MENU_TRANSITIONS.get(current, frozenset()) - return targets if self._staff else targets - self._STAFF_ONLY_STATES - - def _set_hovered_state(self, state: BeamlineStateEnum | None) -> None: - self._hovered_state = state - self._hover_hint_timer.start() - - @Slot() - def _clear_hovered_state(self) -> None: - self._hovered_state = None - self._hover_hint_timer.stop() - QToolTip.hideText() - - def _show_hover_hint(self) -> None: - state = self._hovered_state - if state is None or state == self._current_state or state in self._available_targets(): - return - self._show_unavailable_hint(state) - - def _show_unavailable_hint(self, state: BeamlineStateEnum) -> None: - if not self._staff and state in self._STAFF_ONLY_STATES: - # Not a routes problem: the state is admin-gated. Red warning - # tip (QSS appended in _apply_highlight), no dialog to close. - button = self._buttons[state] - QToolTip.showText( - QCursor.pos(), - f"{state.display_name()} requires admin mode (staff accounts only).", - button, - button.rect(), - ) - return - sources = set(_GRAPH.get(state, set())) - sources |= {s for s, targets in MENU_TRANSITIONS.items() if state in targets} - sources.discard(state) - if not sources: - return - reachable = ", ".join(sorted(s.display_name() for s in sources)) - button = self._buttons[state] - # Anchoring to the button rect makes Qt drop the tip as soon as the - # mouse leaves the entry, instead of letting it linger. - QToolTip.showText( - QCursor.pos(), - f"You can only go to {state.display_name()} by being in: {reachable}.", - button, - button.rect(), - ) - - def _emit_for_state(self, state: BeamlineStateEnum) -> None: - # Unavailable transitions are not clickable (grey + forbidden cursor). - if state not in self._available_targets(): - return - self._pending_target_state = state - - if state == BeamlineStateEnum.SampleExchange: - self.sample_exchange.emit() - elif state == BeamlineStateEnum.SampleAlignment: - self.sample_alignment.emit() - elif state == BeamlineStateEnum.DewarTransfer: - self.dewar_exchange.emit() - elif state == BeamlineStateEnum.RobotSampleExchange: - self.robot_sample_exchange.emit() - elif state == BeamlineStateEnum.BeamLocation: - self.beam_location.emit() - elif state == BeamlineStateEnum.BeamstopAlignment: - self.beamstop_alignment.emit() - elif state == BeamlineStateEnum.FluxMeasurement: - self.flux_measurement.emit() - elif state == BeamlineStateEnum.DataCollection: - self.data_collection.emit() - elif state == BeamlineStateEnum.XtalSnapshot: - self.xtal_snapshot.emit() - elif state == BeamlineStateEnum.XrayFluorescence: - self.xray_fluorescence.emit() - - def _style_separator(self, separator: QLabel) -> None: - separator.setStyleSheet( - f"color: {self._colors['unavailable']};" - f" background: transparent; border: none; font-size: {FONT_VALUE};" - ) - - def set_theme(self, theme: str) -> None: - """Adopt the theme's state colors (MainWindow._apply_theme calls this - on every switch — the colors are painted in code, so the app QSS - alone cannot restyle them).""" - self._theme = theme - self._colors = state_colors(theme) - for separator in self._separators: - self._style_separator(separator) - self._apply_highlight() - - def _sync_breathing(self, button: HoverableButton | None) -> None: - # The transition target used to sit solid blue while Moving, reading - # as "already there". Breathe it via an opacity effect instead of a - # stylesheet animation: restyling would repolish the button per frame. - if button is self._breathing_button: - return - if self._breathing_button is not None: - # Qt deletes the old effect (and the animation parented to it). - self._breathing_button.setGraphicsEffect(None) # pyright: ignore[reportArgumentType] - self._breathing_button = button - if button is None: - return - effect = QGraphicsOpacityEffect(button) - button.setGraphicsEffect(effect) - animation = QPropertyAnimation(effect, QByteArray(b"opacity"), effect) - animation.setDuration(1600) - animation.setStartValue(1.0) - animation.setKeyValueAt(0.5, 0.35) - animation.setEndValue(1.0) - animation.setLoopCount(-1) - animation.start() - - def _apply_highlight(self) -> None: - available = self._available_targets() - pending_button: HoverableButton | None = None - for state, button in self._buttons.items(): - is_current = state == self._current_state - is_pending = ( - state == self._pending_target_state - and self._current_state == BeamlineStateEnum.Moving - ) - is_available = state in available - if is_pending: - pending_button = button - - # Availability drives the look: active = bold (red for - # Maintenance, blue otherwise), reachable = orange, rest = grey. - # No backgrounds, no rounded corners. - if is_current or is_pending: - color = ( - self._colors["error"] - if state == BeamlineStateEnum.Maintenance - else self._colors["info"] - ) - bold = True - elif is_available: - color = self._colors["available"] - bold = False - else: - color = self._colors["unavailable"] - bold = False - - # Font set in code (not QSS) so _update_label_mode can measure - # the real metrics when deciding one- vs two-line labels. - font = QFont(self.font()) - font.setPixelSize(18) - font.setWeight(QFont.Weight.Bold if bold else QFont.Weight.Normal) - if button.font() != font: - button.setFont(font) - # Guarded updates: this runs on every DAQ tick, and re-applying an - # unchanged stylesheet repolishes the button, which drops the hover - # cursor under a resting mouse until it moves again. - # Hover underline (the app-wide tab/chip affordance) only on - # entries that mean something: the current state and reachable - # targets — not the grey dead ends. - hover_underline = ( - " text-decoration: underline;" if (is_current or is_pending or is_available) else "" - ) - qss = ( - f"QPushButton {{ border: none; background: transparent; color: {color};" - f" padding: 1px 8px; }}" - f" QPushButton:hover {{ color: {color};{hover_underline} }}" - ) - # QToolTip inherits QSS from its widget: red-wash only the - # admin-gated buttons' tips, so the current-state tip (a staff - # user may have parked the beamline here) stays normal. - if not self._staff and state in self._STAFF_ONLY_STATES and not is_current: - qss += " " + admin_tip_qss(self._theme) - if button.styleSheet() != qss: - button.setStyleSheet(qss) - - # Clickability follows availability; unavailable states get the - # forbidden cursor and only the deferred 3 s explanation tooltip. - # The current state is not a click target, but it is not - # forbidden either — plain cursor + a "you are here" tip. - if is_current or is_pending: - cursor = Qt.CursorShape.ArrowCursor - tooltip = f"{state.display_name()}: this is the current state" - elif is_available: - cursor = Qt.CursorShape.PointingHandCursor - tooltip = self._TOOLTIPS.get(state, state.display_name()) - else: - cursor = Qt.CursorShape.ForbiddenCursor - tooltip = "" - if button.cursor().shape() != cursor: - button.setCursor(cursor) - if button.toolTip() != tooltip: - button.setToolTip(tooltip) - - self._sync_breathing(pending_button) - - def set_current_state(self, state: BeamlineStateEnum | None) -> None: - self._current_state = state - if ( - state is not None - and state != BeamlineStateEnum.Moving - and self._pending_target_state == state - ): - self._pending_target_state = None - self._apply_highlight() - - def update_daq_status(self, status: DAQStatusModel) -> None: - self._busy = bool(status.busy) - # set_current_state re-applies the highlight, so a busy flip - # restyles the strip on the same tick even if the state held. - self.set_current_state(status.state) diff --git a/src/aare/gui/panels/data_collection_settings.py b/src/aare/gui/panels/data_collection_settings.py deleted file mode 100644 index 59be7f06..00000000 --- a/src/aare/gui/panels/data_collection_settings.py +++ /dev/null @@ -1,299 +0,0 @@ -from aarecommon.math.diffraction_geometry import DiffractionGeometry -from aarecommon.math.sample_geometry import SampleGeometryModel -from aarecommon.models.models import DAQStatusModel -from PySide6.QtCore import Signal, Slot -from PySide6.QtWidgets import ( - QCheckBox, - QDoubleSpinBox, - QFrame, - QHBoxLayout, - QLabel, - QPushButton, - QSizePolicy, - QStackedWidget, - QTabBar, - QVBoxLayout, - QWidget, -) - -from aare.gui.panels.file_path_panel import FilePathPanel -from aare.gui.panels.fluorescence_data_collection import FluorescenceDataCollectionPanel -from aare.gui.panels.manual_sample_panel import ManualSamplePanel -from aare.gui.panels.monochromator_panel import ( - ENERGY_AT_TARGET_TOL_KEV, - ENERGY_MAX_KEV, - ENERGY_MIN_KEV, - ENERGY_RANGE_TIP, -) -from aare.gui.panels.raster_data_collection import RasterDataCollectionPanel -from aare.gui.panels.rotation_data_collection import RotationDataCollectionPanel -from aare.gui.panels.smart_rotation_panel import SimpleRotationSettingsPanel -from aare.gui.scan_logic.raster_grid_manager import RasterGridManager -from aare.gui.styles import BANNER_TAB_GAP -from aare.gui.widgets.motor_move_group import SpinMoveState -from aare.gui.widgets.title_label import TitleLabel, tighten_column - - -class DataCollectionSettings(QFrame): - cancel = Signal() - # Same convention as the Beamline setup panel: keV in the GUI, eV on emit. - change_energy = Signal(float) - - set_width = 400 - - def __init__( - self, - s: SampleGeometryModel, - raster_mgr: RasterGridManager, - diffraction: DiffractionGeometry, - parent=None, - ): - super().__init__(parent) - self.setObjectName("dataCollectionSettings") - self.setFixedWidth(self.set_width) - self.setFrameShape(QFrame.Shape.StyledPanel) - self.setFrameShadow(QFrame.Shadow.Raised) - - v_layout = QVBoxLayout(self) - self.file_path_panel = FilePathPanel(self) - v_layout.addWidget(self.file_path_panel) - - # Between Dataset path and Exp. Config., collapsible like both; - # main_window aliases this instead of the former bottom dock. - self.manual_sample_panel = ManualSamplePanel(self) - v_layout.addWidget(self.manual_sample_panel) - - # Auto Centering applies to every scan type, so it lives outside the - # experiment tabs, between Manual sample and Exp. Config. The checkbox - # arms an automatic run after each sample mount (see update_daq_status). - self.find_tip = QPushButton("Auto Centering", parent=self) - self.auto_center_after_mount = QCheckBox("apply after mounting", parent=self) - self.auto_center_after_mount.setToolTip( - "Run Auto Centering automatically after each sample mount" - ) - auto_center_row = QWidget(self) - auto_center_layout = QHBoxLayout(auto_center_row) - auto_center_layout.setContentsMargins(0, 0, 0, 0) - auto_center_layout.addWidget(self.find_tip, 1) - auto_center_layout.addWidget(self.auto_center_after_mount) - v_layout.addWidget(auto_center_row) - - # QTabBar + QStackedWidget instead of QTabWidget: the grid button - # must sit BETWEEN the tab bar and the pages, which a QTabWidget - # cannot host. - self._tab_bar = QTabBar(self) - self._stack = QStackedWidget(self) - - self.raster = RasterDataCollectionPanel( - parent=self, raster_mgr=raster_mgr, diffraction=diffraction - ) - self.screening = RotationDataCollectionPanel(parent=self, diffraction=diffraction) - self.simple = SimpleRotationSettingsPanel(parent=self) - self.fluo = FluorescenceDataCollectionPanel(parent=self) - for panel, label in ( - (self.raster, "Raster scan"), - (self.screening, "Rotation"), - (self.simple, "Simple"), - (self.fluo, "XRF"), - ): - self._stack.addWidget(panel) - self._tab_bar.addTab(label) - # XRF hidden from users for now, not removed: index 3 stays valid so - # _on_tab_changed and the panel loops need no change. Unhide when ready. - self._tab_bar.setTabVisible(3, False) - - # Only meaningful for raster scans; hidden on the other tabs - # (_on_tab_changed). - self.bounding_box = QPushButton("Draw a Grid", parent=self) - - # Live readout mirrored from the Beamline setup panel, same reason: - # "what is" and "what to set" must not share one ambiguous row. - # Fed per DAQ tick in update_daq_status. - self.current_energy_label = QLabel("—", parent=self) - current_energy_row = QWidget(self) - current_energy_layout = QHBoxLayout(current_energy_row) - current_energy_layout.setContentsMargins(0, 0, 0, 0) - current_energy_layout.addWidget(QLabel("Current energy / λ", parent=current_energy_row)) - current_energy_layout.addWidget(self.current_energy_label) - current_energy_layout.addStretch() - - # Energy row copied from the Beamline setup panel so users can change - # energy without leaving the experiment configuration. - self.energy_spin = QDoubleSpinBox(parent=self) - self.energy_spin.setDecimals(3) - self.energy_spin.setRange(ENERGY_MIN_KEV, ENERGY_MAX_KEV) - self.energy_spin.setToolTip(ENERGY_RANGE_TIP) - self.energy_spin.setSingleStep(0.1) - self.energy_spin.setValue(12.0) - self.change_energy_button = QPushButton("Change Energy", parent=self) - self.change_energy_button.clicked.connect(self._emit_change_energy) - # MotorMoveGroup semantics for the button-gated spin, same as the - # Beamline setup row: neutral tracks the readback, edit stages - # pending, the click turns moving until arrival. - self._energy_state = SpinMoveState( - self.energy_spin, self.change_energy_button, tol=ENERGY_AT_TARGET_TOL_KEV, parent=self - ) - energy_row = QWidget(self) - energy_layout = QHBoxLayout(energy_row) - energy_layout.setContentsMargins(0, 0, 0, 0) - energy_layout.addWidget(QLabel("Set Energy (keV)", parent=energy_row)) - energy_layout.addWidget(self.energy_spin) - energy_layout.addWidget(self.change_energy_button) - - # Pane frame carries the border QTabWidget::pane used to draw - # (#expConfigPane rule in styles.py). - pane = QFrame(self) - pane.setObjectName("expConfigPane") - pane_layout = QVBoxLayout(pane) - # No bottom padding: the pages' own bottom margins breathe inside the - # border, and the Abort button should hug the pane. - pane_layout.setContentsMargins(6, 6, 6, 0) - pane_layout.addWidget(self.bounding_box) - pane_layout.addWidget(current_energy_row) - pane_layout.addWidget(energy_row) - pane_layout.addWidget(self._stack) - - # Own container: TitleLabel collapse hides its siblings, so without it - # "Exp. Config." would also swallow the dataset path and abort button. - exp_config = QWidget(self) - exp_config_layout = QVBoxLayout(exp_config) - exp_config_layout.setContentsMargins(0, 0, 0, 0) - exp_config_layout.setSpacing(0) # tab bar flush on the pane, like QTabWidget - exp_config_layout.addWidget( - TitleLabel( - "Experiment configuration", exp_config, collapsible=True, default_collapsed=False - ) - ) - # Explicit spacer, not layout spacing: the tab bar must keep sitting - # flush on the pane below, only the banner gets breathing room. - exp_config_layout.addSpacing(BANNER_TAB_GAP) - exp_config_layout.addWidget(self._tab_bar) - exp_config_layout.addWidget(pane) - v_layout.addWidget(exp_config) - - # Abort lives inside each tab now, under that tab's action buttons; - # all four feed the same cancel signal. - for panel in (self.raster, self.screening, self.simple, self.fluo): - panel.abort_button.clicked.connect(self.cancel_button_clicked) - v_layout.addStretch() - tighten_column(v_layout) - # Abort hugs the pane: undo the uniform bottom margin tighten_column - # just gave the Exp. Config. group. - m = exp_config_layout.contentsMargins() - exp_config_layout.setContentsMargins(m.left(), m.top(), m.right(), 0) - - raster_mgr.update_filename(self.file_path_panel.filename) - self.screening.update_filename(self.file_path_panel.filename) - self.simple.update_filename(self.file_path_panel.filename) - - self.file_path_panel.set_scan_kind("raster") - self.file_path_panel.path_updated.connect(raster_mgr.update_filename) - self.file_path_panel.path_updated.connect(self.screening.update_filename) - self.file_path_panel.path_updated.connect(self.simple.update_filename) - self._sample_id = None - # False until the first DAQ status: a sample already mounted at GUI - # startup must not trigger an auto-centering (hardware would move - # uninvited on every restart). - self._status_seen = False - # Armed on mount, fired on the first idle status tick (see _track_sample). - self._center_after_mount_pending = False - self._automation_running = False - - self._tab_bar.currentChanged.connect(self._stack.setCurrentIndex) - self._tab_bar.currentChanged.connect(self._on_tab_changed) - self._tab_bar.currentChanged.connect(self._sync_stack_height) - self._sync_stack_height(self._tab_bar.currentIndex()) - - @Slot(int) - def _sync_stack_height(self, idx: int): - # QStackedWidget's sizeHint is its TALLEST page, which left a dead gap - # above the Abort button on shorter tabs. Ignored vertical policy on - # hidden pages makes the stack track only the current page's height. - for i in range(self._stack.count()): - page = self._stack.widget(i) - vertical = QSizePolicy.Policy.Preferred if i == idx else QSizePolicy.Policy.Ignored - page.setSizePolicy(QSizePolicy.Policy.Preferred, vertical) - self._stack.adjustSize() - - @Slot() - def _emit_change_energy(self): - self.change_energy.emit(float(self.energy_spin.value()) * 1000.0) - - @Slot() - def switch_to_raster(self): - self._tab_bar.setCurrentIndex(0) - - @Slot() - def cancel_button_clicked(self): - self.cancel.emit() - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - energy = s.diffraction.energy_keV - # 0.0 is the server's detector-unavailable fallback, and the - # wavelength property divides by it — guard before touching it. - if not energy: - text = "— / —" - else: - text = f"{energy:.3f} keV / {s.diffraction.wavelength_angstrom:.4f} Å" - # 0.0 stays out: syncing the fallback would clamp the spin to min - self._energy_state.update_actual(energy) - # Guarded: runs per DAQ tick (2 Hz), skip the repaint when unchanged. - if self.current_energy_label.text() != text: - self.current_energy_label.setText(text) - - self.raster.update_daq_status(s) - self.screening.update_daq_status(s) - self.simple.update_daq_status(s) - self._track_sample(None if s.sample is None else s.sample.db_id, s.busy) - - def _track_sample(self, db_id: int | None, busy: bool = False): - # Separate from update_daq_status so tests can drive mount detection - # without building a full DAQStatusModel. - if db_id is None: - # Forget on unmount so remounting the same sample counts as a - # fresh mount below. - self._sample_id = None - self._center_after_mount_pending = False - elif db_id != self._sample_id: - self._sample_id = db_id - self._tab_bar.setCurrentIndex(0) - self._center_after_mount_pending = ( - self._status_seen - and self.auto_center_after_mount.isChecked() - and not self._automation_running - ) - self._status_seen = True - # The server publishes the new sample while /sample/mount still holds - # the hw lock, and /alc/center_loop takes that lock non-blocking, so a - # click on the id change alone was rejected as busy (a quiet error the - # GUI swallows). Wait for the first idle tick instead: same as the - # user waiting a bit and clicking. - if self._center_after_mount_pending and not busy: - self._center_after_mount_pending = False - # Reuse the button wiring (clicked -> daq.center_loop in - # main_window) instead of a second signal path. - self.find_tip.click() - - @Slot(bool) - def set_automation_running(self, running: bool): - # Queue automation mounts and centers each sample itself and frees the - # hw lock between /scan/auto calls; a GUI centering in that gap would - # steal the lock from the next scan and stop the queue. - # ponytail: Pause drops the flag while the current scan may still be - # in its mount phase -> at most one extra centering on that sample. - # Track in-flight /scan/auto instead if that ever matters. - self._automation_running = running - if running: - self._center_after_mount_pending = False - - @Slot(int) - def _on_tab_changed(self, idx: int): - self.bounding_box.setVisible(idx == 0) - # 0: Raster, 1: Rotation (incl. screening), 2: Simple (rotation wrapper), 3: XRF (ignore) - kind = "rotation" - if idx == 0: - kind = "raster" - elif idx == 1 or idx == 2: - kind = "rotation" - self.file_path_panel.set_scan_kind(kind) diff --git a/src/aare/gui/panels/developer_help_dialog.py b/src/aare/gui/panels/developer_help_dialog.py deleted file mode 100644 index 734f46e8..00000000 --- a/src/aare/gui/panels/developer_help_dialog.py +++ /dev/null @@ -1,659 +0,0 @@ -from __future__ import annotations - -import json -import logging -import time - -from aarecommon.config.logger import attach_to_logger, find_existing_formatter, setup_logger -from aarecommon.errors.codes import error_code_help -from aarecommon.models.models import OpenGuiSessionInfo -from PySide6.QtCore import Qt, QUrl, Slot -from PySide6.QtGui import QDesktopServices, QGuiApplication -from PySide6.QtWidgets import ( - QCheckBox, - QDialog, - QDialogButtonBox, - QFormLayout, - QFrame, - QHBoxLayout, - QLabel, - QLineEdit, - QMessageBox, - QPushButton, - QSpinBox, - QTableWidget, - QTableWidgetItem, - QTabWidget, - QTextEdit, - QVBoxLayout, - QWidget, -) - -from aare.gui.constants import LOGGER_NAME -from aare.gui.log import QtLogEmitter, QtLogHandler -from aare.gui.styles import ( - FLAT_CARD_RADIUS, - PANEL_BG_FAINT, - PANEL_BG_SOFT, - PANEL_BORDER, - PANEL_BORDER_DARK, - PANEL_BORDER_LIGHT, - WHITE, - card_style, -) -from aare.gui.threads.daq_worker import DAQWorker - -logger = setup_logger(LOGGER_NAME) - - -class DeveloperHelpDialog(QDialog): - def __init__(self, *, daq: DAQWorker, is_staff: bool, parent=None): - super().__init__(parent) - self._daq = daq - self._is_staff = bool(is_staff) - - self._codes: dict[str, str] = {} - self._last_payload: dict = {} - self._freeze_payload: bool = False - self._always_highlight_last_error: bool = True - self._gui_sessions: list[OpenGuiSessionInfo] = [] - - self.setWindowTitle("Developer / Help") - self.setMinimumSize(860, 560) - - root = QVBoxLayout(self) - root.setContentsMargins(12, 12, 12, 12) - root.setSpacing(8) - - # Compact banner (staff only) - self._banner = QLabel(self) - self._banner.setVisible(self._is_staff) - self._banner.setWordWrap(True) - self._banner.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) - # Square cards throughout this dialog: the rounded corner cut-outs - # render black on the container's non-composited X11. - self._banner.setStyleSheet( - card_style( - PANEL_BG_SOFT, - PANEL_BORDER, - selector="QLabel", - radius=FLAT_CARD_RADIUS, - extra="padding: 6px 8px;", - ) - ) - root.addWidget(self._banner) - - # Top controls - top = QHBoxLayout() - top.setSpacing(8) - root.addLayout(top) - - top.addWidget(QLabel("Filter:", self)) - - self._filter = QLineEdit(self) - self._filter.setPlaceholderText("Type to filter (matches name, value, or help)…") - self._filter.setClearButtonEnabled(True) - self._filter.setMinimumHeight(28) - self._filter.setStyleSheet( - "QLineEdit {" - f" background: {WHITE};" - f" border: 1px solid {PANEL_BORDER_DARK};" - " padding: 4px 8px;" - "}" - ) - self._filter.textChanged.connect(self._apply_filter) - top.addWidget(self._filter, 1) - - self._refresh_btn = QPushButton("Refresh", self) - self._refresh_btn.clicked.connect(self.refresh) - top.addWidget(self._refresh_btn) - - self._freeze_cb = QCheckBox("Freeze payload", self) - self._freeze_cb.setVisible(self._is_staff) - self._freeze_cb.toggled.connect(self._set_freeze_payload) - top.addWidget(self._freeze_cb) - - self._highlight_cb = QCheckBox("Always highlight last error code", self) - self._highlight_cb.setVisible(self._is_staff) - self._highlight_cb.setChecked(True) - self._highlight_cb.toggled.connect(self._set_always_highlight) - top.addWidget(self._highlight_cb) - - self._copy_selected_btn = QPushButton("Copy code", self) - self._copy_selected_btn.clicked.connect(self._copy_selected_code) - top.addWidget(self._copy_selected_btn) - - self._copy_all_btn = QPushButton("Copy all (filtered)", self) - self._copy_all_btn.clicked.connect(self._copy_all_filtered) - top.addWidget(self._copy_all_btn) - - self._copy_payload_btn = QPushButton("Copy payload", self) - self._copy_payload_btn.setVisible(self._is_staff) - self._copy_payload_btn.clicked.connect(self._copy_payload) - top.addWidget(self._copy_payload_btn) - - self._open_gui_log_btn = QPushButton("Open GUI log", self) - self._open_gui_log_btn.setVisible(self._is_staff) - self._open_gui_log_btn.clicked.connect(lambda: self._open_log_file_for_logger("aareGUI")) - top.addWidget(self._open_gui_log_btn) - - self._open_daq_log_btn = QPushButton("Open DAQ log", self) - self._open_daq_log_btn.setVisible(self._is_staff) - self._open_daq_log_btn.clicked.connect(lambda: self._open_log_file_for_logger("aareDAQ")) - top.addWidget(self._open_daq_log_btn) - - self._tabs = QTabWidget(self) - root.addWidget(self._tabs, 1) - - self._codes_table = QTableWidget(self) - self._codes_table.setColumnCount(1) - self._codes_table.setHorizontalHeaderLabels(["Name"]) - self._codes_table.setSortingEnabled(True) - self._codes_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers) - self._codes_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows) - self._codes_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection) - self._codes_table.itemSelectionChanged.connect(self._update_code_details) - self._codes_table.horizontalHeader().setStretchLastSection(True) - - self._details_frame = QFrame(self) - self._details_frame.setFrameShape(QFrame.Shape.StyledPanel) - self._details_frame.setStyleSheet( - card_style(PANEL_BG_FAINT, PANEL_BORDER, radius=FLAT_CARD_RADIUS) - ) - - details_layout = QVBoxLayout(self._details_frame) - details_layout.setContentsMargins(10, 10, 10, 10) - details_layout.setSpacing(8) - - form = QFormLayout() - form.setLabelAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) - details_layout.addLayout(form) - - self._detail_name = QLabel("-", self) - self._detail_name.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) - form.addRow("Name:", self._detail_name) - - value_row = QHBoxLayout() - value_row.setSpacing(8) - self._detail_value = QLabel("-", self) - self._detail_value.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) - self._copy_value_btn = QPushButton("Copy value", self) - self._copy_value_btn.clicked.connect(self._copy_selected_value) - value_row.addWidget(self._detail_value, 1) - value_row.addWidget(self._copy_value_btn, 0) - value_row_widget = QWidget(self) - value_row_widget.setLayout(value_row) - form.addRow("Value:", value_row_widget) - - self._detail_help = QLabel("-", self) - self._detail_help.setWordWrap(True) - self._detail_help.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) - self._detail_help.setStyleSheet( - card_style( - WHITE, - PANEL_BORDER_LIGHT, - selector="QLabel", - radius=FLAT_CARD_RADIUS, - extra="padding: 8px;", - ) - ) - details_layout.addWidget(QLabel("Help:", self)) - details_layout.addWidget(self._detail_help, 1) - - codes_container = QWidget(self) - codes_layout = QVBoxLayout(codes_container) - codes_layout.setContentsMargins(0, 0, 0, 0) - codes_layout.setSpacing(8) - codes_layout.addWidget(self._codes_table, 1) - codes_layout.addWidget(self._details_frame, 0) - - self._tabs.addTab(codes_container, "Error codes") - - self._payload_summary = QLabel(self) - self._payload_summary.setVisible(self._is_staff) - self._payload_summary.setWordWrap(True) - self._payload_summary.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) - - self._payload_text = QTextEdit(self) - self._payload_text.setReadOnly(True) - self._payload_text.setLineWrapMode(QTextEdit.LineWrapMode.NoWrap) - - if self._is_staff: - payload_container = QWidget(self) - payload_layout = QVBoxLayout(payload_container) - payload_layout.setContentsMargins(0, 0, 0, 0) - payload_layout.addWidget(self._payload_summary, 0) - payload_layout.addWidget(self._payload_text, 1) - self._tabs.addTab(payload_container, "Last error payload") - else: - self._payload_text.setPlainText("Hidden (staff only).") - - self._payloads_text = QTextEdit(self) - self._payloads_text.setReadOnly(True) - self._payloads_text.setLineWrapMode(QTextEdit.LineWrapMode.NoWrap) - if self._is_staff: - payloads_container = QWidget(self) - payloads_layout = QVBoxLayout(payloads_container) - payloads_layout.setContentsMargins(0, 0, 0, 0) - payloads_layout.addWidget(self._payloads_text, 1) - self._tabs.addTab(payloads_container, "Recent payloads") - - self._tracebacks_text = QTextEdit(self) - self._tracebacks_text.setReadOnly(True) - self._tracebacks_text.setLineWrapMode(QTextEdit.LineWrapMode.NoWrap) - self._tracebacks_text.setPlainText("Tracebacks will appear here (last 10).") - - if self._is_staff: - tb_container = QWidget(self) - tb_layout = QVBoxLayout(tb_container) - tb_layout.setContentsMargins(0, 0, 0, 0) - tb_layout.addWidget(self._tracebacks_text, 1) - self._tabs.addTab(tb_container, "Tracebacks") - - self._error_log_text = QTextEdit(self) - self._error_log_text.setReadOnly(True) - self._error_log_text.setLineWrapMode(QTextEdit.LineWrapMode.NoWrap) - if self._is_staff: - log_container = QWidget(self) - log_layout = QVBoxLayout(log_container) - log_layout.setContentsMargins(0, 0, 0, 0) - log_layout.addWidget(self._error_log_text, 1) - self._tabs.addTab(log_container, "Error log") - - if self._is_staff: - self._gui_sessions_table = QTableWidget(self) - self._gui_sessions_table.setColumnCount(8) - self._gui_sessions_table.setHorizontalHeaderLabels( - [ - "Session", - "User", - "Staff", - "Baton", - "Last seen", - "Last interaction", - "Close requested", - "Requested by", - ] - ) - self._gui_sessions_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers) - self._gui_sessions_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows) - self._gui_sessions_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection) - self._gui_sessions_table.setSortingEnabled(True) - self._gui_sessions_table.horizontalHeader().setStretchLastSection(True) - - self._gui_refresh_btn = QPushButton("Refresh GUIs", self) - self._gui_refresh_btn.clicked.connect(self._daq.load_gui_sessions) - - self._gui_close_grace_spin = QSpinBox(self) - self._gui_close_grace_spin.setRange(5, 3600) - self._gui_close_grace_spin.setValue(60) - self._gui_close_grace_spin.setSuffix(" s") - - self._gui_request_close_btn = QPushButton("Request Close", self) - self._gui_request_close_btn.clicked.connect(self._request_close_selected_gui) - - self._gui_force_remove_btn = QPushButton("Force Remove", self) - self._gui_force_remove_btn.clicked.connect(self._force_remove_selected_gui) - - gui_controls = QHBoxLayout() - gui_controls.addWidget(self._gui_refresh_btn) - gui_controls.addWidget(QLabel("Grace:", self)) - gui_controls.addWidget(self._gui_close_grace_spin) - gui_controls.addWidget(self._gui_request_close_btn) - gui_controls.addWidget(self._gui_force_remove_btn) - gui_controls.addStretch(1) - - gui_container = QWidget(self) - gui_layout = QVBoxLayout(gui_container) - gui_layout.setContentsMargins(0, 0, 0, 0) - gui_layout.setSpacing(8) - gui_layout.addLayout(gui_controls) - gui_layout.addWidget(self._gui_sessions_table, 1) - - self._tabs.addTab(gui_container, "Active GUIs") - - buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close, parent=self) - buttons.rejected.connect(self.reject) - buttons.accepted.connect(self.accept) - root.addWidget(buttons) - - self._daq.error_codes_loaded.connect(self.set_error_codes) - self._daq.last_error_payload_changed.connect(self.set_last_error_payload) - self._daq.last_error_payloads_changed.connect(self.set_last_error_payloads) - if self._is_staff: - self._daq.gui_sessions_loaded.connect(self._set_gui_sessions) - - if self._is_staff: - self._qt_log_emitter = QtLogEmitter() - self._qt_log_emitter.message.connect(self._append_error_log_line) - - self._qt_log_handler = QtLogHandler(self._qt_log_emitter) - self._qt_log_handler.setLevel(logging.ERROR) - self._qt_log_handler.setFormatter(find_existing_formatter()) - - attach_to_logger("aareGUI", self._qt_log_handler) - attach_to_logger("aareDAQ", self._qt_log_handler) - - self._update_banner() - self._update_code_details() - - def _open_log_file_for_logger(self, logger_name: str) -> None: - """ - Opens the first FileHandler path attached to the given logger name. - """ - log = logging.getLogger(logger_name) - paths: list[str] = [] - for h in getattr(log, "handlers", []) or []: - p = getattr(h, "baseFilename", None) - if p and isinstance(p, str): - paths.append(p) - - if not paths: - self._banner.setText(f"No file handler found for logger '{logger_name}'.") - return - - QDesktopServices.openUrl(QUrl.fromLocalFile(paths[0])) - - @Slot(bool) - def _set_freeze_payload(self, enabled: bool) -> None: - self._freeze_payload = bool(enabled) - - @Slot(bool) - def _set_always_highlight(self, enabled: bool) -> None: - self._always_highlight_last_error = bool(enabled) - - @Slot() - def refresh(self) -> None: - self._daq.get_error_codes() - self.set_last_error_payload(self._daq.get_last_error_payload()) - if self._is_staff: - self.set_last_error_payloads(self._daq.get_last_error_payloads()) - self._daq.load_gui_sessions() - - @Slot(dict) - def set_error_codes(self, codes: dict) -> None: - self._codes = {str(k): str(v) for k, v in (codes or {}).items()} - self._apply_filter() - - @Slot(dict) - def set_last_error_payload(self, payload: dict) -> None: - if not self._is_staff: - return - if self._freeze_payload: - return - - self._last_payload = payload or {} - pretty = json.dumps(self._last_payload, indent=2, sort_keys=True, default=str) - self._payload_text.setPlainText(pretty) - - code, msg = self._extract_code_message() - url = str((self._last_payload or {}).get("url") or "") - status = (self._last_payload or {}).get("http_status") - self._payload_summary.setText( - f"URL: {url}\nHTTP: {status}\nCode: {code or '-'}\nMessage: {msg or '-'}" - ) - - self._update_banner() - self._select_code_from_last_error() - - @Slot(list) - def set_last_error_payloads(self, payloads: list) -> None: - if not self._is_staff: - return - blocks: list[str] = [] - for i, p in enumerate(payloads[-10:], start=max(1, len(payloads) - 9)): - try: - pretty = json.dumps(p or {}, indent=2, sort_keys=True, default=str) - except Exception: - logger.debug("Could not pretty-print the error payload", exc_info=True) - pretty = str(p) - blocks.append(f"#{i}\n{pretty}") - self._payloads_text.setPlainText("\n\n".join(blocks) if blocks else "(none captured yet)") - - @Slot(str) - def _append_error_log_line(self, line: str) -> None: - if not self._is_staff: - return - self._error_log_text.append(line) - - def _code_name_for_value(self, value: str) -> str | None: - for k, v in self._codes.items(): - if v == value: - return k - return None - - def _extract_code_message(self) -> tuple[str | None, str | None]: - body = (self._last_payload or {}).get("body_json") - if isinstance(body, dict): - code = body.get("code") - msg = body.get("message") - return (str(code) if code is not None else None, str(msg) if msg is not None else None) - return (None, None) - - def _update_banner(self) -> None: - if not self._is_staff: - return - - code, msg = self._extract_code_message() - if code or msg: - parts = [] - if code: - parts.append(f"Last error: {code}") - if msg: - parts.append(msg) - self._banner.setText(" — ".join(parts)) - else: - self._banner.setText("Last error: (none captured yet)") - - def _code_name_for_value(self, value: str) -> str | None: - for name, v in (self._codes or {}).items(): - if str(v) == str(value): - return str(name) - return None - - def _select_code_by_name(self, name: str) -> None: - if not name: - return - for row in range(self._codes_table.rowCount()): - item = self._codes_table.item(row, 0) - if item and item.text() == name: - self._codes_table.setCurrentCell(row, 0) - self._codes_table.scrollToItem(item) - return - - def _select_code_from_last_error(self) -> None: - if not self._codes: - return - code_value, _ = self._extract_code_message() - if not code_value: - return - name = self._code_name_for_value(code_value) - if name: - self._select_code_by_name(name) - - @Slot() - def _apply_filter(self) -> None: - term = (self._filter.text() or "").strip().lower() - - items = sorted(self._codes.items(), key=lambda kv: kv[0]) - - if term: - - def _match(name: str, value: str) -> bool: - h = error_code_help(value) or "" - return term in f"{name}\n{value}\n{h}".lower() - - items = [(k, v) for (k, v) in items if _match(k, v)] - - self._codes_table.setRowCount(len(items)) - for row, (k, v) in enumerate(items): - item = QTableWidgetItem(k) - item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsEditable) - self._codes_table.setItem(row, 0, item) - - self._codes_table.resizeColumnsToContents() - # Keep selection sensible (don’t resize columns here; avoids jitter) - if self._codes_table.rowCount() > 0 and self._codes_table.currentRow() < 0: - self._codes_table.setCurrentCell(0, 0) - - self._update_code_details() - - # If enabled, re-try selection after the table content changes - if self._is_staff and self._always_highlight_last_error and not self._freeze_payload: - self._select_code_from_last_error() - - def _selected_code(self) -> tuple[str | None, str | None]: - row = self._codes_table.currentRow() - if row < 0: - return (None, None) - name_item = self._codes_table.item(row, 0) - if not name_item: - return (None, None) - name = name_item.text() - value = self._codes.get(name) - return (name, value) - - @Slot() - def _update_code_details(self) -> None: - name, value = self._selected_code() - if not name or not value: - self._detail_name.setText("-") - self._detail_value.setText("-") - self._detail_help.setText("Select an error code to see details.") - self._copy_value_btn.setEnabled(False) - return - - self._detail_name.setText(name) - self._detail_value.setText(value) - self._detail_help.setText(error_code_help(value) or "(no help text defined yet)") - self._copy_value_btn.setEnabled(True) - - @Slot() - def _copy_selected_code(self) -> None: - name, value = self._selected_code() - if not name or not value: - QGuiApplication.clipboard().setText("") - return - QGuiApplication.clipboard().setText(f"{name}={value}") - - @Slot() - def _copy_selected_value(self) -> None: - _, value = self._selected_code() - QGuiApplication.clipboard().setText(value or "") - - @Slot() - def _copy_all_filtered(self) -> None: - rows = self._codes_table.rowCount() - out = {} - for r in range(rows): - name = self._codes_table.item(r, 0).text() - out[name] = self._codes.get(name, "") - QGuiApplication.clipboard().setText(json.dumps(out, indent=2, sort_keys=True)) - - @Slot() - def _copy_payload(self) -> None: - if not self._is_staff: - return - QGuiApplication.clipboard().setText(self._payload_text.toPlainText()) - - def _format_age(self, ts: float | None) -> str: - if ts is None: - return "-" - delta = max(0, int(time.time() - float(ts))) - if delta < 60: - return f"{delta}s ago" - if delta < 3600: - return f"{delta // 60}m {delta % 60}s ago" - return f"{delta // 3600}h {(delta % 3600) // 60}m ago" - - @Slot(list) - def _set_gui_sessions(self, sessions: list) -> None: - if not self._is_staff: - return - - self._gui_sessions = [ - s if isinstance(s, OpenGuiSessionInfo) else OpenGuiSessionInfo.model_validate(s) - for s in sessions - ] - self._gui_sessions_table.setSortingEnabled(False) - self._gui_sessions_table.setRowCount(len(self._gui_sessions)) - - for row, session in enumerate(self._gui_sessions): - values = [ - str(session.session), - session.username, - "Yes" if session.staff else "No", - "Yes" if getattr(session, "holds_baton", False) else "No", - self._format_age(session.last_seen_ts), - self._format_age(session.last_interaction_ts), - "Yes" if session.close_requested else "No", - session.close_requested_by or "-", - ] - for col, value in enumerate(values): - item = QTableWidgetItem(value) - item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsEditable) - if col == 0: - item.setData(Qt.ItemDataRole.UserRole, session.session) - self._gui_sessions_table.setItem(row, col, item) - - self._gui_sessions_table.resizeColumnsToContents() - self._gui_sessions_table.setSortingEnabled(True) - - def _selected_gui_session_id(self) -> int | None: - if not self._is_staff: - return None - row = self._gui_sessions_table.currentRow() - if row < 0: - return None - item = self._gui_sessions_table.item(row, 0) - if item is None: - return None - value = item.data(Qt.ItemDataRole.UserRole) - try: - return int(value) - except Exception: - logger.debug("Could not read the selected GUI session id", exc_info=True) - return None - - @Slot() - def _request_close_selected_gui(self) -> None: - session_id = self._selected_gui_session_id() - if session_id is None: - QMessageBox.information(self, "Active GUIs", "Please select a GUI session first.") - return - - grace_seconds = int(self._gui_close_grace_spin.value()) - answer = QMessageBox.question( - self, - "Request GUI Close", - f"Request GUI session {session_id} to close with a {grace_seconds}s grace period?", - ) - if answer != QMessageBox.StandardButton.Yes: - return - - self._daq.request_gui_close(session_id, grace_seconds) - self._daq.load_gui_sessions() - - @Slot() - def _force_remove_selected_gui(self) -> None: - session_id = self._selected_gui_session_id() - if session_id is None: - QMessageBox.information(self, "Active GUIs", "Please select a GUI session first.") - return - - answer = QMessageBox.warning( - self, - "Force Remove GUI Session", - ( - f"Force remove GUI session {session_id} from Redis?\n\n" - "This is intended for stale/crashed GUIs and may also clear the active baton/session if it belongs " - "to that session." - ), - QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, - QMessageBox.StandardButton.No, - ) - if answer != QMessageBox.StandardButton.Yes: - return - - self._daq.force_remove_gui_session(session_id) - self._daq.load_gui_sessions() diff --git a/src/aare/gui/panels/face_detection_panel.py b/src/aare/gui/panels/face_detection_panel.py deleted file mode 100644 index fa8cf5d8..00000000 --- a/src/aare/gui/panels/face_detection_panel.py +++ /dev/null @@ -1,150 +0,0 @@ -import numpy as np -from aarecommon.config.logger import setup_logger -from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas -from matplotlib.figure import Figure -from PySide6.QtCore import Signal -from PySide6.QtWidgets import QGridLayout, QLabel, QPushButton, QVBoxLayout, QWidget - -from aare.gui.constants import LOGGER_NAME -from aare.gui.styles import GO_TEXT -from aare.gui.widgets.number_line_edit import NumberLineEdit -from aare.gui.widgets.title_label import TitleLabel - -logger = setup_logger(LOGGER_NAME) - - -class FaceDetectionPanel(QWidget): - face_detection = Signal(int, int) - - def __init__(self, parent=None): - super().__init__(parent) - self.steps = 14 - self.step_size = 15 - self._manual_run_requested = False - - def _set_steps(val: float): - self.steps = int(val) - - def _set_step_size(val: float): - self.step_size = int(val) - - self.fig = Figure(figsize=(5, 4)) - self.fig.subplots_adjust(left=0.18, right=0.97, bottom=0.10, top=0.95, hspace=0.45) - self.canvas = FigureCanvas(self.fig) - self.ax1 = self.fig.add_subplot(2, 1, 1) - self.ax2 = self.fig.add_subplot(2, 1, 2) - - self._top_layout = QGridLayout() - self._top_layout.addWidget(TitleLabel("TELL sample changer", self), 0, 0, 1, 3) - self.status_lbl = QLabel("Idle") - self._top_layout.addWidget(self.status_lbl, 0, 2) - - self._top_layout.addWidget(QLabel("step size", parent=self), 1, 0) - self.step_size_enter = NumberLineEdit(0, 50, 15, decimals=4, parent=self) - self._top_layout.addWidget(self.step_size_enter, 1, 1, 1, 3) - self.step_size_enter.newValue.connect(_set_step_size) - self._top_layout.addWidget(QLabel("°", parent=self), 1, 4) - - self._top_layout.addWidget(QLabel("number of steps", parent=self), 2, 0) - self.steps_enter = NumberLineEdit(0, 50, 14, decimals=4, parent=self) - self._top_layout.addWidget(self.steps_enter, 2, 1, 1, 3) - self._top_layout.addWidget(QLabel("", parent=self), 2, 4) - self.steps_enter.newValue.connect(_set_steps) - - self.face_detection_button = QPushButton("Face Detection") - self.face_detection_button.setStyleSheet(f"color: {GO_TEXT};") - self.face_detection_button.clicked.connect(self.run_and_refresh) - self._top_layout.addWidget(self.face_detection_button, 3, 0, 1, 3) - - self._top_layout.setColumnStretch(0, 1) - self._top_layout.setColumnStretch(1, 0) - - self._layout = QVBoxLayout(self) - self._layout.addLayout(self._top_layout) - self._layout.addWidget(self.canvas) - self.setLayout(self._layout) - - def run_and_refresh(self): - try: - self._manual_run_requested = True - self.status_lbl.setText("Starting...") - self.face_detection_button.setEnabled(False) - self.face_detection.emit(int(self.steps), int(self.step_size)) - except Exception as e: - logger.warning("Face detection run failed", exc_info=True) - self._manual_run_requested = False - self.status_lbl.setText(f"Error: {e}") - self.face_detection_button.setEnabled(True) - - def update_plot(self, data): - samples = data.get("samples", []) or [] - running = bool(data.get("running", False)) - angle = data.get("current_angle_deg") - data.get("status", "") - - if running: - if self._manual_run_requested: - self.status_lbl.setText( - f"Running... angle {angle}" if angle is not None else "Running..." - ) - else: - self.status_lbl.setText( - f"Automation running... angle {angle}" - if angle is not None - else "Automation running..." - ) - else: - if self._manual_run_requested: - self.status_lbl.setText("Done") - self.face_detection_button.setEnabled(True) - self._manual_run_requested = False - elif samples: - self.status_lbl.setText("Showing latest result") - else: - self.status_lbl.setText("Idle") - - self.ax1.clear() - self.ax2.clear() - - if not samples: - self.ax1.text(0.5, 0.5, "No data", ha="center", va="center") - self.ax2.text(0.5, 0.5, "No data", ha="center", va="center") - self.canvas.draw_idle() - return - - angles = np.array([s["angle_deg"] for s in samples], dtype=float) - heights = np.array([s["height"] for s in samples], dtype=float) - areas = np.array([s["area"] for s in samples], dtype=float) - - self.ax1.scatter(angles, heights, s=16, c="tab:blue", label="Height") - self.ax2.scatter(angles, areas, s=16, c="tab:green", label="Area") - - ang_grid = np.linspace(angles.min(), angles.max(), 400) - - hf = data.get("height_fit", {}) or {} - if {"A", "B", "phi_rad", "C"} <= hf.keys(): - A, B, phi, C = hf["A"], hf["B"], hf["phi_rad"], hf["C"] - height_fit = A + B * np.cos(C * np.deg2rad(ang_grid) - phi) - self.ax1.plot(ang_grid, height_fit, color="tab:orange", label="Height fit") - if "best_angle_deg" in hf: - self.ax1.axvline(hf["best_angle_deg"], color="tab:orange", ls="--", alpha=0.6) - - af = data.get("area_fit", {}) or {} - if {"A", "B", "phi_rad", "C"} <= af.keys(): - A2, B2, phi2, C2 = af["A"], af["B"], af["phi_rad"], af["C"] - area_fit = A2 + B2 * np.cos(C2 * np.deg2rad(ang_grid) - phi2) - self.ax2.plot(ang_grid, area_fit, color="tab:red", label="Area fit") - if "best_angle_deg" in af: - self.ax2.axvline(af["best_angle_deg"], color="tab:red", ls="--", alpha=0.6) - - self.ax1.set_xlabel("Angle (deg)") - self.ax1.set_ylabel("Height") - self.ax1.legend() - self.ax1.grid(True, alpha=0.3) - - self.ax2.set_xlabel("Angle (deg)") - self.ax2.set_ylabel("Area") - self.ax2.legend() - self.ax2.grid(True, alpha=0.3) - - self.canvas.draw_idle() diff --git a/src/aare/gui/panels/file_path_panel.py b/src/aare/gui/panels/file_path_panel.py deleted file mode 100644 index f6ede787..00000000 --- a/src/aare/gui/panels/file_path_panel.py +++ /dev/null @@ -1,259 +0,0 @@ -import os -from datetime import datetime -from pathlib import Path - -from aarecommon.config.beamline import mx_beamline -from aarecommon.models.models import DAQStatusModel, SampleShortInfo -from PySide6.QtCore import Qt, Signal, Slot -from PySide6.QtWidgets import QGridLayout, QLabel, QLineEdit, QMessageBox, QSpinBox, QWidget - -from aare.gui.widgets.title_label import TitleLabel - -## Logic for filenames: -## 1. For rasters 'raster/' subfolder is added at the top level of the path (managed by DAQ) - e.g. raster/20250101/PX-456/01/dataset -## 2. For screening 'screening/' subfolder is added at the last level of the path (managed by GUI) - e.g. 20250101/PX-456/01/dataset/screening -## 3. If sample is not registered in the database, it is by default placed in test/ -## 4. If sample is registered in the database and has puck information, it is by default placed in /// -## 5. If sample is registered in the database as manual, it is by default placed in /manual/ - - -def find_file_path_panel(widget) -> "FilePathPanel | None": - """The FilePathPanel that owns ``widget``'s tab, or None outside the GUI. - - Walks up the widget tree: the scan panels are handed parent=DataCollectionSettings - but QStackedWidget.addWidget() reparents them to the stack, so a plain - parent() lookup finds no file_path_panel and the Run guard is skipped. - """ - w = widget.parent() - while w is not None: - panel = getattr(w, "file_path_panel", None) - if panel is not None: - return panel - w = w.parent() - return None - - -class FilePathPanel(QWidget): - path_updated = Signal(str) - - def __init__(self, parent=None): - super().__init__(parent) - grid_layout = QGridLayout(self) - # No horizontal inset: aligns the banner and fields edge-to-edge with - # the zero-margin Exp. Config. section below. - _m = grid_layout.contentsMargins() - grid_layout.setContentsMargins(0, _m.top(), 0, _m.bottom()) - self._sample_name = "sample" - self._sample_id = -1 - self._dewar_pos = "None" - self._puck_name = "Manual" - self._puck_pos = 0 - self._curr_pgroup = "p11206" - self._beamline = mx_beamline().value.lower() - - self._filename = "" - self._scan_kind = "raster" # default: "rotation" | "screening" | "raster" - - self._formatted_date = datetime.now().strftime("%Y%m%d") - - grid_layout.addWidget( - TitleLabel("Dataset path", self, collapsible=True, default_collapsed=False), 0, 0, 1, 2 - ) - - grid_layout.addWidget(QLabel("Directory", parent=self), 1, 0) - self.directory_edit = QLineEdit("{date}/{puck}/{pos}", parent=self) - self.directory_edit.setToolTip( - "Provide subdirectory for your files. The following macros are allowed:
" - "{date} - date in format yyyymmdd
" - "{puck} - puck name
" - "{pos} - pin position in puck
" - "{sample} - sample name
" - "{sample_id} - sample id
" - "{prefix} - file prefix value" - ) - grid_layout.addWidget(self.directory_edit, 1, 1) - - grid_layout.addWidget(QLabel("File prefix", parent=self), 2, 0) - self.file_prefix_edit = QLineEdit("{sample}", parent=self) - self.file_prefix_edit.setToolTip( - "Provide file prefix for your files. The following macros are allowed:
" - "{date} - date in format yyyymmdd
" - "{puck} - puck name
" - "{pos} - pin position in puck
" - "{sample} - sample name
" - "{sample_id} - sample id" - ) - - grid_layout.addWidget(self.file_prefix_edit, 2, 1) - - grid_layout.addWidget(QLabel("Run number", parent=self), 3, 0) - self.run_number_edit = QSpinBox(parent=self) - self.run_number_edit.setValue(1) - self.run_number_edit.setRange(1, 999) - self.run_number_edit.setAlignment(Qt.AlignmentFlag.AlignRight) - grid_layout.addWidget(self.run_number_edit, 3, 1) - - grid_layout.addWidget(QLabel("File name", parent=self), 4, 0) - self.file_name_label = QLabel(parent=self) - self.file_name_label.setWordWrap(True) - grid_layout.addWidget(self.file_name_label, 4, 1) - - self.directory_edit.textChanged.connect(self.set_directory) - self.file_prefix_edit.textChanged.connect(self.set_file_prefix) - self.run_number_edit.valueChanged.connect(self.set_run_number) - self.update_filename() - - def _expand_macros(self, base: str, rn: int) -> str: - name = f"{base}_{rn:03d}" - name = name.replace("{date}", self._formatted_date) - name = name.replace("{sample}", self._sample_name) - name = name.replace("{CrystalName}", self._sample_name) - name = name.replace("{puck}", self._puck_name) - name = name.replace("{position}", f"{self._puck_pos:02d}") - name = name.replace("{sample_id}", f"{self._sample_id}") - name = name.replace("{beamline}", f"{self._beamline}") - name = name.replace( - "{prefix}", f"{self._puck_name}/{self._puck_pos:02d}/{self._sample_name}" - ) - return name - - def _effective_dataset_base(self, base_no_run: str) -> str: - root = Path("/sls/mx/data") / self._curr_pgroup / "raw" - p = Path(base_no_run) - match self._scan_kind: - case "rotation": - p = Path("data") / p - case "screening": - p = Path("screening") / p - case "raster": - p = Path("raster") / p - case _: - pass - return str(root / p) - - # Master files a run can produce: plain scans write "_master.h5", - # X-ray Centering writes "_raster2d_master.h5" / "_raster1d_master.h5" - # (see daq/operations/raster/service.py). Exact names only: a glob or a - # directory test marks runs red that nothing will ever write. - _MASTER_SUFFIXES = ("_master.h5", "_raster2d_master.h5", "_raster1d_master.h5") - - def _exists_for_run(self, expanded_base_with_run: str) -> bool: - # expanded_base_with_run is the base without scan-kind transforms yet - effective = self._effective_dataset_base(expanded_base_with_run) - return any(os.path.exists(effective + suffix) for suffix in self._MASTER_SUFFIXES) - - def update_filename(self): - dir_name = self.directory_edit.text() - file_prefix = self.file_prefix_edit.text() - run_number = self.run_number_edit.value() - - dir_name = dir_name.replace("{prefix}", file_prefix) - - if dir_name == "": - base = "" - elif dir_name[-1] == "/": - base = dir_name - else: - base = dir_name + "/" - - base += "run" if file_prefix == "" else file_prefix - - # Literal: the name is exactly what the fields say. No silent skip to - # the next free run here, or the click-time guard below never sees a - # clash; the label just turns red until the user (or the guard) acts. - # Store the GUI’s base (without applying scan-kind transforms) for wiring into requests later - self._filename = self._expand_macros(base, run_number) - - # Preview label shows the effective path (what will be written), in the - # plain theme color: a clash is reported by the Run guard's popup, not - # by a red label. - effective = self._effective_dataset_base(self._filename) - self.file_name_label.setText(effective + "_master.h5") - self.path_updated.emit(self._filename) - - @Slot() - def increment_run_number(self): - self.run_number_edit.setValue(self.run_number_edit.value() + 1) - self.update_filename() - - @Slot() - def reset_run_number(self): - self.run_number_edit.setValue(1) - - @Slot(str) - def set_directory(self, _: str): - self.update_filename() - - @Slot(str) - def set_file_prefix(self, _: str): - self.update_filename() - - @Slot(int) - def set_run_number(self, _: int): - self.update_filename() - - @property - def filename(self) -> str: - return self._filename - - @Slot(SampleShortInfo) - def update_sample(self, sample: SampleShortInfo): - if sample is None: - self._sample_id = -1 - self._sample_name = "sample" - self._dewar_pos = "None" - self._puck_name = "Manual" - self._puck_pos = 99 - self.directory_edit.setText(f"{self._formatted_date}/test") - else: - self._sample_id = sample.db_id - self._sample_name = sample.sample_name - self._dewar_pos = sample.loc_str() - self._puck_name = sample.puck_name - self._puck_pos = sample.pin - self.run_number_edit.setValue(1) - - if sample.aaredb_params is not None and sample.aaredb_params.directory is not None: - self.directory_edit.setText(f"{sample.aaredb_params.directory}") - elif sample.location is not None: - self.directory_edit.setText( - f"{self._formatted_date}/{self._puck_name}/{self._puck_pos:02d}" - ) - else: - self.directory_edit.setText(f"{self._formatted_date}/manual/{self._sample_name}") - self.update_filename() - - @Slot(DAQStatusModel) - def update_daq_status(self, status: DAQStatusModel): - if status.session.current_pgroup: - self._curr_pgroup = status.session.current_pgroup - - @Slot(str) - def set_scan_kind(self, kind: str): - # kind in {"rotation","screening","raster"} - self._scan_kind = kind - self.update_filename() - - def effective_path_for_base(self, base_with_run: str) -> str: - return self._effective_dataset_base(base_with_run) - - def file_path_error_box(self, scan_kind: str) -> bool: - """Click-time guard for the Run buttons: True when the run may start. - - On a clash: bump the run number by one, tell the user, refuse the run. - The next click checks the new name again, so nothing is ever skipped - without the user seeing it. - """ - self._scan_kind = scan_kind - self.update_filename() # label/path for the clicked kind (screening vs rotation) - if not self._exists_for_run(self.filename): - return True - path = self.effective_path_for_base(self.filename) + "_master.h5" - self.increment_run_number() - QMessageBox.warning( - self, - "File exists", - f"File already exists:\n{path}\n\n" - f"Run number increased to {self.run_number_edit.value()}. Please run data collection again.", - ) - return False diff --git a/src/aare/gui/panels/fluorescence_data_collection.py b/src/aare/gui/panels/fluorescence_data_collection.py deleted file mode 100644 index 244fced3..00000000 --- a/src/aare/gui/panels/fluorescence_data_collection.py +++ /dev/null @@ -1,59 +0,0 @@ -from aarecommon.models.models import FluorescenceSpectrumParameterModel -from PySide6.QtCore import Signal, Slot -from PySide6.QtWidgets import QCheckBox, QGridLayout, QLabel, QPushButton, QWidget - -from aare.gui.styles import ABORT_TEXT, GO_TEXT -from aare.gui.widgets.number_line_edit import NumberLineEdit - - -class FluorescenceDataCollectionPanel(QWidget): - fluo_scan = Signal(FluorescenceSpectrumParameterModel) - - def __init__(self, parent=None): - super().__init__(parent) - - lay = QGridLayout(self) - - # Beam transmission (0..1) - lay.addWidget(QLabel("Beam transmission", self), 0, 0) - self.transmission = NumberLineEdit( - 0.0, 1.0, decimals=4, default=0.1, parent=self, track_pending=True - ) - lay.addWidget(self.transmission, 0, 1) - - # Exposure time (seconds) - lay.addWidget(QLabel("Exposure time", self), 1, 0) - self.exposure = NumberLineEdit( - 0.01, 60.0, decimals=3, default=1.0, parent=self, track_pending=True - ) - lay.addWidget(self.exposure, 1, 1) - lay.addWidget(QLabel("s", self), 1, 2) - - # Accumulate checkbox (reverse of erase) - self.accumulate_cb = QCheckBox("Accumulate", self) # accumulate=True => erase=False - self.accumulate_cb.setChecked(False) - lay.addWidget(self.accumulate_cb, 2, 0, 1, 3) - - # Add vertical stretch - lay.setRowStretch(3, 1) - - # Run button - self.run_btn = QPushButton("Run fluorescence", self) - self.run_btn.setStyleSheet(f"color: {GO_TEXT};") - lay.addWidget(self.run_btn, 4, 0, 1, 3) - - # Per-tab Abort (DataCollectionSettings wires it to the DAQ cancel). - self.abort_button = QPushButton("Abort measurement", self) - self.abort_button.setStyleSheet(f"color: {ABORT_TEXT};") - lay.addWidget(self.abort_button, 5, 0, 1, 3) - - self.run_btn.clicked.connect(self._emit_params) - - @Slot() - def _emit_params(self): - t = float(self.transmission.value) - exp = float(self.exposure.value) - erase = not self.accumulate_cb.isChecked() - self.fluo_scan.emit( - FluorescenceSpectrumParameterModel(acq_time_s=exp, transmission=t, erase=erase) - ) diff --git a/src/aare/gui/panels/fluorescence_panel.py b/src/aare/gui/panels/fluorescence_panel.py deleted file mode 100644 index 84109e2c..00000000 --- a/src/aare/gui/panels/fluorescence_panel.py +++ /dev/null @@ -1,256 +0,0 @@ -import numpy as np -from aarecommon.config.logger import setup_logger -from aarecommon.models.models import DAQStatusModel, FluorescenceSpectrumOutputModel -from PySide6.QtCharts import QChart, QChartView, QLineSeries, QValueAxis -from PySide6.QtCore import QEvent, Qt, Slot -from PySide6.QtGui import QPainter, QPen -from PySide6.QtWidgets import QGraphicsSimpleTextItem, QGridLayout, QLabel, QWidget - -from aare.gui.constants import LOGGER_NAME -from aare.gui.styles import SPECTRUM_LINE, qcolor - -logger = setup_logger(LOGGER_NAME) - - -class FluorescencePanel(QWidget): - def __init__(self, parent=None): - super().__init__(parent) - - self.setMinimumWidth(300) - grid = QGridLayout(self) - - # Replace Matplotlib with Qt Charts - self.series = QLineSeries() - self.chart = QChart() - self.chart.addSeries(self.series) - self.chart.legend().hide() - self.chart.setTitle("Fluorescence Spectrum") - - # Axes - self.axis_x = QValueAxis() - self.axis_x.setTitleText("Energy [keV]") - self.axis_y = QValueAxis() - self.axis_y.setTitleText("Counts") - self.chart.addAxis(self.axis_x, Qt.AlignBottom) - self.chart.addAxis(self.axis_y, Qt.AlignLeft) - self.series.attachAxis(self.axis_x) - self.series.attachAxis(self.axis_y) - - # Chart view - self.chart_view = QChartView(self.chart) - self.chart_view.setRenderHint(QPainter.Antialiasing) - grid.addWidget(self.chart_view, 0, 0) - - # Enable context menu on chart view - self.chart_view.setContextMenuPolicy(Qt.CustomContextMenu) - self.chart_view.customContextMenuRequested.connect(self._show_context_menu) - - self._last_x_keV = None - self._last_y_counts = None - self._sample_name = None - - # Average dead time label - self.avg_dead_label = QLabel("Average dead time: -") - self.avg_dead_label.setAlignment(Qt.AlignLeft) - grid.addWidget(self.avg_dead_label, 1, 0) - - # Peak info label (energy/counts for highest value) - self.peak_info_label = QLabel("Peak: -") - self.peak_info_label.setAlignment(Qt.AlignLeft) - grid.addWidget(self.peak_info_label, 2, 0) - - # Popup label for clicked point (use scene item instead of chart.addText) - self._marker = QGraphicsSimpleTextItem("") - self._marker.setVisible(False) - self.chart.scene().addItem(self._marker) - - # Vertical marker line (two-point series) - self._vline = QLineSeries() - pen = QPen(qcolor(SPECTRUM_LINE)) - pen.setWidth(2) - self._vline.setPen(pen) - self.chart.addSeries(self._vline) - self._vline.attachAxis(self.axis_x) - self._vline.attachAxis(self.axis_y) - self._vline.setVisible(False) - - # Enable mouse tracking for hover readout - self.chart_view.setMouseTracking(True) - self.chart_view.viewport().setMouseTracking(True) - self.chart_view.viewport().installEventFilter(self) - - def eventFilter(self, obj, event): - try: - if obj is self.chart_view.viewport() and event.type() == QEvent.Type.MouseMove: - p = event.position() - plot = self.chart.plotArea() - if not plot.contains(p) or self.series.count() == 0: - self.chart_view.setToolTip("") - self._vline.setVisible(False) - return False - # Map pixel X -> chart X - x_val = self.axis_x.min() + (self.axis_x.max() - self.axis_x.min()) * ( - (p.x() - plot.left()) / plot.width() - ) - - # Snap to the largest Y within +/- 10 indices around nearest index - center = self._nearest_index(x_val) - n = self.series.count() - left = max(0, center - 10) - right = min(n - 1, center + 10) - best_i = max(range(left, right + 1), key=lambda i: self.series.at(i).y()) - - pt = self.series.at(best_i) - self.chart_view.setToolTip(f"Energy {pt.x():.3f} keV counts {pt.y():.3f}") - self._update_vline(pt.x()) - return False - except Exception as e: - logger.debug(f"eventFilter error: {e}", exc_info=True) - return False - - def _show_context_menu(self, pos): - try: - from PySide6.QtWidgets import QFileDialog, QMenu - - menu = QMenu(self.chart_view) - act_save_csv = menu.addAction("Save spectrum as CSV...") - global_pos = self.chart_view.mapToGlobal(pos) - action = menu.exec(global_pos) - if action == act_save_csv: - if self.series.count() == 0: - logger.info("No data to save.") - return - - # Prefer cached arrays; fall back to reading from series - x_vals = self._last_x_keV - y_vals = self._last_y_counts - if x_vals is None or y_vals is None or len(x_vals) != self.series.count(): - x_vals = [self.series.at(i).x() for i in range(self.series.count())] - y_vals = [self.series.at(i).y() for i in range(self.series.count())] - - default_name = "spectrum.csv" - if self._sample_name is not None: - default_name = f"{self._sample_name}_spectrum.csv" - - path, _ = QFileDialog.getSaveFileName( - self, "Save Spectrum CSV", default_name, "CSV files (*.csv)" - ) - if not path: - return - try: - import csv - - with open(path, "w", newline="") as f: - writer = csv.writer(f) - writer.writerow(["Energy_keV", "Counts"]) - for x, y in zip(x_vals, y_vals): - writer.writerow([f"{x:.6f}", f"{y:.6f}"]) - logger.info(f"Spectrum saved to {path}") - except Exception: - logger.exception("Failed to save CSV") - except Exception: - logger.exception("Context menu error") - - def _update_vline(self, x_val: float): - # Draw vertical line spanning current Y axis range at x_val - try: - ymin = self.axis_y.min() - ymax = self.axis_y.max() - self._vline.replace(0, x_val, ymin) if self._vline.count() > 0 else self._vline.append( - x_val, ymin - ) - if self._vline.count() == 1: - self._vline.append(x_val, ymax) - else: - self._vline.replace(1, x_val, ymax) - self._vline.setVisible(True) - except Exception as e: - logger.debug(f"vline error: {e}", exc_info=True) - - def _nearest_index(self, x_val: float) -> int: - n = self.series.count() - if n == 0: - return 0 - lo, hi = 0, n - 1 - while lo < hi: - mid = (lo + hi) // 2 - if self.series.at(mid).x() < x_val: - lo = mid + 1 - else: - hi = mid - cand = [max(0, lo - 1), lo] - best_i = cand[0] - best_d = abs(self.series.at(best_i).x() - x_val) - for i in cand[1:]: - d = abs(self.series.at(i).x() - x_val) - if d < best_d: - best_i, best_d = i, d - return best_i - - @Slot(FluorescenceSpectrumOutputModel) - def update_plot(self, f: FluorescenceSpectrumOutputModel): - try: - self.series.clear() - self._marker.setVisible(False) - self._vline.setVisible(False) - self._vline.clear() - self._last_x_keV = None - self._last_y_counts = None - - # Update average dead time label (if provided) - try: - if hasattr(f, "average_dead_time") and f.average_dead_time is not None: - self.avg_dead_label.setText( - f"Average dead time: {f.average_dead_time * 100.0:.3f}%" - ) - else: - self.avg_dead_label.setText("Average dead time: -") - except Exception: - logger.debug("Could not compute the average dead time", exc_info=True) - self.avg_dead_label.setText("Average dead time: -") - - # Default peak label - self.peak_info_label.setText("Peak: -") - - if len(f.spectrum) > 0 and len(f.spectrum) == len(f.energy_eV): - x = np.array(f.energy_eV, dtype=float) / 1000.0 # keV - y = np.array(f.spectrum, dtype=float) - - # Ensure sorted by X for binary search and consistent series order - order = np.argsort(x) - x = x[order] - y = y[order] - # Cache arrays for export - self._last_x_keV = x.tolist() - self._last_y_counts = y.tolist() - # Append data - for xi, yi in zip(x, y): - self.series.append(float(xi), float(yi)) - # Peak info (highest Y) - if y.size: - max_idx = int(np.argmax(y)) - peak_keV = float(x[max_idx]) - peak_counts = float(y[max_idx]) - self.peak_info_label.setText( - f"Peak: {peak_keV:.3f} keV, {peak_counts:.3f} counts" - ) - # Axes - xmin = float(np.min(x)) if x.size else -1.0 - xmax = float(np.max(x)) if x.size else 1.0 - ymin = float(np.min(y)) if y.size else 0.0 - ymax = float(np.max(y)) if y.size else 1.0 - if xmin == xmax: - xmax = xmin + 1.0 - if ymin == ymax: - ymax = ymin + 1.0 - self.axis_x.setRange(xmin, xmax) - self.axis_y.setRange(ymin, ymax) - except Exception: - logger.exception("Update plot error") - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - if s.sample is not None: - self._sample_name = s.sample.sample_name - else: - self._sample_name = None diff --git a/src/aare/gui/panels/illumination_panel.py b/src/aare/gui/panels/illumination_panel.py deleted file mode 100644 index d96bcbc6..00000000 --- a/src/aare/gui/panels/illumination_panel.py +++ /dev/null @@ -1,86 +0,0 @@ -import time - -from aarecommon.models.models import DAQStatusModel -from PySide6.QtCore import Qt, Signal, Slot -from PySide6.QtWidgets import QGridLayout, QLabel, QSlider, QWidget - -from aare.gui.widgets.title_label import TitleLabel - -# Skip readback updates this long after a user change: a status response already -# in flight when the PUT was queued would otherwise snap the slider back. -READBACK_GRACE_S = 1.5 - - -class IlluminationPanel(QWidget): - front_light = Signal(int) - back_light = Signal(int) - - def __init__(self, parent=None): - super().__init__(parent) - grid_layout = QGridLayout(self) - - grid_layout.addWidget( - TitleLabel("Light", self, collapsible=True, default_collapsed=False), 0, 0, 1, 2 - ) - - front_label = QLabel("Front light", parent=self) - front_label.setAlignment(Qt.AlignmentFlag.AlignCenter) - grid_layout.addWidget(front_label, 1, 0, 1, 2) - self.is_sliding = False - self._last_user_change = 0.0 - - self.front_light_slider = QSlider(orientation=Qt.Orientation.Horizontal, parent=self) - self.front_light_slider.setRange(0, 100) - # tracking off: valueChanged fires once per deliberate change (wheel notch, - # key step, groove page-step, drag release). sliderReleased alone missed - # every path except a handle drag, so wheel adjustments were never sent - # and the 500 ms status poll reverted them. - self.front_light_slider.setTracking(False) - self.front_light_slider.sliderPressed.connect(self.on_slider_pressed) - self.front_light_slider.sliderReleased.connect(self.on_slider_released) - self.front_light_slider.valueChanged.connect(self.on_front_value_changed) - grid_layout.addWidget(self.front_light_slider, 2, 0, 1, 2) - - back_label = QLabel("Back light", parent=self) - back_label.setAlignment(Qt.AlignmentFlag.AlignCenter) - grid_layout.addWidget(back_label, 3, 0, 1, 2) - - self.back_light_slider = QSlider(orientation=Qt.Orientation.Horizontal, parent=self) - self.back_light_slider.setRange(0, 100) - self.back_light_slider.setTracking(False) - self.back_light_slider.sliderPressed.connect(self.on_slider_pressed) - self.back_light_slider.sliderReleased.connect(self.on_slider_released) - self.back_light_slider.valueChanged.connect(self.on_back_value_changed) - grid_layout.addWidget(self.back_light_slider, 4, 0, 1, 2) - - @Slot() - def on_slider_pressed(self): - self.is_sliding = True - - @Slot() - def on_slider_released(self): - self.is_sliding = False - - @Slot(int) - def on_front_value_changed(self, v: int): - self._last_user_change = time.monotonic() - self.front_light.emit(v) - - @Slot(int) - def on_back_value_changed(self, v: int): - self._last_user_change = time.monotonic() - self.back_light.emit(v) - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - if self.is_sliding or time.monotonic() - self._last_user_change < READBACK_GRACE_S: - return - # blockSignals: readback must not loop back into valueChanged and echo - # a PUT to the server every poll. - for slider, val in ( - (self.front_light_slider, s.bl.front_light), - (self.back_light_slider, s.bl.back_light), - ): - slider.blockSignals(True) - slider.setValue(round(val)) - slider.blockSignals(False) diff --git a/src/aare/gui/panels/local_contact_panel.py b/src/aare/gui/panels/local_contact_panel.py deleted file mode 100644 index d43b45c0..00000000 --- a/src/aare/gui/panels/local_contact_panel.py +++ /dev/null @@ -1,857 +0,0 @@ -from __future__ import annotations - -from collections.abc import Callable -from typing import ClassVar - -from aarecommon.config.config_models import GridscanAnalysisMode -from aarecommon.config.logger import setup_logger -from aarecommon.models.models import DAQStatusModel -from PySide6.QtCore import QUrl, Slot -from PySide6.QtGui import QDesktopServices -from PySide6.QtWidgets import ( - QCheckBox, - QDialog, - QDialogButtonBox, - QDoubleSpinBox, - QFrame, - QGridLayout, - QGroupBox, - QHBoxLayout, - QInputDialog, - QLabel, - QMessageBox, - QPushButton, - QScrollArea, - QTabWidget, - QTextEdit, - QVBoxLayout, - QWidget, -) - -from aare.gui.constants import LOGGER_NAME -from aare.gui.panels.beamline_recovery_panel import RecoveryPanel -from aare.gui.styles import ( - BAD_CARD_BORDER, - BORDER, - CARD_BORDER, - CHIP_BAD_BG, - CHIP_BAD_TEXT, - HEADING_TEXT, - SURFACE, - card_style, -) -from aare.gui.threads.daq_worker import DAQWorker -from aare.gui.widgets.local_contact_status_widget import LocalContactStatusWidget -from aare.gui.widgets.text_list_dialog import TextListDialog - -logger = setup_logger(LOGGER_NAME) - - -class LocalContactPanel(QFrame): - TAB_STATUS = "Status" - TAB_RECOVERY = "Recovery" - TAB_TELL = "TELL" - TAB_BEC = "BEC" - TAB_HARDWARE = "Hardware" - TAB_DETECTOR = "Detector" - TAB_CONFIG = "Config" - - DEVICE_TITLES: ClassVar[dict[str, str]] = { - "bec": "BEC", - "detector": "Detector", - "tell": "TELL", - "aerotech": "Aerotech", - "smargon": "Smargon", - } - - def __init__(self, *, daq: DAQWorker, parent=None): - super().__init__(parent) - self._daq = daq - self._sim_checkboxes: dict[str, QCheckBox] = {} - self._links_payload: dict = {} - self._device_state_payload: dict = {} - self._local_contact_error_message: str | None = None - self._last_status: DAQStatusModel | None = None - self._status_widgets: list[LocalContactStatusWidget] = [] - self._bec_macros_dialog: TextListDialog | None = None - self._bec_devices_dialog: TextListDialog | None = None - self._local_contact_config_payload: dict = {} - # Recreated with proper parents in _build_config_tab; parentless here - # so no orphan widget floats over the panel (the old parent=self - # copies painted themselves over the top-left corner). - self._mount_to_center_sleep_s = QDoubleSpinBox() - self._line_scan_loop_face_y_padding_fraction_each_side = QDoubleSpinBox() - self._line_scan_loop_all_y_padding_fraction_each_side = QDoubleSpinBox() - - self.setFrameShape(QFrame.Shape.StyledPanel) - self.setFrameShadow(QFrame.Shadow.Raised) - self.setObjectName("localContactPanel") - self.setStyleSheet( - f""" - QFrame#localContactPanel {{ - border: 1px solid {BORDER}; - }} - QGroupBox {{ - background-color: {SURFACE}; - border: 1px solid {CARD_BORDER}; - margin-top: 15px; - padding-top: 15px; - font-weight: 700; - color: {HEADING_TEXT}; - }} - QGroupBox::title {{ - subcontrol-origin: margin; - subcontrol-position: top left; - left: 10px; - padding: 0 6px 0 6px; - font:bold; - }} - """ - ) - - layout = QVBoxLayout(self) - layout.setContentsMargins(8, 8, 8, 8) - layout.setSpacing(8) - - # No TitleLabel banner: the dialog window title already says it. - self._info_label = QLabel( - "Staff tools for beamline recovery and local-contact operations.", self - ) - self._info_label.setWordWrap(True) - layout.addWidget(self._info_label) - - self._transfer_error_frame = QFrame(self) - self._transfer_error_frame.setVisible(False) - self._transfer_error_frame.setStyleSheet( - card_style(CHIP_BAD_BG, BAD_CARD_BORDER, CHIP_BAD_TEXT) - ) - transfer_error_layout = QVBoxLayout(self._transfer_error_frame) - transfer_error_layout.setContentsMargins(10, 10, 10, 10) - - self._transfer_error_title = QLabel( - "Error transferring information from DAQ", self._transfer_error_frame - ) - self._transfer_error_title.setStyleSheet("font-weight: 700;") - transfer_error_layout.addWidget(self._transfer_error_title) - - self._transfer_error_text = QTextEdit(self._transfer_error_frame) - self._transfer_error_text.setReadOnly(True) - self._transfer_error_text.setMinimumHeight(90) - transfer_error_layout.addWidget(self._transfer_error_text) - - layout.addWidget(self._transfer_error_frame) - - self._tabs = QTabWidget(self) - layout.addWidget(self._tabs, 1) - - # Every tab scrolls: the dialog's explicit minimum size is smaller - # than some tabs' content, and without a scroll area Qt squeezes the - # rows below text height (clipped labels on the Hardware tab). - self._tabs.addTab(self._scrolled(self._build_status_tab()), self.TAB_STATUS) - self._tabs.addTab(self._scrolled(self._build_recovery_tab()), self.TAB_RECOVERY) - self._tabs.addTab(self._scrolled(self._build_tell_tab()), self.TAB_TELL) - self._tabs.addTab(self._scrolled(self._build_bec_tab()), self.TAB_BEC) - self._tabs.addTab(self._scrolled(self._build_hardware_tab()), self.TAB_HARDWARE) - self._tabs.addTab(self._scrolled(self._build_detector_tab()), self.TAB_DETECTOR) - self._tabs.addTab(self._scrolled(self._build_config_tab()), self.TAB_CONFIG) - - self._daq.local_contact_simulation_state_loaded.connect(self._apply_simulation_state) - self._daq.local_contact_device_state_loaded.connect(self._apply_device_state) - self._daq.local_contact_links_loaded.connect(self._apply_links) - self._daq.local_contact_config_loaded.connect(self._apply_local_contact_config) - self._daq.local_contact_config_saved.connect(self._apply_local_contact_config) - self._daq.local_contact_transfer_error.connect(self._show_local_contact_transfer_error) - self._daq.bec_user_macros_loaded.connect(self._show_bec_user_macros) - self._daq.bec_devices_loaded.connect(self._show_bec_devices) - self._daq.update.connect(self._update_from_status) - - self._daq.load_local_contact_simulation_state() - self._daq.load_local_contact_device_state() - self._daq.load_local_contact_links() - self._daq.load_local_contact_config() - - def set_active_tab(self, tab_name: str) -> None: - for index in range(self._tabs.count()): - if self._tabs.tabText(index).strip().lower() == str(tab_name).strip().lower(): - self._tabs.setCurrentIndex(index) - return - logger.warning(f"Unknown Local Contact tab requested: {tab_name}") - - def _register_status_widget(self, widget: LocalContactStatusWidget) -> LocalContactStatusWidget: - self._status_widgets.append(widget) - if self._last_status is not None: - widget.set_daq_status(self._last_status) - if self._device_state_payload: - widget.set_device_state_payload(self._device_state_payload) - return widget - - def _make_status_widget( - self, *, title: str, summary: str, fields: tuple[str, ...] - ) -> LocalContactStatusWidget: - widget = LocalContactStatusWidget( - title=title, visible_fields=fields, summary=summary, parent=self - ) - return self._register_status_widget(widget) - - @staticmethod - def _scrolled(widget: QWidget) -> QScrollArea: - area = QScrollArea() - area.setWidgetResizable(True) - area.setFrameShape(QFrame.Shape.NoFrame) - area.setWidget(widget) - return area - - def _build_status_tab(self) -> QWidget: - tab = QWidget(self) - layout = QVBoxLayout(tab) - layout.setContentsMargins(6, 6, 6, 6) - layout.setSpacing(8) - layout.addWidget( - self._make_status_widget( - title="DAQ status overview", - summary="Full DAQ and backend status summary for Local Contact.", - fields=( - "beamline_state", - "busy", - "sample", - "tell_connected", - "tell_state", - "tell_error", - "bec", - "detector", - "tell", - "aerotech", - "smargon", - "smargon_connected", - "smargon_error", - "aerotech_connected", - "aerotech_error", - "session", - "open_guis", - "box", - "last_best_res", - "last_best_b_factor", - "crystal_size", - "beamline_name", - "ring_current", - "front_light", - "back_light", - "cryojet", - "shutter", - "exposure_shutter", - "flux", - "transmission", - "zoom", - "commissioning_mode", - "omega", - "beam_size", - "smargon_position", - "aerotech_position", - "detector_description", - "detector_serial", - "dtz", - "energy", - "wavelength", - "beam_center", - ), - ) - ) - layout.addStretch(1) - return tab - - def _build_recovery_tab(self) -> QWidget: - tab = QWidget(self) - layout = QVBoxLayout(tab) - layout.setContentsMargins(6, 6, 6, 6) - layout.setSpacing(8) - - layout.addWidget( - self._make_status_widget( - title="Recovery status", - summary="Recovery-relevant DAQ state.", - fields=("beamline_state", "busy", "sample", "tell_connected", "tell_state"), - ) - ) - layout.addWidget(RecoveryPanel(daq=self._daq, parent=tab), 1) - return tab - - def _build_tell_tab(self) -> QWidget: - tab = QWidget(self) - layout = QVBoxLayout(tab) - layout.setContentsMargins(6, 6, 6, 6) - layout.setSpacing(8) - - layout.addWidget( - self._make_status_widget( - title="TELL status", - summary="TELL-focused state and connection details.", - fields=( - "tell", - "tell_connected", - "tell_state", - "tell_error", - "busy", - "beamline_state", - ), - ) - ) - - grid = QGridLayout() - grid.setHorizontalSpacing(8) - grid.setVerticalSpacing(8) - - grid.addWidget( - self._make_button("Unmount", self._daq.unmount, "Requesting sample unmount."), 0, 0 - ) - - grid.addWidget( - self._make_button("Park and dry", self._daq.park_and_dry, "Requesting park and dry."), - 0, - 1, - ) - grid.addWidget( - self._make_button("Toggle blower", self._daq.tell_toggle_blower, "Toggling blower."), - 1, - 0, - ) - - grid.addWidget(self._make_button("Anneal", self._anneal_from_dialog), 1, 1) - grid.addWidget(self._make_button("TELL access info", self._show_tell_access_info), 2, 0) - - wrapper = QGroupBox("TELL actions", tab) - wrapper_layout = QVBoxLayout(wrapper) - wrapper_layout.setContentsMargins(10, 12, 10, 10) - inner = QWidget(wrapper) - inner.setLayout(grid) - wrapper_layout.addWidget(inner) - layout.addWidget(wrapper) - - layout.addStretch(1) - return tab - - def _build_bec_tab(self) -> QWidget: - tab = QWidget(self) - layout = QVBoxLayout(tab) - layout.setContentsMargins(6, 6, 6, 6) - layout.setSpacing(8) - - layout.addWidget( - self._make_status_widget( - title="BEC status", - summary="BEC-focused state and related backend status.", - fields=("bec", "busy", "beamline_state", "detector", "aerotech", "smargon"), - ) - ) - - tools = QGroupBox("BEC tools", tab) - tools_layout = QVBoxLayout(tools) - tools_layout.setContentsMargins(10, 12, 10, 10) - tools_layout.setSpacing(6) - - tools_layout.addWidget(tools) - - tools_layout.addWidget( - self._make_button( - "Load BEC user macros", self._daq.bec_load_user_macros, "Loading BEC user macros." - ) - ) - tools_layout.addWidget( - self._make_button( - "Show BEC user macros", - self._daq.bec_list_all_user_macros, - "Listing BEC user macros.", - ) - ) - tools_layout.addWidget( - self._make_button( - "Show BEC position devices", self._daq.bec_list_all_devices, "Listing BEC devices." - ) - ) - tools_layout.addWidget( - self._make_button( - "Reinitialise BEC planner/devices", - lambda: self._daq.bec_reinitialise_planner_and_position_devices("auto"), - "Reinitialising BEC planner and position devices.", - ) - ) - - device_config = QGroupBox("Device config", tab) - device_config_layout = QVBoxLayout(device_config) - device_config_layout.setContentsMargins(10, 12, 10, 10) - device_config_layout.setSpacing(6) - - device_config_layout.addWidget( - self._make_button( - "Save current beamstop x and y 'in' positions", - self._daq.bec_save_current_bs_pos, - "Saving current BEC beamstop safe position.", - ) - ) - device_config_layout.addWidget( - self._make_button( - "Save current collimator position as x and y 'in'.", - self._daq.bec_save_current_collimator_pos, - "Saving current BEC collimator work position.", - ) - ) - device_config_layout.addWidget( - self._make_button( - "Save current aerotech position", - self._daq.bec_save_current_aerotech_position, - "Saving current BEC aerotech work position and reloading devices.", - ) - ) - - layout.addWidget(tools) - layout.addWidget(device_config) - layout.addStretch(1) - return tab - - def _build_hardware_tab(self) -> QWidget: - tab = QWidget(self) - layout = QVBoxLayout(tab) - layout.setContentsMargins(6, 6, 6, 6) - layout.setSpacing(8) - - layout.addWidget( - self._make_status_widget( - title="Hardware status", - summary="Hardware-related backend and beamline status.", - fields=("aerotech", "smargon", "detector", "bec", "tell", "busy", "beamline_state"), - ) - ) - - label = QLabel("Hardware tools grouped by action.", tab) - label.setWordWrap(True) - layout.addWidget(label) - - layout.addWidget( - self._build_section( - "Web panels", - [ - self._build_link_button("Detector web panel", "detector"), - self._build_link_button("Smargon web panel", "smargon"), - self._build_link_button("Aerotech web panel", "aerotech"), - ], - ) - ) - - layout.addWidget( - self._build_section( - "Restart Backend", - [ - self._make_restart_button("tell", "Restart TELL backend"), - self._make_restart_button("bec", "Restart BEC backend"), - self._make_restart_button("detector", "Restart detector backend"), - self._make_restart_button("smargon", "Restart Smargon backend"), - self._make_restart_button("aerotech", "Restart Aerotech backend"), - ], - ) - ) - - layout.addWidget( - self._build_section( - "Simulate", - [ - self._make_sim_checkbox("tell", "Simulate TELL"), - self._make_sim_checkbox("bec", "Simulate BEC"), - self._make_sim_checkbox("detector", "Simulate detector"), - self._make_sim_checkbox("smargon", "Simulate Smargon"), - self._make_sim_checkbox("aerotech", "Simulate Aerotech"), - ], - ) - ) - - layout.addWidget( - self._build_section( - "Initialise", - [ - self._make_button( - "Initialize detector", - self._daq.initialize_detector, - "Initializing detector.", - ), - self._make_button( - "Initialise Smargon", self._daq.initialise_smargon, "Initialising Smargon." - ), - self._make_button( - "Initialise Aerotech", - self._daq.initialize_aerotech, - "Initialising Aerotech.", - ), - ], - ) - ) - - layout.addStretch(1) - return tab - - def _build_detector_tab(self) -> QWidget: - tab = QWidget(self) - layout = QVBoxLayout(tab) - layout.setContentsMargins(6, 6, 6, 6) - layout.setSpacing(8) - - layout.addWidget( - self._make_status_widget( - title="Detector status", - summary="Detector-focused state and metadata.", - fields=( - "detector", - "bec", - "busy", - "beamline_state", - "dtz", - "detector_description", - "detector_serial", - ), - ) - ) - - grid = QGridLayout() - grid.setHorizontalSpacing(8) - grid.setVerticalSpacing(8) - row = 0 - grid.addWidget(QLabel("Detector operations", tab), row, 0, 1, 2) - row += 1 - - grid.addWidget( - self._make_button( - "Cancel current state", self._daq.cancel, "Cancelling current detector/scan state." - ), - row, - 0, - ) - grid.addWidget( - self._make_button( - "Resync detector/DTZ hardware cache", - self._daq.resync_local_contact_detector_metadata, - "Resyncing detector metadata and DTZ limits cache.", - ) - ) - - wrapper = QGroupBox("Detector actions", tab) - wrapper_layout = QVBoxLayout(wrapper) - wrapper_layout.setContentsMargins(10, 12, 10, 10) - inner = QWidget(wrapper) - inner.setLayout(grid) - wrapper_layout.addWidget(inner) - layout.addWidget(wrapper) - - layout.addStretch(1) - return tab - - def _build_config_tab(self) -> QWidget: - tab = QWidget(self) - layout = QVBoxLayout(tab) - layout.setContentsMargins(6, 6, 6, 6) - layout.setSpacing(8) - - description = QLabel("Staff-only tuning values used by automation and recovery flows.", tab) - description.setWordWrap(True) - layout.addWidget(description) - - form_box = QGroupBox("Automation timing", tab) - form_layout = QGridLayout(form_box) - form_layout.setContentsMargins(10, 12, 10, 10) - form_layout.setHorizontalSpacing(8) - form_layout.setVerticalSpacing(8) - - label = QLabel("Mount → center delay (s)", form_box) - self._mount_to_center_sleep_s = QDoubleSpinBox(form_box) - self._mount_to_center_sleep_s.setRange(0.0, 120.0) - self._mount_to_center_sleep_s.setDecimals(1) - self._mount_to_center_sleep_s.setSingleStep(0.5) - self._mount_to_center_sleep_s.setSuffix(" s") - self._mount_to_center_sleep_s.setToolTip( - "Delay after sample mounting and before loop centering starts." - ) - - form_layout.addWidget(label, 0, 0) - form_layout.addWidget(self._mount_to_center_sleep_s, 0, 1) - - loop_face_padding_label = QLabel("Line scan loop_face Y padding / side", form_box) - self._line_scan_loop_face_y_padding_fraction_each_side = QDoubleSpinBox(form_box) - self._line_scan_loop_face_y_padding_fraction_each_side.setRange(0.0, 5.0) - self._line_scan_loop_face_y_padding_fraction_each_side.setDecimals(2) - self._line_scan_loop_face_y_padding_fraction_each_side.setSingleStep(0.05) - self._line_scan_loop_face_y_padding_fraction_each_side.setToolTip( - "Second auto-center line-scan Y padding per side for loop_face. " - "0.50 means 50% above and 50% below, giving 200% total detected height." - ) - - loop_all_padding_label = QLabel("Line scan loop_all Y padding / side", form_box) - self._line_scan_loop_all_y_padding_fraction_each_side = QDoubleSpinBox(form_box) - self._line_scan_loop_all_y_padding_fraction_each_side.setRange(0.0, 5.0) - self._line_scan_loop_all_y_padding_fraction_each_side.setDecimals(2) - self._line_scan_loop_all_y_padding_fraction_each_side.setSingleStep(0.05) - self._line_scan_loop_all_y_padding_fraction_each_side.setToolTip( - "Second auto-center line-scan Y padding per side for loop_all. " - "0.50 means 50% above and 50% below." - ) - - form_layout.addWidget(loop_face_padding_label, 1, 0) - form_layout.addWidget(self._line_scan_loop_face_y_padding_fraction_each_side, 1, 1) - form_layout.addWidget(loop_all_padding_label, 2, 0) - form_layout.addWidget(self._line_scan_loop_all_y_padding_fraction_each_side, 2, 1) - - button_row = QWidget(tab) - button_layout = QHBoxLayout(button_row) - button_layout.setContentsMargins(0, 0, 0, 0) - button_layout.setSpacing(8) - - save_button = QPushButton("Save config", button_row) - save_button.clicked.connect(self._save_local_contact_config) - - reload_button = QPushButton("Reload config", button_row) - reload_button.clicked.connect(self._daq.load_local_contact_config) - - button_layout.addWidget(save_button) - button_layout.addWidget(reload_button) - button_layout.addStretch(1) - - analysis_settings = QGroupBox("Analysis settings", tab) - analysis_settings_layout = QGridLayout(analysis_settings) - analysis_settings_layout.setContentsMargins(10, 12, 10, 10) - analysis_settings_layout.setHorizontalSpacing(8) - analysis_settings_layout.setVerticalSpacing(8) - analysis_choice_label = QLabel("Gridscan analysis mode:", analysis_settings) - find_xtal_button = QPushButton('classic "find_xtal.py"', analysis_settings) - jfj_gs_u_button = QPushButton('Meitian\'s "jfjoch_gridscan_union.py"', analysis_settings) - current_label = QLabel("Current:", analysis_settings) - current_value_label = QLabel("Unknown/default", analysis_settings) - analysis_settings_layout.addWidget(analysis_choice_label, 1, 0) - analysis_settings_layout.addWidget(find_xtal_button, 2, 0) - analysis_settings_layout.addWidget(jfj_gs_u_button, 2, 1) - analysis_settings_layout.addWidget(current_label, 2, 2) - analysis_settings_layout.addWidget(current_value_label, 2, 3) - - find_xtal_button.clicked.connect( - lambda: self._daq.set_gridscan_analysis_mode(GridscanAnalysisMode.FindXtal) - ) - jfj_gs_u_button.clicked.connect( - lambda: self._daq.set_gridscan_analysis_mode(GridscanAnalysisMode.JfjochGridscanUnion) - ) - self._daq.gridscan_analysis_mode.connect(current_value_label.setText) - self._daq.refresh_gridscan_analysis_mode() - - layout.addWidget(form_box) - layout.addWidget(button_row) - layout.addWidget(analysis_settings) - layout.addStretch(1) - return tab - - def _build_section(self, title: str, widgets: list[QWidget]) -> QWidget: - box = QGroupBox(title, self) - box_layout = QVBoxLayout(box) - box_layout.setContentsMargins(10, 12, 10, 10) - box_layout.setSpacing(6) - - for widget in widgets: - box_layout.addWidget(widget) - - return box - - def _make_sim_checkbox(self, device: str, text: str) -> QWidget: - row_widget = QWidget(self) - row_layout = QHBoxLayout(row_widget) - row_layout.setContentsMargins(0, 0, 0, 0) - row_layout.setSpacing(8) - - name = QLabel(self.DEVICE_TITLES.get(device, device.title()), row_widget) - name.setMinimumWidth(90) - name.setStyleSheet("font-weight: 700;") - - checkbox = QCheckBox(text, row_widget) - checkbox.toggled.connect( - lambda checked, d=device: self._daq.set_local_contact_simulation(d, checked) - ) - self._sim_checkboxes[device] = checkbox - - row_layout.addWidget(name) - row_layout.addWidget(checkbox, 1) - return row_widget - - def _make_restart_button(self, device: str, text: str) -> QWidget: - row_widget = QWidget(self) - row_layout = QHBoxLayout(row_widget) - row_layout.setContentsMargins(0, 0, 0, 0) - row_layout.setSpacing(8) - - name = QLabel(self.DEVICE_TITLES.get(device, device.title()), row_widget) - name.setMinimumWidth(90) - name.setStyleSheet("font-weight: 700;") - - button = QPushButton(text, row_widget) - button.clicked.connect( - lambda: self._run_logged_action( - f"Restarting {device} backend.", - lambda: self._daq.restart_local_contact_device(device), - ) - ) - - row_layout.addWidget(name) - row_layout.addWidget(button, 1) - return row_widget - - def _build_link_button(self, text: str, key: str) -> QPushButton: - button = QPushButton(text, self) - button.clicked.connect(lambda: self._open_link(key)) - return button - - @Slot(dict) - def _apply_simulation_state(self, payload: dict) -> None: - for device, checkbox in self._sim_checkboxes.items(): - value = bool(payload.get(device, False)) - checkbox.blockSignals(True) - checkbox.setChecked(value) - checkbox.blockSignals(False) - - @Slot(dict) - def _apply_device_state(self, payload: dict) -> None: - self._device_state_payload = payload or {} - for widget in self._status_widgets: - widget.set_device_state_payload(self._device_state_payload) - - @Slot(dict) - def _apply_links(self, payload: dict) -> None: - self._links_payload = payload or {} - - @Slot(str) - def _show_local_contact_transfer_error(self, message: str) -> None: - self._local_contact_error_message = message - self._transfer_error_text.setPlainText(message) - self._transfer_error_frame.setVisible(True) - - @Slot(list) - def _show_bec_user_macros(self, items: list) -> None: - if self._bec_macros_dialog is None: - self._bec_macros_dialog = TextListDialog(title="BEC user macros", parent=self) - self._bec_macros_dialog.set_items( - [str(item) for item in items], empty_message="No BEC user macros found." - ) - self._bec_macros_dialog.show() - self._bec_macros_dialog.raise_() - self._bec_macros_dialog.activateWindow() - - @Slot(list) - def _show_bec_devices(self, items: list) -> None: - if self._bec_devices_dialog is None: - self._bec_devices_dialog = TextListDialog(title="BEC position devices", parent=self) - self._bec_devices_dialog.set_items( - [str(item) for item in items], empty_message="No BEC devices found." - ) - self._bec_devices_dialog.show() - self._bec_devices_dialog.raise_() - self._bec_devices_dialog.activateWindow() - - @Slot(DAQStatusModel) - def _update_from_status(self, status: DAQStatusModel) -> None: - self._last_status = status - for widget in self._status_widgets: - widget.set_daq_status(status) - if self._local_contact_error_message is None: - self._daq.load_local_contact_device_state() - - def _open_link(self, key: str) -> None: - url = self._links_payload.get(key) - if not url: - QMessageBox.information( - self, "Link unavailable", f"No configured link is available for {key}." - ) - return - QDesktopServices.openUrl(QUrl(str(url))) - - @Slot() - def _show_tell_access_info(self) -> None: - message = ( - self._links_payload.get("tell_hint") or "Please check TELL status via Remmina / VNC." - ) - QMessageBox.information(self, "TELL access", str(message)) - - def _make_button( - self, text: str, callback: Callable[[], None], log_message: str | None = None - ) -> QPushButton: - button = QPushButton(text, self) - if log_message is None: - button.clicked.connect(callback) - else: - button.clicked.connect(lambda: self._run_logged_action(log_message, callback)) - return button - - @Slot() - def _anneal_from_dialog(self) -> None: - seconds, ok = QInputDialog.getDouble(self, "Anneal", "Anneal time (s):", 1.0, 0.1, 60.0, 1) - if not ok: - return - self._daq.anneal(seconds) - - @Slot() - def _run_logged_action(self, message: str, callback: Callable[[], None]) -> None: - logger.info(message) - callback() - - @Slot(dict) - def _apply_local_contact_config(self, payload: dict) -> None: - self._local_contact_config_payload = payload or {} - - self._mount_to_center_sleep_s.blockSignals(True) - self._mount_to_center_sleep_s.setValue( - float(self._local_contact_config_payload.get("mount_to_center_sleep_s", 0.0)) - ) - self._mount_to_center_sleep_s.blockSignals(False) - - self._line_scan_loop_face_y_padding_fraction_each_side.blockSignals(True) - self._line_scan_loop_face_y_padding_fraction_each_side.setValue( - float( - self._local_contact_config_payload.get( - "line_scan_loop_face_y_padding_fraction_each_side", 0.5 - ) - ) - ) - self._line_scan_loop_face_y_padding_fraction_each_side.blockSignals(False) - - self._line_scan_loop_all_y_padding_fraction_each_side.blockSignals(True) - self._line_scan_loop_all_y_padding_fraction_each_side.setValue( - float( - self._local_contact_config_payload.get( - "line_scan_loop_all_y_padding_fraction_each_side", 0.5 - ) - ) - ) - self._line_scan_loop_all_y_padding_fraction_each_side.blockSignals(False) - - @Slot() - def _save_local_contact_config(self) -> None: - payload = { - "mount_to_center_sleep_s": float(self._mount_to_center_sleep_s.value()), - "line_scan_loop_face_y_padding_fraction_each_side": float( - self._line_scan_loop_face_y_padding_fraction_each_side.value() - ), - "line_scan_loop_all_y_padding_fraction_each_side": float( - self._line_scan_loop_all_y_padding_fraction_each_side.value() - ), - } - self._daq.set_local_contact_config(payload) - - -class LocalContactDialog(QDialog): - def __init__(self, *, daq: DAQWorker, parent=None): - super().__init__(parent) - self.setWindowTitle("Local Contact") - self.setMinimumSize(920, 700) - - layout = QVBoxLayout(self) - layout.setContentsMargins(12, 12, 12, 12) - layout.setSpacing(8) - - self._panel = LocalContactPanel(daq=daq, parent=self) - layout.addWidget(self._panel, 1) - - buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close, parent=self) - buttons.rejected.connect(self.reject) - buttons.accepted.connect(self.accept) - layout.addWidget(buttons) - - def set_active_tab(self, tab_name: str) -> None: - self._panel.set_active_tab(tab_name) diff --git a/src/aare/gui/panels/log_panel.py b/src/aare/gui/panels/log_panel.py deleted file mode 100644 index 65530d37..00000000 --- a/src/aare/gui/panels/log_panel.py +++ /dev/null @@ -1,281 +0,0 @@ -import logging - -from aarecommon.config.logger import attach_to_logger, find_existing_formatter -from PySide6.QtCore import QTimer, Signal, Slot -from PySide6.QtWidgets import ( - QFrame, - QHBoxLayout, - QLabel, - QPlainTextEdit, - QPushButton, - QToolButton, - QVBoxLayout, - QWidget, -) - -from aare.gui.log import QtLogEmitter, QtLogHandler -from aare.gui.styles import ( - FLAT_CARD_RADIUS, - LOG_BORDER, - LOG_ERROR_BG, - LOG_ERROR_BORDER, - LOG_INFO_BG, - LOG_INFO_BORDER, - LOG_PANEL_BG, - LOG_SUCCESS_BG, - LOG_SUCCESS_BORDER, - LOG_WARN_BG, - LOG_WARN_BORDER, - TEXT, - card_style, -) - - -class RuntimeNotificationWidget(QFrame): - cleared = Signal() - show_log_requested = Signal() - - def __init__(self, parent=None): - super().__init__(parent) - self.setObjectName("runtimeNotification") - self.setProperty("noticeLevel", "error") - self.setFrameShape(QFrame.Shape.StyledPanel) - self.setVisible(False) - - self._auto_clear_timer = QTimer(self) - self._auto_clear_timer.setSingleShot(True) - self._auto_clear_timer.timeout.connect(self.clear_notification) - - self._title = QLabel("", self) - self._title.setObjectName("runtimeNotificationTitle") - - self._message = QLabel("", self) - self._message.setObjectName("runtimeNotificationMessage") - self._message.setWordWrap(True) - - self._minimise_button = QToolButton(self) - self._minimise_button.setText("—") - self._minimise_button.setToolTip("Minimise notification") - self._minimise_button.clicked.connect(self._toggle_minimised) - - self._clear_button = QPushButton("Clear", self) - self._clear_button.clicked.connect(self.clear_notification) - - self._show_log_button = QPushButton("Show log", self) - self._show_log_button.clicked.connect(self.show_log_requested.emit) - - header_layout = QHBoxLayout() - header_layout.setContentsMargins(0, 0, 0, 0) - header_layout.addWidget(self._title, 1) - header_layout.addWidget(self._minimise_button) - - button_layout = QHBoxLayout() - button_layout.setContentsMargins(0, 0, 0, 0) - button_layout.addStretch(1) - button_layout.addWidget(self._show_log_button) - button_layout.addWidget(self._clear_button) - - self._body = QWidget(self) - self._body.setObjectName("runtimeNotificationBody") - body_layout = QVBoxLayout(self._body) - body_layout.setContentsMargins(0, 0, 0, 0) - body_layout.setSpacing(8) - body_layout.addWidget(self._message) - body_layout.addLayout(button_layout) - - root_layout = QVBoxLayout(self) - root_layout.setContentsMargins(12, 10, 12, 10) - root_layout.setSpacing(8) - root_layout.addLayout(header_layout) - root_layout.addWidget(self._body) - - self._full_title = "" - self._full_message = "" - self._minimised = False - self._sticky = True - - self.setStyleSheet( - card_style( - LOG_PANEL_BG, - LOG_BORDER, - selector="QFrame#runtimeNotification", - radius=FLAT_CARD_RADIUS, - ) - + card_style( - LOG_ERROR_BG, - LOG_ERROR_BORDER, - selector='QFrame#runtimeNotification[noticeLevel="error"]', - radius=FLAT_CARD_RADIUS, - ) - + card_style( - LOG_WARN_BG, - LOG_WARN_BORDER, - selector='QFrame#runtimeNotification[noticeLevel="warning"]', - radius=FLAT_CARD_RADIUS, - ) - + card_style( - LOG_SUCCESS_BG, - LOG_SUCCESS_BORDER, - selector='QFrame#runtimeNotification[noticeLevel="success"]', - radius=FLAT_CARD_RADIUS, - ) - + card_style( - LOG_INFO_BG, - LOG_INFO_BORDER, - selector='QFrame#runtimeNotification[noticeLevel="info"]', - radius=FLAT_CARD_RADIUS, - ) - # Transparent children: the app-wide QWidget background rule would - # otherwise paint opaque strips over the card tint. Text color is - # pinned dark: the card fills above stay light pastel in BOTH - # themes, so theme-following text goes white-on-cream in Sunset. - + f" QLabel#runtimeNotificationTitle {{ color: {TEXT};" - + " font-weight: bold; background: transparent; }" - + f" QLabel#runtimeNotificationMessage {{ color: {TEXT}; background: transparent; }}" - + " QWidget#runtimeNotificationBody { background: transparent; }" - ) - - def _set_level(self, level: str) -> None: - self.setProperty("noticeLevel", level) - self.style().unpolish(self) - self.style().polish(self) - self.update() - - @Slot() - def _toggle_minimised(self) -> None: - self._minimised = not self._minimised - self._body.setVisible(not self._minimised) - self._minimise_button.setText("+" if self._minimised else "—") - if self._minimised: - self._title.setText(self._full_title or "Notification") - else: - self._title.setText(self._full_title) - - def show_notification( - self, - *, - title: str, - message: str, - level: str = "error", - sticky: bool = True, - auto_clear_ms: int | None = None, - ) -> None: - self._auto_clear_timer.stop() - self._sticky = sticky - self._full_title = title.strip() or "Notification" - self._full_message = message.strip() - - self._set_level(level) - self._title.setText(self._full_title) - self._message.setText(self._full_message) - # allow dismising of notification, if bad, then remove - self._clear_button.setVisible(True) - self._body.setVisible(True) - self._minimised = False - self._minimise_button.setText("—") - self.setVisible(True) - - if not sticky: - timeout = 5000 if auto_clear_ms is None else int(auto_clear_ms) - self._auto_clear_timer.start(timeout) - - def show_waiting(self, *, title: str, message: str, auto_clear_ms: int | None = None) -> None: - self.show_notification( - title=title, message=message, level="warning", sticky=True, auto_clear_ms=auto_clear_ms - ) - - @Slot() - def clear_notification(self) -> None: - self._auto_clear_timer.stop() - self._full_title = "" - self._full_message = "" - self._title.clear() - self._message.clear() - self.setVisible(False) - self.cleared.emit() - - -class LogPanel(QWidget): - """Console-log card: notification banner + log view. A tab inside the - Information dock (was its own LogDock QDockWidget until the Automation - progress / Console log docks merged). Revealing the dock/tab is the - owner's job — this panel only signals when it needs to be seen.""" - - reveal_requested = Signal() - - def __init__(self, parent=None): - super().__init__(parent) - self.setObjectName("logPanel") - self.notification = RuntimeNotificationWidget(self) - self.notification.show_log_requested.connect(self._focus_log) - - self.view = QPlainTextEdit(self) - self.view.setReadOnly(True) - - layout = QVBoxLayout(self) - layout.setContentsMargins(6, 6, 6, 6) - layout.setSpacing(6) - layout.addWidget(self.notification) - layout.addWidget(self.view, 1) - - self._mirror_views: list[QPlainTextEdit] = [] - - self.emitter = QtLogEmitter() - self.emitter.message.connect(self._append_line) - - self.handler = QtLogHandler(self.emitter) - # hide debug message from log panel - self.handler.setLevel(logging.INFO) - self.handler.setFormatter(find_existing_formatter()) - - def attach_logger(self, logger_name: str = "aareGUI"): - attach_to_logger(logger_name, self.handler) - - @Slot(str) - def _append_line(self, text: str): - self.view.appendPlainText(text) - - def make_mirror_view(self) -> QPlainTextEdit: - """Second view on the same emitter, for pop-out windows: history is - copied once at creation, live lines reach every mirror, clear() - empties them all. (One QTextDocument shared by two QPlainTextEdits - would make their layouts fight, hence the separate documents.)""" - view = QPlainTextEdit() - view.setReadOnly(True) - # Frameless inside the pop-out — no nested boxes in this window. - view.setStyleSheet("QPlainTextEdit { border: none; }") - view.setPlainText(self.view.toPlainText()) - self.emitter.message.connect(view.appendPlainText) - self._mirror_views.append(view) - return view - - @Slot() - def _focus_log(self) -> None: - self.reveal_requested.emit() - self.view.setFocus() - - def show_notification( - self, - *, - title: str, - message: str, - level: str = "error", - sticky: bool = True, - auto_clear_ms: int | None = None, - ) -> None: - self.reveal_requested.emit() - self.notification.show_notification( - title=title, message=message, level=level, sticky=sticky, auto_clear_ms=auto_clear_ms - ) - - def show_waiting_notification(self, *, title: str, message: str) -> None: - self.reveal_requested.emit() - self.notification.show_waiting(title=title, message=message) - - def clear_notification(self) -> None: - self.notification.clear_notification() - - def clear(self): - self.view.clear() - for mirror in self._mirror_views: - mirror.clear() diff --git a/src/aare/gui/panels/loop_centering_panel.py b/src/aare/gui/panels/loop_centering_panel.py deleted file mode 100644 index ee2a3a5d..00000000 --- a/src/aare/gui/panels/loop_centering_panel.py +++ /dev/null @@ -1,19 +0,0 @@ -from PySide6.QtWidgets import QGridLayout, QPushButton, QWidget - -from aare.gui.widgets.title_label import TitleLabel - - -class LoopCenteringPanel(QWidget): - def __init__(self, parent=None): - super().__init__(parent) - grid_layout = QGridLayout(self) - - grid_layout.addWidget(TitleLabel("Loop centering", self, collapsible=True), 0, 0, 1, 2) - grid_layout.setColumnStretch(0, 1) - grid_layout.setColumnStretch(1, 1) - - self.find_tip = QPushButton("Center", parent=self) - grid_layout.addWidget(self.find_tip, 1, 0) - - self.bounding_box = QPushButton("Make Raster Grid", parent=self) - grid_layout.addWidget(self.bounding_box, 1, 1) diff --git a/src/aare/gui/panels/manual_sample_panel.py b/src/aare/gui/panels/manual_sample_panel.py deleted file mode 100644 index f7f554e2..00000000 --- a/src/aare/gui/panels/manual_sample_panel.py +++ /dev/null @@ -1,131 +0,0 @@ -from aarecommon.models.models import DAQStatusModel, SampleShortInfo -from aareDB import DataCollectionParameters -from PySide6.QtCore import Signal, Slot -from PySide6.QtWidgets import QCheckBox, QGridLayout, QLabel, QLineEdit, QPushButton, QWidget - -from aare.gui.styles import SURFACE -from aare.gui.widgets.number_line_edit import NumberLineEdit -from aare.gui.widgets.title_label import TitleLabel - - -class ManualSamplePanel(QWidget): - sample_manual = Signal(SampleShortInfo) - sample_clear = Signal() - - def __init__(self, parent=None): - super().__init__(parent) - self._sample_name = "Lyso" - - self._pgroup = "p16371" - - grid_layout = QGridLayout(self) - # No horizontal inset: aligns the banner edge-to-edge with the Dataset - # path / Exp. Config. sections around it in the left column. - _m = grid_layout.contentsMargins() - grid_layout.setContentsMargins(0, _m.top(), 0, _m.bottom()) - - # Kept as attribute: the Ctrl+M shortcut expands the panel via title. - self.title = TitleLabel("Manual sample", self, collapsible=True) - grid_layout.addWidget(self.title, 0, 0, 1, 3) - - grid_layout.addWidget(QLabel("Sample"), 1, 0) - self._text_name = QLineEdit(self._sample_name) - grid_layout.addWidget(self._text_name, 1, 1) - self._text_name.textChanged.connect(self._name_changed) - self._text_name.setStyleSheet(f"background-color: {SURFACE};") - - # Unit cell parameters - self._unit_cell = QCheckBox("Provide unit cell") - grid_layout.addWidget(self._unit_cell, 2, 1) - - # a, b, c parameters (in Ångströms) - grid_layout.addWidget(QLabel("a"), 3, 0) - self._text_a = NumberLineEdit(5, 1000, 39, parent=self) - grid_layout.addWidget(self._text_a, 3, 1) - grid_layout.addWidget(QLabel("Å"), 3, 2) - - grid_layout.addWidget(QLabel("b"), 4, 0) - self._text_b = NumberLineEdit(5, 1000, 78, parent=self) - grid_layout.addWidget(self._text_b, 4, 1) - grid_layout.addWidget(QLabel("Å"), 4, 2) - - grid_layout.addWidget(QLabel("c"), 5, 0) - self._text_c = NumberLineEdit(5, 1000, 78, parent=self) - grid_layout.addWidget(self._text_c, 5, 1) - grid_layout.addWidget(QLabel("Å"), 5, 2) - - # alpha, beta, gamma parameters (in degrees) - grid_layout.addWidget(QLabel("α"), 6, 0) - self._text_alpha = NumberLineEdit(30, 330, 90, parent=self) - grid_layout.addWidget(self._text_alpha, 6, 1) - grid_layout.addWidget(QLabel("°"), 6, 2) - - grid_layout.addWidget(QLabel("β"), 7, 0) - self._text_beta = NumberLineEdit(30, 330, 90, parent=self) - grid_layout.addWidget(self._text_beta, 7, 1) - grid_layout.addWidget(QLabel("°"), 7, 2) - - grid_layout.addWidget(QLabel("γ"), 8, 0) - self._text_gamma = NumberLineEdit(30, 330, 90, parent=self) - grid_layout.addWidget(self._text_gamma, 8, 1) - grid_layout.addWidget(QLabel("°"), 8, 2) - - grid_layout.addWidget(QLabel("SG"), 9, 0) - self._text_sg = NumberLineEdit(1, 250, 1, 0, parent=self) - grid_layout.addWidget(self._text_sg, 9, 1) - - self._add_button = QPushButton("Add") - grid_layout.addWidget(self._add_button, 10, 0, 1, 3) - self._add_button.clicked.connect(self._add_clicked) - - self._unit_cell.toggled.connect(self._unit_cell_toggled) - self._unit_cell_toggled(False) - - @Slot(bool) - def _unit_cell_toggled(self, checked: bool): - if checked: - self._text_a.setEnabled(True) - self._text_b.setEnabled(True) - self._text_c.setEnabled(True) - self._text_alpha.setEnabled(True) - self._text_beta.setEnabled(True) - self._text_gamma.setEnabled(True) - self._text_sg.setEnabled(True) - else: - self._text_a.setEnabled(False) - self._text_b.setEnabled(False) - self._text_c.setEnabled(False) - self._text_alpha.setEnabled(False) - self._text_beta.setEnabled(False) - self._text_gamma.setEnabled(False) - self._text_sg.setEnabled(False) - - @Slot(str) - def _name_changed(self, s: str): - self._sample_name = s - - @Slot() - def _add_clicked(self): - data_processing = None - - if self._unit_cell.isChecked(): - data_processing = DataCollectionParameters( - spacegroupnumber=int(self._text_sg.value), - cellparameters=f"{self._text_a.value:.2f} {self._text_b.value:.2f} {self._text_c.value:.2f} {self._text_alpha.value:.2f} {self._text_beta.value:.2f} {self._text_gamma.value:.2f}", - ) - - s = SampleShortInfo( - db_id=-1, - puck_name="", - dewar_name="", - sample_name=self._sample_name, - run_number=1, # can't be -1. So have defaulted to 1 for now. - pin=1, - aaredb_params=data_processing, - user=self._pgroup, - ) - self.sample_manual.emit(s) - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - self._pgroup = s.session.current_pgroup diff --git a/src/aare/gui/panels/monochromator_panel.py b/src/aare/gui/panels/monochromator_panel.py deleted file mode 100644 index 499ac290..00000000 --- a/src/aare/gui/panels/monochromator_panel.py +++ /dev/null @@ -1,142 +0,0 @@ -from aarecommon.config.beamline import mx_beamline -from aarecommon.models.beamline import MXBeamline -from aarecommon.models.models import DAQStatusModel -from PySide6.QtCore import Signal, Slot -from PySide6.QtWidgets import QDoubleSpinBox, QGridLayout, QLabel, QPushButton, QWidget - -from aare.gui.styles import THEME_SUNRISE, status_colors -from aare.gui.widgets.motor_move_group import SpinMoveState -from aare.gui.widgets.title_label import TitleLabel - -# TODO: placeholder range (was an arbitrary 1-30; nothing downstream validates — -# daq.change_energy forwards straight to bec) — confirm the real monochromator -# limits with the Beamline Scientist. Shared by both Set Energy rows. -# X10SA mono reaches 6-30 keV; others keep the placeholder until confirmed. -# in the 6124 planner it says 10 to 20 keV at PXII -ENERGY_MIN_KEV, ENERGY_MAX_KEV = (10.0, 20.0) if mx_beamline() == MXBeamline.X10SA else (4.0, 20.0) -# "arrived" window for the moving->neutral transition; per-hardware knob like -# MotorMoveGroup's tol (the mono never lands exactly on the setpoint) -ENERGY_AT_TARGET_TOL_KEV = 0.001 -ENERGY_RANGE_TIP = ( - f"Minimum: {ENERGY_MIN_KEV:.3f} keV\nMaximum: {ENERGY_MAX_KEV:.3f} keV\n" - "Range to be confirmed with Beamline Scientist" -) - - -class MonochromatorPanel(QWidget): - mono_pitch_scan = Signal() - change_energy = Signal(float) - open_shutter = Signal() - move_beam_to_box = Signal() - close_shutter = Signal() - - def __init__(self, parent=None): - super().__init__(parent) - - grid_layout = QGridLayout(self) - grid_layout.addWidget( - TitleLabel("Beamline setup", self, collapsible=True, default_collapsed=False), - 0, - 0, - 1, - 3, - ) - - self.mono_pitch_scan_button = QPushButton("Mono Pitch Rock and Go to Max", parent=self) - self.mono_pitch_scan_button.clicked.connect(self.mono_pitch_scan.emit) - grid_layout.addWidget(self.mono_pitch_scan_button, 1, 0, 1, 3) - - # Live readout above the setpoint, so "what is" and "what to set" - # stop sharing one ambiguous Energy row. Fed per DAQ tick. - grid_layout.addWidget(QLabel("Current energy / λ", parent=self), 2, 0) - self.current_energy_label = QLabel("—", parent=self) - grid_layout.addWidget(self.current_energy_label, 2, 1, 1, 2) - - # One row (label | value | button) instead of three — vertical space. - # Display in keV; the DAQ API stays in eV (converted on emit). - # Unit lives in the label, not as a spinbox suffix — the suffix ate - # field width and sat between the value and the +/- arrow. - grid_layout.addWidget(QLabel("Set Energy (keV)", parent=self), 3, 0) - - self.energy_spin = QDoubleSpinBox(parent=self) - self.energy_spin.setDecimals(3) - self.energy_spin.setRange(ENERGY_MIN_KEV, ENERGY_MAX_KEV) - self.energy_spin.setToolTip(ENERGY_RANGE_TIP) - self.energy_spin.setSingleStep(0.1) - self.energy_spin.setValue(12.0) - grid_layout.addWidget(self.energy_spin, 3, 1) - - self.change_energy_button = QPushButton("Change Energy", parent=self) - self.change_energy_button.clicked.connect(self._emit_change_energy) - grid_layout.addWidget(self.change_energy_button, 3, 2) - # MotorMoveGroup semantics for the button-gated spin: neutral tracks - # the readback, edit stages pending, click turns moving until arrival. - self._energy_state = SpinMoveState( - self.energy_spin, self.change_energy_button, tol=ENERGY_AT_TARGET_TOL_KEV, parent=self - ) - - # Fast shutter row: status left, Open/Close buttons right — same - # rich-text scheme as the status bar flag so the two readouts match. - # Colors are painted in code (set_theme), QSS can't reach the spans. - self._colors = status_colors(THEME_SUNRISE) - self._shutter_open: bool | None = None - self.shutter_status_label = QLabel("Fast Shutter: —", parent=self) - grid_layout.addWidget(self.shutter_status_label, 4, 0) - - self.open_shutter_button = QPushButton("Open", parent=self) - self.open_shutter_button.clicked.connect(self.open_shutter.emit) - grid_layout.addWidget(self.open_shutter_button, 4, 1) - - self.close_shutter_button = QPushButton("Close", parent=self) - self.close_shutter_button.clicked.connect(self.close_shutter.emit) - grid_layout.addWidget(self.close_shutter_button, 4, 2) - - self.move_beam_to_box_button = QPushButton("Move Beam to Box", parent=self) - self.move_beam_to_box_button.clicked.connect(self.move_beam_to_box.emit) - self._move_beam_tooltip = "Adjust VFM and HFM motors to stear the beam." - self.set_beam_to_box_button_state(False, self._move_beam_tooltip) - grid_layout.addWidget(self.move_beam_to_box_button, 5, 0, 1, 3) - - @Slot(bool) - def update_beam_steering_available(self, enabled: bool): - msg = self._move_beam_tooltip if enabled else "Beam steering unavailable." - self.set_beam_to_box_button_state(enabled, msg) - - def set_beam_to_box_button_state(self, enabled: bool, tooltip: str): - self.move_beam_to_box_button.setEnabled(enabled) - self.move_beam_to_box_button.setToolTip(tooltip) - - def set_theme(self, theme: str) -> None: - """Adopt the theme's flag colors and re-render the shutter status.""" - self._colors = status_colors(theme) - self._render_shutter() - - def _render_shutter(self) -> None: - if self._shutter_open is None: - text = "Fast Shutter: —" - elif self._shutter_open: - text = ( - f"""Fast Shutter: Open ☢️ """ - ) - else: - text = ( - f"""Fast Shutter: Closed 🚪 """ - ) - if self.shutter_status_label.text() != text: - self.shutter_status_label.setText(text) - - @Slot() - def _emit_change_energy(self): - self.change_energy.emit(float(self.energy_spin.value()) * 1000.0) - - @Slot(DAQStatusModel) - def update_daq_status(self, status: DAQStatusModel): - energy = status.diffraction.energy_keV - text = f"{energy:.3f} keV / {status.diffraction.wavelength_angstrom:.4f} Å" - self._energy_state.update_actual(energy) - # Guarded: runs per DAQ tick (2 Hz), skip the repaint when unchanged. - if self.current_energy_label.text() != text: - self.current_energy_label.setText(text) - - self._shutter_open = bool(status.bl.shutter_open) - self._render_shutter() diff --git a/src/aare/gui/panels/omega_panel.py b/src/aare/gui/panels/omega_panel.py deleted file mode 100644 index 8f7aee08..00000000 --- a/src/aare/gui/panels/omega_panel.py +++ /dev/null @@ -1,74 +0,0 @@ -from aarecommon.models.models import DAQStatusModel -from PySide6.QtCore import Signal, Slot -from PySide6.QtWidgets import QGridLayout, QHBoxLayout, QLabel, QWidget - -from aare.gui.widgets.button_with_payload import ButtonWithPayload -from aare.gui.widgets.number_line_edit import NumberLineEdit -from aare.gui.widgets.title_label import TitleLabel - - -class OmegaEntryWidget(QWidget): - def __init__(self, parent=None): - super().__init__(parent) - h_layout = QHBoxLayout(self) - h_layout.setContentsMargins(0, 0, 0, 0) - - self.edit = NumberLineEdit(-720, 720, 0, parent=self) - h_layout.addWidget(self.edit) - h_layout.addWidget(QLabel("°", parent=self)) - h_layout.addStretch() - - -class OmegaPanel(QWidget): - set_omega = Signal(float) - set_omega_rel = Signal(float) - - def __init__(self, parent=None): - super().__init__(parent) - self._omega = 0 - - grid_layout = QGridLayout(self) - - grid_layout.addWidget( - TitleLabel("Omega", self, collapsible=True, default_collapsed=False), 0, 0, 1, 2 - ) - grid_layout.setColumnStretch(0, 1) - grid_layout.setColumnStretch(1, 1) - omega_settings = [ - {"name": "Go to 0°", "payload": {"abs": 0.0}}, - {"name": "-10°", "payload": {"rel": -10.0}}, - {"name": "+10°", "payload": {"rel": 10.0}}, - {"name": "-45°", "payload": {"rel": -45.0}}, - {"name": "+45°", "payload": {"rel": 45.0}}, - {"name": "-90°", "payload": {"rel": -90.0}}, - {"name": "+90°", "payload": {"rel": 90.0}}, - {"name": "-180°", "payload": {"rel": -180.0}}, - {"name": "+180°", "payload": {"rel": 180.0}}, - ] - - self.edit = OmegaEntryWidget(self) - self.edit.edit.newValue.connect(self.omega_value_entered) - grid_layout.addWidget(self.edit, 1, 0) - - i = 1 - for x in omega_settings: - button = ButtonWithPayload(x["name"], x["payload"], parent=self) - grid_layout.addWidget(button, int(i / 2 + 1), int(i % 2)) - i += 1 - button.pressed.connect(self.omega_button_pressed) - - @Slot(dict) - def omega_button_pressed(self, payload: dict): - if "rel" in payload: - self.set_omega_rel.emit(payload["rel"]) - elif "abs" in payload: - self.set_omega.emit(payload["abs"]) - - @Slot(float) - def omega_value_entered(self, f: float): - self.set_omega.emit(f) - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - self.edit.edit.update_value(s.geom.omega_deg) - self._omega = s.geom.omega_deg diff --git a/src/aare/gui/panels/prediction_metrics_panel.py b/src/aare/gui/panels/prediction_metrics_panel.py deleted file mode 100644 index 7302ea30..00000000 --- a/src/aare/gui/panels/prediction_metrics_panel.py +++ /dev/null @@ -1,816 +0,0 @@ -""" -Prediction Metrics Panel - Real-time feedback on ML prediction stream. - -Displays: -- Confidence histogram distribution -- Object counts by class -- Frame timing / FPS -- Rolling statistics over time -- Optional ground-truth comparison (IoU, FP/FN tracking) -""" - -import csv -import time -from collections import deque -from dataclasses import dataclass, field -from typing import ClassVar - -from aarecommon.config.logger import setup_logger -from aarecommon.models.models import MLBoxType -from PySide6.QtCharts import ( - QBarCategoryAxis, - QBarSeries, - QBarSet, - QChart, - QChartView, - QLineSeries, - QValueAxis, -) -from PySide6.QtCore import Qt, QTimer, Slot -from PySide6.QtGui import QColor, QPainter, QPen -from PySide6.QtWidgets import ( - QFileDialog, - QGridLayout, - QGroupBox, - QHBoxLayout, - QLabel, - QPushButton, - QSpinBox, - QSplitter, - QVBoxLayout, - QWidget, -) - -from aare.gui.constants import LOGGER_NAME -from aare.gui.styles import ( - CHART_BLUE, - CHART_GREEN, - CHART_MUTED, - CHART_ORANGE, - CHART_RED, - CONFIDENCE_BIN_COLORS, - FONT_BODY, - FONT_TITLE, - qcolor, -) -from aare.gui.styles import CHART_CLASS_COLORS as CLASS_COLORS - -logger = setup_logger(LOGGER_NAME) - - -# ───────────────────────────────────────────────────────────────────────────── -# Data Models -# ───────────────────────────────────────────────────────────────────────────── - - -@dataclass -class PredictionFrame: - """Single frame of prediction data.""" - - timestamp: float - boxes: list[dict] = field(default_factory=list) - frame_time_ms: float = 0.0 - class_counts: dict[str, int] = field(default_factory=dict) - confidences: list[float] = field(default_factory=list) - mean_confidence: float = 0.0 - max_confidence: float = 0.0 - - -@dataclass -class GroundTruthComparison: - """Comparison result against ground truth.""" - - iou_scores: list[float] = field(default_factory=list) - false_positives: int = 0 - false_negatives: int = 0 - misclassifications: list[dict] = field(default_factory=list) - - -# ───────────────────────────────────────────────────────────────────────────── -# Class Name Utilities -# ───────────────────────────────────────────────────────────────────────────── - - -def get_class_name(cls_id: int) -> str: - """Convert class ID to human-readable name.""" - try: - return MLBoxType(cls_id).name - except (ValueError, KeyError): - return f"Class_{cls_id}" - - -def get_class_color(class_name: str) -> str: - """Get color for a class name (matches bounding box colors).""" - return CLASS_COLORS.get(class_name, CHART_MUTED) - - -# ───────────────────────────────────────────────────────────────────────────── -# Confidence Histogram Widget -# ───────────────────────────────────────────────────────────────────────────── - - -class ConfidenceHistogramWidget(QWidget): - """Real-time histogram of prediction confidence scores.""" - - BINS: ClassVar[list[float]] = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0] - BIN_COLORS: ClassVar[list[str]] = CONFIDENCE_BIN_COLORS - - def __init__(self, parent=None): - super().__init__(parent) - self._setup_ui() - - def _setup_ui(self): - layout = QVBoxLayout(self) - layout.setContentsMargins(0, 0, 0, 0) - - self.bar_set = QBarSet("Detections") - self.bar_set.append([0] * (len(self.BINS) - 1)) - - # Color each bar by confidence level - for i, color in enumerate(self.BIN_COLORS): - self.bar_set.setColor(QColor(color)) - - series = QBarSeries() - series.append(self.bar_set) - series.setBarWidth(0.8) - - self.chart = QChart() - self.chart.addSeries(series) - self.chart.setTitle("Confidence Distribution") - self.chart.setAnimationOptions(QChart.AnimationOption.NoAnimation) - self.chart.legend().setVisible(False) - - categories = [ - f"{self.BINS[i]:.1f}-{self.BINS[i + 1]:.1f}" for i in range(len(self.BINS) - 1) - ] - self.axis_x = QBarCategoryAxis() - self.axis_x.append(categories) - self.chart.addAxis(self.axis_x, Qt.AlignmentFlag.AlignBottom) - series.attachAxis(self.axis_x) - - self.axis_y = QValueAxis() - self.axis_y.setRange(0, 10) - self.axis_y.setTitleText("Count") - self.axis_y.setLabelFormat("%d") - self.chart.addAxis(self.axis_y, Qt.AlignmentFlag.AlignLeft) - series.attachAxis(self.axis_y) - - chart_view = QChartView(self.chart) - chart_view.setRenderHint(QPainter.RenderHint.Antialiasing) - chart_view.setMinimumHeight(200) - - layout.addWidget(chart_view) - - def update_histogram(self, confidences: list[float]): - """Update histogram from list of confidence values.""" - counts = [0] * (len(self.BINS) - 1) - - for conf in confidences: - for i in range(len(self.BINS) - 1): - if self.BINS[i] <= conf < self.BINS[i + 1]: - counts[i] += 1 - break - # Handle conf == 1.0 edge case - if conf >= 1.0: - counts[-1] += 1 - - for i, count in enumerate(counts): - self.bar_set.replace(i, count) - - # Auto-scale Y axis - max_count = max(counts) if counts else 1 - self.axis_y.setRange(0, max(10, max_count + 2)) - - -# ───────────────────────────────────────────────────────────────────────────── -# Object Count Widget -# ───────────────────────────────────────────────────────────────────────────── - - -class ObjectCountWidget(QWidget): - """Displays real-time object counts by class with colored labels matching bounding boxes.""" - - def __init__(self, parent=None): - super().__init__(parent) - self._class_labels: dict[str, QLabel] = {} - self._setup_ui() - - def _setup_ui(self): - layout = QVBoxLayout(self) - layout.setContentsMargins(0, 0, 0, 0) - - group = QGroupBox("Object Counts") - self._grid = QGridLayout(group) - self._grid.setSpacing(8) - - # Pre-create labels for known classes with matching bounding box colors - known_classes = ["Crystal", "Loop_face", "Loop_all", "Pin", "Ice", "Needle"] - for i, cls_name in enumerate(known_classes): - color = get_class_color(cls_name) - - # Create colored indicator square - indicator = QLabel("■") - indicator.setStyleSheet(f"color: {color}; font-size: {FONT_TITLE};") - indicator.setFixedWidth(20) - - # Class name label - name_label = QLabel(f"{cls_name}:") - name_label.setStyleSheet("font-weight: bold;") - - # Count label with matching color - count_label = QLabel("0") - count_label.setStyleSheet(f"color: {color}; font-size: {FONT_BODY}; font-weight: bold;") - count_label.setAlignment(Qt.AlignmentFlag.AlignRight) - - row = i // 2 - col = (i % 2) * 3 - - self._grid.addWidget(indicator, row, col) - self._grid.addWidget(name_label, row, col + 1) - self._grid.addWidget(count_label, row, col + 2) - self._class_labels[cls_name] = count_label - - layout.addWidget(group) - - def update_counts(self, class_counts: dict[str, int]): - """Update displayed counts.""" - # Reset all to 0 first - for label in self._class_labels.values(): - label.setText("0") - - # Update with actual counts - for cls_name, count in class_counts.items(): - if cls_name in self._class_labels: - self._class_labels[cls_name].setText(str(count)) - - -# ───────────────────────────────────────────────────────────────────────────── -# Timing Stats Widget -# ───────────────────────────────────────────────────────────────────────────── - - -class TimingStatsWidget(QWidget): - """Displays frame timing, FPS, and processing latency.""" - - def __init__(self, parent=None): - super().__init__(parent) - self._setup_ui() - - def _setup_ui(self): - layout = QVBoxLayout(self) - layout.setContentsMargins(0, 0, 0, 0) - - group = QGroupBox("Timing") - grid = QGridLayout(group) - - # Frame time - grid.addWidget(QLabel("Frame time:"), 0, 0) - self.frame_time_label = QLabel("- ms") - self.frame_time_label.setStyleSheet("font-weight: bold;") - grid.addWidget(self.frame_time_label, 0, 1) - - # FPS - grid.addWidget(QLabel("FPS:"), 0, 2) - self.fps_label = QLabel("-") - self.fps_label.setStyleSheet("font-weight: bold;") - grid.addWidget(self.fps_label, 0, 3) - - # Detection count - grid.addWidget(QLabel("Detections:"), 1, 0) - self.detection_count_label = QLabel("0") - self.detection_count_label.setStyleSheet("font-weight: bold;") - grid.addWidget(self.detection_count_label, 1, 1) - - # Mean confidence - grid.addWidget(QLabel("Mean conf:"), 1, 2) - self.mean_conf_label = QLabel("-") - self.mean_conf_label.setStyleSheet("font-weight: bold;") - grid.addWidget(self.mean_conf_label, 1, 3) - - layout.addWidget(group) - - def update_stats( - self, frame_time_ms: float, fps: float, detection_count: int, mean_confidence: float - ): - """Update timing statistics display.""" - self.frame_time_label.setText(f"{frame_time_ms:.1f} ms") - self.fps_label.setText(f"{fps:.1f}") - self.detection_count_label.setText(str(detection_count)) - - if mean_confidence > 0: - self.mean_conf_label.setText(f"{mean_confidence:.2f}") - else: - self.mean_conf_label.setText("-") - - -# ───────────────────────────────────────────────────────────────────────────── -# Error Tracking Widget -# ───────────────────────────────────────────────────────────────────────────── - - -class ErrorTrackingWidget(QWidget): - """ - Tracks and displays error metrics. - - Note: FP/FN tracking requires ground truth data to be meaningful. - Without ground truth, this shows detection statistics instead. - """ - - def __init__(self, parent=None): - super().__init__(parent) - self._false_positives = 0 - self._false_negatives = 0 - self._empty_frame_count = 0 - self._total_frames = 0 - self._low_confidence_count = 0 - self._confidence_threshold = 0.5 - self._setup_ui() - - def _setup_ui(self): - layout = QVBoxLayout(self) - layout.setContentsMargins(0, 0, 0, 0) - - group = QGroupBox("Detection Quality") - grid = QGridLayout(group) - - # Empty frames (no detections) - grid.addWidget(QLabel("Empty frames:"), 0, 0) - self.empty_frames_label = QLabel("0") - self.empty_frames_label.setStyleSheet(f"color: {CHART_RED}; font-weight: bold;") - grid.addWidget(self.empty_frames_label, 0, 1) - - # Low confidence detections - grid.addWidget(QLabel("Low conf (<0.5):"), 0, 2) - self.low_conf_label = QLabel("0") - self.low_conf_label.setStyleSheet(f"color: {CHART_ORANGE}; font-weight: bold;") - grid.addWidget(self.low_conf_label, 0, 3) - - # Detection rate - grid.addWidget(QLabel("Detection rate:"), 1, 0) - self.detection_rate_label = QLabel("-") - self.detection_rate_label.setStyleSheet(f"color: {CHART_GREEN}; font-weight: bold;") - grid.addWidget(self.detection_rate_label, 1, 1) - - # Reset button - self.reset_button = QPushButton("Reset") - self.reset_button.clicked.connect(self.reset_counters) - grid.addWidget(self.reset_button, 1, 3) - - layout.addWidget(group) - - def update_from_frame(self, frame: PredictionFrame): - """Update error tracking from a prediction frame.""" - self._total_frames += 1 - - if not frame.boxes: - self._empty_frame_count += 1 - - for conf in frame.confidences: - if conf < self._confidence_threshold: - self._low_confidence_count += 1 - - self._update_display() - - def _update_display(self): - self.empty_frames_label.setText(str(self._empty_frame_count)) - self.low_conf_label.setText(str(self._low_confidence_count)) - - if self._total_frames > 0: - rate = (self._total_frames - self._empty_frame_count) / self._total_frames - self.detection_rate_label.setText(f"{rate * 100:.1f}%") - else: - self.detection_rate_label.setText("-") - - def reset_counters(self): - """Reset all counters.""" - self._false_positives = 0 - self._false_negatives = 0 - self._empty_frame_count = 0 - self._total_frames = 0 - self._low_confidence_count = 0 - self._update_display() - - -# ───────────────────────────────────────────────────────────────────────────── -# Rolling Statistics Chart -# ───────────────────────────────────────────────────────────────────────────── - - -class RollingStatsChart(QWidget): - """Time-series chart showing rolling detection statistics.""" - - def __init__(self, window_seconds: float = 60.0, parent=None): - super().__init__(parent) - self._window_s = window_seconds - self._data: deque[PredictionFrame] = deque(maxlen=1000) - self._setup_ui() - - def _setup_ui(self): - layout = QVBoxLayout(self) - layout.setContentsMargins(0, 0, 0, 0) - - # Detection count series (left Y axis) - self.count_series = QLineSeries() - self.count_series.setName("Detections") - self.count_series.setPen(QPen(qcolor(CHART_BLUE), 2)) - - # Mean confidence series (right Y axis) - self.conf_series = QLineSeries() - self.conf_series.setName("Mean Confidence") - self.conf_series.setPen(QPen(qcolor(CHART_GREEN), 2)) - - self.chart = QChart() - self.chart.addSeries(self.count_series) - self.chart.addSeries(self.conf_series) - self.chart.setTitle("Rolling Statistics") - self.chart.setAnimationOptions(QChart.AnimationOption.NoAnimation) - self.chart.legend().setVisible(True) - - # Time axis - self.axis_x = QValueAxis() - self.axis_x.setTitleText("Time [s ago]") - self.axis_x.setRange(-self._window_s, 0) - self.chart.addAxis(self.axis_x, Qt.AlignmentFlag.AlignBottom) - - # Left Y axis for detection counts - self.axis_y_count = QValueAxis() - self.axis_y_count.setTitleText("Detections") - self.axis_y_count.setRange(0, 20) - self.chart.addAxis(self.axis_y_count, Qt.AlignmentFlag.AlignLeft) - - # Right Y axis for confidence (0-1 scale) - self.axis_y_conf = QValueAxis() - self.axis_y_conf.setTitleText("Confidence") - self.axis_y_conf.setRange(0, 1) - self.chart.addAxis(self.axis_y_conf, Qt.AlignmentFlag.AlignRight) - - # Attach series to axes - self.count_series.attachAxis(self.axis_x) - self.count_series.attachAxis(self.axis_y_count) - - self.conf_series.attachAxis(self.axis_x) - self.conf_series.attachAxis(self.axis_y_conf) - - chart_view = QChartView(self.chart) - chart_view.setRenderHint(QPainter.RenderHint.Antialiasing) - chart_view.setMinimumHeight(250) - - layout.addWidget(chart_view) - - def add_frame(self, frame: PredictionFrame): - """Add a prediction frame to the rolling data.""" - self._data.append(frame) - self._trim_old_data(frame.timestamp) - - def _trim_old_data(self, now: float): - """Remove data older than the window.""" - cutoff = now - self._window_s - while self._data and self._data[0].timestamp < cutoff: - self._data.popleft() - - def refresh(self): - """Refresh the chart display using bulk operations.""" - if not self._data: - return - - from PySide6.QtCore import QPointF - - now = self._data[-1].timestamp - - count_points = [] - conf_points = [] - - for frame in self._data: - t = frame.timestamp - now - count_points.append(QPointF(t, len(frame.boxes))) - conf_points.append(QPointF(t, frame.mean_confidence)) - - # Bulk replace for performance - self.count_series.replace(count_points) - self.conf_series.replace(conf_points) - - # Auto-scale detection count axis - if count_points: - max_count = max((p.y() for p in count_points), default=0) - self.axis_y_count.setRange(0, max(10, max_count + 2)) - - -# ───────────────────────────────────────────────────────────────────────────── -# Main Panel -# ───────────────────────────────────────────────────────────────────────────── - - -class PredictionMetricsPanel(QWidget): - """ - Comprehensive panel for real-time ML prediction feedback. - - Connect to PredictionSubscriber.prediction signal: - prediction_subscriber.prediction.connect(panel.update_from_prediction) - """ - - def __init__(self, parent=None): - super().__init__(parent) - self._last_frame_ts: float | None = None - self._frame_times: deque[float] = deque(maxlen=30) - self._history: deque[PredictionFrame] = deque(maxlen=1500) - self._paused = False - - self._track_only_when_visible = True - self._input_min_interval_s = 0.20 - self._last_input_ts = 0.0 - self._dirty = False - - self._setup_ui() - self._setup_refresh_timer() - - def _setup_ui(self): - layout = QVBoxLayout(self) - - # ─── Top Controls ─── - controls = QHBoxLayout() - - self.pause_button = QPushButton("Pause") - self.pause_button.setCheckable(True) - self.pause_button.toggled.connect(self._set_paused) - controls.addWidget(self.pause_button) - - self.export_button = QPushButton("Export CSV") - self.export_button.clicked.connect(self._export_csv) - controls.addWidget(self.export_button) - - self.clear_button = QPushButton("Clear History") - self.clear_button.clicked.connect(self._clear_history) - controls.addWidget(self.clear_button) - - controls.addSpacing(20) - - controls.addWidget(QLabel("Rolling window:")) - self.window_spin = QSpinBox() - self.window_spin.setRange(10, 300) - self.window_spin.setValue(60) - self.window_spin.setSuffix(" s") - self.window_spin.valueChanged.connect(self._update_window) - controls.addWidget(self.window_spin) - - controls.addStretch() - - self.status_label = QLabel("Waiting for predictions...") - self.status_label.setStyleSheet(f"color: {CHART_MUTED};") - controls.addWidget(self.status_label) - - layout.addLayout(controls) - - # ─── Main Content with Splitter ─── - splitter = QSplitter(Qt.Orientation.Vertical) - - # Top section: stats widgets - top_widget = QWidget() - top_layout = QHBoxLayout(top_widget) - top_layout.setContentsMargins(0, 0, 0, 0) - - # Left column - left_col = QVBoxLayout() - self.histogram = ConfidenceHistogramWidget() - left_col.addWidget(self.histogram) - - self.object_counts = ObjectCountWidget() - left_col.addWidget(self.object_counts) - - top_layout.addLayout(left_col, stretch=1) - - # Right column - right_col = QVBoxLayout() - self.timing_stats = TimingStatsWidget() - right_col.addWidget(self.timing_stats) - - self.error_tracking = ErrorTrackingWidget() - right_col.addWidget(self.error_tracking) - - right_col.addStretch() - top_layout.addLayout(right_col, stretch=1) - - splitter.addWidget(top_widget) - - # Bottom section: rolling chart - self.rolling_chart = RollingStatsChart(window_seconds=60.0) - splitter.addWidget(self.rolling_chart) - - splitter.setSizes([300, 300]) - layout.addWidget(splitter) - - def _setup_refresh_timer(self): - """Setup timer to refresh charts periodically.""" - self._refresh_timer = QTimer(self) - self._refresh_timer.setInterval(500) # Reduce to 2 Hz (was 4 Hz) - self._refresh_timer.timeout.connect(self._refresh_display) - self._refresh_timer.start() - - # Separate slower timer for the expensive rolling chart - self._chart_refresh_timer = QTimer(self) - self._chart_refresh_timer.setInterval(1000) # 1 Hz for heavy chart - self._chart_refresh_timer.timeout.connect(self.rolling_chart.refresh) - self._chart_refresh_timer.start() - - def _set_paused(self, paused: bool): - """Pause/resume updates.""" - self._paused = paused - self.pause_button.setText("Resume" if paused else "Pause") - self._update_status() - - def _update_window(self, seconds: int): - """Update rolling window size.""" - self.rolling_chart._window_s = float(seconds) - - def _clear_history(self): - """Clear all historical data.""" - self._history.clear() - self._frame_times.clear() - self._last_frame_ts = None - self.error_tracking.reset_counters() - self.rolling_chart._data.clear() - self._refresh_display() - - def _update_status(self): - """Update status label.""" - if self._paused: - self.status_label.setText("Paused") - self.status_label.setStyleSheet(f"color: {CHART_ORANGE};") - elif self._history: - count = len(self._history) - self.status_label.setText(f"Live: {count} frames recorded") - self.status_label.setStyleSheet(f"color: {CHART_GREEN};") - else: - self.status_label.setText("Waiting for predictions...") - self.status_label.setStyleSheet(f"color: {CHART_MUTED};") - - def showEvent(self, event) -> None: - super().showEvent(event) - if self._refresh_timer is not None and not self._refresh_timer.isActive(): - self._refresh_timer.start() - if self._chart_refresh_timer is not None and not self._chart_refresh_timer.isActive(): - self._chart_refresh_timer.start() - self._dirty = True - - def hideEvent(self, event) -> None: - super().hideEvent(event) - if self._track_only_when_visible: - if self._refresh_timer is not None: - self._refresh_timer.stop() - if self._chart_refresh_timer is not None: - self._chart_refresh_timer.stop() - - @Slot(dict) - def update_from_prediction(self, payload: dict): - """ - Update panel from prediction payload. - - Expected payload format: - { - "boxes": [ - {"cls": 0, "conf": 0.95, "x1": 100, "y1": 100, "x2": 200, "y2": 200}, - ... - ], - "frame_id": 12345, # optional - "time": 1234567890.123 # optional - } - """ - if self._paused: - return - - if self._track_only_when_visible and not self.isVisible(): - return - - now = time.monotonic() - if (now - self._last_input_ts) < self._input_min_interval_s: - return - - # Calculate frame time - frame_time_ms = 0.0 - if self._last_frame_ts is not None: - frame_time_ms = (now - self._last_frame_ts) * 1000 - self._frame_times.append(frame_time_ms) - self._last_frame_ts = now - - # Parse boxes - boxes = payload.get("boxes", []) - - # Handle both list and dict box formats - if isinstance(boxes, dict): - boxes = list(boxes.values()) - - # Extract data - class_counts: dict[str, int] = {} - confidences: list[float] = [] - - for box in boxes: - if isinstance(box, dict): - cls_id = box.get("cls", box.get("class", -1)) - conf = box.get("conf", box.get("confidence", 0.0)) - else: - cls_id = getattr(box, "cls", -1) - conf = getattr(box, "conf", 0.0) - if hasattr(cls_id, "value"): - cls_id = cls_id.value - - cls_name = get_class_name(int(cls_id)) - class_counts[cls_name] = class_counts.get(cls_name, 0) + 1 - confidences.append(float(conf)) - - mean_conf = sum(confidences) / len(confidences) if confidences else 0.0 - max_conf = max(confidences) if confidences else 0.0 - - frame = PredictionFrame( - timestamp=now, - boxes=boxes, - frame_time_ms=frame_time_ms, - class_counts=class_counts, - confidences=confidences, - mean_confidence=mean_conf, - max_confidence=max_conf, - ) - - self._history.append(frame) - self.rolling_chart.add_frame(frame) - self.error_tracking.update_from_frame(frame) - - self._dirty = True - - def _refresh_display(self): - """Refresh all display components except rolling chart.""" - if not self._history: - return - if not self._dirty and self.isVisible(): - return - - latest = self._history[-1] - - # Update histogram - self.histogram.update_histogram(latest.confidences) - - # Update object counts - self.object_counts.update_counts(latest.class_counts) - - # Update timing stats - avg_frame_time = ( - sum(self._frame_times) / len(self._frame_times) if self._frame_times else 0.0 - ) - fps = 1000.0 / avg_frame_time if avg_frame_time > 0 else 0.0 - - self.timing_stats.update_stats( - frame_time_ms=avg_frame_time, - fps=fps, - detection_count=len(latest.boxes), - mean_confidence=latest.mean_confidence, - ) - - self._update_status() - self._dirty = False - - def _export_csv(self): - """Export history to CSV file.""" - if not self._history: - logger.info("No prediction history to export") - return - - path, _ = QFileDialog.getSaveFileName( - self, "Export Prediction Metrics", "prediction_metrics.csv", "CSV files (*.csv)" - ) - if not path: - return - - try: - with open(path, "w", newline="") as f: - writer = csv.writer(f) - writer.writerow( - [ - "timestamp", - "frame_time_ms", - "detection_count", - "mean_confidence", - "max_confidence", - "crystal_count", - "loop_face_count", - "loop_all_count", - "pin_count", - ] - ) - - for frame in self._history: - writer.writerow( - [ - f"{frame.timestamp:.6f}", - f"{frame.frame_time_ms:.2f}", - len(frame.boxes), - f"{frame.mean_confidence:.4f}", - f"{frame.max_confidence:.4f}", - frame.class_counts.get("Crystal", 0), - frame.class_counts.get("Loop_face", 0), - frame.class_counts.get("Loop_all", 0), - frame.class_counts.get("Pin", 0), - ] - ) - - logger.info(f"Exported {len(self._history)} frames to {path}") - - except Exception: - logger.exception("Failed to export prediction metrics") diff --git a/src/aare/gui/panels/raster_data_collection.py b/src/aare/gui/panels/raster_data_collection.py deleted file mode 100644 index 9aee838a..00000000 --- a/src/aare/gui/panels/raster_data_collection.py +++ /dev/null @@ -1,205 +0,0 @@ -from aarecommon.config.logger import setup_logger -from aarecommon.math.diffraction_geometry import DiffractionGeometry -from aarecommon.models.models import BeamlineStateEnum -from PySide6.QtCore import Qt, Signal, Slot -from PySide6.QtWidgets import QComboBox, QLabel, QMessageBox, QPushButton, QSlider - -from aare.gui.constants import LOGGER_NAME -from aare.gui.panels.scan_settings_panel import ScanSettingsPanel -from aare.gui.scan_logic.raster_grid_manager import RasterGridManager, RasterGridMetric -from aare.gui.styles import ABORT_TEXT, GO_TEXT -from aare.gui.widgets.number_line_edit import NumberLineEdit -from aare.gui.widgets.raster_grid_table import RasterGridTable - -logger = setup_logger(LOGGER_NAME) - - -# TODO prevent raster if no grid, or at least rpevent smargon from doing danngerous move to 0,0,0!!! -class RasterDataCollectionPanel(ScanSettingsPanel): - grid_size_updated = Signal(float, float) - exp_time_updated = Signal(float) - evaluate_grid = Signal() - evaluate_grid_auto = Signal() - grid_metric_updated = Signal(RasterGridMetric) - raster_alpha_changed = Signal(int) - - def __init__( - self, raster_mgr: RasterGridManager, diffraction: DiffractionGeometry, parent=None - ): - super().__init__( - diffraction=diffraction, - default_dtz=raster_mgr.active_grid.dtz, - default_transmission=raster_mgr.active_grid.transmission, - # Plain "Transmission": the tab IS the gridscan, and the longer - # "Gridscan transmission" clips in the label column. - transmission_label="Transmission", - parent=parent, - ) - - self._default_exp_time = raster_mgr.active_grid.exp_time_s - # Image time typed in by the user; None means "follow the sample". - self._user_exp_time: float | None = None - - self._n_x = raster_mgr.active_grid.n_x - self._n_y = raster_mgr.active_grid.n_y - self._size_x = raster_mgr.active_grid.grid_size_mm.x * 1000.0 - self._size_y = raster_mgr.active_grid.grid_size_mm.y * 1000.0 - self._total_time = self._default_exp_time * self._n_x * self._n_y - - # Grid element size: the drawn grid decides it, the user can ask for a - # different one. It has no spreadsheet counterpart, so it stays outside - # the Database/User toggle. - self.width_enter = NumberLineEdit( - 5, 100, self._size_x, decimals=0, parent=self, track_pending=True - ) - self.height_enter = NumberLineEdit( - 5, 100, self._size_y, decimals=0, parent=self, track_pending=True - ) - self._add_pair_row(3, "Grid element size", self.width_enter, self.height_enter, "μm") - for field in (self.width_enter, self.height_enter): - field.newValue.connect(self._on_element_size_committed) - self._add_field(field) - - self.image_time_enter = NumberLineEdit( - 0.0005, 10.0, self._default_exp_time, decimals=4, parent=self, track_pending=True - ) - self._add_row(4, "Image time", self.image_time_enter, "s") - self._add_database_field(self.image_time_enter, self._on_exp_time_committed) - - self.n_x_label = QLabel("-", parent=self) - self.n_y_label = QLabel("-", parent=self) - self._add_pair_row(5, "Grid elements", self.n_x_label, self.n_y_label) - - self.size_x_label = QLabel("-", parent=self) - self.size_y_label = QLabel("-", parent=self) - self._add_pair_row(6, "Grid size", self.size_x_label, self.size_y_label, "μm") - - self.metric_combo = QComboBox() - self.metric_combo.addItem("Raster score", RasterGridMetric.RASTER_SCORE) - self.metric_combo.addItem("Spot count (low res.)", RasterGridMetric.SPOTS_LOW_RES) - self.metric_combo.addItem("Spot count", RasterGridMetric.SPOTS) - self.metric_combo.addItem("Spot count (indexed)", RasterGridMetric.SPOTS_INDEXED) - self.metric_combo.addItem("Spot count (ice)", RasterGridMetric.SPOTS_ICE) - self.metric_combo.addItem("Spot ratio (ice/low res.)", RasterGridMetric.SPOTS_ICE_LOW_RES) - self.metric_combo.addItem("Background estimate", RasterGridMetric.BKG) - self.metric_combo.addItem("Indexing result", RasterGridMetric.INDEXING) - self.metric_combo.addItem("Profile Radius", RasterGridMetric.PR) - self.metric_combo.addItem("B-factor", RasterGridMetric.BFACTOR) - self.metric_combo.addItem("Resolution (ML est.)", RasterGridMetric.RES) - - self.metric_combo.setCurrentIndex(self.metric_combo.findData(RasterGridMetric.RASTER_SCORE)) - self.metric_combo.currentIndexChanged.connect(self.metric_changed) - self._add_row(7, "Metric", self.metric_combo) - - slider = QSlider(orientation=Qt.Orientation.Horizontal, parent=self) - slider.setRange(0, 255) - slider.setValue(127) - slider.valueChanged.connect(lambda: self.raster_alpha_changed.emit(255 - slider.value())) - self._add_row(8, "Transparency", slider) - - self._table = RasterGridTable(raster_mgr) - self._layout.addWidget(self._table, 9, 0, 1, 5) - - self.total_time = QLabel(f"{self._total_time} min 0 s") - self._add_row(11, "Measurement time", self.total_time) - - self.start_button = QPushButton("Evaluate grid") - self.start_button.setStyleSheet(f"color: {GO_TEXT};") - self.start_button.clicked.connect(self._on_evaluate_clicked) - self._layout.addWidget(self.start_button, 12, 0, 1, 5) - - self.auto_button = QPushButton("X-ray Centering") - self.auto_button.setStyleSheet(f"color: {GO_TEXT};") - self.auto_button.clicked.connect(self._on_evaluate_auto_clicked) - self._layout.addWidget(self.auto_button, 13, 0, 1, 5) - - # Per-tab Abort (DataCollectionSettings wires it to the DAQ cancel). - self.abort_button = QPushButton("Abort measurement") - self.abort_button.setStyleSheet(f"color: {ABORT_TEXT};") - self._layout.addWidget(self.abort_button, 14, 0, 1, 5) - - # every field exists now: fill in the measurement time and the grid - self._values_changed() - self.update_grid_scan_size() - - # -- the panel's settings ---------------------------------------------- - @Slot(float) - def _on_exp_time_committed(self, value: float): - self._user_exp_time = value - self._user_took_over() - - def _write_active_values(self): - super()._write_active_values() - self.image_time_enter.set_committed_value( - self._setting(self._user_exp_time, self._db_params.exp_time_s, self._default_exp_time) - ) - - def _values_changed(self): - super()._values_changed() - self.exp_time_updated.emit(self.image_time_enter.committed_value) - self.calculate_total_time() - - # -- grid geometry ------------------------------------------------------ - @Slot(float) - def _on_element_size_committed(self, _value: float): - """The user asked for a different element size: the grid manager - recomputes how many elements fit and reports back to - grid_scan_size_change, which writes the size it settled on.""" - self._size_x = self.width_enter.committed_value - self._size_y = self.height_enter.committed_value - self.grid_size_updated.emit(self._size_x / 1000.0, self._size_y / 1000.0) - self.update_grid_scan_size() - - @Slot(int, int, float, float) - def grid_scan_size_change(self, n_x: int, n_y: int, size_x_mm: float, size_y_mm: float): - """The drawn grid changed (resized, or the beam size moved the default - element size).""" - self._size_x = size_x_mm * 1000.0 - self._size_y = size_y_mm * 1000.0 - self._n_x = n_x - self._n_y = n_y - self.update_grid_scan_size() - - def update_grid_scan_size(self): - self.width_enter.set_committed_value(self._size_x) - self.height_enter.set_committed_value(self._size_y) - self.n_x_label.setText(str(self._n_x)) - self.size_x_label.setText(f"{self._size_x * self._n_x:.1f}") - self.n_y_label.setText(str(self._n_y)) - self.size_y_label.setText(f"{self._size_y * self._n_y:.1f}") - self.calculate_total_time() - - def metric_changed(self, _: int): - self.grid_metric_updated.emit(self.metric_combo.currentData()) - - def calculate_total_time(self): - exp_time_s = self.image_time_enter.committed_value - if self._n_x <= 0 or self._n_y <= 0 or exp_time_s < 0: - self._total_time = 0.0 - else: - # 30% buffer added - self._total_time = self._n_x * self._n_y * exp_time_s * 1.3 - mins = int(self._total_time // 60) - secs = round(self._total_time % 60) - if secs == 60: - mins += 1 - secs = 0 - self.total_time.setText(f"{mins} min {secs} s") - - # -- running ------------------------------------------------------------ - def _ready_to_run(self) -> bool: - if self._beamline_state != BeamlineStateEnum.SampleAlignment: - logger.error(f"Beamline state {self._beamline_state} is not Sample Alignment") - QMessageBox.critical(None, "Error", "Beamline state is not Sample Alignment") - return False - return self.check_before_run(scan_kind="raster") - - @Slot() - def _on_evaluate_clicked(self): - if self._ready_to_run(): - self.evaluate_grid.emit() - - @Slot() - def _on_evaluate_auto_clicked(self): - if self._ready_to_run(): - self.evaluate_grid_auto.emit() diff --git a/src/aare/gui/panels/reference_tools_panel.py b/src/aare/gui/panels/reference_tools_panel.py deleted file mode 100644 index 6095a3ab..00000000 --- a/src/aare/gui/panels/reference_tools_panel.py +++ /dev/null @@ -1,299 +0,0 @@ -# reference_tools_panel.py - -from aarecommon.config.logger import setup_logger -from aarecommon.models.models import DAQStatusModel, SampleShortInfo, SampleShortInfoList -from PySide6.QtCore import QAbstractTableModel, QModelIndex, Qt, Signal, Slot -from PySide6.QtGui import QBrush -from PySide6.QtWidgets import QAbstractItemView, QFrame, QGridLayout, QHeaderView, QMenu, QTableView - -from aare.gui.constants import LOGGER_NAME -from aare.gui.styles import SAMPLE_ROW_QUEUED_BG, SAMPLE_STATUS_TEXT, qcolor -from aare.gui.widgets.title_label import TitleLabel - -logger = setup_logger(LOGGER_NAME) - - -def get_entry(sample: SampleShortInfo, column: int): - if column == 0: - return sample.loc_str() - elif column == 1: - return sample.sample_name - elif column == 2: - return sample.mount_count - # data() feeds this `header index - 1`: rotation/raster were cross-wired - # against the header, so "Raster count" showed rotation counts and vice - # versa. Order now matches the header (workflow order, same as the Dewar - # table): mount -> raster -> screening -> rotation. - elif column == 3: - return sample.raster_count - elif column == 4: - return sample.screening_count - elif column == 5: - return sample.rotation_count - return "" - - -class ReferenceToolsModel(QAbstractTableModel): - def __init__( - self, - rows: list[SampleShortInfo] | None = None, - parent=None, - current_reference: int | None = None, - ): - super().__init__(parent) - - self.samples: list[SampleShortInfo] = rows or [] - self.current_reference = current_reference - # Column 0 is display-only: the row position ("#"), matching the - # Dewar samples table; the vertical header is hidden in the panel. - self.header = [ - "#", - "Position", - "Sample name", - "Mount count", - "Raster count", - "Screening count", - "Rotation count", - ] - self._sort_col = 1 - self._sort_order = Qt.SortOrder.AscendingOrder - self._sorted_samples: list[SampleShortInfo] = [] - if self.samples: - self._sort() - else: - self._sorted_samples = [] - - def rowCount(self, parent: QModelIndex | None = None) -> int: - return len(self._sorted_samples) - - def columnCount(self, parent: QModelIndex | None = None) -> int: - return len(self.header) - - def data(self, index: QModelIndex, role=None): - if not index.isValid(): - return None - - if index.row() >= len(self._sorted_samples): - return None - - if role == Qt.ItemDataRole.DisplayRole: - if index.column() == 0: - return str(index.row() + 1) - return get_entry(self._sorted_samples[index.row()], index.column() - 1) - elif role == Qt.ItemDataRole.TextAlignmentRole: - return Qt.AlignmentFlag.AlignCenter - elif role == Qt.ItemDataRole.BackgroundRole: - # Tint only the current-reference row; plain rows return None so - # the theme QSS paints them (a hardcoded WHITE fill here was the - # big white table in dark mode and fought the light theme's - # alternating stripes). - if self._sorted_samples[index.row()].db_id == self.current_reference: - return QBrush(qcolor(SAMPLE_ROW_QUEUED_BG)) - elif ( - role == Qt.ItemDataRole.ForegroundRole - and self._sorted_samples[index.row()].db_id == self.current_reference - ): - # Fixed dark ink on the tint — the tint stays pale in BOTH themes, - # so the dark theme's near-white text would vanish on it. - return QBrush(qcolor(SAMPLE_STATUS_TEXT)) - - return None - - def headerData(self, section: int, orientation, role=None): - if role != Qt.ItemDataRole.DisplayRole: - return None - if orientation == Qt.Orientation.Horizontal: - return self.header[section] if section < len(self.header) else f"Column {section + 1}" - return str(section + 1) - - def update_rows(self, rows: list[SampleShortInfo]): - self.beginResetModel() - try: - self.samples = rows - if self.samples: # Only sort if we have samples - self._sort() - else: - self._sorted_samples = [] # Clear sorted samples if no data - finally: - self.endResetModel() - - def sort(self, column, order): - # The "#" column is display-only — nothing to sort by. - if column == 0: - return - self.layoutAboutToBeChanged.emit() - self._sort_order = order - self._sort_col = column - self._sort() - self.layoutChanged.emit() - - def _sort(self): - """Sort samples, using special handling for location column.""" - if not self.samples: - self._sorted_samples = [] - return - - if self._sort_col == 1: - # Special sorting for location (Position column) - self._sorted_samples = sorted( - self.samples, - key=lambda row: row.loc_str_sort(), - reverse=(self._sort_order == Qt.SortOrder.DescendingOrder), - ) - elif self._sort_col == 3: - # Numeric sort for Mount count; place None last on ascending, first on descending - none_sentinel = ( - float("inf") if self._sort_order == Qt.SortOrder.AscendingOrder else float("-inf") - ) - self._sorted_samples = sorted( - self.samples, - key=lambda row: ( - row.mount_count if isinstance(row.mount_count, (int, float)) else none_sentinel - ), - reverse=(self._sort_order == Qt.SortOrder.DescendingOrder), - ) - else: - # String sort with empty fallback (get_entry columns sit one left - # of the view columns because of the display-only "#"). - self._sorted_samples = sorted( - self.samples, - key=lambda row: get_entry(row, self._sort_col - 1) or "", - reverse=(self._sort_order == Qt.SortOrder.DescendingOrder), - ) - - def get_item(self, row: int) -> SampleShortInfo | None: - """Get sample at the given row index.""" - if 0 <= row < len(self._sorted_samples): - return self._sorted_samples[row] - return None - - def update_current_reference(self, reference_id: int | None): - """Update which sample is highlighted as current reference.""" - self.current_reference = reference_id - # Trigger repaint of background colors - if self.rowCount() > 0: - self.dataChanged.emit( - self.index(0, 0), - self.index(self.rowCount() - 1, self.columnCount() - 1), - [Qt.ItemDataRole.BackgroundRole, Qt.ItemDataRole.ForegroundRole], - ) - - -class ReferenceToolsPanel(QFrame): - mount = Signal(SampleShortInfo, bool) - unmount = Signal() - - def __init__( - self, - samples: SampleShortInfoList | None = None, - parent=None, - refresh_interval_ms: int = 5000, - model: ReferenceToolsModel | None = None, - ): - """ - :param samples: optional initial SampleShortInfoList to populate the table - :param parent: Qt parent - :param refresh_interval_ms: how often to call request_refresh (panel doesn't implement the request itself) - :param model: share an existing model instead of owning one (pop-out window) - """ - super().__init__(parent) - - if samples is None: - samples = SampleShortInfoList(s=[]) - - self.setFrameShape(QFrame.Shape.StyledPanel) - self.setFrameShadow(QFrame.Shadow.Raised) - - layout = QGridLayout(self) - self.setLayout(layout) - # Flush layout, matching TellSamplePanel: full-width banner, no - # padding ring, no gap to the dock's tab row. - layout.setContentsMargins(0, 0, 0, 0) - layout.setSpacing(0) - - layout.addWidget(TitleLabel("Reference tools", parent=self), 0, 0, 1, 4) - - self.table_view = QTableView(parent=self) - # Row colors carry the separation — no grid lines. Alternating rows - # come from the theme QSS (alternate-background-color), same as the - # Dewar sample list. - self.table_view.setShowGrid(False) - self.table_view.setAlternatingRowColors(True) - layout.addWidget(self.table_view, 1, 0, 1, 4) - - # initialize model with provided samples (or adopt the shared one) - self.table_model = model if model is not None else ReferenceToolsModel(rows=samples.s) - self.table_view.setModel(self.table_model) - - self.table_view.setEditTriggers(QTableView.EditTrigger.NoEditTriggers) - logger.debug("Setting up table header") - header = self.table_view.horizontalHeader() - logger.debug("Setting up table header") - header.setSectionResizeMode(QHeaderView.ResizeMode.Interactive) - logger.debug("Setting up table header") - header.setStretchLastSection(True) - # No bold column titles when cells are selected. - header.setHighlightSections(False) - # Row numbers live in the display-only "#" column (like the Dewar - # table), not the vertical header. - self.table_view.verticalHeader().setVisible(False) - logger.debug("Setting up table view sorting") - # Adopt the model's current order first — a second panel on a shared - # model must not re-sort it on open. - header.setSortIndicator(self.table_model._sort_col, self.table_model._sort_order) - self.table_view.setSortingEnabled(True) - logger.debug("Setting up table view context menu") - self.table_view.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) - self.table_view.customContextMenuRequested.connect(self._context_menu) - self.table_view.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) - self.table_view.setSelectionMode(QTableView.SelectionMode.SingleSelection) - - # Columns at full content width, sized once (see TellSamplePanel). - self._columns_autosized = False - if self.table_model.rowCount() > 0: - self.table_view.resizeColumnsToContents() - self._columns_autosized = True - - def _selected_item(self) -> SampleShortInfo | None: - idx = self.table_view.currentIndex() - if not idx.isValid(): - return None - return self.table_model.get_item(idx.row()) - - def _context_menu(self, position): - idx = self.table_view.indexAt(position) - - if not idx.isValid(): - return - - item = self.table_model.get_item(idx.row()) - - if item is None: - return - - menu = QMenu() - act_mount = menu.addAction("Mount") - - act_unmount = menu.addAction("Unmount") - - action = menu.exec_(self.table_view.viewport().mapToGlobal(position)) - - if action == act_mount: - self.mount.emit(item, True) - elif action == act_unmount: - self.unmount.emit() - - @Slot(SampleShortInfoList) - def new_list(self, samples: SampleShortInfoList): - # signal from DAQWorker will call this with the model - self.table_model.update_rows(rows=samples.s) - if not self._columns_autosized and self.table_model.rowCount() > 0: - self.table_view.resizeColumnsToContents() - self._columns_autosized = True - - @Slot(DAQStatusModel) - def update_daq_status(self, status: DAQStatusModel): - # The "No sample mounted" label and Unmount button were dropped — - # mounted state now shows as the existing row highlight instead. - sample = status.sample - self.table_model.update_current_reference(sample.db_id if sample is not None else None) diff --git a/src/aare/gui/panels/rotation_data_collection.py b/src/aare/gui/panels/rotation_data_collection.py deleted file mode 100644 index 114c4fab..00000000 --- a/src/aare/gui/panels/rotation_data_collection.py +++ /dev/null @@ -1,373 +0,0 @@ -from pathlib import Path - -from aarecommon.config.beamline import cfg_get, mx_beamline -from aarecommon.config.logger import setup_logger -from aarecommon.math.diffraction_geometry import DiffractionGeometry -from aarecommon.models.beamline import MXBeamline -from aarecommon.models.models import BeamlineStateEnum, DAQStatusModel -from aarecommon.models.rotation_scan import RotationScanRequest -from PySide6.QtCore import Signal, Slot -from PySide6.QtWidgets import QComboBox, QLabel, QMessageBox, QPushButton - -from aare.gui.constants import LOGGER_NAME -from aare.gui.panels.scan_settings_panel import ScanSettingsPanel -from aare.gui.styles import ABORT_TEXT, GO_TEXT -from aare.gui.widgets.number_line_edit import NumberLineEdit - -logger = setup_logger(LOGGER_NAME) - -MAX_OMEGA_SPEED_DEG_S = 500.0 -# 900 Hz at X06DA, 120 Hz at X10SA -MIN_EXP_TIME_S = {MXBeamline.X06DA: 1 / 900, MXBeamline.X10SA: 1 / 120} - - -def omega_speed_deg_s(image_angle_deg: float, exp_time_s: float) -> float: - """How fast omega has to turn to cover one image in one exposure. The - goniometer caps this, and it is a limit on the pair - neither number is - wrong on its own - so no single field's validator can express it.""" - if exp_time_s <= 0: - return float("inf") - return image_angle_deg / exp_time_s - - -def add_screening_to_path(path): - p = Path(path) - return "screening" / p - - -def add_data_to_path(path): - p = Path(path) - return "data" / p - - -class RotationDataCollectionPanel(ScanSettingsPanel): - rotation_scan = Signal(RotationScanRequest) - viewer_track_online = Signal() - - def __init__( - self, - diffraction: DiffractionGeometry, - default_dtz: float = 200.0, - default_transmission: float = 1.0, - parent=None, - ): - super().__init__( - parent=parent, - diffraction=diffraction, - default_dtz=cfg_get( - "daq.data_collection_settings.default_rotation_settings.dtz", default_dtz - ), - default_transmission=cfg_get( - "daq.data_collection_settings.default_rotation_settings.transmission", - default_transmission, - ), - # Row 11 = first row under the "Rotation" header: the rotation - # transmission belongs next to the rotation fields, not at the - # top of the tab where it read as applying to screening too. - transmission_row=11, - transmission_label="Rotation transmission", - ) - - self._filename = "" - self._omega = 0 - self._dose_mgy = 0 - self._total_time = 0.0 - self._min_exp_time_s = MIN_EXP_TIME_S.get(mx_beamline(), 0.0005) - - # Settings the user typed in; None means "follow the mounted sample". - # The screening fields are not here: they have no spreadsheet - # counterpart, so they always keep whatever the user left in them. - self._user_total_angle: float | None = None - self._user_image_angle: float | None = None - self._user_exp_time: float | None = None - - self.omega_button = QPushButton("Ω") - self.omega_button.setFixedWidth(30) - self.omega_button.clicked.connect(self.update_omega_start) - - self.start_angle = NumberLineEdit( - -720, 720.0, 0.0, decimals=3, parent=self, track_pending=True - ) - self._add_row(3, "Start angle", self.start_angle, "°", trailing=self.omega_button) - self._add_field(self.start_angle) - - self._layout.addWidget( - QLabel("
Screening
", parent=self), 4, 0, 1, 6 - ) - - self.screening_type = QComboBox(parent=self) - self.screening_type.addItem("1 image", {"steps": 1, "omega_step_deg": 0}) - self.screening_type.addItem("2 images, 90° apart", {"steps": 2, "omega_step_deg": 90}) - self.screening_type.addItem("4 images, 90° apart", {"steps": 4, "omega_step_deg": 90}) - self.screening_type.addItem("3 images, 60° apart", {"steps": 3, "omega_step_deg": 60}) - self.screening_type.addItem("4 images, 60° apart", {"steps": 4, "omega_step_deg": 60}) - self.screening_type.addItem("2 images, 45° apart", {"steps": 2, "omega_step_deg": 45}) - self.screening_type.addItem("4 images, 45° apart", {"steps": 4, "omega_step_deg": 45}) - self.screening_type.addItem("5 images, 45° apart", {"steps": 5, "omega_step_deg": 45}) - - self._layout.addWidget(self.screening_type, 5, 0, 1, 6) - - self.screening_image_angle = NumberLineEdit( - 0, 90.0, 0.5, decimals=3, parent=self, track_pending=True - ) - self._add_row(6, "Image angle", self.screening_image_angle, "°") - self._add_field(self.screening_image_angle) - - default_screening_exp_time = cfg_get( - "daq.data_collection_settings.default_screening_settings.exp_time_s", 0.1 - ) - self.screening_image_time_enter = NumberLineEdit( - self._min_exp_time_s, - 10.0, - default_screening_exp_time, - decimals=4, - parent=self, - track_pending=True, - ) - self._add_row(7, "Image time", self.screening_image_time_enter, "s") - self._add_field(self.screening_image_time_enter) - - self.screening_transmission_enter = NumberLineEdit( - 0, 1.0, self._default_transmission, decimals=4, parent=self, track_pending=True - ) - self._add_row(8, "Screening transmission", self.screening_transmission_enter) - self._add_field(self.screening_transmission_enter) - - self.screening_button = QPushButton("Run screening") - self.screening_button.setStyleSheet(f"color: {GO_TEXT};") - self.screening_button.clicked.connect(self.run_screening) - self._layout.addWidget(self.screening_button, 9, 0, 1, 6) - - self._layout.addWidget( - QLabel("
Rotation
", parent=self), 10, 0, 1, 6 - ) - - default_steps = cfg_get( - "daq.data_collection_settings.default_rotation_settings.steps", 1800 - ) - self._default_image_angle = cfg_get( - "daq.data_collection_settings.default_rotation_settings.increment_omega_deg", 0.2 - ) - self._default_total_angle = default_steps * self._default_image_angle - self._default_exp_time = cfg_get( - "daq.data_collection_settings.default_rotation_settings.exp_time_s", 0.01 - ) - - self.total_angle = NumberLineEdit( - 0, 9999.0, self._default_total_angle, decimals=3, parent=self, track_pending=True - ) - self._add_row(12, "Total angle", self.total_angle, "°") - self._add_database_field(self.total_angle, self._on_total_angle_committed) - - self.image_angle = NumberLineEdit( - 0, 10.0, self._default_image_angle, decimals=3, parent=self, track_pending=True - ) - self._add_row(13, "Image angle", self.image_angle, "°") - self._add_database_field(self.image_angle, self._on_image_angle_committed) - - self.image_time_enter = NumberLineEdit( - self._min_exp_time_s, - 10.0, - self._default_exp_time, - decimals=4, - parent=self, - track_pending=True, - ) - self._add_row(14, "Image time", self.image_time_enter, "s") - self._add_database_field(self.image_time_enter, self._on_exp_time_committed) - - self.omega_speed = QLabel("-") - self._add_row(15, "Rotation speed", self.omega_speed, "°/s") - - self.total_time = QLabel(f"{self._total_time} min 0 s") - self._add_row(16, "Total measurement time", self.total_time) - - self.dose = QLabel(f"{self._dose_mgy}") - self._add_row(17, "Dose", self.dose, "MGy") - - self.measurement_button = QPushButton("Run rotation") - self.measurement_button.setStyleSheet(f"color: {GO_TEXT};") - self.measurement_button.clicked.connect(self.run_measurement) - self._layout.addWidget(self.measurement_button, 18, 0, 1, 6) - - # Per-tab Abort (DataCollectionSettings wires it to the DAQ cancel). - self.abort_button = QPushButton("Abort measurement") - self.abort_button.setStyleSheet(f"color: {ABORT_TEXT};") - self._layout.addWidget(self.abort_button, 19, 0, 1, 6) - - # every field exists now: fill in the speed and measurement time - self._values_changed() - - # -- the panel's settings ---------------------------------------------- - @Slot(float) - def _on_total_angle_committed(self, value: float): - self._user_total_angle = value - self._user_took_over() - - @Slot(float) - def _on_image_angle_committed(self, value: float): - self._user_image_angle = value - self._user_took_over() - - @Slot(float) - def _on_exp_time_committed(self, value: float): - self._user_exp_time = value - self._user_took_over() - - def _write_active_values(self): - super()._write_active_values() - db = self._db_params - self.total_angle.set_committed_value( - self._setting(self._user_total_angle, db.total_angle_deg, self._default_total_angle) - ) - self.image_angle.set_committed_value( - self._setting(self._user_image_angle, db.image_angle_deg, self._default_image_angle) - ) - self.image_time_enter.set_committed_value( - self._setting(self._user_exp_time, db.exp_time_s, self._default_exp_time) - ) - - def _values_changed(self): - super()._values_changed() - self._update_speed_readout() - self._update_measurement_time() - - # -- derived read-outs -------------------------------------------------- - def _update_speed_readout(self): - speed = omega_speed_deg_s( - self.image_angle.committed_value, self.image_time_enter.committed_value - ) - self.omega_speed.setText("-" if speed == float("inf") else f"{speed:.1f}") - too_fast = speed > MAX_OMEGA_SPEED_DEG_S - # A red read-out rather than a red field: the cap is on the pair. - self.omega_speed.setStyleSheet(f"color: {ABORT_TEXT};" if too_fast else "") - - def image_number(self) -> int: - total_angle = self.total_angle.committed_value - image_angle = self.image_angle.committed_value - if total_angle <= 0 or total_angle < image_angle or image_angle <= 0: - logger.warning(f"Cannot count images for {total_angle}° in steps of {image_angle}°") - return 0 - return round(total_angle / image_angle) - - def _update_measurement_time(self): - self._total_time = self.image_number() * self.image_time_enter.committed_value - mins = int(self._total_time // 60) - secs = round(self._total_time % 60) - if secs == 60: - mins += 1 - secs = 0 - self.total_time.setText(f"{mins} min {secs} s") - - # -- running ------------------------------------------------------------ - def _pair_is_runnable(self, angle: NumberLineEdit, time: NumberLineEdit) -> bool: - """Both halves of an image angle / image time pair have to be inside - their own limits, and together they have to stay under the omega speed - cap. QDoubleValidator only paints a field red, so a run has to ask.""" - speed = omega_speed_deg_s(angle.committed_value, time.committed_value) - if not (angle.hasAcceptableInput() and time.hasAcceptableInput()): - msg = ( - "Image angle / image time outside limits " - f"(min image time {self._min_exp_time_s:.4f} s)" - ) - elif speed > MAX_OMEGA_SPEED_DEG_S: - msg = ( - f"{angle.committed_value:.3f}° in {time.committed_value:.4f} s needs " - f"{speed:.0f} °/s, above the {MAX_OMEGA_SPEED_DEG_S:.0f} °/s limit" - ) - else: - return True - logger.error(msg) - QMessageBox.critical(self, "Error", msg) - return False - - @Slot() - def run_screening(self): - if self._beamline_state != BeamlineStateEnum.SampleAlignment: - logger.error(f"Beamline state {self._beamline_state} is not Sample Alignment") - QMessageBox.critical(None, "Error", "Beamline state is not Sample Alignment") - return - if not self._pair_is_runnable(self.screening_image_angle, self.screening_image_time_enter): - return - if not self.check_before_run(scan_kind="screening"): - logger.error("Cannot run measurement because of check") - return - screening_settings = self.screening_type.currentData() - - is_single_image = ( - screening_settings["steps"] == 1 and screening_settings["omega_step_deg"] == 0 - ) - - if is_single_image: - r = RotationScanRequest( - file_prefix=str(add_screening_to_path(self._filename)), - start_omega_deg=self.start_angle.committed_value, - incr_omega_deg=self.screening_image_angle.committed_value, - wedge_omega_deg=screening_settings["omega_step_deg"], - steps=1, - dtz=self.dtz_enter.committed_value, - transmission=self.screening_transmission_enter.committed_value, - screening=True, - exp_time_s=self.screening_image_time_enter.committed_value, - ) - else: - r = RotationScanRequest( - file_prefix=str(add_screening_to_path(self._filename)), - start_omega_deg=self.start_angle.committed_value, - wedge_omega_deg=self.screening_image_angle.committed_value, - incr_omega_deg=screening_settings["omega_step_deg"], - steps=screening_settings["steps"], - dtz=self.dtz_enter.committed_value, - transmission=self.screening_transmission_enter.committed_value, - screening=True, - exp_time_s=self.screening_image_time_enter.committed_value, - ) - - self.rotation_scan.emit(r) - self.viewer_track_online.emit() - - @Slot() - def run_measurement(self): - if self._beamline_state != BeamlineStateEnum.SampleAlignment: - logger.error(f"Beamline state {self._beamline_state} is not Sample Alignment") - QMessageBox.critical(None, "Error", "Beamline state is not Sample Alignment") - return - if not self._pair_is_runnable(self.image_angle, self.image_time_enter): - return - if not self.check_before_run(scan_kind="rotation"): - logger.error("Cannot run measurement because of check") - return - r = RotationScanRequest( - file_prefix=str(add_data_to_path(self._filename)), - start_omega_deg=self.start_angle.committed_value, - steps=self.image_number(), - incr_omega_deg=self.image_angle.committed_value, - dtz=self.dtz_enter.committed_value, - transmission=self.transmission_enter.committed_value, - screening=False, - exp_time_s=self.image_time_enter.committed_value, - ) - self.rotation_scan.emit(r) - self.viewer_track_online.emit() - - # -- status ------------------------------------------------------------- - @Slot(str) - def update_filename(self, filename: str): - self._filename = filename - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - super().update_daq_status(s) - self._omega = s.geom.omega_deg - - lambda_a = s.diffraction.wavelength_angstrom - kdose = 2000 / (lambda_a * lambda_a) - beam_area = s.geom.beam_size_mm.x * s.geom.beam_size_mm.y * 1e6 - transmission = self.transmission_enter.committed_value - self._dose_mgy = (self._total_time * s.bl.flux_ph_s * transmission) / (beam_area * kdose) - self.dose.setText(f"{(self._dose_mgy / 1e6):.1f}") - - @Slot() - def update_omega_start(self): - if not self.start_angle.isReadOnly(): - self.start_angle.force_update_value(self._omega) diff --git a/src/aare/gui/panels/samcam_panel.py b/src/aare/gui/panels/samcam_panel.py deleted file mode 100644 index 0b577a6e..00000000 --- a/src/aare/gui/panels/samcam_panel.py +++ /dev/null @@ -1,215 +0,0 @@ -from aarecommon.models.models import DAQStatusModel, SampleCameraSettings -from PySide6.QtCore import Signal, Slot -from PySide6.QtWidgets import ( - QCheckBox, - QComboBox, - QDoubleSpinBox, - QGridLayout, - QHBoxLayout, - QLabel, - QLineEdit, - QPushButton, - QVBoxLayout, - QWidget, -) - -from aare.gui.widgets.title_label import TitleLabel - - -class SamcamPanel(QWidget): - # Signals for when exposure or gain values change - changed = Signal(SampleCameraSettings) - show_detections_changed = Signal(bool) - show_detection_polygons_changed = Signal(bool) - show_target_point_changed = Signal(bool) - show_target_coordinates_changed = Signal(bool) - show_overlay_legend_changed = Signal(bool) - compact_overlay_legend_changed = Signal(bool) - target_color_changed = Signal(str) - screenshot_requested = Signal(str, str) - save_beam_location_setting = Signal() - old_settings = SampleCameraSettings(gain=100, exposure=0.001) - - def __init__(self, parent=None): - super().__init__(parent) - - # Create layout - layout = QVBoxLayout() - - layout.addWidget( - TitleLabel("Sample camera", self, collapsible=True, default_collapsed=False) - ) - - # Exposure + gain share one row to save vertical space. - exposure_gain_layout = QHBoxLayout() - self.exposure_spinbox = QDoubleSpinBox() - self.exposure_spinbox.setRange(0, 1.0) # Adjust range as needed - self.exposure_spinbox.setSingleStep(0.001) - self.exposure_spinbox.setDecimals(3) - self.exposure_spinbox.valueChanged.connect(self._changed) - - self.gain_spinbox = QDoubleSpinBox() - self.gain_spinbox.setRange(0, 1000) # Adjust range as needed - self.gain_spinbox.setSingleStep(1) - self.gain_spinbox.setDecimals(1) - self.gain_spinbox.valueChanged.connect(self._changed) - - # 3:2 stretch — exposure shows 3 decimals plus the side arrows and - # was getting cut; gain (1 decimal) can afford the narrower field. - exposure_gain_layout.addWidget(QLabel("Exposure (s):")) - exposure_gain_layout.addWidget(self.exposure_spinbox, 3) - exposure_gain_layout.addWidget(QLabel("Gain:")) - exposure_gain_layout.addWidget(self.gain_spinbox, 2) - - # Persist the current gain/exposure as the beam-location preset for the - # current zoom (only meaningful in beam-location mode). - self.save_beam_location_button = QPushButton("Save samcam settings (bl)") - self.save_beam_location_button.clicked.connect(self.save_beam_location_setting.emit) - - screenshot_filename_layout = QHBoxLayout() - screenshot_filename_label = QLabel("Filename:") - self.screenshot_filename_edit = QLineEdit() - self.screenshot_filename_edit.setPlaceholderText("optional") - screenshot_filename_layout.addWidget(screenshot_filename_label) - screenshot_filename_layout.addWidget(self.screenshot_filename_edit) - - screenshot_message_layout = QHBoxLayout() - screenshot_message_label = QLabel("Message:") - self.screenshot_message_edit = QLineEdit() - self.screenshot_message_edit.setPlaceholderText("optional") - screenshot_message_layout.addWidget(screenshot_message_label) - screenshot_message_layout.addWidget(self.screenshot_message_edit) - - self.screenshot_button = QPushButton("Save samcam image") - self.screenshot_button.clicked.connect(self._request_screenshot) - - # Overlay checkboxes, two columns to save vertical space; related - # toggles share a row. - self.show_detections_checkbox = QCheckBox("Show ML detections") - self.show_detections_checkbox.setChecked(False) # Default to checked - self.show_detections_checkbox.toggled.connect(self.show_detections_changed.emit) - - self.show_detection_polygons_checkbox = QCheckBox("Show ML polygons") - self.show_detection_polygons_checkbox.setChecked(True) - self.show_detection_polygons_checkbox.toggled.connect( - self.show_detection_polygons_changed.emit - ) - - self.show_target_point_checkbox = QCheckBox("Show target point") - self.show_target_point_checkbox.setChecked(True) - self.show_target_point_checkbox.toggled.connect(self.show_target_point_changed.emit) - - self.show_target_coordinates_checkbox = QCheckBox("Show target coordinates") - self.show_target_coordinates_checkbox.setChecked(True) - self.show_target_coordinates_checkbox.toggled.connect( - self.show_target_coordinates_changed.emit - ) - - self.show_overlay_legend_checkbox = QCheckBox("Show overlay legend") - self.show_overlay_legend_checkbox.setChecked(False) - self.show_overlay_legend_checkbox.toggled.connect(self.show_overlay_legend_changed.emit) - - self.compact_overlay_legend_checkbox = QCheckBox("Compact legend") - self.compact_overlay_legend_checkbox.setChecked(False) - self.compact_overlay_legend_checkbox.toggled.connect( - self.compact_overlay_legend_changed.emit - ) - - checkbox_grid = QGridLayout() - for i, checkbox in enumerate( - ( - self.show_detections_checkbox, - self.show_detection_polygons_checkbox, - self.show_target_point_checkbox, - self.show_target_coordinates_checkbox, - self.show_overlay_legend_checkbox, - self.compact_overlay_legend_checkbox, - ) - ): - checkbox_grid.addWidget(checkbox, i // 2, i % 2) - - # Target color - target_color_layout = QHBoxLayout() - target_color_label = QLabel("Target colour:") - self.target_color_combo = QComboBox() - self.target_color_combo.addItems(["Cyan", "Dark Blue", "Dark Red"]) - self.target_color_combo.setCurrentText("Cyan") - self.target_color_combo.currentTextChanged.connect(self.target_color_changed.emit) - target_color_layout.addWidget(target_color_label) - target_color_layout.addWidget(self.target_color_combo) - - # Add controls to main layout - layout.addLayout(exposure_gain_layout) - samcam_buttons_layout = QHBoxLayout() - samcam_buttons_layout.addWidget(self.save_beam_location_button) - samcam_buttons_layout.addWidget(self.screenshot_button) - layout.addLayout(samcam_buttons_layout) - layout.addLayout(screenshot_filename_layout) - layout.addLayout(screenshot_message_layout) - layout.addLayout(checkbox_grid) - layout.addLayout(target_color_layout) - self.setLayout(layout) - - def _changed(self): - self.changed.emit( - SampleCameraSettings( - gain=self.gain_spinbox.value(), exposure=self.exposure_spinbox.value() - ) - ) - - def _request_screenshot(self): - self.screenshot_requested.emit( - self.screenshot_filename_edit.text(), self.screenshot_message_edit.text() - ) - - def apply_overlay_settings( - self, - *, - show_detections: bool, - show_detection_polygons: bool, - show_target_point: bool, - show_target_coordinates: bool, - show_overlay_legend: bool, - compact_overlay_legend: bool, - target_color: str, - ) -> None: - for widget in ( - self.show_detections_checkbox, - self.show_detection_polygons_checkbox, - self.show_target_point_checkbox, - self.show_target_coordinates_checkbox, - self.show_overlay_legend_checkbox, - self.compact_overlay_legend_checkbox, - self.target_color_combo, - ): - widget.blockSignals(True) - - self.show_detections_checkbox.setChecked(show_detections) - self.show_detection_polygons_checkbox.setChecked(show_detection_polygons) - self.show_target_point_checkbox.setChecked(show_target_point) - self.show_target_coordinates_checkbox.setChecked(show_target_coordinates) - self.show_overlay_legend_checkbox.setChecked(show_overlay_legend) - self.compact_overlay_legend_checkbox.setChecked(compact_overlay_legend) - self.target_color_combo.setCurrentText(target_color) - - for widget in ( - self.show_detections_checkbox, - self.show_detection_polygons_checkbox, - self.show_target_point_checkbox, - self.show_target_coordinates_checkbox, - self.show_overlay_legend_checkbox, - self.compact_overlay_legend_checkbox, - self.target_color_combo, - ): - widget.blockSignals(False) - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - if self.old_settings != s.bl.sample_camera: - self.exposure_spinbox.blockSignals(True) - self.gain_spinbox.blockSignals(True) - self.gain_spinbox.setValue(s.bl.sample_camera.gain) - self.exposure_spinbox.setValue(s.bl.sample_camera.exposure) - self.exposure_spinbox.blockSignals(False) - self.gain_spinbox.blockSignals(False) - self.old_settings = s.bl.sample_camera diff --git a/src/aare/gui/panels/sample_queue_panel.py b/src/aare/gui/panels/sample_queue_panel.py deleted file mode 100644 index 1fa6a9b9..00000000 --- a/src/aare/gui/panels/sample_queue_panel.py +++ /dev/null @@ -1,501 +0,0 @@ -from aarecommon.config.logger import setup_logger -from aarecommon.models.models import ( - BeamlineStateEnum, - DAQStatusModel, - SampleShortInfo, - SampleShortInfoList, - SessionsStateEnum, -) -from PySide6.QtCore import Qt, QTimer, Signal, Slot -from PySide6.QtGui import QKeySequence, QShortcut -from PySide6.QtWidgets import ( - QCheckBox, - QFrame, - QHBoxLayout, - QHeaderView, - QMessageBox, - QPushButton, - QSizePolicy, - QTableView, - QVBoxLayout, -) - -from aare.gui.constants import LOGGER_NAME -from aare.gui.models.sample_queue_model import SampleQueueSpreadsheet -from aare.gui.widgets.message_box import LOW_CURRENT_THRESHOLD, conditions_auto_check -from aare.gui.widgets.title_label import TitleLabel - -logger = setup_logger(LOGGER_NAME) - - -class SampleQueuePanel(QFrame): - auto_scan = Signal(SampleShortInfo) - unmount = Signal() - unmount_then_park_and_dry = Signal() - viewer_track_online = Signal() - samples_in_queue_changed = Signal(int) - automation_running_changed = Signal(bool) - step_through_changed = Signal(bool) - - def __init__( - self, parent=None, samples: SampleShortInfoList | None = None, show_user: bool = False - ): - super().__init__(parent) - self._baton_holder = None - self._busy = None - self._beamline_state = None - self._pause = True - self._set_to_pause = False - self._warning_msg_box = None - self._current_db_id: int | None = None - self._step_through = False - self.ring_current = None - self._experiment_shutter_state = None - self._door_prohibited = None - self._tell_connected = True - - self._recovery_timer = QTimer(self) - self._recovery_timer.setSingleShot(True) - self._recovery_timer.setInterval(600 * 1000) # 10 minutes - self._recovery_timer.timeout.connect(self.resume_automation) - - self.setFrameShape(QFrame.Shape.StyledPanel) - self.setFrameShadow(QFrame.Shadow.Raised) - - layout = QVBoxLayout(self) - self.setLayout(layout) - - layout.addWidget(TitleLabel("Sample queue", self)) - self.table_view = QTableView(self) - # Themed stripes from the QSS, matching the other sample tables — the - # model no longer paints plain rows white. - self.table_view.setAlternatingRowColors(True) - - self.table_model = SampleQueueSpreadsheet(show_user=show_user) - self.table_view.setModel(self.table_model) - header = self.table_view.horizontalHeader() - header.setSectionResizeMode(QHeaderView.ResizeMode.Stretch) - - self.table_view.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) - self.table_view.setAcceptDrops(True) - self.table_view.setDropIndicatorShown(True) - self.table_view.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows) - - self.delete_shortcut = QShortcut(QKeySequence.StandardKey.Delete, self.table_view) - self.delete_shortcut.setContext(Qt.ShortcutContext.WidgetWithChildrenShortcut) - self.delete_shortcut.activated.connect(self.remove_selected_samples) - - self.run_pause_shortcut = QShortcut(QKeySequence(Qt.Key.Key_Space), self.table_view) - self.run_pause_shortcut.setContext(Qt.ShortcutContext.WidgetWithChildrenShortcut) - self.run_pause_shortcut.activated.connect(self.run) - - layout.addWidget(self.table_view) - - button_layout = QHBoxLayout() - self.play_button = QPushButton("▶ Run", self) - self.play_button.clicked.connect(self.run) - - self.remove_button = QPushButton("🗑 Remove selected", self) - self.remove_button.clicked.connect(self.remove_selected_samples) - - self.clear_button = QPushButton("✖ Clear list", self) - self.clear_button.clicked.connect(self.clear) - - self.park_and_dry_when_cleared = QCheckBox("Park and dry when automation finishes", self) - self.park_and_dry_when_cleared.setChecked(True) - - self.pause_on_conditions_cb = QCheckBox( - "Pause on bad conditions (beam/shutter/door/robot)", self - ) - self.pause_on_conditions_cb.setChecked(True) - self.pause_on_conditions_cb.setToolTip( - "When on, automation refuses to start and pauses between samples if the beam, " - "experiment shutter, hutch doors or robot are not ready. Uncheck for testing " - "to run straight through." - ) - - button_layout.addWidget(self.play_button) - button_layout.addWidget(self.remove_button) - button_layout.addWidget(self.clear_button) - button_layout.addWidget(self.park_and_dry_when_cleared) - button_layout.addWidget(self.pause_on_conditions_cb) - - layout.addLayout(button_layout) - self._emit_samples_in_queue_changed() - self.automation_running_changed.emit(False) - self.step_through_changed.emit(False) - - def _samples_left_in_queue(self) -> int: - total = len(self.table_model.samples) - if self._pause or total == 0: - return total - return max(0, total - 1) - - def _emit_samples_in_queue_changed(self) -> None: - self.samples_in_queue_changed.emit(self._samples_left_in_queue()) - - def set_step_through(self, enabled: bool) -> None: - self._step_through = bool(enabled) - self.step_through_changed.emit(self._step_through) - - def is_step_through(self) -> bool: - return self._step_through - - def queue_preview( - self, - ) -> tuple[SampleShortInfo | None, SampleShortInfo | None, SampleShortInfo | None]: - samples = self.table_model.samples - current = samples[0] if len(samples) > 0 else None - next_sample = samples[1] if len(samples) > 1 else None - next_next_sample = samples[2] if len(samples) > 2 else None - return current, next_sample, next_next_sample - - def queue_samples(self, samples: list[SampleShortInfo], replace: bool = True) -> None: - if replace: - self.table_model.updateData(list(samples)) - else: - merged = list(self.table_model.samples) - existing_ids = {sample.db_id for sample in merged} - for sample in samples: - if sample.db_id not in existing_ids: - merged.append(sample) - self.table_model.updateData(merged) - self._emit_samples_in_queue_changed() - - def ensure_default_queue_from_samples(self, samples: list[SampleShortInfo]) -> None: - if len(self.table_model.samples) > 0: - return - - ordered = sorted( - [sample for sample in samples if sample.location is not None], - key=lambda sample: sample.loc_str_sort(), - ) - self.queue_samples(ordered, replace=True) - - def annotate_sample_comment(self, db_id: int, comment: str) -> None: - self.table_model.annotate_sample(db_id, comment) - - def skip_current_sample(self) -> None: - if not self.table_model.samples: - return - - current = self.table_model.samples[0] - self.table_model.remove_sample(current.db_id) - self._current_db_id = None - - if not self._pause and len(self.table_model.samples) > 0: - next_item = self.table_model.samples[0] - if self._step_through: - self.pause_automation(set_id_to_None=False) - else: - self._current_db_id = next_item.db_id - self._emit_samples_in_queue_changed() - self.auto_scan.emit(next_item) - else: - self._finish_empty_queue() - - self._emit_samples_in_queue_changed() - - def remove_samples(self, db_ids) -> None: - """Remove the given samples from the queue. Public entry point for the - combined dewar view, whose selection lives outside this panel.""" - for db_id in db_ids: - self.table_model.remove_sample(db_id) - self._emit_samples_in_queue_changed() - - def remove_selected_samples(self): - selected_indexes = self.table_view.selectionModel().selectedRows() - if not selected_indexes: - return - - rows = sorted([index.row() for index in selected_indexes], reverse=True) - - for row in rows: - if 0 <= row < len(self.table_model.samples): - sample = self.table_model.samples[row] - self.table_model.remove_sample(sample.db_id) - - self._emit_samples_in_queue_changed() - - def _checks_enabled(self) -> bool: - return self.pause_on_conditions_cb.isChecked() - - def _bad_conditions(self) -> list[str]: - """Beamline conditions that currently block/should pause automation.""" - problems: list[str] = [] - if self.ring_current is None or self.ring_current < LOW_CURRENT_THRESHOLD: - rc = "unknown" if self.ring_current is None else f"{round(self.ring_current, 2)} mA" - problems.append(f"beam (ring current {rc})") - if not self._experiment_shutter_state: - problems.append("experiment shutter closed") - if self._door_prohibited is False: - problems.append("hutch doors open / not searched") - if not self._tell_connected: - problems.append("robot (TELL) not connected") - return problems - - def _conditions_ok(self) -> bool: - return len(self._bad_conditions()) == 0 - - def resume_automation(self): - if self._warning_msg_box: - self._warning_msg_box.done(0) - self._warning_msg_box = None - - if self._pause and len(self.table_model.samples) > 0: - logger.info("Resuming automation after timeout") - self.run() - - def manual_resume_from_warning(self): - logger.info("User chose to resume automation manually from dialog") - self.resume_automation() - - def show_warning_recovery_dialog(self): - self._warning_msg_box = QMessageBox(self) - self._warning_msg_box.setIcon(QMessageBox.Icon.Warning) - self._warning_msg_box.setWindowTitle("TELL Warning") - self._warning_msg_box.setText("TELL reported a warning. Please see console for details.") - self._warning_msg_box.setInformativeText( - "Automation paused for 10 minutes to allow sufficient dry time." - "\nClick 'Continue Now' to resume immediately, or wait for auto-resume." - ) - - continue_btn = self._warning_msg_box.addButton( - "Continue Now", QMessageBox.ButtonRole.AcceptRole - ) - self._warning_msg_box.setWindowModality(Qt.WindowModality.NonModal) - continue_btn.clicked.connect(self.manual_resume_from_warning) - self._warning_msg_box.show() - - def show_error_dialog(self, title: str, msg: str, info: str | None = None): - self._warning_msg_box = QMessageBox(self) - self._warning_msg_box.setIcon(QMessageBox.Icon.Warning) - self._warning_msg_box.setWindowTitle(title) - self._warning_msg_box.setText(msg) - if info: - self._warning_msg_box.setInformativeText(info) - self._warning_msg_box.setWindowModality(Qt.WindowModality.NonModal) - self._warning_msg_box.show() - - def is_running(self): - return not self._pause - - def _finish_empty_queue(self): - self.pause_automation() - - logger.info("Automation queue empty; unmounting current sample.") - - if self.park_and_dry_when_cleared.isChecked(): - logger.info("Automation queue empty; parking and drying TELL.") - self.unmount_then_park_and_dry.emit() - else: - self.unmount.emit() - - def run(self): - self._recovery_timer.stop() - - # Pausing must ALWAYS be possible, regardless of beamline state, busy - # flag, baton or maintenance. Only starting/resuming is gated on - # conditions, so handle the pause toggle first and return immediately. - if not self._pause: - self._set_to_pause = True - self._pause = True - self.table_model.set_running(False) - self.play_button.setText("▶ Run") - self._emit_samples_in_queue_changed() - self.automation_running_changed.emit(False) - return - - # --- Starting/resuming: require the beamline to be in a good state. --- - checks_enabled = self._checks_enabled() - if checks_enabled: - if self._warning_msg_box: - self._warning_msg_box.done(0) - self._warning_msg_box = None - - if self._beamline_state != BeamlineStateEnum.SampleAlignment: - self.show_error_dialog( - title="wrong beamline state", - msg="Cannot run automation while beamline is not in sample alignment state", - info="Please change the state at the bottom of the menu", - ) - return - - if self._busy: - logger.error(f"Cannot run automation while beamline is busy. Busy flag = {self._busy}") - self.show_error_dialog( - title="Beamline is busy", - msg="Cannot run automation while beamline is busy", - info="Please wait until beamline is idle or contact your local contact for support", - ) - return - - if self._baton_holder is SessionsStateEnum.Vacant: - self.show_error_dialog( - title="Session is vacant", - msg="Starting automation while session is vacant is not currently implemented", - info="Please grab the baton before continuing " - "or contact your local contact for support", - ) - return - - elif self._baton_holder is not SessionsStateEnum.OwnedByYou: - self.show_error_dialog( - title="You do not hold the baton", - msg="You do not hold the baton.", - info="Please request the baton if it is your shift." - "If your baton request is denied and it should be the start of your shift," - "please contact your local contact for support", - ) - return - - if self._beamline_state is BeamlineStateEnum.Maintenance: - self.show_error_dialog( - title="Maintenance mode", - msg="Cannot run automation while beamline is in maintenance mode", - info=( - "Change to safe state such as Sample Exchange before trying to continue. " - "If this issue persists please contact your local contact for support." - ), - ) - return - - if len(self.table_model.samples) > 0: - if checks_enabled: - bad = self._bad_conditions() - if bad: - logger.warning(f"Cannot start automation; beamline not ready: {bad}") - self.show_error_dialog( - title="Beamline not ready", - msg="Cannot start automation:\n- " + "\n- ".join(bad), - info="Fix the above, or untick 'Pause on bad conditions' for testing.", - ) - return - - self.table_model.set_running(True) - self._set_to_pause = False - self._pause = False - self.play_button.setText("⏸ Pause") - current = self.table_model.samples[0] - self._current_db_id = current.db_id - self._emit_samples_in_queue_changed() - self.automation_running_changed.emit(True) - self.auto_scan.emit(current) - self.viewer_track_online.emit() - else: - logger.debug("No samples in queue, skipping") - self.show_error_dialog( - title="No Samples in Queue", - msg="Cannot run automation as there are no samples in the queue.", - info="Please add samples to the queue.", - ) - return - - def clear(self): - self.table_model.clearSamples() - self._emit_samples_in_queue_changed() - self.automation_running_changed.emit(False) - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - self.ring_current = s.bl.ring_current_mA - self._experiment_shutter_state = s.bl.exp_shutter_open - self._door_prohibited = getattr(s.bl, "pss_prohibited", None) - self._tell_connected = getattr(s, "tell_connected", True) - self._beamline_state = s.state - self._busy = s.busy - self._baton_holder = s.session.session - - def pause_automation(self, set_id_to_None: bool = True): - self.table_model.set_running(False) - self._pause = True - self.play_button.setText("▶ Run") - if set_id_to_None: - self._current_db_id = None - self._emit_samples_in_queue_changed() - self.automation_running_changed.emit(False) - - @Slot(int, bool, str) - def automated_scan_done(self, db_id: int, success: bool, reply: str): - if self._current_db_id is not None and db_id != self._current_db_id: - return - - if self._checks_enabled() and not self._conditions_ok(): - self.pause_automation(set_id_to_None=False) - bad = self._bad_conditions() - logger.warning(f"Automation paused; beamline not ready: {bad}") - msg = "Automation paused — beamline not ready:\n- " + "\n- ".join(bad) - - if conditions_auto_check(self, msg): - logger.debug("User chose to continue; resuming automation") - self.table_model.set_running(True) - self._pause = False - self.play_button.setText("⏸ Pause") - self._emit_samples_in_queue_changed() - else: - logger.debug("Conditions not met or user stopped; ending automation") - self.unmount.emit() - self._emit_samples_in_queue_changed() - return - - if success: - self.table_model.remove_sample(db_id) - self._current_db_id = None - - if not self._pause and len(self.table_model.samples) > 0: - next_item = self.table_model.samples[0] - if self._step_through: - self.pause_automation(set_id_to_None=False) - else: - self._current_db_id = next_item.db_id - self._emit_samples_in_queue_changed() - self.auto_scan.emit(next_item) - else: - self._finish_empty_queue() - - else: - if reply == "Warning": - self.table_model.remove_sample(db_id) - self._current_db_id = None - self.pause_automation() - logger.warning("TELL Warning: Pausing for 10 minutes.") - self._recovery_timer.start() - self.show_warning_recovery_dialog() - - elif reply == "Critical": - self.table_model.remove_sample(db_id) - self._current_db_id = None - self.pause_automation() - logger.critical("TELL Critical Error: Stopping automation.") - self.show_error_dialog( - title=reply, - msg="Critical Error", - info="Repeated mount failures.\n" - "Please check to see if pins" - " are loaded in these postions." - "\n If not please continue with new " - "samples.\nOtherwise contact your" - " local contact for support", - ) - elif reply == "Authentication Error": - self.pause_automation() - self.show_error_dialog( - title=reply, - msg="Authentication Error", - info="Please take the session to continue", - ) - else: - self.table_model.remove_sample(db_id) - self._current_db_id = None - if not self._pause and len(self.table_model.samples) > 0: - next_item = self.table_model.samples[0] - if self._step_through: - self.pause_automation(set_id_to_None=False) - else: - self._current_db_id = next_item.db_id - self._emit_samples_in_queue_changed() - self.auto_scan.emit(next_item) - else: - self._finish_empty_queue() - - self._emit_samples_in_queue_changed() diff --git a/src/aare/gui/panels/scan_settings_panel.py b/src/aare/gui/panels/scan_settings_panel.py deleted file mode 100644 index 59faed7e..00000000 --- a/src/aare/gui/panels/scan_settings_panel.py +++ /dev/null @@ -1,399 +0,0 @@ -"""Common part of the scan settings panels (Rotation, Raster). - -Where the numbers in the fields come from ------------------------------------------ -Every setting is worth one of three things, in this order: - -1. the value the user typed into it, while "User values" is selected, -2. the value the mounted sample asks for - its row in the aareDB spreadsheet, -3. the panel default, for a spreadsheet cell the user left empty. - -``ScanSettingsPanel._setting`` is that rule, and each panel spells out its -settings one line at a time in ``_write_active_values``. - -Committing a field - Enter, or leaving it - stores the number as the user's and -selects "User values". Only that one setting becomes the user's: everything -they did not touch keeps following the sample, so a new sample still brings its -own exposure time, angles and resolution. The toggle switches all of them back -and forth without forgetting anything. - -A number that was typed but never committed does not count: the field shows it -in the pending colour and the panel keeps using the value it had. What a scan -collects is read straight from the fields' committed values, so the panels keep -no second copy of them. -""" - -from collections.abc import Callable -from dataclasses import dataclass -from typing import Any - -from aarecommon.config.logger import setup_logger -from aarecommon.math.diffraction_geometry import DiffractionGeometry -from aarecommon.models.models import DAQStatusModel, SampleShortInfo, SessionsStateEnum -from PySide6.QtCore import Qt, Signal, Slot -from PySide6.QtWidgets import ( - QButtonGroup, - QGridLayout, - QHBoxLayout, - QLabel, - QRadioButton, - QVBoxLayout, - QWidget, -) - -from aare.gui.constants import LOGGER_NAME -from aare.gui.panels.file_path_panel import find_file_path_panel -from aare.gui.widgets.message_box import precondition_check -from aare.gui.widgets.number_line_edit import NumberLineEdit - -logger = setup_logger(LOGGER_NAME) - - -# Columns already reported as unusable, so the status loop says it once. -_BAD_COLUMNS: set[str] = set() - - -def _spreadsheet_float(params: Any, column: str) -> float | None: - """One cell of the sample's spreadsheet row, as a float. An empty cell, a - cell that does not hold a number, and a column aareDB does not have all - read as None: aareDB owns these names, and a renamed column must not kill - the status loop. Each bad column is reported once - pydantic's own message - names the column it expected instead.""" - try: - value = getattr(params, column) - return None if value is None else float(value) - except (AttributeError, TypeError, ValueError) as e: - if column not in _BAD_COLUMNS: - _BAD_COLUMNS.add(column) - logger.error(f"Ignoring the aareDB parameter {column!r}: {e}") - return None - - -@dataclass -class SampleParameters: - """The mounted sample's data collection parameters, in the panels' own - vocabulary. ``from_sample`` is the only place that knows the aareDB - spreadsheet column names. Every field is optional - the cell may be empty. - """ - - resolution_a: float | None = None - transmission: float | None = None - total_angle_deg: float | None = None - image_angle_deg: float | None = None - exp_time_s: float | None = None - - @classmethod - def from_sample(cls, sample: SampleShortInfo | None) -> "SampleParameters": - params = None if sample is None else sample.aaredb_params - if params is None: - return cls() - # DataCollectionParameters.transmission is the 0-to-1 fraction the - # scan requests use (aarecommon >= 0.7 rejects anything above 1.0 by - # design; the percent spreadsheets humans write are converted inside - # AareDB). No scaling here: dividing again would turn 20% into 0.2%. - return cls( - resolution_a=_spreadsheet_float(params, "targetresolution"), - transmission=_spreadsheet_float(params, "transmission"), - total_angle_deg=_spreadsheet_float(params, "totalangle"), - image_angle_deg=_spreadsheet_float(params, "oscillation"), - exp_time_s=_spreadsheet_float(params, "exposure"), - ) - - -class ScanSettingsPanel(QWidget): - """Detector distance / resolution / transmission plus the Database-vs-User - toggle. See the module docstring for where the numbers come from. - - A panel deriving from this one: - - * creates its own fields and registers them with :meth:`_add_field` (panel - only) or :meth:`_add_database_field` (also filled from the spreadsheet), - * keeps one ``_user_`` attribute per database-backed field of its - own, set by that field's commit slot, - * extends :meth:`_write_active_values` with a line per setting, - * ends its ``__init__`` with ``self._values_changed()``, so its read-outs - start out right once every field exists. - """ - - dtz_updated = Signal(float) - transmission_updated = Signal(float) - - # TODO min and max dtz is set by beamline add max - MIN_DTZ = 108.0 # this is beamline dependent - - def __init__( - self, - diffraction: DiffractionGeometry, - default_dtz: float = 200.0, - default_transmission: float = 1.0, - transmission_row: int = 2, - transmission_label: str = "Transmission", - parent=None, - ): - super().__init__(parent) - self._diffraction = diffraction - self._default_dtz = default_dtz - self._default_transmission = default_transmission - - self._beamline_state = None - self._ring_current = None - self._experiment_shutter_state = None - self._door_prohibited = None - self._can_edit_params = False - - # Parameters of the mounted sample; all-empty while nothing is mounted. - self._db_params = SampleParameters() - - # The settings the user typed in; None means "follow the sample". - self._user_resolution: float | None = None - self._user_dtz: float | None = None - self._user_transmission: float | None = None - - # Every numeric field of the panel, locked while the beamline is busy. - self._fields: list[NumberLineEdit] = [] - self._show_user_values = False - - # Outer layout: the Database/User toggle above the settings grid. - # Subclasses keep adding their widgets to self._layout (the grid), so - # they are unaffected by the wrapping. - outer = QVBoxLayout(self) - outer.setContentsMargins(0, 0, 0, 0) - outer.setSpacing(0) - # Created here, not in _build_source_toggle: basedpyright only counts - # instance variables assigned in __init__ as initialized. - self._database_radio = QRadioButton("Database values", self) - self._user_radio = QRadioButton("User values", self) - self._source_group = QButtonGroup(self) - outer.addWidget(self._build_source_toggle()) - - grid_host = QWidget(self) - self._layout = QGridLayout(grid_host) - # Toggle-to-grid gap = one grid row gap (top). Bottom 3 + the column's - # 3px spacing = one row gap between the last button and Abort too. - m = self._layout.contentsMargins() - self._layout.setContentsMargins(m.left(), 6, m.right(), 3) - outer.addWidget(grid_host) - - # Resolution and detector distance are two views of one setting: - # committing either one rewrites the other. - default_resolution = self._dtz_to_res(default_dtz) - self.high_res_enter = NumberLineEdit( - 1.0, 10, default=default_resolution, decimals=2, parent=self, track_pending=True - ) - self._add_row(0, "High resolution", self.high_res_enter, "Å") - self._add_database_field(self.high_res_enter, self._on_resolution_committed) - - self.dtz_enter = NumberLineEdit( - self.MIN_DTZ, 1000, default=default_dtz, decimals=2, parent=self, track_pending=True - ) - self._add_row(1, "Detector distance", self.dtz_enter, "mm") - self._add_database_field(self.dtz_enter, self._on_dtz_committed) - - # Placed where the subclass says: transmission is a per-mode setting - # (user request), so each tab puts its own row next to its section - # instead of a shared top-level "Rotation transmission" for all tabs. - self.transmission_enter = NumberLineEdit( - 0, 1.0, default=default_transmission, decimals=4, parent=self, track_pending=True - ) - self._add_row(transmission_row, transmission_label, self.transmission_enter) - self._add_database_field(self.transmission_enter, self._on_transmission_committed) - - # -- grid rows ---------------------------------------------------------- - def _add_row( - self, row: int, label: str, field: QWidget, unit: str = "", trailing: QWidget | None = None - ) -> None: - """One row of the settings grid: label, the field, its unit. A read-out - (a QLabel) is right-aligned like the input boxes. ``trailing`` takes the - last column and narrows the field by one to make room for it.""" - self._layout.addWidget(QLabel(label, parent=self), row, 0) - self._align_readout(field) - span = 2 if trailing is not None else 3 - self._layout.addWidget(field, row, 1, 1, span) - if unit: - self._layout.addWidget(QLabel(unit, parent=self), row, 1 + span) - if trailing is not None: - self._layout.addWidget(trailing, row, 4) - - def _add_pair_row( - self, row: int, label: str, first: QWidget, second: QWidget, unit: str = "" - ) -> None: - """A row holding two values side by side: label, first x second, unit.""" - self._layout.addWidget(QLabel(label, parent=self), row, 0) - self._layout.addWidget(QLabel(" x ", parent=self), row, 2) - for widget, column in ((first, 1), (second, 3)): - self._align_readout(widget) - self._layout.addWidget(widget, row, column) - if unit: - self._layout.addWidget(QLabel(unit, parent=self), row, 4) - - def _align_readout(self, widget: QWidget) -> None: - # NumberLineEdit aligns itself; a QLabel showing a value has to be told - if isinstance(widget, QLabel): - widget.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) - - # -- field registration ------------------------------------------------- - def _add_field(self, field: NumberLineEdit) -> None: - """A numeric input with no spreadsheet counterpart: it is locked while - the beamline is busy, and the Database/User toggle leaves it alone.""" - self._fields.append(field) - - def _add_database_field( - self, field: NumberLineEdit, on_commit: Callable[[float], None] - ) -> None: - """A numeric input that also has a spreadsheet counterpart. ``on_commit`` - stores the committed number as the user's value for that setting and - calls :meth:`_user_took_over`.""" - self._add_field(field) - field.newValue.connect(on_commit) - - # -- Database / User toggle --------------------------------------------- - def _build_source_toggle(self) -> QWidget: - container = QWidget(self) - row = QHBoxLayout(container) - row.setContentsMargins(0, 0, 0, 0) - self._database_radio.setChecked(True) - self._source_group.addButton(self._database_radio) - self._source_group.addButton(self._user_radio) - # One connection is enough: toggled fires on both directions. - self._user_radio.toggled.connect(self._on_user_values_toggled) - row.addWidget(self._database_radio) - row.addWidget(self._user_radio) - row.addStretch() - return container - - @Slot(bool) - def _on_user_values_toggled(self, checked: bool): - self._show_user_values = checked - self._refresh_fields() - - def _user_took_over(self): - """Select "User values" and let the derived read-outs catch up. Called - by every commit slot, after it stored the setting the user changed.""" - self._show_user_values = True - # blocked: _on_user_values_toggled would rewrite the fields from here, - # in the middle of the commit that got us here - self._user_radio.blockSignals(True) - self._user_radio.setChecked(True) - self._user_radio.blockSignals(False) - self._values_changed() - - @Slot(float) - def _on_transmission_committed(self, value: float): - self._user_transmission = value - self._user_took_over() - - @Slot(float) - def _on_resolution_committed(self, value: float): - self._user_resolution = value - self._user_dtz = self._res_to_dtz(value) - self.dtz_enter.force_update_value(self._user_dtz) - self._user_took_over() - - @Slot(float) - def _on_dtz_committed(self, value: float): - self._user_dtz = value - self._user_resolution = self._dtz_to_res(value) - self.high_res_enter.force_update_value(self._user_resolution) - self._user_took_over() - - def _refresh_fields(self): - """Show the values of the active source. A field that already shows its - value is left alone, so a refresh that changes nothing cannot steal - text the user is in the middle of typing.""" - self._write_active_values() - self._values_changed() - - def _setting(self, user: float | None, database: float | None, default: float) -> float: - """What a setting is worth: the value the user typed while "User - values" is selected, else the one the mounted sample asks for, else the - panel default.""" - if self._show_user_values and user is not None: - return user - if database is not None: - return database - return default - - def _write_active_values(self): - """Show every setting that follows the toggle. Panels extend this with - a line per setting of their own.""" - db = self._db_params - resolution = self._setting( - self._user_resolution, db.resolution_a, self._dtz_to_res(self._default_dtz) - ) - self.high_res_enter.set_committed_value(resolution) - # The distance follows the resolution unless the user set it directly. - self.dtz_enter.set_committed_value( - self._setting(self._user_dtz, None, self._res_to_dtz(resolution)) - ) - self.transmission_enter.set_committed_value( - self._setting(self._user_transmission, db.transmission, self._default_transmission) - ) - - def _values_changed(self) -> None: - """Runs whenever the effective values change: a commit, the toggle, a - new sample. Panels extend it to refresh their read-outs; here it pushes - the two settings the raster grid manager keeps a copy of.""" - self.dtz_updated.emit(self.dtz_enter.committed_value) - self.transmission_updated.emit(self.transmission_enter.committed_value) - - # -- resolution <-> detector distance ----------------------------------- - def _dtz_to_res(self, dtz: float) -> float: - return self._diffraction.resolution_angstrom(dtz) - - def _res_to_dtz(self, res: float) -> float: - return max(self._diffraction.calc_dtz_mm(res), self.MIN_DTZ) - - # -- status ------------------------------------------------------------- - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - previous_energy = self._diffraction.energy_keV - - self._diffraction = s.diffraction - self._beamline_state = s.state - self._ring_current = s.bl.ring_current_mA - self._experiment_shutter_state = s.bl.exp_shutter_open - self._door_prohibited = getattr(s.bl, "pss_prohibited", None) - - self.dtz_enter.update_limits(s.bl.dtz_min, s.bl.dtz_max) - self.high_res_enter.update_limits( - self._dtz_to_res(s.bl.dtz_min), self._dtz_to_res(s.bl.dtz_max) - ) - - if self._diffraction.energy_keV != previous_energy: - dtz = self.dtz_enter.committed_value - resolution = self._dtz_to_res(dtz) - self.high_res_enter.set_committed_value(resolution) - - if self._show_user_values and self._user_dtz is not None: - self._user_resolution = resolution - - self._can_edit_params = (not s.busy) and ( - s.session.session in (SessionsStateEnum.OwnedByYou, SessionsStateEnum.PendingElseToYou) - ) - for field in self._fields: - field.setReadOnly(not self._can_edit_params) - - # A different sample, or an edited spreadsheet row for the same one. - db_params = SampleParameters.from_sample(s.sample) - if db_params != self._db_params: - logger.info(f"Sample parameters changed to {db_params}") - self._db_params = db_params - self._refresh_fields() - - def check_before_run(self, scan_kind: str): - if not precondition_check( - self, - ring_current=self._ring_current, - shutter_open=self._experiment_shutter_state, - door_prohibited=self._door_prohibited, - ): - logger.warning("Beamline not ready; user chose not to continue scan") - return False - file_path_panel = find_file_path_panel(self) - if file_path_panel is not None: - reply = file_path_panel.file_path_error_box(scan_kind=scan_kind) - logger.debug(f"reply from file path panel: {reply}") - if not reply: - logger.warning("Error with file path.") - return False - return True diff --git a/src/aare/gui/panels/smargon_panel.py b/src/aare/gui/panels/smargon_panel.py deleted file mode 100644 index da20a50b..00000000 --- a/src/aare/gui/panels/smargon_panel.py +++ /dev/null @@ -1,130 +0,0 @@ -from aarecommon.math.coordinate import Coordinate, SmargonCoordinate -from aarecommon.math.sample_geometry import SampleGeometryModel -from aarecommon.models.models import DAQStatusModel -from PySide6.QtCore import Signal, Slot -from PySide6.QtWidgets import QGridLayout, QLabel, QPushButton, QWidget - -from aare.gui.widgets.button_with_payload import ButtonWithPayload -from aare.gui.widgets.motor_move_group import MotorMoveGroup -from aare.gui.widgets.number_line_edit import NumberLineEdit -from aare.gui.widgets.title_label import TitleLabel - - -class SmargonMoveWidget(QWidget): - smargon_rel = Signal(Coordinate) - - def __init__(self, parent=None): - super().__init__(parent) - - grid_layout = QGridLayout(self) - grid_layout.setColumnStretch(0, 1) - grid_layout.setColumnStretch(1, 1) - grid_layout.setColumnStretch(2, 1) - - self.button_left = ButtonWithPayload("←", payload={"x": 1, "y": 0, "z": 0}) - self.button_right = ButtonWithPayload("→", payload={"x": -1, "y": 0, "z": 0}) - self.button_up = ButtonWithPayload("↑", payload={"x": 0, "y": 1, "z": 0}) - self.button_down = ButtonWithPayload("↓", payload={"x": 0, "y": -1, "z": 0}) - - self.button_left.pressed.connect(self.smargon_button) - self.button_right.pressed.connect(self.smargon_button) - self.button_up.pressed.connect(self.smargon_button) - self.button_down.pressed.connect(self.smargon_button) - - grid_layout.addWidget(self.button_up, 0, 1) - grid_layout.addWidget(self.button_left, 1, 0) - grid_layout.addWidget(self.button_right, 1, 2) - grid_layout.addWidget(self.button_down, 2, 1) - - self.button_in = ButtonWithPayload("+", payload={"x": 0, "y": 0, "z": 1}) - self.button_out = ButtonWithPayload("-", payload={"x": 0, "y": 0, "z": -1}) - - self.button_in.pressed.connect(self.smargon_button) - self.button_out.pressed.connect(self.smargon_button) - grid_layout.addWidget(self.button_in, 3, 2) - grid_layout.addWidget(self.button_out, 3, 0) - - @Slot(dict) - def smargon_button(self, payload: dict): - self.smargon_rel.emit(Coordinate(x=payload["x"], y=payload["y"], z=payload["z"])) - - -class SmargonPanel(QWidget): - smargon = Signal(SmargonCoordinate) - - def __init__(self, parent=None): - super().__init__(parent) - self._geom: SampleGeometryModel | None = None - self._step = 100 - - grid_layout = QGridLayout(self) - - grid_layout.addWidget( - TitleLabel("Smargon", self, collapsible=True, default_collapsed=False), 0, 0, 1, 7 - ) - - grid_layout.addWidget(QLabel("Chi", parent=self), 1, 0) - # Vincent says Chi is limited to 0 to 30 - self.chi_enter = NumberLineEdit(-0.2, 30, decimals=1, parent=self) - grid_layout.addWidget(self.chi_enter, 1, 1) - grid_layout.addWidget(QLabel("°", parent=self), 1, 2) - - grid_layout.addWidget(QLabel("Phi", parent=self), 1, 3) - self.phi_enter = NumberLineEdit(-0.2, 360, decimals=1, parent=self) - grid_layout.addWidget(self.phi_enter, 1, 4) - - grid_layout.addWidget(QLabel("°", parent=self), 1, 5) - - # Chi/Phi are staged (orange) and only sent on Move (green until the - # motor reports the target reached) — see MotorMoveGroup. - self.move_group = MotorMoveGroup(parent=self) - self.move_group.add_box("chi", self.chi_enter) - self.move_group.add_box("phi", self.phi_enter) - self.move_group.applied.connect(self._move_axes) - # Own row: sharing row 1 squeezed the Chi/Phi entry boxes. - grid_layout.addWidget(self.move_group.button, 2, 0, 1, 7) - - self.home_button = QPushButton("Move to mounting position", parent=self) - grid_layout.addWidget(self.home_button, 3, 0, 1, 7) - self.home_button.clicked.connect(self.home) - - self.move_panel = SmargonMoveWidget(parent=self) - grid_layout.addWidget(self.move_panel, 4, 0, 1, 7) - self.move_panel.smargon_rel.connect(self.smargon_rel) - - grid_layout.addWidget(QLabel("Step", parent=self), 5, 0) - self.step = NumberLineEdit(1, 1000, 100, 0, parent=self) - # Span to the μm label so the box gets real width instead of the - # narrow column shared with the Chi entry. - grid_layout.addWidget(self.step, 5, 1, 1, 4) - grid_layout.addWidget(QLabel("μm", parent=self), 5, 5) - self.step.newValue.connect(self.step_changed) - - @Slot(float) - def step_changed(self, f: float): - self._step = f - - @Slot() - def home(self): - # TODO move SMARGON_HOME to REDIS, allow GUI to read this value - self.smargon.emit(SmargonCoordinate(sh_mm=Coordinate(x=0, y=0, z=18), phi_deg=0, chi_deg=0)) - - @Slot(dict) - def _move_axes(self, targets: dict[str, float]): - # only the staged axes move — absent keys stay None (no motion) - self.smargon.emit(SmargonCoordinate(chi_deg=targets.get("chi"), phi_deg=targets.get("phi"))) - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - self.move_group.update_actual("chi", s.geom.smargon.chi_deg) - self.move_group.update_actual("phi", s.geom.smargon.phi_deg) - self._geom = s.geom - - @Slot(Coordinate) - def smargon_rel(self, c: Coordinate): - if self._geom is None: - return - - self.smargon.emit( - SmargonCoordinate(sh_mm=self._geom.beamline_to_smargon(c * self._step / 1000.0)) - ) diff --git a/src/aare/gui/panels/smargon_trace_panel.py b/src/aare/gui/panels/smargon_trace_panel.py deleted file mode 100644 index d1b1fb8e..00000000 --- a/src/aare/gui/panels/smargon_trace_panel.py +++ /dev/null @@ -1,645 +0,0 @@ -from __future__ import annotations - -import csv -from math import sqrt -from pathlib import Path - -import numpy as np -from aarecommon.config.logger import setup_logger -from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as FigureCanvas -from matplotlib.figure import Figure -from PySide6.QtCore import QSettings, Qt, QTimer -from PySide6.QtWidgets import ( - QCheckBox, - QComboBox, - QFileDialog, - QFormLayout, - QGroupBox, - QHBoxLayout, - QLabel, - QPushButton, - QTableWidget, - QTableWidgetItem, - QVBoxLayout, - QWidget, -) - -from aare.gui.constants import LOGGER_NAME - -logger = setup_logger(LOGGER_NAME) - - -class SmargonTracePanel(QWidget): - HOME_X_MM = 0.0 - HOME_Y_MM = 0.0 - HOME_Z_MM = 18.0 - TABLE_MAX_ROWS = 20 - - COLOR_X = "tab:red" - COLOR_Y = "tab:green" - COLOR_Z = "tab:blue" - COLOR_DISTANCE = "tab:purple" - - SETTINGS_GROUP = "smargon_trace_panel" - - def __init__(self, csv_path: str | Path = "logs/smargon_trace.csv", parent=None): - super().__init__(parent) - - self._csv_path = Path(csv_path) - self._active_csv_path: Path | None = None - self._last_mtime_ns: int | None = None - self._last_rows: list[dict[str, object]] = [] - self._last_distances: list[float] = [] - self._last_lengths: list[float] = [] - - self._status = QLabel("Waiting for smargon trace data...") - self._status.setWordWrap(True) - - self._summary = QLabel( - f"Home position: " - f"X={self.HOME_X_MM:.3f} mm, " - f"Y={self.HOME_Y_MM:.3f} mm, " - f"Z={self.HOME_Z_MM:.3f} mm" - ) - self._summary.setWordWrap(True) - - self._metrics = QLabel("Latest metrics: distance=n/a | length=n/a") - self._metrics.setWordWrap(True) - - self._show_summary_cb = QCheckBox("Summary") - self._show_delta_cb = QCheckBox("Delta") - self._show_absolute_cb = QCheckBox("Absolute") - self._show_distance_cb = QCheckBox("Total distance") - self._show_table_cb = QCheckBox("Table") - - self._show_summary_cb.setChecked(True) - self._show_delta_cb.setChecked(True) - self._show_absolute_cb.setChecked(False) - self._show_distance_cb.setChecked(False) - self._show_table_cb.setChecked(False) - - self._units_combo = QComboBox() - self._units_combo.addItems(["mm", "µm"]) - self._units_combo.setCurrentText("mm") - self._units_combo.setMaximumWidth(90) - - self._export_btn = QPushButton("Export table CSV") - self._export_btn.clicked.connect(self._export_table_csv) - - display_group = QGroupBox("Display") - display_layout = QHBoxLayout(display_group) - display_layout.setContentsMargins(8, 6, 8, 6) - display_layout.setSpacing(10) - display_layout.addWidget(self._show_summary_cb) - display_layout.addWidget(self._show_delta_cb) - display_layout.addWidget(self._show_absolute_cb) - display_layout.addWidget(self._show_distance_cb) - display_layout.addWidget(self._show_table_cb) - display_layout.addStretch() - display_layout.addWidget(QLabel("Units:")) - display_layout.addWidget(self._units_combo) - display_layout.addWidget(self._export_btn) - - self._summary_group = QGroupBox("Summary") - summary_layout = QFormLayout(self._summary_group) - summary_layout.setContentsMargins(8, 6, 8, 6) - summary_layout.setSpacing(6) - summary_layout.addRow("Status:", self._status) - summary_layout.addRow("Position:", self._summary) - summary_layout.addRow("Metrics:", self._metrics) - - self._figure = Figure(figsize=(7, 7)) - self._canvas = FigureCanvas(self._figure) - - self._table = QTableWidget(self) - self._table.setColumnCount(8) - self._table.setHorizontalHeaderLabels( - ["Point", "Event", "Sample", "X", "Y", "Z", "Distance", "Length"] - ) - self._table.verticalHeader().setVisible(False) - self._table.setAlternatingRowColors(True) - self._table.setVisible(False) - - layout = QVBoxLayout(self) - layout.setContentsMargins(6, 6, 6, 6) - layout.setSpacing(8) - layout.addWidget(display_group) - layout.addWidget(self._summary_group) - layout.addWidget(self._canvas) - layout.addWidget(self._table) - - self._show_summary_cb.toggled.connect(self._on_controls_changed) - self._show_delta_cb.toggled.connect(self._on_controls_changed) - self._show_absolute_cb.toggled.connect(self._on_controls_changed) - self._show_distance_cb.toggled.connect(self._on_controls_changed) - self._show_table_cb.toggled.connect(self._on_controls_changed) - self._units_combo.currentTextChanged.connect(lambda _text: self._on_controls_changed()) - - self._load_settings() - - self._timer = QTimer(self) - self._timer.setInterval(1000) - self._timer.timeout.connect(self.refresh_plot) - self._timer.start() - - self._apply_visibility_settings() - self.refresh_plot(force=True) - - def refresh_plot(self, force: bool = False) -> None: - csv_path = self._resolve_csv_path() - - if csv_path is None or not csv_path.exists(): - self._active_csv_path = None - self._last_mtime_ns = None - self._last_rows = [] - self._last_distances = [] - self._last_lengths = [] - self._status.setText( - "No trace file found. Tried: " + ", ".join(str(p) for p in self._candidate_paths()) - ) - self._summary.setText( - f"Home position: " - f"X={self.HOME_X_MM:.3f} mm, " - f"Y={self.HOME_Y_MM:.3f} mm, " - f"Z={self.HOME_Z_MM:.3f} mm" - ) - self._metrics.setText("Latest metrics: distance=n/a | length=n/a") - self._draw_empty("No smargon trace file found yet") - self._clear_table() - return - - try: - stat = csv_path.stat() - if ( - not force - and self._active_csv_path == csv_path - and self._last_mtime_ns == stat.st_mtime_ns - ): - return - - self._active_csv_path = csv_path - self._last_mtime_ns = stat.st_mtime_ns - - rows = self._read_rows(csv_path) - if not rows: - self._last_rows = [] - self._last_distances = [] - self._last_lengths = [] - self._status.setText(f"Trace file is empty: {csv_path}") - self._summary.setText( - f"Home position: " - f"X={self.HOME_X_MM:.3f} mm, " - f"Y={self.HOME_Y_MM:.3f} mm, " - f"Z={self.HOME_Z_MM:.3f} mm" - ) - self._metrics.setText("Latest metrics: distance=n/a | length=n/a") - self._draw_empty("Smargon trace file is empty") - self._clear_table() - return - - unit_name, unit_scale = self._unit_settings() - - x = list(range(1, len(rows) + 1)) - - shx_mm = [row["shx_mm"] for row in rows] - shy_mm = [row["shy_mm"] for row in rows] - shz_mm = [row["shz_mm"] for row in rows] - - dx_mm = [value - self.HOME_X_MM for value in shx_mm] - dy_mm = [value - self.HOME_Y_MM for value in shy_mm] - dz_mm = [value - self.HOME_Z_MM for value in shz_mm] - - shx = [value * unit_scale for value in shx_mm] - shy = [value * unit_scale for value in shy_mm] - shz = [value * unit_scale for value in shz_mm] - - dx = [value * unit_scale for value in dx_mm] - dy = [value * unit_scale for value in dy_mm] - dz = [value * unit_scale for value in dz_mm] - - distances_mm = [ - sqrt(dx0**2 + dy0**2 + dz0**2) for dx0, dy0, dz0 in zip(dx_mm, dy_mm, dz_mm) - ] - distances = [value * unit_scale for value in distances_mm] - - lengths_mm = [self._projected_length_mm(row) for row in rows] - lengths = [value * unit_scale for value in lengths_mm] - - self._last_rows = rows - self._last_distances = distances - self._last_lengths = lengths - - self._redraw_plots( - x=x, - shx=shx, - shy=shy, - shz=shz, - dx=dx, - dy=dy, - dz=dz, - distances=distances, - unit_name=unit_name, - ) - - last = rows[-1] - last_dx_mm = dx_mm[-1] - last_dy_mm = dy_mm[-1] - last_dz_mm = dz_mm[-1] - - distance_value = distances[-1] - length_value = lengths[-1] - - self._status.setText( - f"Loaded {len(rows)} points from {csv_path} | " - f"last event={last['event']} | " - f"sample_id={last['sample_id']}" - ) - self._summary.setText( - f"Home: X={self.HOME_X_MM * unit_scale:.3f}, " - f"Y={self.HOME_Y_MM * unit_scale:.3f}, " - f"Z={self.HOME_Z_MM * unit_scale:.3f} {unit_name} | " - f"Latest: X={last['shx_mm'] * unit_scale:.5f}, " - f"Y={last['shy_mm'] * unit_scale:.5f}, " - f"Z={last['shz_mm'] * unit_scale:.5f} {unit_name} | " - f"Δ: X={last_dx_mm * unit_scale:+.5f}, " - f"Y={last_dy_mm * unit_scale:+.5f}, " - f"Z={last_dz_mm * unit_scale:+.5f} {unit_name}" - ) - self._metrics.setText( - f"distance={distance_value:.5f} {unit_name} | " - f"length={length_value:.5f} {unit_name} (beamline-plane projected)" - ) - - self._populate_table( - rows=rows, - distances=distances, - lengths=lengths, - unit_name=unit_name, - unit_scale=unit_scale, - ) - - except Exception as e: - logger.warning(f"Failed to load the smargon trace from {csv_path}", exc_info=True) - self._last_rows = [] - self._last_distances = [] - self._last_lengths = [] - self._status.setText(f"Failed to load trace from {csv_path}: {e}") - self._summary.setText( - f"Home position: " - f"X={self.HOME_X_MM:.3f} mm, " - f"Y={self.HOME_Y_MM:.3f} mm, " - f"Z={self.HOME_Z_MM:.3f} mm" - ) - self._metrics.setText("Latest metrics: distance=n/a | length=n/a") - self._draw_empty("Failed to parse smargon trace") - self._clear_table() - - def showEvent(self, event) -> None: - super().showEvent(event) - self.refresh_plot(force=True) - - def _on_controls_changed(self) -> None: - self._save_settings() - self._apply_visibility_settings() - - def _load_settings(self) -> None: - settings = QSettings() - settings.beginGroup(self.SETTINGS_GROUP) - self._show_summary_cb.setChecked(settings.value("show_summary", True, type=bool)) - self._show_delta_cb.setChecked(settings.value("show_delta", True, type=bool)) - self._show_absolute_cb.setChecked(settings.value("show_absolute", False, type=bool)) - self._show_distance_cb.setChecked(settings.value("show_distance", False, type=bool)) - self._show_table_cb.setChecked(settings.value("show_table", False, type=bool)) - self._units_combo.setCurrentText(settings.value("units", "mm", type=str)) - settings.endGroup() - - def _save_settings(self) -> None: - settings = QSettings() - settings.beginGroup(self.SETTINGS_GROUP) - settings.setValue("show_summary", self._show_summary_cb.isChecked()) - settings.setValue("show_delta", self._show_delta_cb.isChecked()) - settings.setValue("show_absolute", self._show_absolute_cb.isChecked()) - settings.setValue("show_distance", self._show_distance_cb.isChecked()) - settings.setValue("show_table", self._show_table_cb.isChecked()) - settings.setValue("units", self._units_combo.currentText()) - settings.endGroup() - - def _apply_visibility_settings(self) -> None: - if not ( - self._show_delta_cb.isChecked() - or self._show_absolute_cb.isChecked() - or self._show_distance_cb.isChecked() - ): - self._show_delta_cb.blockSignals(True) - self._show_delta_cb.setChecked(True) - self._show_delta_cb.blockSignals(False) - - self._summary_group.setVisible(self._show_summary_cb.isChecked()) - self._table.setVisible(self._show_table_cb.isChecked()) - self.refresh_plot(force=True) - - def _export_table_csv(self) -> None: - if not self._last_rows: - return - - unit_name, unit_scale = self._unit_settings() - file_path, _ = QFileDialog.getSaveFileName( - self, "Export Smargon Trace Table", "smargon_trace_export.csv", "CSV Files (*.csv)" - ) - if not file_path: - return - - with open(file_path, "w", encoding="utf-8", newline="") as f: - writer = csv.writer(f) - writer.writerow( - [ - "point", - "timestamp", - "event", - "sample_id", - f"shx_{unit_name}", - f"shy_{unit_name}", - f"shz_{unit_name}", - f"distance_{unit_name}", - f"length_{unit_name}", - "omega_deg", - "phi_deg", - "chi_deg", - ] - ) - - for idx, (row, distance_value, length_value) in enumerate( - zip(self._last_rows, self._last_distances, self._last_lengths), start=1 - ): - writer.writerow( - [ - idx, - row["timestamp"], - row["event"], - row["sample_id"], - float(row["shx_mm"]) * unit_scale, - float(row["shy_mm"]) * unit_scale, - float(row["shz_mm"]) * unit_scale, - distance_value, - length_value, - row["omega_deg"], - row["phi_deg"], - row["chi_deg"], - ] - ) - - def _redraw_plots( - self, - *, - x: list[int], - shx: list[float], - shy: list[float], - shz: list[float], - dx: list[float], - dy: list[float], - dz: list[float], - distances: list[float], - unit_name: str, - ) -> None: - self._figure.clear() - - enabled = [] - if self._show_delta_cb.isChecked(): - enabled.append("delta") - if self._show_absolute_cb.isChecked(): - enabled.append("absolute") - if self._show_distance_cb.isChecked(): - enabled.append("distance") - - axes = self._figure.subplots(len(enabled), 1, squeeze=False) - axes_list = [row[0] for row in axes] - - for ax, plot_name in zip(axes_list, enabled): - if plot_name == "delta": - ax.plot(x, dx, marker="o", color=self.COLOR_X, label=f"ΔSHX [{unit_name}]") - ax.plot(x, dy, marker="o", color=self.COLOR_Y, label=f"ΔSHY [{unit_name}]") - ax.plot(x, dz, marker="o", color=self.COLOR_Z, label=f"ΔSHZ [{unit_name}]") - ax.axhline(0.0, color="black", linewidth=1.0, alpha=0.5) - ax.set_title("Smargon displacement from home") - ax.set_ylabel(f"Δ position [{unit_name}]") - ax.grid(True, alpha=0.3) - ax.legend(loc="best") - - elif plot_name == "absolute": - ax.plot(x, shx, marker="o", color=self.COLOR_X, label=f"SHX [{unit_name}]") - ax.plot(x, shy, marker="o", color=self.COLOR_Y, label=f"SHY [{unit_name}]") - ax.plot(x, shz, marker="o", color=self.COLOR_Z, label=f"SHZ [{unit_name}]") - ax.set_title("Smargon absolute position") - ax.set_ylabel(f"Position [{unit_name}]") - ax.grid(True, alpha=0.3) - ax.legend(loc="best") - - elif plot_name == "distance": - ax.plot( - x, - distances, - marker="o", - color=self.COLOR_DISTANCE, - label=f"Total distance [{unit_name}]", - ) - ax.set_title("Total distance from home") - ax.set_ylabel(f"Distance [{unit_name}]") - ax.grid(True, alpha=0.3) - ax.legend(loc="best") - - ax.set_xlabel("Trace point") - - self._figure.tight_layout() - self._canvas.draw_idle() - - def _populate_table( - self, - *, - rows: list[dict[str, object]], - distances: list[float], - lengths: list[float], - unit_name: str, - unit_scale: float, - ) -> None: - recent_rows = rows[-self.TABLE_MAX_ROWS :] - recent_distances = distances[-self.TABLE_MAX_ROWS :] - recent_lengths = lengths[-self.TABLE_MAX_ROWS :] - - self._table.setRowCount(len(recent_rows)) - self._table.setHorizontalHeaderLabels( - [ - "Point", - "Event", - "Sample", - f"X [{unit_name}]", - f"Y [{unit_name}]", - f"Z [{unit_name}]", - f"Distance [{unit_name}]", - f"Length [{unit_name}]", - ] - ) - - start_idx = len(rows) - len(recent_rows) + 1 - for row_idx, (row, distance_value, length_value) in enumerate( - zip(recent_rows, recent_distances, recent_lengths) - ): - values = [ - str(start_idx + row_idx), - str(row["event"]), - str(row["sample_id"]), - f"{float(row['shx_mm']) * unit_scale:.5f}", - f"{float(row['shy_mm']) * unit_scale:.5f}", - f"{float(row['shz_mm']) * unit_scale:.5f}", - f"{distance_value:.5f}", - f"{length_value:.5f}", - ] - for col_idx, value in enumerate(values): - item = QTableWidgetItem(value) - item.setTextAlignment(Qt.AlignmentFlag.AlignCenter) - self._table.setItem(row_idx, col_idx, item) - - self._table.resizeColumnsToContents() - - def _clear_table(self) -> None: - self._table.setRowCount(0) - - def _unit_settings(self) -> tuple[str, float]: - if self._units_combo.currentText() == "µm": - return "µm", 1000.0 - return "mm", 1.0 - - def _candidate_paths(self) -> list[Path]: - here = Path(__file__).resolve() - project_root = here.parents[4] - - candidates = [ - Path.cwd() / self._csv_path, - project_root / self._csv_path, - project_root / "src" / "aare" / "daq" / "logs" / "smargon_trace.csv", - project_root / "src" / "aare" / "gui" / "logs" / "smargon_trace.csv", - Path("/sls/mx/applications/logs/smargon_trace.csv"), - ] - - out: list[Path] = [] - seen: set[str] = set() - for path in candidates: - key = str(path.resolve()) if path.exists() else str(path) - if key not in seen: - out.append(path) - seen.add(key) - return out - - def _resolve_csv_path(self) -> Path | None: - existing = [p for p in self._candidate_paths() if p.exists()] - if not existing: - return None - return max(existing, key=lambda p: p.stat().st_mtime_ns) - - def _read_rows(self, csv_path: Path) -> list[dict[str, object]]: - rows: list[dict[str, object]] = [] - - with csv_path.open("r", encoding="utf-8", newline="") as f: - reader = csv.DictReader(f) - for row in reader: - try: - rows.append( - { - "timestamp": row.get("timestamp", row.get("ts", "")), - "event": row.get("event", ""), - "sample_id": row.get("sample_id", ""), - "omega_deg": float(row.get("omega_deg", "nan")), - "zoom": float(row.get("zoom", "nan")), - "shx_mm": float(row.get("shx_mm", "nan")), - "shy_mm": float(row.get("shy_mm", "nan")), - "shz_mm": float(row.get("shz_mm", "nan")), - "phi_deg": float(row.get("phi_deg", "nan")), - "chi_deg": float(row.get("chi_deg", "nan")), - } - ) - except (TypeError, ValueError): - continue - - return rows - - def _projected_length_mm(self, row: dict[str, object]) -> float: - rel = np.array( - [ - float(row["shx_mm"]) - self.HOME_X_MM, - float(row["shy_mm"]) - self.HOME_Y_MM, - float(row["shz_mm"]) - self.HOME_Z_MM, - ], - dtype=float, - ) - - vec_x = self._smargon_nudge_basis( - axis="x", - omega_deg=float(row["omega_deg"]), - phi_deg=float(row["phi_deg"]), - chi_deg=float(row["chi_deg"]), - ) - vec_y = self._smargon_nudge_basis( - axis="y", - omega_deg=float(row["omega_deg"]), - phi_deg=float(row["phi_deg"]), - chi_deg=float(row["chi_deg"]), - ) - - beam_x = float(np.dot(rel, vec_x)) - beam_y = float(np.dot(rel, vec_y)) - - return sqrt(beam_x**2 + beam_y**2) - - def _smargon_nudge_basis( - self, *, axis: str, omega_deg: float, phi_deg: float, chi_deg: float - ) -> np.ndarray: - phi = np.radians(np.around(phi_deg, decimals=1)) - chi = np.radians(np.around(chi_deg, decimals=1)) - omega = np.radians(np.around(omega_deg, decimals=1)) - - if axis == "x": - coord_x, coord_y, coord_z = 1.0, 0.0, 0.0 - elif axis == "y": - coord_x, coord_y, coord_z = 0.0, 1.0, 0.0 - else: - raise ValueError(f"Unsupported axis: {axis}") - - co = np.cos(omega) - so = np.sin(omega) - cp = np.cos(phi) - sp = np.sin(phi) - cc = np.cos(chi) - sc = np.sin(chi) - - offset_x = ( - -coord_z * co * sp - - coord_y * so * sp - + coord_x * cp * sc - - coord_y * co * cc * cp - + coord_z * so * cc * cp - ) - offset_y = ( - -coord_z * co * cp - - coord_y * so * cp - - coord_x * sc * sp - + coord_y * co * cc * sp - - coord_z * so * cc * sp - ) - offset_z = -coord_x * cc - coord_y * co * sc + coord_z * so * sc - - vec = np.array([offset_x, offset_y, offset_z], dtype=float) - norm = np.linalg.norm(vec) - - if norm == 0.0: - return np.array([0.0, 0.0, 0.0], dtype=float) - - return vec / norm - - def _draw_empty(self, message: str) -> None: - self._figure.clear() - ax = self._figure.add_subplot(111) - ax.set_title("Smargon trace") - ax.text(0.5, 0.5, message, ha="center", va="center", transform=ax.transAxes) - ax.set_xticks([]) - ax.set_yticks([]) - self._figure.tight_layout() - self._canvas.draw_idle() diff --git a/src/aare/gui/panels/smart_rotation_panel.py b/src/aare/gui/panels/smart_rotation_panel.py deleted file mode 100644 index fb6e0b5c..00000000 --- a/src/aare/gui/panels/smart_rotation_panel.py +++ /dev/null @@ -1,541 +0,0 @@ -import math - -from aarecommon.config.beamline import mx_beamline -from aarecommon.config.logger import setup_logger -from aarecommon.models.beamline import MXBeamline -from aarecommon.models.models import CrystalSize, DAQStatusModel, SimpleScanParameters -from aarecommon.models.rotation_scan import RotationScanRequest -from PySide6.QtCore import Qt, Signal, Slot -from PySide6.QtWidgets import QGridLayout, QLabel, QPushButton, QSizePolicy, QSpacerItem, QWidget - -from aare.gui.constants import LOGGER_NAME -from aare.gui.panels.file_path_panel import find_file_path_panel -from aare.gui.panels.rotation_data_collection import ( - MAX_OMEGA_SPEED_DEG_S, - MIN_EXP_TIME_S, - add_data_to_path, -) -from aare.gui.styles import ABORT_TEXT, GO_TEXT, STATUS_ALERT -from aare.gui.widgets.number_line_edit import NumberLineEdit - -logger = setup_logger(LOGGER_NAME) - -# --- Dose model ----------------------------------------------------------- -# kdose: photons um^-2 needed per Gy at lambda = 1 A, from Holton (2009) -# J. Synchrotron Rad. 16, 133-142. The lambda^2 scaling below is the -# photoelectric limit (mu_en/rho ~ lambda^3, photon energy ~ 1/lambda) and -# assumes negligible heavy-metal content; Se-Met and metalloprotein crystals -# absorb more than this, so use RADDOSE-3D for those. -KDOSE_1A_PH_UM2_GY = 2000.0 - -# Protein-solvent glass transition. Warkentin & Thorne fit two Arrhenius -# regimes either side of ~200 K: below it damage is athermal (Ea ~ 1 kJ/mol), -# above it diffusion-dominated (Ea ~ 18 kJ/mol) and the cryo budget no longer -# applies. Switching at 250 K would apply the cryo budget in the 200-250 K -# band and overdose there by close to an order of magnitude. -GLASS_TRANSITION_K = 200.0 - -# --- Strategy quantisation ------------------------------------------------ -# Detector frame rate we pin on the flux-rich beamline (X10SA), where the -# strategy solves for transmission instead of exposure time. -FIXED_FRAME_RATE_HZ = 100.0 -DEFAULT_MIN_EXP_TIME_S = 0.0005 -# Shortest frame the strategy will ask a beamline for, where that is longer -# than the detector's own floor in MIN_EXP_TIME_S. X06DA's detector reaches -# 1/900 s, but 2 ms is the shortest usable frame for a strategy collection -# there. Stated explicitly so it does not silently drop to 1.2 ms if -# EXP_TIME_STEP_S is ever made finer. -STRATEGY_MIN_EXP_TIME_S = {MXBeamline.X06DA: 0.002} -# Entry limits for the visible-resolution field. Named because the clamp on -# the DAQ value has to use the same numbers as the widget's validator. -VISIBLE_RES_MIN_A = 0.8 -VISIBLE_RES_MAX_A = 10.0 -VISIBLE_RES_DEFAULT_A = 2.0 -# Two DAQ resolutions closer than this are the same raster result reported -# again, not a new one. -DAQ_RES_EPS_A = 0.001 -VISIBLE_RES_LABEL = "Visible resolution" -DTZ_STEP_MM = 10.0 -EXP_TIME_STEP_S = 0.001 -TRANSMISSION_SIG_DIGITS = 2 - - -# Grid steps are not representable in binary (0.001, 0.1, ...), so an exact -# multiple can land a hair either side of the integer. Without this tolerance -# _floor_to(1.7, 0.1) returns 1.6 and _ceil_to(0.011, 0.001) returns 0.012. -_QUANT_EPS = 1e-9 - - -def _floor_to(value: float, step: float) -> float: - # Rounded back to 12 dp so the result is a clean grid value: 17 * 0.1 is - # 1.7000000000000002, which would be displayed and emitted verbatim. - return round(math.floor(value / step + _QUANT_EPS) * step, 12) - - -def _ceil_to(value: float, step: float) -> float: - return round(math.ceil(value / step - _QUANT_EPS) * step, 12) - - -def _floor_significant(value: float, digits: int) -> float: - """Round down to `digits` significant digits. - - Down, not nearest: every quantisation in the strategy is allowed to spend - less than the dose budget but never more. - """ - if value <= 0.0: - return 0.0 - step = 10.0 ** (math.floor(math.log10(value) + _QUANT_EPS) - (digits - 1)) - return _floor_to(value, step) - - -class SimpleRotationSettingsPanel(QWidget): - rotation_scan = Signal(RotationScanRequest) - viewer_track_online = Signal() - parameters_changed = Signal(SimpleScanParameters) - - def __init__(self, parent=None): - - super().__init__(parent) - - self._beamline = mx_beamline() - self._daq_best_res = None - # Distinguishes "no DAQ resolution yet" from "DAQ reports none", so the - # first status tick always paints the label. - self._daq_res_applied = False - self.n_images = 1 - self.transmission = 1.0 - self.delivered_dose_MGy = 0.0 - self.target_dose_MGy = None - self.dose_rate_MGy_s = None - self._filename = "" - self.dtz = 120 - self.image_time_s = 0.1 - self._d = None - self._omega = 0 - self.total_time_s = 0 - self.parameters = SimpleScanParameters() - self._prev_params = SimpleScanParameters() - - self._layout = QGridLayout(self) - # Top margin 0 like the Raster/Rotation pages (their toggle row sits - # at margin 0), so the gap under the ML-centring row matches. - m = self._layout.contentsMargins() - self._layout.setContentsMargins(m.left(), 0, m.right(), 3) - - # Visible resolution (entry). The label carries the provenance of the - # value: silence means it came from the DAQ, otherwise it says so. - self.visible_res_label = QLabel(VISIBLE_RES_LABEL, parent=self) - self._layout.addWidget(self.visible_res_label, 0, 0) - self.visible_res_enter = NumberLineEdit( - VISIBLE_RES_MIN_A, - VISIBLE_RES_MAX_A, - decimals=2, - default=VISIBLE_RES_DEFAULT_A, - parent=self, - track_pending=True, - ) - self._layout.addWidget(self.visible_res_enter, 0, 1, 1, 3) - self._layout.addWidget(QLabel("Å", parent=self), 0, 4) - self.visible_res_enter.newValue.connect(self.set_visible_resolution) - - self._layout.addWidget(QLabel("Start angle", parent=self), 1, 0) - self.start_angle_enter = NumberLineEdit( - -720, 720.0, 0.0, decimals=3, parent=self, track_pending=True - ) - self._layout.addWidget(self.start_angle_enter, 1, 1, 1, 3) - self._layout.addWidget(QLabel("°", parent=self), 1, 4) - - self.omega_button = QPushButton("Ω") - self.omega_button.setFixedWidth(30) - self.omega_button.clicked.connect(self.update_omega_start) - self._layout.addWidget(self.omega_button, 1, 5) - self.start_angle_enter.newValue.connect(self.set_start_angle) - - # Angular range (entry) - self._layout.addWidget(QLabel("Total angle", parent=self), 2, 0) - self.angular_range_enter = NumberLineEdit( - 5.0, 1000.0, decimals=3, default=360.0, parent=self, track_pending=True - ) - self._layout.addWidget(self.angular_range_enter, 2, 1, 1, 3) - self._layout.addWidget(QLabel("°", parent=self), 2, 4) - self.angular_range_enter.newValue.connect(self.set_total_angle) - - self._layout.addWidget(QLabel("Image angle", parent=self), 3, 0) - self.image_angle_enter = NumberLineEdit( - 0.001, 1.000, decimals=3, default=0.2, parent=self, track_pending=True - ) - self._layout.addWidget(self.image_angle_enter, 3, 1, 1, 3) - self._layout.addWidget(QLabel("°", parent=self), 3, 4) - self.image_angle_enter.newValue.connect(self.set_image_angle) - - self._layout.addWidget(QLabel("Dose 1 Å res.", parent=self), 4, 0) - self.dose_ang_enter = NumberLineEdit( - 0.01, 20.0, decimals=2, default=5.0, parent=self, track_pending=True - ) - self._layout.addWidget(self.dose_ang_enter, 4, 1, 1, 3) - self._layout.addWidget(QLabel("MGy/Å", parent=self), 4, 4) - self.dose_ang_enter.newValue.connect(self.set_dose_ang) - - # Run + Abort directly under the last configurable row; the read-only - # block below is reference info, not something to scroll past to act. - self.run_rotation_button = QPushButton("Run rotation", parent=self) - self.run_rotation_button.setStyleSheet(f"color: {GO_TEXT};") - self.run_rotation_button.clicked.connect(self.run_measurement) - self._layout.addWidget(self.run_rotation_button, 5, 0, 1, 6) - - self.abort_button = QPushButton("Abort measurement", parent=self) - self.abort_button.setStyleSheet(f"color: {ABORT_TEXT};") - self._layout.addWidget(self.abort_button, 6, 0, 1, 6) - - # Calculated labels - self._layout.addWidget(QLabel("Target resolution", parent=self), 7, 0) - self.target_res_label = QLabel("--", parent=self) - self.target_res_label.setAlignment( - Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter - ) - self._layout.addWidget(self.target_res_label, 7, 1, 1, 3) - self._layout.addWidget(QLabel("Å", parent=self), 7, 4) - - self._layout.addWidget(QLabel("Image time", parent=self), 8, 0) - self.image_time_label = QLabel("--", parent=self) - self.image_time_label.setAlignment( - Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter - ) - self._layout.addWidget(self.image_time_label, 8, 1, 1, 3) - self._layout.addWidget(QLabel("s", parent=self), 8, 4) - - self._layout.addWidget(QLabel("Transmission", parent=self), 9, 0) - self.transmission_label = QLabel("--", parent=self) - self.transmission_label.setAlignment( - Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter - ) - self._layout.addWidget(self.transmission_label, 9, 1, 1, 3) - self._layout.addWidget(QLabel("%", parent=self), 9, 4) - - self._layout.addWidget(QLabel("Detector distance", parent=self), 10, 0) - self.dtz_label = QLabel("--", parent=self) - self.dtz_label.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) - self._layout.addWidget(self.dtz_label, 10, 1, 1, 3) - self._layout.addWidget(QLabel("mm", parent=self), 10, 4) - - self._layout.addWidget(QLabel("Beam Size", parent=self), 11, 0) - self.beam_size_label = QLabel("--", parent=self) - self.beam_size_label.setAlignment( - Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter - ) - self._layout.addWidget(self.beam_size_label, 11, 1, 1, 3) - self._layout.addWidget(QLabel("um2", parent=self), 11, 4) - - self._layout.addWidget(QLabel("Target Dose", parent=self), 12, 0) - self.target_dose_label = QLabel("--", parent=self) - self.target_dose_label.setAlignment( - Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter - ) - self._layout.addWidget(self.target_dose_label, 12, 1, 1, 3) - self._layout.addWidget(QLabel("MGy", parent=self), 12, 4) - - self._layout.addWidget(QLabel("Calculated Dose Rate", parent=self), 13, 0) - self.calculated_dose_rate_label = QLabel("--", parent=self) - self.calculated_dose_rate_label.setAlignment( - Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter - ) - self._layout.addWidget(self.calculated_dose_rate_label, 13, 1, 1, 3) - self._layout.addWidget(QLabel("MGy s-1", parent=self), 13, 4) - - self._layout.addWidget(QLabel("Calculated Dose", parent=self), 14, 0) - self.calculated_dose_label = QLabel("--", parent=self) - self.calculated_dose_label.setAlignment( - Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter - ) - self._layout.addWidget(self.calculated_dose_label, 14, 1, 1, 3) - self._layout.addWidget(QLabel("MGy", parent=self), 14, 4) - - self._layout.addWidget(QLabel("Total measurement time", parent=self), 15, 0) - self.total_time = QLabel(f"{self.total_time_s} min 0 s") - self.total_time.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) - self._layout.addWidget(self.total_time, 15, 1, 1, 3) - - # Vertical stretch below everything (surplus space sink). - self._layout.addItem( - QSpacerItem(0, 0, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding), 16, 0, 1, 6 - ) - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - self._d = s - # TODO only take best res from flat face scan - # TODO identify flat face! - self._omega = s.geom.omega_deg - self._apply_daq_resolution(s.last_best_res) - - # self.omega.new_value(s.geom.omega_deg) - self.beam_size_label.setText( - f"{s.geom.beam_size_mm.x * 1000.0} x {s.geom.beam_size_mm.y * 1000.0}" - ) - self.update_calculated_labels() - - def _apply_daq_resolution(self, best_res: float | None) -> None: - """Track ``DAQStatusModel.last_best_res`` in the resolution field. - - Written on every *change* of the DAQ value rather than on every 2 Hz - tick, so a fresh raster result always lands while a repeat of the same - value leaves a manual override alone. - - Two things this deliberately does not use: - - * ``update_value`` compares against ``saved_value``, which - ``on_editing_finished`` never updates (it self-assigns), so it only - ever sees programmatic writes. Once the operator has typed over a - pushed value, the same DAQ value could never re-assert itself. - ``set_committed_value`` compares against what the field actually - shows, which is the question being asked here. - * A bare ``is not None`` guard. The DAQ clears ``last_best_res`` on - mount, and skipping the update then leaves the previous crystal's - resolution in the field with nothing to say it is stale. - """ - if not self._daq_res_applied: - unchanged = False - elif best_res is None or self._daq_best_res is None: - unchanged = best_res is None and self._daq_best_res is None - else: - unchanged = abs(best_res - self._daq_best_res) <= DAQ_RES_EPS_A - if unchanged: - return - - self._daq_res_applied = True - self._daq_best_res = best_res - if best_res is None: - # No raster result for this sample: either none has run yet, or the - # pgroup gate in the status endpoint stripped it. Either way the - # field is showing a default, and the strategy below is built on a - # number nothing measured -- say so instead of looking authoritative. - value = self.visible_res_enter.get_default() - self.visible_res_label.setText( - f"""{VISIBLE_RES_LABEL} (no raster)""" - ) - else: - value = max(VISIBLE_RES_MIN_A, min(VISIBLE_RES_MAX_A, float(best_res))) - self.visible_res_label.setText(VISIBLE_RES_LABEL) - self.visible_res_enter.set_committed_value(value) - self.update_calculated_labels() - - @Slot(float) - def set_visible_resolution(self, v: float): - self.update_calculated_labels() - - @Slot(float) - def set_total_angle(self, v: float): - self.update_calculated_labels() - - @Slot(float) - def set_image_angle(self, v: float): - self.update_calculated_labels() - - @Slot(float) - def set_dose_ang(self, v: float): - self.update_calculated_labels() - - @Slot(float) - def set_start_angle(self, v: float): - self.update_calculated_labels() - - @Slot(str) - def update_filename(self, filename: str): - self._filename = filename - - @Slot() - def update_omega_start(self): - self.start_angle_enter.update_value(self._omega) - - def update_total_time_label(self): - mins = int(self.total_time_s // 60) - secs = round(self.total_time_s % 60) - if secs == 60: - mins += 1 - secs = 0 - self.total_time.setText(f"{mins} min {secs} s") - - def _solve_transmission(self, budget_time_s: float, image_time_s: float) -> float: - """Transmission that spends the dose budget over ``n_images`` frames. - - Snapped down to TRANSMISSION_SIG_DIGITS so quantisation can only - under-spend the budget, and capped at 100%: when the crystal cannot - absorb its budget at full beam we accept the under-dose rather than - stretching the exposure. - """ - beam_on_s = self.n_images * image_time_s - if beam_on_s <= 0.0 or budget_time_s <= 0.0: - return 1.0 - # Only ever clamped down: clamping up to a floor would push the - # delivered dose back above the budget. - return min(1.0, _floor_significant(budget_time_s / beam_on_s, TRANSMISSION_SIG_DIGITS)) - - def _update_dtz(self, d_tar: float) -> None: - """Detector distance for ``d_tar``, snapped to DTZ_STEP_MM and clamped - to the beamline travel limits. - - The snap goes *down*: calc_dtz_mm returns the largest distance that - still puts d_tar on the detector edge, so rounding up would drop the - target resolution off the edge. - """ - requested = self._d.diffraction.calc_dtz_mm(d_tar) - dtz_min = _ceil_to(self._d.bl.dtz_min, DTZ_STEP_MM) - dtz_max = _floor_to(self._d.bl.dtz_max, DTZ_STEP_MM) - - if requested <= 0.0: - # d_tar is not reachable at this wavelength at any distance. - self.dtz = dtz_min - self.dtz_label.setText(f"""-""") - return - - snapped = _floor_to(requested, DTZ_STEP_MM) - if snapped < dtz_min: - self.dtz = dtz_min - self.dtz_label.setText( - f"""{snapped:.0f}""" - ) - elif snapped > dtz_max: - self.dtz = dtz_max - self.dtz_label.setText( - f"""{snapped:.0f}""" - ) - else: - self.dtz = snapped - self.dtz_label.setText(f"{self.dtz:.0f}") - - def update_calculated_labels(self): - if self._d is None: - return - - total_angle = self.angular_range_enter.value - image_angle = max(self.image_angle_enter.value, 0.001) - - # The DAQ resolution estimate is unbiased, so it is the target as-is: - # no additive fudge and no reciprocal-space shift. - d_tar = self.visible_res_enter.value - self.target_res_label.setText(f"{d_tar:.2f}") - - kdose = KDOSE_1A_PH_UM2_GY / self._d.diffraction.wavelength_angstrom**2 - - beam_size_um_x = self._d.geom.beam_size_mm.x * 1000.0 - beam_size_um_y = self._d.geom.beam_size_mm.y * 1000.0 - beam_area_um2 = beam_size_um_x * beam_size_um_y - - # Flux is reported by the DAQ at 100% transmission. - flux_ph_s = self._d.bl.flux_ph_s - if beam_area_um2 > 0.0 and flux_ph_s > 0.0: - self.dose_rate_MGy_s = flux_ph_s / (beam_area_um2 * kdose) / 1e6 - else: - self.dose_rate_MGy_s = 0.0 - - self.target_dose_MGy = self.dose_ang_enter.value * d_tar - - self.n_images = max(1, round(total_angle / image_angle)) - - # Beam-on time at 100% transmission that spends exactly the budget. - if self.dose_rate_MGy_s > 0.0: - budget_time_s = self.target_dose_MGy / self.dose_rate_MGy_s - else: - budget_time_s = 0.0 - - # Floors on a single frame: the detector frame time raised to the - # strategy floor where one is set, and the goniometer top speed at the - # requested oscillation width. - detector_min_s = MIN_EXP_TIME_S.get(self._beamline, DEFAULT_MIN_EXP_TIME_S) - min_exp_time_s = max( - STRATEGY_MIN_EXP_TIME_S.get(self._beamline, detector_min_s), - image_angle / MAX_OMEGA_SPEED_DEG_S, - ) - - if self._beamline is MXBeamline.X10SA: - # Flux-rich: pin the detector at FIXED_FRAME_RATE_HZ and spend the - # dose budget through transmission. - frame_time_s = max(1.0 / FIXED_FRAME_RATE_HZ, min_exp_time_s) - image_time_s = _ceil_to(frame_time_s, EXP_TIME_STEP_S) - transmission = self._solve_transmission(budget_time_s, image_time_s) - else: - # Flux-limited: hold the beam at 100% and solve for exposure time. - transmission = 1.0 - image_time_s = _floor_to(budget_time_s / self.n_images, EXP_TIME_STEP_S) - if image_time_s < min_exp_time_s: - # Cannot expose any shorter, so the balance comes out of - # transmission instead. - image_time_s = _ceil_to(min_exp_time_s, EXP_TIME_STEP_S) - transmission = self._solve_transmission(budget_time_s, image_time_s) - - self.image_time_s = image_time_s - self.transmission = transmission - - # Wall-clock, not the beam-on budget: this is what the operator waits - # for, and the two differ whenever transmission is below 100%. - self.total_time_s = self.n_images * self.image_time_s - self.update_total_time_label() - - self.delivered_dose_MGy = self.dose_rate_MGy_s * self.transmission * self.total_time_s - - self._update_dtz(d_tar) - - self.target_dose_label.setText(f"{self.target_dose_MGy:.2f}") - self.calculated_dose_rate_label.setText(f"{(self.dose_rate_MGy_s * self.transmission):.3f}") - self.transmission_label.setText(f"{self.transmission * 100:.3g}") - self.image_time_label.setText(f"{self.image_time_s:.3f}") - - if self.delivered_dose_MGy < 0.95 * self.target_dose_MGy: - # Capped at 100% transmission: the crystal cannot absorb its - # budget at this flux, so the data will be weaker than planned. - self.calculated_dose_label.setText( - f"""""" - f"""{self.delivered_dose_MGy:.2f}""" - ) - else: - self.calculated_dose_label.setText(f"{self.delivered_dose_MGy:.2f}") - - self.parameters = SimpleScanParameters( - dtz=round(self.dtz), - exp_time_s=self.image_time_s, - start_omega_deg=self.start_angle_enter.value, - incr_omega_deg=image_angle, - steps=self.n_images, - transmission=self.transmission, - last_best_res=d_tar, - crystal_size=CrystalSize(x=0, y=0, z=0), - flux_ph_s=flux_ph_s, - calculated_dose_Mgy=self.delivered_dose_MGy, - calculated_dose_rate_MGy_s=self.dose_rate_MGy_s, - target_dose_MGy=self.target_dose_MGy, - dose_rate_MGy_s=self.dose_rate_MGy_s, - beam_size_x_um=beam_size_um_x, - beam_size_y_um=beam_size_um_y, - d_vis=d_tar, - d_tar=d_tar, - ) - - if self._prev_params != self.parameters: - self._prev_params = self.parameters - self.parameters_changed.emit(self.parameters) - - @Slot() - def run_measurement(self): - # Same file-exists guard as the Rotation tab; this panel is not a - # ScanSettingsPanel, so it has no check_before_run() to inherit. - file_path_panel = find_file_path_panel(self) - if file_path_panel is not None and not file_path_panel.file_path_error_box( - scan_kind="rotation" - ): - return - # Send exactly what the panel last calculated and displayed, rather - # than re-reading the widgets: dtz, exposure and transmission are a - # single consistent solution and must not be mixed with a newer entry. - p = self.parameters - r = RotationScanRequest( - file_prefix=str(add_data_to_path(self._filename)), - start_omega_deg=p.start_omega_deg, - steps=p.steps, - incr_omega_deg=p.incr_omega_deg, - dtz=p.dtz, - transmission=p.transmission, - screening=False, - exp_time_s=p.exp_time_s, - ) - self.rotation_scan.emit(r) - self.viewer_track_online.emit() diff --git a/src/aare/gui/panels/status_panel.py b/src/aare/gui/panels/status_panel.py deleted file mode 100644 index 31f77b69..00000000 --- a/src/aare/gui/panels/status_panel.py +++ /dev/null @@ -1,78 +0,0 @@ -from aarecommon.math.sample_geometry import SampleGeometryModel -from aarecommon.models.models import DAQStatusModel -from PySide6.QtCore import Qt, Slot -from PySide6.QtGui import QPixmap -from PySide6.QtWidgets import QFrame, QGridLayout, QLabel, QSizePolicy, QSpacerItem - -from aare.gui.styles import STATUS_ALERT -from aare.gui.widgets.status_label import StatusLabel -from aare.gui.widgets.title_label import TitleLabel - - -class StatusPanel(QFrame): - def __init__(self, parent=None): - super().__init__(parent) - self.setFrameShape(QFrame.Shape.StyledPanel) - self.setFrameShadow(QFrame.Shadow.Raised) - - layout = QGridLayout(self) - self.setLayout(layout) - - layout.addWidget(TitleLabel("Beamline status", self), 0, 0, 1, 5) - - layout.addWidget(QLabel("Ring current", parent=self), 2, 1) - self.ring_current = StatusLabel(val=400) - layout.addWidget(self.ring_current, 2, 2) - layout.addWidget(QLabel("mA", parent=self), 2, 3) - - layout.addWidget(QLabel("Flux", parent=self), 3, 1) - self.flux = StatusLabel(val=45300) - layout.addWidget(self.flux, 3, 2) - layout.addWidget(QLabel("109 ph/s", parent=self), 3, 3) - - layout.addWidget(QLabel("Wavelength", parent=self), 4, 1) - self.wavelength = StatusLabel(val=1.00, decimals=3) - layout.addWidget(self.wavelength, 4, 2) - layout.addWidget(QLabel("Å", parent=self), 4, 3) - - layout.addWidget(QLabel("Beam size", parent=self), 5, 1) - self.beam_size = QLabel("20 x 20") - self.beam_size.setAlignment(Qt.AlignmentFlag.AlignCenter) - layout.addWidget(self.beam_size, 5, 2) - layout.addWidget(QLabel("µm", parent=self), 5, 3) - - layout.addWidget(QLabel("Omega", parent=self), 6, 1) - self.omega = StatusLabel(val=0.1, decimals=2) - layout.addWidget(self.omega, 6, 2) - layout.addWidget(QLabel("°", parent=self), 6, 3) - - horizontal_spacer_1 = QSpacerItem( - 40, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding - ) - layout.addItem(horizontal_spacer_1, 1, 0, 1, 1) - - horizontal_spacer_2 = QSpacerItem( - 40, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding - ) - - layout.addItem(horizontal_spacer_2, 7, 4, 1, 1) - - @Slot(QPixmap, SampleGeometryModel) - def update_daq_status(self, s: DAQStatusModel): - self.omega.new_value(s.geom.omega_deg) - self.beam_size.setText( - f"{s.geom.beam_size_mm.x * 1000.0} x {s.geom.beam_size_mm.y * 1000.0}" - ) - - if s.bl.ring_current_mA < 390.0: - self.ring_current.setText( - f'{s.bl.ring_current_mA:.1f}' - ) - else: - self.ring_current.setText(f"{s.bl.ring_current_mA:.1f}") - - self.flux.setText(f"{(s.bl.flux_ph_s / 1e9):.2f}") - if s.diffraction.wavelength_angstrom is None: - self.wavelength.setText("N/A") - else: - self.wavelength.setText(f"{s.diffraction.wavelength_angstrom:.3f}") diff --git a/src/aare/gui/panels/target_stability_panel.py b/src/aare/gui/panels/target_stability_panel.py deleted file mode 100644 index 03757327..00000000 --- a/src/aare/gui/panels/target_stability_panel.py +++ /dev/null @@ -1,1423 +0,0 @@ -import csv -import math -import threading -import time -from collections import deque - -from aarecommon.config.logger import setup_logger -from PySide6.QtCharts import QChart, QChartView, QLineSeries, QValueAxis -from PySide6.QtCore import QPoint, QPointF, Qt, QTimer, Slot -from PySide6.QtGui import QColor, QMouseEvent, QPainter, QPen, QWheelEvent -from PySide6.QtWidgets import ( - QCheckBox, - QComboBox, - QDoubleSpinBox, - QFileDialog, - QGroupBox, - QHBoxLayout, - QLabel, - QMessageBox, - QPushButton, - QVBoxLayout, - QWidget, -) - -from aare.gui.constants import LOGGER_NAME -from aare.gui.styles import ( - CHART_BLUE, - CHART_BLUE_LIGHT, - CHART_BLUE_PALE, - CHART_CYAN, - CHART_GREEN, - CHART_ORANGE, - CHART_PURPLE, - CHART_RED, - CHART_RED_DARK, - CHART_RED_LIGHT, -) - -logger = setup_logger(LOGGER_NAME) - - -class InteractiveChartView(QChartView): - def __init__(self, chart: QChart, panel: "TargetStabilityPanel"): - super().__init__(chart) - self._panel = panel - self._last_pos: QPoint | None = None - self.setRenderHint(QPainter.RenderHint.Antialiasing) - self.setRubberBand(QChartView.RubberBand.NoRubberBand) - self.setMouseTracking(True) - - def wheelEvent(self, event: QWheelEvent) -> None: - delta = event.angleDelta().y() - if delta == 0: - event.ignore() - return - - factor = 0.85 if delta > 0 else 1.0 / 0.85 - - if event.modifiers() & Qt.KeyboardModifier.ShiftModifier: - self._panel._zoom_score_axis(factor) - event.accept() - return - - self._panel._zoom_selected_wheel_axis(factor) - event.accept() - - def mousePressEvent(self, event: QMouseEvent) -> None: - if event.button() == Qt.MouseButton.LeftButton: - click_pos = event.position() - self.chart().mapToValue(click_pos.toPoint()) - - if self._panel._try_select_series_at_point(click_pos.toPoint()): - event.accept() - return - - self._last_pos = event.position().toPoint() - self.setCursor(Qt.CursorShape.ClosedHandCursor) - event.accept() - return - - if event.button() == Qt.MouseButton.RightButton: - self._panel._reset_view() - event.accept() - return - - super().mousePressEvent(event) - - def mouseMoveEvent(self, event: QMouseEvent) -> None: - if self._last_pos is not None and (event.buttons() & Qt.MouseButton.LeftButton): - pos = event.position().toPoint() - delta = pos - self._last_pos - self._last_pos = pos - self._panel._pan_selected_axes( - delta.x(), delta.y(), self.viewport().width(), self.viewport().height() - ) - event.accept() - return - - super().mouseMoveEvent(event) - - def mouseReleaseEvent(self, event: QMouseEvent) -> None: - if event.button() == Qt.MouseButton.LeftButton: - self._last_pos = None - self.setCursor(Qt.CursorShape.ArrowCursor) - event.accept() - return - - super().mouseReleaseEvent(event) - - -class TargetStabilityPanel(QWidget): - SIGMA_COLOR = CHART_BLUE - SIGMA_X_COLOR = CHART_BLUE_LIGHT - SIGMA_Y_COLOR = CHART_BLUE_PALE - - DISTANCE_COLOR = CHART_RED - DX_COLOR = CHART_RED_LIGHT - DY_COLOR = CHART_RED_DARK - - SCORE_COLOR = CHART_ORANGE - STEP_COLOR = CHART_CYAN - - TARGET_COLOR = CHART_GREEN - BEAM_COLOR = CHART_PURPLE - - SCORE_FROM_STEP_XY = "Step XY" - SCORE_FROM_SIGMA_XY = "Sigma XY" - - WHEEL_X = "X axis" - WHEEL_LEFT_Y = "Left Y" - WHEEL_RIGHT_Y = "Right Y" - WHEEL_SCORE = "Score" - - PAN_ALL = "All visible" - PAN_X = "X only" - PAN_LEFT_Y = "Left Y only" - PAN_RIGHT_Y = "Right Y only" - PAN_SCORE = "Score only" - - TRACE_TARGET_SIGMA = "sigma" - TRACE_TARGET_SIGMA_X = "sigma_x" - TRACE_TARGET_SIGMA_Y = "sigma_y" - TRACE_TARGET_DISTANCE = "distance" - TRACE_TARGET_DX = "dx" - TRACE_TARGET_DY = "dy" - TRACE_TARGET_SCORE = "score" - TRACE_TARGET_STEP = "step" - - def __init__(self, parent=None): - super().__init__(parent) - - self._live_window_s = 60.0 - self._sigma_window_s = 1.0 - self._paused = False - self._beam_center: tuple[float, float] | None = None - self._latest_target_point: tuple[float, float] | None = None - self._auto_scale_enabled = True - self._active_trace_target = self.TRACE_TARGET_SIGMA - - self._track_only_when_visible = True - - self._metrics_update_interval_s = 0.5 - self._last_metrics_update_ts = 0.0 - self._stability_ref_px = 1.0 - - self._input_min_interval_s = 0.10 - self._last_input_ts = 0.0 - self._chart_dirty = False - - self._samples = deque(maxlen=10000) - self._plot_points = deque(maxlen=10000) - self._sigma_samples = deque(maxlen=10000) - - self._rolling_count = 0 - self._rolling_sum_dx = 0.0 - self._rolling_sum_dy = 0.0 - self._rolling_sum_dx2 = 0.0 - self._rolling_sum_dy2 = 0.0 - - self._rolling_step_count = 0 - self._rolling_step_dx2_sum = 0.0 - self._rolling_step_dy2_sum = 0.0 - self._rolling_step_xy2_sum = 0.0 - - self._kahan_c_dx = 0.0 - self._kahan_c_dy = 0.0 - self._kahan_c_dx2 = 0.0 - self._kahan_c_dy2 = 0.0 - - self._collecting_until: float | None = None - self._collected_samples: list[dict] = [] - self._frozen_plot_points: list[dict] | None = None - - self._data_lock = threading.Lock() - - layout = QVBoxLayout(self) - - controls = QHBoxLayout() - self.pause_button = QPushButton("Pause") - self.pause_button.setCheckable(True) - self.pause_button.toggled.connect(self._set_paused) - - self.seconds_spin = QDoubleSpinBox() - self.seconds_spin.setRange(1.0, 600.0) - self.seconds_spin.setDecimals(1) - self.seconds_spin.setSingleStep(1.0) - self.seconds_spin.setValue(10.0) - self.seconds_spin.setSuffix(" s") - self.seconds_spin.valueChanged.connect(self._update_action_labels) - - self.avg_spin = QDoubleSpinBox() - self.avg_spin.setRange(0.02, 60.0) - self.avg_spin.setDecimals(2) - self.avg_spin.setSingleStep(0.02) - self.avg_spin.setValue(1.0) - self.avg_spin.setSuffix(" s") - self.avg_spin.valueChanged.connect(self._set_sigma_window) - - self.save_button = QPushButton() - self.save_button.clicked.connect(self._save_last_x_seconds) - - self.collect_button = QPushButton() - self.collect_button.clicked.connect(self._collect_next_x_seconds) - - self.auto_scale_button = QPushButton("Auto scale") - self.auto_scale_button.clicked.connect(self._reset_view) - - self.help_button = QPushButton("Metrics help") - self.help_button.clicked.connect(self._show_metrics_help) - - self.score_basis_combo = QComboBox() - self.score_basis_combo.addItems([self.SCORE_FROM_STEP_XY, self.SCORE_FROM_SIGMA_XY]) - self.score_basis_combo.setCurrentText(self.SCORE_FROM_STEP_XY) - self.score_basis_combo.currentTextChanged.connect(self._on_score_basis_changed) - - self.wheel_mode_combo = QComboBox() - self.wheel_mode_combo.addItems( - [self.WHEEL_X, self.WHEEL_LEFT_Y, self.WHEEL_RIGHT_Y, self.WHEEL_SCORE] - ) - self.wheel_mode_combo.setCurrentText(self.WHEEL_X) - self.wheel_mode_combo.currentTextChanged.connect(lambda _text: self._update_status_label()) - - self.pan_mode_combo = QComboBox() - self.pan_mode_combo.addItems( - [self.PAN_ALL, self.PAN_X, self.PAN_LEFT_Y, self.PAN_RIGHT_Y, self.PAN_SCORE] - ) - self.pan_mode_combo.setCurrentText(self.PAN_ALL) - self.pan_mode_combo.currentTextChanged.connect(lambda _text: self._update_status_label()) - - self.status_label = QLabel("Waiting for target-point data...") - self.status_label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) - - self.metrics_label = QLabel( - "Target: (-, -) | Beam: (-, -) | Distance: - px | Std dev: - px" - ) - self.metrics_label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) - self.metrics_label.setTextFormat(Qt.TextFormat.RichText) - self.metrics_label.setWordWrap(True) - - self.controls_legend_label = QLabel( - "Mouse: wheel=selected axis zoom | Shift+wheel=score | left-drag=selected pan mode | right-click=reset | click a trace point to target its axis" - ) - self.controls_legend_label.setAlignment( - Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter - ) - self.controls_legend_label.setWordWrap(True) - - controls.addWidget(self.pause_button) - controls.addWidget(QLabel("Window:")) - controls.addWidget(self.seconds_spin) - controls.addWidget(self.save_button) - controls.addWidget(self.collect_button) - controls.addWidget(self.auto_scale_button) - controls.addWidget(self.help_button) - controls.addSpacing(8) - controls.addWidget(QLabel("Score from:")) - controls.addWidget(self.score_basis_combo) - controls.addSpacing(8) - controls.addWidget(QLabel("Wheel:")) - controls.addWidget(self.wheel_mode_combo) - controls.addWidget(QLabel("Avg:")) - controls.addWidget(self.avg_spin) - controls.addWidget(QLabel("Pan:")) - controls.addWidget(self.pan_mode_combo) - controls.addStretch() - - self.series = QLineSeries() - self.series.setName("Rolling σ") - self.series.setPointsVisible(False) - self.series.setPen(QPen(QColor(self.SIGMA_COLOR), 2.0)) - - self.sigma_x_series = QLineSeries() - self.sigma_x_series.setName("σx") - self.sigma_x_series.setPointsVisible(False) - self.sigma_x_series.setPen(QPen(QColor(self.SIGMA_X_COLOR), 2.0)) - - self.sigma_y_series = QLineSeries() - self.sigma_y_series.setName("σy") - self.sigma_y_series.setPointsVisible(False) - self.sigma_y_series.setPen(QPen(QColor(self.SIGMA_Y_COLOR), 2.0)) - - self.distance_series = QLineSeries() - self.distance_series.setName("Distance") - self.distance_series.setPointsVisible(False) - self.distance_series.setPen(QPen(QColor(self.DISTANCE_COLOR), 2.0)) - - self.dx_series = QLineSeries() - self.dx_series.setName("Distance X (dx)") - self.dx_series.setPointsVisible(False) - self.dx_series.setPen(QPen(QColor(self.DX_COLOR), 2.0)) - - self.dy_series = QLineSeries() - self.dy_series.setName("Distance Y (dy)") - self.dy_series.setPointsVisible(False) - self.dy_series.setPen(QPen(QColor(self.DY_COLOR), 2.0)) - - self.score_series = QLineSeries() - self.score_series.setName("Stability score") - self.score_series.setPointsVisible(False) - self.score_series.setPen(QPen(QColor(self.SCORE_COLOR), 2.0)) - - self.step_series = QLineSeries() - self.step_series.setName("Rolling RMS step motion") - self.step_series.setPointsVisible(False) - self.step_series.setPen(QPen(QColor(self.STEP_COLOR), 2.0)) - - self.chart = QChart() - self.chart.setAnimationOptions(QChart.AnimationOption.NoAnimation) - for series in ( - self.series, - self.sigma_x_series, - self.sigma_y_series, - self.distance_series, - self.dx_series, - self.dy_series, - self.score_series, - self.step_series, - ): - self.chart.addSeries(series) - - self.chart.legend().setVisible(True) - self.chart.setTitle("Target stability, distance, score, and step motion (last 60 s)") - - self.axis_x = QValueAxis() - self.axis_x.setTitleText("Time [s ago]") - self.axis_x.setRange(-self._live_window_s, 0.0) - - self.axis_y = QValueAxis() - self.axis_y.setTitleText("Sigma / step [px]") - self.axis_y.setRange(0.0, 10.0) - - self.axis_y_distance = QValueAxis() - self.axis_y_distance.setTitleText("Distance / offset [px]") - self.axis_y_distance.setRange(-10.0, 10.0) - - self.axis_y_score = QValueAxis() - self.axis_y_score.setTitleText("Score [0-100]") - self.axis_y_score.setRange(0.0, 100.0) - - self.chart.addAxis(self.axis_x, Qt.AlignmentFlag.AlignBottom) - self.chart.addAxis(self.axis_y, Qt.AlignmentFlag.AlignLeft) - self.chart.addAxis(self.axis_y_distance, Qt.AlignmentFlag.AlignRight) - self.chart.addAxis(self.axis_y_score, Qt.AlignmentFlag.AlignRight) - - for series in (self.series, self.sigma_x_series, self.sigma_y_series, self.step_series): - series.attachAxis(self.axis_x) - series.attachAxis(self.axis_y) - - for series in (self.distance_series, self.dx_series, self.dy_series): - series.attachAxis(self.axis_x) - series.attachAxis(self.axis_y_distance) - - self.score_series.attachAxis(self.axis_x) - self.score_series.attachAxis(self.axis_y_score) - - self._connect_series_selection(self.series, self.TRACE_TARGET_SIGMA) - self._connect_series_selection(self.sigma_x_series, self.TRACE_TARGET_SIGMA_X) - self._connect_series_selection(self.sigma_y_series, self.TRACE_TARGET_SIGMA_Y) - self._connect_series_selection(self.distance_series, self.TRACE_TARGET_DISTANCE) - self._connect_series_selection(self.dx_series, self.TRACE_TARGET_DX) - self._connect_series_selection(self.dy_series, self.TRACE_TARGET_DY) - self._connect_series_selection(self.score_series, self.TRACE_TARGET_SCORE) - self._connect_series_selection(self.step_series, self.TRACE_TARGET_STEP) - - self.show_sigma_cb = QCheckBox("Rolling σ") - self.show_sigma_cb.setChecked(True) - self.show_sigma_cb.toggled.connect(self._update_trace_visibility) - self._style_trace_checkbox(self.show_sigma_cb, self.SIGMA_COLOR) - - self.show_sigma_x_cb = QCheckBox("σx") - self.show_sigma_x_cb.setChecked(False) - self.show_sigma_x_cb.toggled.connect(self._update_trace_visibility) - self._style_trace_checkbox(self.show_sigma_x_cb, self.SIGMA_X_COLOR) - - self.show_sigma_y_cb = QCheckBox("σy") - self.show_sigma_y_cb.setChecked(False) - self.show_sigma_y_cb.toggled.connect(self._update_trace_visibility) - self._style_trace_checkbox(self.show_sigma_y_cb, self.SIGMA_Y_COLOR) - - self.show_distance_cb = QCheckBox("Distance") - self.show_distance_cb.setChecked(True) - self.show_distance_cb.toggled.connect(self._update_trace_visibility) - self._style_trace_checkbox(self.show_distance_cb, self.DISTANCE_COLOR) - - self.show_dx_cb = QCheckBox("Distance X (dx)") - self.show_dx_cb.setChecked(False) - self.show_dx_cb.toggled.connect(self._update_trace_visibility) - self._style_trace_checkbox(self.show_dx_cb, self.DX_COLOR) - - self.show_dy_cb = QCheckBox("Distance Y (dy)") - self.show_dy_cb.setChecked(False) - self.show_dy_cb.toggled.connect(self._update_trace_visibility) - self._style_trace_checkbox(self.show_dy_cb, self.DY_COLOR) - - self.show_score_cb = QCheckBox("Score") - self.show_score_cb.setChecked(False) - self.show_score_cb.toggled.connect(self._update_trace_visibility) - self._style_trace_checkbox(self.show_score_cb, self.SCORE_COLOR) - - self.show_step_cb = QCheckBox("Step XY") - self.show_step_cb.setChecked(False) - self.show_step_cb.toggled.connect(self._update_trace_visibility) - self._style_trace_checkbox(self.show_step_cb, self.STEP_COLOR) - - trace_group = QGroupBox("Traces") - trace_layout = QVBoxLayout(trace_group) - trace_layout.setContentsMargins(8, 8, 8, 8) - trace_layout.setSpacing(6) - trace_layout.addWidget(self.show_sigma_cb) - trace_layout.addWidget(self.show_sigma_x_cb) - trace_layout.addWidget(self.show_sigma_y_cb) - trace_layout.addWidget(self.show_distance_cb) - trace_layout.addWidget(self.show_dx_cb) - trace_layout.addWidget(self.show_dy_cb) - trace_layout.addWidget(self.show_step_cb) - trace_layout.addWidget(self.show_score_cb) - trace_layout.addStretch() - - right_panel = QVBoxLayout() - right_panel.addWidget(trace_group) - right_panel.addStretch() - - self.chart_view = InteractiveChartView(self.chart, self) - - plot_row = QHBoxLayout() - plot_row.addWidget(self.chart_view, 1) - plot_row.addLayout(right_panel) - - layout.addLayout(controls) - layout.addWidget(self.status_label) - layout.addWidget(self.metrics_label) - layout.addWidget(self.controls_legend_label) - layout.addLayout(plot_row) - - self._update_action_labels() - self._update_trace_visibility() - self._update_metrics_label(force=True) - - self._refresh_timer = QTimer(self) - self._refresh_timer.setInterval(500) - self._refresh_timer.timeout.connect(self._refresh_chart) - self._refresh_timer.start() - - def _style_trace_checkbox(self, checkbox: QCheckBox, color_hex: str) -> None: - checkbox.setStyleSheet( - f""" - QCheckBox {{ - color: {color_hex}; - font-weight: 600; - }} - """ - ) - - def _connect_series_selection(self, series: QLineSeries, target_name: str) -> None: - series.clicked.connect(lambda _point, target=target_name: self._select_trace_target(target)) - - def _try_select_series_at_point(self, view_pos: QPoint) -> bool: - """Check if click is near a visible series point and select it. Returns True if found.""" - hit_threshold = 10 # pixels - - series_map = { - self.series: (self.TRACE_TARGET_SIGMA, self.show_sigma_cb), - self.sigma_x_series: (self.TRACE_TARGET_SIGMA_X, self.show_sigma_x_cb), - self.sigma_y_series: (self.TRACE_TARGET_SIGMA_Y, self.show_sigma_y_cb), - self.distance_series: (self.TRACE_TARGET_DISTANCE, self.show_distance_cb), - self.dx_series: (self.TRACE_TARGET_DX, self.show_dx_cb), - self.dy_series: (self.TRACE_TARGET_DY, self.show_dy_cb), - self.score_series: (self.TRACE_TARGET_SCORE, self.show_score_cb), - self.step_series: (self.TRACE_TARGET_STEP, self.show_step_cb), - } - - for series, (target_name, checkbox) in series_map.items(): - if not checkbox.isChecked(): - continue - for i in range(series.count()): - point = series.at(i) - screen_pos = self.chart.mapToPosition(point, series) - dx = abs(screen_pos.x() - view_pos.x()) - dy = abs(screen_pos.y() - view_pos.y()) - if dx < hit_threshold and dy < hit_threshold: - self._select_trace_target(target_name) - return True - return False - - def _select_trace_target(self, target_name: str) -> None: - self._active_trace_target = target_name - - if target_name in { - self.TRACE_TARGET_SIGMA, - self.TRACE_TARGET_SIGMA_X, - self.TRACE_TARGET_SIGMA_Y, - self.TRACE_TARGET_STEP, - }: - self.wheel_mode_combo.setCurrentText(self.WHEEL_LEFT_Y) - self.pan_mode_combo.setCurrentText(self.PAN_LEFT_Y) - elif target_name in { - self.TRACE_TARGET_DISTANCE, - self.TRACE_TARGET_DX, - self.TRACE_TARGET_DY, - }: - self.wheel_mode_combo.setCurrentText(self.WHEEL_RIGHT_Y) - self.pan_mode_combo.setCurrentText(self.PAN_RIGHT_Y) - elif target_name == self.TRACE_TARGET_SCORE: - self.wheel_mode_combo.setCurrentText(self.WHEEL_SCORE) - self.pan_mode_combo.setCurrentText(self.PAN_SCORE) - - self._update_status_label() - - def _set_paused(self, paused: bool) -> None: - self._paused = paused - if paused: - self.pause_button.setText("Resume (Live)" if self._collected_samples else "Resume") - else: - self._unfreeze_plot() - self.pause_button.setText("Pause") - self._update_status_label() - self._update_metrics_label(force=True) - - def _seconds_text(self) -> str: - seconds = float(self.seconds_spin.value()) - if seconds.is_integer(): - return f"{int(seconds)}" - return f"{seconds:.1f}" - - def _update_action_labels(self) -> None: - seconds_text = self._seconds_text() - self.save_button.setText(f"Save last {seconds_text} s") - self.collect_button.setText(f"Collect next {seconds_text} s") - - def _format_xy(self, point: tuple[float, float] | None) -> str: - if point is None: - return "(-, -)" - return f"({point[0]:.2f}, {point[1]:.2f})" - - def _stability_score(self, value_px: float) -> float: - ref = max(1e-6, self._stability_ref_px) - return 100.0 / (1.0 + (value_px / ref)) - - def _score_source_label(self) -> str: - return self.score_basis_combo.currentText() - - def _show_metrics_help(self) -> None: - msg = QMessageBox(self) - msg.setWindowTitle("Target stability metrics") - msg.setIcon(QMessageBox.Icon.Information) - msg.setTextFormat(Qt.TextFormat.RichText) - msg.setText( - "Definitions

" - "target = detected target point from the incoming payload
" - "beam = beam center / beam marker previously set for this panel

" - "Offsets
" - "dx = target_x - beam_x
" - "dy = target_y - beam_y
" - "distance = sqrt(dx² + dy²)

" - "Metrics
" - "Distance: sqrt(dx² + dy²)
" - "Distance X: dx
" - "Distance Y: dy

" - "σx: std(dx) over the sigma window
" - "σy: std(dy) over the sigma window
" - "Rolling σ: sqrt(σx² + σy²)
" - "These use target relative to beam via dx and dy

" - "Step X / Step Y: frame-to-frame motion relative to itself
" - "Δdx_i = dx_i - dx_(i-1)
" - "Δdy_i = dy_i - dy_(i-1)

" - "Step XY: sqrt(mean(Δdx² + Δdy²))
" - "This is the best direct metric for how much the target is moving relative to itself

" - "Score: 100 / (1 + metric / ref_px)
" - f"Current score source: {self._score_source_label()}

" - "Interaction
" - "Click a visible point on a trace to target wheel/pan to that trace's axis group." - ) - msg.exec() - - def _current_sigma_stats(self) -> dict[str, float]: - n = self._rolling_count - if n < 2: - return {"std_dx": 0.0, "std_dy": 0.0, "sigma": 0.0} - - mean_dx = self._rolling_sum_dx / n - mean_dy = self._rolling_sum_dy / n - var_dx = max(0.0, (self._rolling_sum_dx2 / n) - (mean_dx * mean_dx)) - var_dy = max(0.0, (self._rolling_sum_dy2 / n) - (mean_dy * mean_dy)) - - std_dx = math.sqrt(var_dx) - std_dy = math.sqrt(var_dy) - sigma = math.hypot(std_dx, std_dy) - - return {"std_dx": std_dx, "std_dy": std_dy, "sigma": sigma} - - def _current_step_jitter_stats(self) -> dict[str, float]: - if self._rolling_step_count <= 0: - return {"rms_step_dx": 0.0, "rms_step_dy": 0.0, "rms_step_xy": 0.0} - - return { - "rms_step_dx": math.sqrt(self._rolling_step_dx2_sum / self._rolling_step_count), - "rms_step_dy": math.sqrt(self._rolling_step_dy2_sum / self._rolling_step_count), - "rms_step_xy": math.sqrt(self._rolling_step_xy2_sum / self._rolling_step_count), - } - - def _current_score_value(self) -> float: - sigma_stats = self._current_sigma_stats() - step_stats = self._current_step_jitter_stats() - - if self.score_basis_combo.currentText() == self.SCORE_FROM_SIGMA_XY: - return self._stability_score(sigma_stats["sigma"]) - return self._stability_score(step_stats["rms_step_xy"]) - - def _update_metrics_label(self, force: bool = False) -> None: - now = time.monotonic() - if not force and (now - self._last_metrics_update_ts) < self._metrics_update_interval_s: - return - self._last_metrics_update_ts = now - - target_text = self._format_xy(self._latest_target_point) - beam_text = self._format_xy(self._beam_center) - - if self._samples: - latest = self._samples[-1] - distance_text = f"{float(latest['distance']):.3f} px" - dx_text = f"{float(latest['dx']):+.3f} px" - dy_text = f"{float(latest['dy']):+.3f} px" - else: - distance_text = "- px" - dx_text = "- px" - dy_text = "- px" - - sigma_stats = self._current_sigma_stats() - step_stats = self._current_step_jitter_stats() - score_value = self._current_score_value() - - self.metrics_label.setText( - f"Target: {target_text} | " - f"Beam: {beam_text} | " - f"Distance: {distance_text} | " - f"dx: {dx_text} | " - f"dy: {dy_text}
" - f"σ: {sigma_stats['sigma']:.3f} px | " - f"σx: {sigma_stats['std_dx']:.3f} px | " - f"σy: {sigma_stats['std_dy']:.3f} px
" - f"Step X: {step_stats['rms_step_dx']:.3f} px | " - f"Step Y: {step_stats['rms_step_dy']:.3f} px | " - f"Step XY: {step_stats['rms_step_xy']:.3f} px | " - f"Score ({self._score_source_label()}): " - f"{score_value:.1f}" - ) - - def _update_trace_visibility(self) -> None: - self.series.setVisible(self.show_sigma_cb.isChecked()) - self.sigma_x_series.setVisible(self.show_sigma_x_cb.isChecked()) - self.sigma_y_series.setVisible(self.show_sigma_y_cb.isChecked()) - - self.distance_series.setVisible(self.show_distance_cb.isChecked()) - self.dx_series.setVisible(self.show_dx_cb.isChecked()) - self.dy_series.setVisible(self.show_dy_cb.isChecked()) - - self.step_series.setVisible(self.show_step_cb.isChecked()) - self.score_series.setVisible(self.show_score_cb.isChecked()) - - self.axis_y.setVisible( - self.show_sigma_cb.isChecked() - or self.show_sigma_x_cb.isChecked() - or self.show_sigma_y_cb.isChecked() - or self.show_step_cb.isChecked() - ) - self.axis_y_distance.setVisible( - self.show_distance_cb.isChecked() - or self.show_dx_cb.isChecked() - or self.show_dy_cb.isChecked() - ) - self.axis_y_score.setVisible(self.show_score_cb.isChecked()) - - self._update_status_label() - - def _on_score_basis_changed(self) -> None: - for point in self._plot_points: - if "sigma" in point and "step_xy" in point: - if self.score_basis_combo.currentText() == self.SCORE_FROM_SIGMA_XY: - point["score"] = self._stability_score(float(point["sigma"])) - else: - point["score"] = self._stability_score(float(point["step_xy"])) - - self._update_metrics_label(force=True) - self._refresh_chart() - - def _zoom_selected_wheel_axis(self, factor: float) -> None: - mode = self.wheel_mode_combo.currentText() - - if mode == self.WHEEL_LEFT_Y: - self._zoom_left_y_axis(factor) - return - if mode == self.WHEEL_RIGHT_Y: - self._zoom_right_y_axis(factor) - return - if mode == self.WHEEL_SCORE: - self._zoom_score_axis(factor) - return - - self._zoom_x_axis(factor) - - def _update_status_label(self) -> None: - if self._paused: - self.status_label.setText("Paused") - return - - if self._beam_center is None: - self.status_label.setText("Waiting for beam center...") - return - - if self._collecting_until is not None: - remaining = max(0.0, self._collecting_until - time.monotonic()) - self.status_label.setText(f"Collecting... {remaining:.1f} s remaining") - return - - sample_count = len(self._samples) - if sample_count == 0: - self.status_label.setText("Waiting for target-point data...") - else: - visible = [] - if self.show_sigma_cb.isChecked(): - visible.append("σ") - if self.show_sigma_x_cb.isChecked(): - visible.append("σx") - if self.show_sigma_y_cb.isChecked(): - visible.append("σy") - if self.show_distance_cb.isChecked(): - visible.append("distance") - if self.show_dx_cb.isChecked(): - visible.append("dx") - if self.show_dy_cb.isChecked(): - visible.append("dy") - if self.show_step_cb.isChecked(): - visible.append("stepXY") - if self.show_score_cb.isChecked(): - visible.append("score") - - self.status_label.setText( - f"Live: {sample_count} samples in last {self._live_window_s:.0f} s | " - f"view={'auto' if self._auto_scale_enabled else 'manual'} | " - f"traces={', '.join(visible) if visible else 'none'} | " - f"score={self._score_source_label()} | " - f"wheel={self.wheel_mode_combo.currentText()} | " - f"pan={self.pan_mode_combo.currentText()} | " - f"active={self._active_trace_target}" - ) - - def set_beam_center(self, x: float, y: float) -> None: - self._beam_center = (float(x), float(y)) - self._update_status_label() - self._update_metrics_label(force=True) - - def showEvent(self, event) -> None: - super().showEvent(event) - if self._refresh_timer is not None and not self._refresh_timer.isActive(): - self._refresh_timer.start() - self._chart_dirty = True - - def hideEvent(self, event) -> None: - super().hideEvent(event) - if ( - self._track_only_when_visible - and self._collecting_until is None - and self._refresh_timer is not None - ): - self._refresh_timer.stop() - - @Slot(dict) - def update_target_point(self, payload: dict) -> None: - if self._paused or self._beam_center is None: - return - - if ( - self._track_only_when_visible - and not self.isVisible() - and self._collecting_until is None - ): - return - - raw = payload.get("target_point") - target_xy = self._coerce_target_point(raw) - if target_xy is None: - return - - self._latest_target_point = target_xy - - ts = time.monotonic() - tx, ty = target_xy - bx, by = self._beam_center - dx = tx - bx - dy = ty - by - distance = math.hypot(dx, dy) - - sample = {"ts": ts, "dx": dx, "dy": dy, "distance": distance} - - should_finish_collection = False - with self._data_lock: - self._samples.append(sample) - self._append_plot_point(sample) - self._trim_samples(ts) - - if self._collecting_until is not None: - self._collected_samples.append(sample.copy()) - if ts >= self._collecting_until: - should_finish_collection = True - - if should_finish_collection: - self._finish_collection() - - self._update_status_label() - - def _set_sigma_window(self, seconds: float) -> None: - self._sigma_window_s = max(0.02, float(seconds)) - self._rebuild_plot_points() - self._update_metrics_label(force=True) - - def _rebuild_plot_points(self) -> None: - self._plot_points.clear() - self._sigma_samples.clear() - - self._rolling_count = 0 - self._rolling_sum_dx = 0.0 - self._rolling_sum_dy = 0.0 - self._rolling_sum_dx2 = 0.0 - self._rolling_sum_dy2 = 0.0 - self._kahan_c_dx = 0.0 - self._kahan_c_dy = 0.0 - self._kahan_c_dx2 = 0.0 - self._kahan_c_dy2 = 0.0 - - for sample in self._samples: - self._append_plot_point(sample) - - def _append_plot_point(self, sample: dict) -> None: - prev_sample = self._sigma_samples[-1] if self._sigma_samples else None - self._sigma_samples.append(sample) - - dx = float(sample["dx"]) - dy = float(sample["dy"]) - - self._rolling_count += 1 - - y = dx - self._kahan_c_dx - t = self._rolling_sum_dx + y - self._kahan_c_dx = (t - self._rolling_sum_dx) - y - self._rolling_sum_dx = t - - y = dy - self._kahan_c_dy - t = self._rolling_sum_dy + y - self._kahan_c_dy = (t - self._rolling_sum_dy) - y - self._rolling_sum_dy = t - - dx2 = dx * dx - y = dx2 - self._kahan_c_dx2 - t = self._rolling_sum_dx2 + y - self._kahan_c_dx2 = (t - self._rolling_sum_dx2) - y - self._rolling_sum_dx2 = t - - dy2 = dy * dy - y = dy2 - self._kahan_c_dy2 - t = self._rolling_sum_dy2 + y - self._kahan_c_dy2 = (t - self._rolling_sum_dy2) - y - self._rolling_sum_dy2 = t - - if prev_sample is not None: - ddx = dx - float(prev_sample["dx"]) - ddy = dy - float(prev_sample["dy"]) - self._rolling_step_count += 1 - self._rolling_step_dx2_sum += ddx * ddx - self._rolling_step_dy2_sum += ddy * ddy - self._rolling_step_xy2_sum += ddx * ddx + ddy * ddy - sample["_step_from_prev"] = (ddx, ddy) - - self._trim_sigma_samples(float(sample["ts"])) - - sigma_stats = self._current_sigma_stats() - step_xy = self._current_step_jitter_stats()["rms_step_xy"] - - score = ( - self._stability_score(float(sigma_stats["sigma"])) - if self.score_basis_combo.currentText() == self.SCORE_FROM_SIGMA_XY - else self._stability_score(step_xy) - ) - - self._plot_points.append( - { - "ts": float(sample["ts"]), - "sigma": sigma_stats["sigma"], - "sigma_x": sigma_stats["std_dx"], - "sigma_y": sigma_stats["std_dy"], - "distance": float(sample["distance"]), - "dx": dx, - "dy": dy, - "step_xy": step_xy, - "score": score, - } - ) - - def _remove_oldest_sigma_sample(self) -> None: - if not self._sigma_samples: - return - - sample = self._sigma_samples.popleft() - dx = float(sample["dx"]) - dy = float(sample["dy"]) - - self._rolling_count -= 1 - - y = -dx - self._kahan_c_dx - t = self._rolling_sum_dx + y - self._kahan_c_dx = (t - self._rolling_sum_dx) - y - self._rolling_sum_dx = t - - y = -dy - self._kahan_c_dy - t = self._rolling_sum_dy + y - self._kahan_c_dy = (t - self._rolling_sum_dy) - y - self._rolling_sum_dy = t - - dx2 = dx * dx - y = -dx2 - self._kahan_c_dx2 - t = self._rolling_sum_dx2 + y - self._kahan_c_dx2 = (t - self._rolling_sum_dx2) - y - self._rolling_sum_dx2 = t - - dy2 = dy * dy - y = -dy2 - self._kahan_c_dy2 - t = self._rolling_sum_dy2 + y - self._kahan_c_dy2 = (t - self._rolling_sum_dy2) - y - self._rolling_sum_dy2 = t - - step = sample.get("_step_from_prev") - if step is not None and self._rolling_step_count > 0: - ddx, ddy = step - self._rolling_step_count -= 1 - self._rolling_step_dx2_sum -= ddx * ddx - self._rolling_step_dy2_sum -= ddy * ddy - self._rolling_step_xy2_sum -= ddx * ddx + ddy * ddy - - if self._rolling_count <= 0: - self._rolling_count = 0 - self._rolling_sum_dx = 0.0 - self._rolling_sum_dy = 0.0 - self._rolling_sum_dx2 = 0.0 - self._rolling_sum_dy2 = 0.0 - self._rolling_step_count = 0 - self._rolling_step_dx2_sum = 0.0 - self._rolling_step_dy2_sum = 0.0 - self._rolling_step_xy2_sum = 0.0 - self._kahan_c_dx = 0.0 - self._kahan_c_dy = 0.0 - self._kahan_c_dx2 = 0.0 - self._kahan_c_dy2 = 0.0 - - def _trim_sigma_samples(self, now: float) -> None: - cutoff = now - self._sigma_window_s - while self._sigma_samples and float(self._sigma_samples[0]["ts"]) < cutoff: - self._remove_oldest_sigma_sample() - - def _remove_oldest_sample(self) -> None: - if not self._samples: - return - self._samples.popleft() - - def _trim_samples(self, now: float) -> None: - cutoff = now - self._live_window_s - - while self._samples and float(self._samples[0]["ts"]) < cutoff: - self._remove_oldest_sample() - - while self._plot_points and float(self._plot_points[0]["ts"]) < cutoff: - self._plot_points.popleft() - - def _data_limits(self) -> tuple[float, float, float, float, float, float, float, float]: - left_values: list[float] = [] - right_values: list[float] = [] - - for point in self._plot_points: - left_values.extend( - [ - float(point["sigma"]), - float(point["sigma_x"]), - float(point["sigma_y"]), - float(point["step_xy"]), - ] - ) - right_values.extend([float(point["distance"]), float(point["dx"]), float(point["dy"])]) - - left_min = min(left_values, default=0.0) - left_max = max(left_values, default=1.0) - right_min = min(right_values, default=-1.0) - right_max = max(right_values, default=1.0) - - left_span = max(1.0, left_max - left_min) - right_span = max(1.0, right_max - right_min) - - score_min = min((float(point["score"]) for point in self._plot_points), default=0.0) - score_max = max((float(point["score"]) for point in self._plot_points), default=100.0) - score_lo = max(0.0, score_min - 5.0) - score_hi = min(100.0, max(score_lo + 10.0, score_max + 5.0)) - - return ( - -self._live_window_s, - 0.0, - left_min - 0.075 * left_span, - left_max + 0.075 * left_span, - right_min - 0.075 * right_span, - right_max + 0.075 * right_span, - score_lo, - score_hi, - ) - - def _reset_view(self) -> None: - self._auto_scale_enabled = True - xmin, xmax, left_ymin, left_ymax, right_ymin, right_ymax, score_lo, score_hi = ( - self._data_limits() - ) - self.axis_x.setRange(xmin, xmax) - self.axis_y.setRange(left_ymin, left_ymax) - self.axis_y_distance.setRange(right_ymin, right_ymax) - self.axis_y_score.setRange(score_lo, score_hi) - self._update_status_label() - - def _zoom_axis(self, axis: QValueAxis, factor: float) -> None: - amin = axis.min() - amax = axis.max() - center = (amin + amax) / 2.0 - half = (amax - amin) * factor / 2.0 - if half <= 1e-9: - return - axis.setRange(center - half, center + half) - - def _zoom_x_axis(self, factor: float) -> None: - self._auto_scale_enabled = False - self._zoom_axis(self.axis_x, factor) - self._clamp_axes() - self._update_status_label() - - def _zoom_left_y_axis(self, factor: float) -> None: - self._auto_scale_enabled = False - if ( - self.show_sigma_cb.isChecked() - or self.show_sigma_x_cb.isChecked() - or self.show_sigma_y_cb.isChecked() - or self.show_step_cb.isChecked() - ): - self._zoom_axis(self.axis_y, factor) - self._clamp_axes() - self._update_status_label() - - def _zoom_right_y_axis(self, factor: float) -> None: - self._auto_scale_enabled = False - if ( - self.show_distance_cb.isChecked() - or self.show_dx_cb.isChecked() - or self.show_dy_cb.isChecked() - ): - self._zoom_axis(self.axis_y_distance, factor) - self._clamp_axes() - self._update_status_label() - - def _zoom_score_axis(self, factor: float) -> None: - self._auto_scale_enabled = False - if self.show_score_cb.isChecked(): - self._zoom_axis(self.axis_y_score, factor) - self._clamp_axes() - self._update_status_label() - - def _pan_selected_axes(self, dx_pixels: int, dy_pixels: int, width: int, height: int) -> None: - if width <= 0 or height <= 0: - return - - self._auto_scale_enabled = False - - x_span = self.axis_x.max() - self.axis_x.min() - y_span = self.axis_y.max() - self.axis_y.min() - y2_span = self.axis_y_distance.max() - self.axis_y_distance.min() - y3_span = self.axis_y_score.max() - self.axis_y_score.min() - - x_span = max(x_span, 1e-9) - y_span = max(y_span, 1e-9) - y2_span = max(y2_span, 1e-9) - y3_span = max(y3_span, 1e-9) - - x_shift = -(dx_pixels / width) * x_span - y_shift = (dy_pixels / height) * y_span - y2_shift = (dy_pixels / height) * y2_span - y3_shift = (dy_pixels / height) * y3_span - - mode = self.pan_mode_combo.currentText() - - if mode == self.PAN_X: - self.axis_x.setRange(self.axis_x.min() + x_shift, self.axis_x.max() + x_shift) - - elif mode == self.PAN_LEFT_Y: - if ( - self.show_sigma_cb.isChecked() - or self.show_sigma_x_cb.isChecked() - or self.show_sigma_y_cb.isChecked() - or self.show_step_cb.isChecked() - ): - self.axis_y.setRange(self.axis_y.min() + y_shift, self.axis_y.max() + y_shift) - - elif mode == self.PAN_RIGHT_Y: - if ( - self.show_distance_cb.isChecked() - or self.show_dx_cb.isChecked() - or self.show_dy_cb.isChecked() - ): - self.axis_y_distance.setRange( - self.axis_y_distance.min() + y2_shift, self.axis_y_distance.max() + y2_shift - ) - - elif mode == self.PAN_SCORE: - if self.show_score_cb.isChecked(): - self.axis_y_score.setRange( - self.axis_y_score.min() + y3_shift, self.axis_y_score.max() + y3_shift - ) - - else: - self.axis_x.setRange(self.axis_x.min() + x_shift, self.axis_x.max() + x_shift) - - if ( - self.show_sigma_cb.isChecked() - or self.show_sigma_x_cb.isChecked() - or self.show_sigma_y_cb.isChecked() - or self.show_step_cb.isChecked() - ): - self.axis_y.setRange(self.axis_y.min() + y_shift, self.axis_y.max() + y_shift) - - if ( - self.show_distance_cb.isChecked() - or self.show_dx_cb.isChecked() - or self.show_dy_cb.isChecked() - ): - self.axis_y_distance.setRange( - self.axis_y_distance.min() + y2_shift, self.axis_y_distance.max() + y2_shift - ) - - if self.show_score_cb.isChecked(): - self.axis_y_score.setRange( - self.axis_y_score.min() + y3_shift, self.axis_y_score.max() + y3_shift - ) - - self._clamp_axes() - self._update_status_label() - - def _clamp_axes(self) -> None: - full_xmin = -self._live_window_s - full_xmax = 0.0 - - xmin = self.axis_x.min() - xmax = self.axis_x.max() - xspan = xmax - xmin - - if xspan >= (full_xmax - full_xmin): - self.axis_x.setRange(full_xmin, full_xmax) - else: - if xmin < full_xmin: - self.axis_x.setRange(full_xmin, full_xmin + xspan) - elif xmax > full_xmax: - self.axis_x.setRange(full_xmax - xspan, full_xmax) - - score_min = self.axis_y_score.min() - score_max = self.axis_y_score.max() - score_span = max(score_max - score_min, 1.0) - - if score_min < 0.0: - self.axis_y_score.setRange(0.0, min(100.0, score_span)) - elif score_max > 100.0: - self.axis_y_score.setRange(max(0.0, 100.0 - score_span), 100.0) - - def _refresh_chart(self) -> None: - now = time.monotonic() - - with self._data_lock: - self._trim_samples(now) - - if not self.isVisible(): - self._update_status_label() - self._update_metrics_label() - return - - if not self._chart_dirty and not self._auto_scale_enabled: - self._update_metrics_label() - return - - if self._paused and self._collecting_until is None and self._frozen_plot_points is None: - self._update_status_label() - self._update_metrics_label() - return - - if self._frozen_plot_points is not None: - plot_data = list(self._frozen_plot_points) - ref_time = plot_data[0]["ts"] if plot_data else now - else: - plot_data = list(self._plot_points) - ref_time = now - - self._chart_dirty = False - - sigma_points = [ - QPointF(float(point["ts"]) - ref_time, float(point["sigma"])) for point in plot_data - ] - sigma_x_points = [ - QPointF(float(point["ts"]) - ref_time, float(point["sigma_x"])) for point in plot_data - ] - sigma_y_points = [ - QPointF(float(point["ts"]) - ref_time, float(point["sigma_y"])) for point in plot_data - ] - distance_points = [ - QPointF(float(point["ts"]) - ref_time, float(point["distance"])) for point in plot_data - ] - dx_points = [ - QPointF(float(point["ts"]) - ref_time, float(point["dx"])) for point in plot_data - ] - dy_points = [ - QPointF(float(point["ts"]) - ref_time, float(point["dy"])) for point in plot_data - ] - score_points = [ - QPointF(float(point["ts"]) - ref_time, float(point["score"])) for point in plot_data - ] - step_points = [ - QPointF(float(point["ts"]) - ref_time, float(point["step_xy"])) for point in plot_data - ] - - self.series.replace(sigma_points) - self.sigma_x_series.replace(sigma_x_points) - self.sigma_y_series.replace(sigma_y_points) - self.distance_series.replace(distance_points) - self.dx_series.replace(dx_points) - self.dy_series.replace(dy_points) - self.score_series.replace(score_points) - self.step_series.replace(step_points) - - if self._auto_scale_enabled: - (xmin, xmax, left_ymin, left_ymax, right_ymin, right_ymax, score_lo, score_hi) = ( - self._data_limits() - ) - self.axis_x.setRange(xmin, xmax) - self.axis_y.setRange(left_ymin, left_ymax) - self.axis_y_distance.setRange(right_ymin, right_ymax) - self.axis_y_score.setRange(score_lo, score_hi) - else: - self._clamp_axes() - - self._update_status_label() - self._update_metrics_label() - - def _save_last_x_seconds(self) -> None: - seconds = float(self.seconds_spin.value()) - now = time.monotonic() - rows = [s for s in self._samples if float(s["ts"]) >= now - seconds] - self._save_rows(rows, suggested_name=f"target_stability_last_{self._seconds_text()}s.csv") - - def _collect_next_x_seconds(self) -> None: - if self._paused: - logger.info("Cannot collect target stability data while paused") - return - - seconds = float(self.seconds_spin.value()) - self._collected_samples = [] - self._collecting_until = time.monotonic() + seconds - self._update_status_label() - logger.info(f"Collecting target stability data for {seconds:.1f} s") - - def _finish_collection(self) -> None: - """Freeze the plot with collected data and prompt to save.""" - self._collecting_until = None - - # Build plot points from collected samples for display - self._frozen_plot_points = [] - temp_sigma_samples = deque(maxlen=10000) - temp_rolling_count = 0 - temp_rolling_sum_dx = 0.0 - temp_rolling_sum_dy = 0.0 - temp_rolling_sum_dx2 = 0.0 - temp_rolling_sum_dy2 = 0.0 - - for sample in self._collected_samples: - temp_sigma_samples.append(sample) - dx = float(sample["dx"]) - dy = float(sample["dy"]) - - temp_rolling_count += 1 - temp_rolling_sum_dx += dx - temp_rolling_sum_dy += dy - temp_rolling_sum_dx2 += dx * dx - temp_rolling_sum_dy2 += dy * dy - - # Trim old samples from rolling window - cutoff = float(sample["ts"]) - self._sigma_window_s - while temp_sigma_samples and float(temp_sigma_samples[0]["ts"]) < cutoff: - old = temp_sigma_samples.popleft() - old_dx = float(old["dx"]) - old_dy = float(old["dy"]) - temp_rolling_count -= 1 - temp_rolling_sum_dx -= old_dx - temp_rolling_sum_dy -= old_dy - temp_rolling_sum_dx2 -= old_dx * old_dx - temp_rolling_sum_dy2 -= old_dy * old_dy - - # Compute sigma stats - if temp_rolling_count >= 2: - mean_dx = temp_rolling_sum_dx / temp_rolling_count - mean_dy = temp_rolling_sum_dy / temp_rolling_count - var_dx = max(0.0, (temp_rolling_sum_dx2 / temp_rolling_count) - (mean_dx * mean_dx)) - var_dy = max(0.0, (temp_rolling_sum_dy2 / temp_rolling_count) - (mean_dy * mean_dy)) - std_dx = math.sqrt(var_dx) - std_dy = math.sqrt(var_dy) - sigma = math.hypot(std_dx, std_dy) - else: - std_dx, std_dy, sigma = 0.0, 0.0, 0.0 - - # Compute step jitter - step_xy = 0.0 - if len(temp_sigma_samples) >= 2: - step_sum = 0.0 - count = 0 - prev = None - for s in temp_sigma_samples: - if prev is not None: - ddx = float(s["dx"]) - float(prev["dx"]) - ddy = float(s["dy"]) - float(prev["dy"]) - step_sum += ddx * ddx + ddy * ddy - count += 1 - prev = s - if count > 0: - step_xy = math.sqrt(step_sum / count) - - score = self._stability_score( - sigma - if self.score_basis_combo.currentText() == self.SCORE_FROM_SIGMA_XY - else step_xy - ) - - self._frozen_plot_points.append( - { - "ts": float(sample["ts"]), - "sigma": sigma, - "sigma_x": std_dx, - "sigma_y": std_dy, - "distance": float(sample["distance"]), - "dx": dx, - "dy": dy, - "step_xy": step_xy, - "score": score, - } - ) - - self._paused = True - self.pause_button.setChecked(True) - self.pause_button.setText("Resume (Live)") - - logger.info("Finished collecting target stability data - plot frozen") - self._update_status_label() - - # Schedule the save dialog to run after the current event processing - # This avoids blocking while any locks might be held - file_name = f"target_stability_collected_{self._seconds_text()}s.csv" - QTimer.singleShot( - 0, lambda: self._save_rows(self._collected_samples, suggested_name=file_name) - ) - self._update_status_label() - - def _unfreeze_plot(self) -> None: - """Return to live data display.""" - self._frozen_plot_points = None - self._collected_samples = [] - self._update_status_label() - - def _save_rows(self, rows: list[dict], suggested_name: str) -> None: - if not rows: - logger.info("No target stability data to save") - return - - path, _ = QFileDialog.getSaveFileName( - self, "Save Target Stability Data", suggested_name, "CSV files (*.csv)" - ) - if not path: - return - - with open(path, "w", newline="") as f: - writer = csv.writer(f) - writer.writerow(["t_monotonic_s", "dx_px", "dy_px", "distance_px"]) - for row in rows: - writer.writerow( - [ - f"{float(row['ts']):.6f}", - f"{float(row['dx']):.6f}", - f"{float(row['dy']):.6f}", - f"{float(row['distance']):.6f}", - ] - ) - - @staticmethod - def _coerce_target_point(raw) -> tuple[float, float] | None: - try: - if isinstance(raw, dict) and "x" in raw and "y" in raw: - 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 {raw}: {e}", exc_info=True) - return None diff --git a/src/aare/gui/panels/tell_sample_panel.py b/src/aare/gui/panels/tell_sample_panel.py deleted file mode 100644 index dceb9a0c..00000000 --- a/src/aare/gui/panels/tell_sample_panel.py +++ /dev/null @@ -1,515 +0,0 @@ -from aarecommon.config.logger import setup_logger -from aarecommon.models.models import ( - BeamlineStateEnum, - DAQStatusModel, - SampleShortInfo, - SampleShortInfoList, -) -from PySide6.QtCore import QEvent, Qt, QTimer, Signal, Slot -from PySide6.QtWidgets import ( - QAbstractItemView, - QButtonGroup, - QFrame, - QGridLayout, - QHBoxLayout, - QHeaderView, - QMenu, - QPushButton, - QSizePolicy, - QTableView, - QWidget, -) - -from aare.gui.constants import LOGGER_NAME -from aare.gui.models.user_sample_model import COL_STATUS, UserSampleSpreadsheet -from aare.gui.widgets.title_label import TitleLabel - -logger = setup_logger(LOGGER_NAME) - - -class FrozenColumnTableView(QTableView): - """QTableView with the "#"/status column frozen (Qt frozen-column - pattern): an overlay view shares the model and selection, sits on top of - column 0, and stays put while the rest scrolls horizontally.""" - - FROZEN_WIDTH = 36 - - # Emitted after this view's font changed (Ctrl+plus/minus zoom): the - # panel re-autosizes its columns, which were sized once at startup. - font_changed = Signal() - - def __init__(self, parent=None): - super().__init__(parent) - self.frozen = QTableView(self) - self.frozen.setFocusPolicy(Qt.FocusPolicy.NoFocus) - self.frozen.verticalHeader().hide() - self.frozen.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - self.frozen.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - self.frozen.setShowGrid(False) - self.frozen.setAlternatingRowColors(True) - self.frozen.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) - self.frozen.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) - self.frozen.setEditTriggers(QTableView.EditTrigger.NoEditTriggers) - self.frozen.setDragEnabled(True) - self.frozen.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Fixed) - self.frozen.horizontalHeader().setHighlightSections(False) - # The overlay must not carry the L3 frame — it sits INSIDE the view. - self.frozen.setStyleSheet("QTableView { border: none; }") - self.viewport().stackUnder(self.frozen) - self.frozen.verticalScrollBar().valueChanged.connect(self.verticalScrollBar().setValue) - self.verticalScrollBar().valueChanged.connect(self.frozen.verticalScrollBar().setValue) - - def setModel(self, model): - super().setModel(model) - self.frozen.setModel(model) - # Share the selection so clicking either view highlights both. - self.frozen.setSelectionModel(self.selectionModel()) - for col in range(1, model.columnCount()): - self.frozen.setColumnHidden(col, True) - self.set_frozen_width(self.FROZEN_WIDTH) - self.frozen.show() - - def set_frozen_width(self, width: int) -> None: - self.setColumnWidth(0, width) - self.frozen.setColumnWidth(0, width) - self._update_frozen_geometry() - - def _update_frozen_geometry(self) -> None: - # The overlay header must be exactly as tall as the main one, or its - # rows sit above the main rows. Qt sizes a header to its tallest - # visible section, and the main header also sees the symbol columns - # ("⧂", "⌕"), whose fallback-font glyphs have a taller line box than - # "#" at some zoom steps (1px off at 125% on macOS fonts). - self.frozen.horizontalHeader().setFixedHeight(self.horizontalHeader().height()) - self.frozen.setGeometry( - self.frameWidth(), - self.frameWidth(), - self.columnWidth(0), - self.viewport().height() + self.horizontalHeader().height(), - ) - - def resizeEvent(self, event): - super().resizeEvent(event) - self._update_frozen_geometry() - - def changeEvent(self, event) -> None: - super().changeEvent(event) - if event.type() in (QEvent.Type.FontChange, QEvent.Type.StyleChange): - # Zoom/theme re-lay the main header; re-sync the overlay once the - # layout settled. Deferred with `self` as receiver context so a - # pending call dies with the view (no callback into a dead C++ - # object). Not an updateGeometries override or a header-signal - # slot: both get invoked during teardown and a Python callback on - # a half-destroyed view leaves a lost exception behind. - QTimer.singleShot(0, self, self._update_frozen_geometry) - if event.type() == QEvent.Type.FontChange: - self.font_changed.emit() - - -class QueueDropChip(QPushButton): - """Filter chip that doubles as a drop target: dragging table rows onto it - relabels them (Queued adds to the automation queue, Flagged marks them - flagged — same mime the old queue dock took). Measured is deliberately - NOT one of these: it is automatic, from the rotation count.""" - - samples_dropped = Signal(SampleShortInfoList) - - def __init__(self, label: str, parent=None): - super().__init__(label, parent) - self.setAcceptDrops(True) - - def dragEnterEvent(self, event): - if event.mimeData().hasText(): - event.acceptProposedAction() - - def dropEvent(self, event): - try: - samples = SampleShortInfoList.model_validate_json(event.mimeData().text()) - except Exception: - logger.debug("Ignoring drop that is not a sample list", exc_info=True) - return - self.samples_dropped.emit(samples) - event.acceptProposedAction() - - -class TellSamplePanel(QFrame): - mount = Signal(SampleShortInfo) - unmount = Signal() - state = Signal(BeamlineStateEnum) - # Queue membership is edited from this table now (aaregui2 concept: the - # dewar list doubles as the queue view); the queue itself lives in the - # SampleQueuePanel these signals are wired to. - add_to_queue = Signal(SampleShortInfoList) - remove_from_queue = Signal(SampleShortInfoList) - - def __init__( - self, - samples: SampleShortInfoList | None = None, - parent=None, - model: UserSampleSpreadsheet | None = None, - ): - """`model`: share an existing spreadsheet model instead of owning one — - used by the pop-out window so both panels operate on the same data, - tints and filters with no syncing.""" - super().__init__(parent) - # Before the table view exists: its font_changed slot reads this, and - # a FontChange can already arrive while the view is being parented - # into this panel (raising inside a C++-invoked slot leaves PySide - # with a lost exception and a later "returned NULL" SystemError). - self._columns_autosized = False - - if samples is None: - samples = SampleShortInfoList(s=[]) - self.setFrameShape(QFrame.Shape.StyledPanel) - self.setFrameShadow(QFrame.Shadow.Raised) - - grid_layout = QGridLayout(self) - self.setLayout(grid_layout) - # Flush layout: the banner spans the full panel width and sits - # directly under the dock's tab row — no padding ring. - grid_layout.setContentsMargins(0, 0, 0, 0) - grid_layout.setSpacing(0) - - grid_layout.addWidget(TitleLabel("TELL sample changer", self), 0, 0, 1, 4) - - # Status filter row (aaregui2 concept): filters the table by queue/ - # collection status, and each checked button wears its row-tint color, - # doubling as the legend. Styled like the Dewar/Auxiliary tab row - # above (square tabs, touching), not pills. Colors live in styles.py. - chip_row = QHBoxLayout() - # Left margin 0: "All" shares the table's left edge; bottom 0: the - # row sits directly on the table. - chip_row.setContentsMargins(0, 2, 6, 0) - # 1px gap so the chips read as separate buttons, not one solid bar. - chip_row.setSpacing(1) - self.status_chips = QButtonGroup(self) - self.status_chips.setExclusive(True) - for label, key in ( - ("All", None), - ("Queued", "queued"), - ("Flagged", "flagged"), - # Unmeasured next to All: both are "what is left" views, the - # remaining chips are hand-applied labels. - # order updated according to Vincent's preference - ("Unmeasured", "unmeasured"), - ("Measured", "measured"), - ): - if key == "queued": - chip = QueueDropChip(label, self) - chip.samples_dropped.connect(self.add_to_queue) - # Deselect after the drop: the selection tint would otherwise - # sit on top of the fresh status color and hide it. - chip.samples_dropped.connect(lambda _: self.table_view.clearSelection()) - chip.setToolTip("Filter queued samples — or drop table rows here to queue them") - elif key == "flagged": - chip = QueueDropChip(label, self) - chip.samples_dropped.connect(self._flag_dropped_samples) - chip.samples_dropped.connect(lambda _: self.table_view.clearSelection()) - chip.setToolTip("Filter flagged samples — or drop table rows here to flag them") - else: - chip = QPushButton(label, self) - if key == "measured": - chip.setToolTip("Filter measured samples (automatic: rotation count ≥ 1)") - elif key == "unmeasured": - chip.setToolTip( - "Filter samples with no rotation data yet — select all here to" - " queue everything still to be done" - ) - chip.setCheckable(True) - chip.setChecked(key is None) - chip.setProperty("status_key", key) - chip.setCursor(Qt.CursorShape.PointingHandCursor) - # Look lives in the per-theme QPushButton#filterChip rules in - # styles.py (status_key picks the checked row-tint fill there) — - # an inline stylesheet here would pin one theme's colors. - chip.setObjectName("filterChip") - self.status_chips.addButton(chip) - chip_row.addWidget(chip) - chip_row.addStretch() - # Ignored-width host (same trick as the automation row in - # main_window): the five chips' ~380px natural minimum otherwise - # propagates dock -> window and blocks shrinking the window on small - # screens. The row clips from the right instead. - chip_host = QWidget(self) - chip_host.setLayout(chip_row) - chip_host.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Fixed) - grid_layout.addWidget(chip_host, 1, 0, 1, 4) - self.status_chips.buttonClicked.connect( - lambda chip: self.table_model.set_status_filter(chip.property("status_key")) - ) - - # Staggered grey/white rows tell rows apart — no grid lines, no row - # tints; status fills the frozen "#" column and selection stays blue. - self.table_view = FrozenColumnTableView() - self.table_view.setShowGrid(False) - self.table_view.setAlternatingRowColors(True) - self.table_view.font_changed.connect(self._on_table_font_changed) - grid_layout.addWidget(self.table_view, 2, 0, 1, 4) - - self.table_model = model if model is not None else UserSampleSpreadsheet(samples=samples.s) - self.table_view.setModel(self.table_model) - - # Adopt the model's current order before enabling sorting: a second - # panel on a shared model must not re-sort it to column 0 on open. - self.table_view.horizontalHeader().setSortIndicator( - self.table_model._sort_col, self.table_model._sort_order - ) - self.table_view.setSortingEnabled(True) - self.table_view.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) - self.table_view.customContextMenuRequested.connect(self.context_menu) - self.table_view.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows) - self.table_view.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection) - - self.table_view.setEditTriggers(QTableView.EditTrigger.NoEditTriggers) - self.table_view.setDragEnabled(True) - header = self.table_view.horizontalHeader() - header.setSectionResizeMode(QHeaderView.ResizeMode.Interactive) - header.setStretchLastSection(True) - # No bold column titles when cells are selected. - header.setHighlightSections(False) - # Row numbers + status color live in the frozen "#" column: fixed - # width, not resizable, stays visible on horizontal scroll. - self.table_view.verticalHeader().setVisible(False) - header.setSectionResizeMode(COL_STATUS, QHeaderView.ResizeMode.Fixed) - self.table_view.set_frozen_width(FrozenColumnTableView.FROZEN_WIDTH) - # Right-click on the frozen column behaves like the main table (the - # handler only uses the row, which both views share). - self.table_view.frozen.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) - self.table_view.frozen.customContextMenuRequested.connect(self.context_menu) - # "#" holds no sortable data; clicking its header selects all rows - # instead (Ctrl+A) — the quick way to act on everything visible. - # The frozen overlay owns the visible "#" header (not sorting-enabled, - # so its sections need explicit clickability); the main header is - # connected too in case the overlay is ever dropped. - self.table_view.frozen.horizontalHeader().setSectionsClickable(True) - self.table_view.frozen.horizontalHeader().sectionClicked.connect( - self._select_all_from_status_header - ) - header.sectionClicked.connect(self._select_all_from_status_header) - - header.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) - header.customContextMenuRequested.connect(self.header_context_menu) - - # Columns at full content width (horizontal scroll instead of - # squishing); done ONCE so later data refreshes don't fight manual - # column adjustments (zoom re-runs it, see _on_table_font_changed). - if self.table_model.rowCount() > 0: - self._autosize_columns() - - def _autosize_columns(self) -> None: - self.table_view.resizeColumnsToContents() - header = self.table_view.horizontalHeader() - # Cap: one long comment must not eat the whole view. - for col in range(1, self.table_model.columnCount()): - if header.sectionSize(col) > 300: - self.table_view.setColumnWidth(col, 300) - # Re-pin the frozen display column after the autosize pass. - self.table_view.set_frozen_width(FrozenColumnTableView.FROZEN_WIDTH) - self._columns_autosized = True - - @Slot() - def _on_table_font_changed(self) -> None: - # Zoom changed the glyph widths under columns sized once at startup - # (headers got truncated). Deferred: the view's own font is updated - # only after this signal. Receiver context: cancels if we die first. - if self._columns_autosized: - QTimer.singleShot(0, self, self._autosize_columns) - - @Slot(SampleShortInfoList) - def new_sample_list(self, samples: SampleShortInfoList): - self.table_model.updateData(samples=samples.s) - if not self._columns_autosized and self.table_model.rowCount() > 0: - self._autosize_columns() - - def annotate_sample_comment(self, db_id: int, comment: str) -> None: - samples = list(self.table_model.samples) - updated_samples: list[SampleShortInfo] = [] - - for sample in samples: - if sample.db_id == db_id: - updated_samples.append(sample.model_copy(update={"comment": comment})) - else: - updated_samples.append(sample) - - self.table_model.updateData(samples=updated_samples) - - @Slot(SampleShortInfoList) - def _flag_dropped_samples(self, samples: SampleShortInfoList) -> None: - # Flagged is display state owned by the (shared) model, so relabeling - # here reaches the docked panel and the pop-out alike. - for sample in samples.s: - self.table_model.set_flagged(sample.db_id, True) - - def set_status_chip(self, key: str | None) -> None: - """Check the chip for `key` without firing its filter — keeps the - main and pop-out chip rows in sync (both drive one shared model).""" - for chip in self.status_chips.buttons(): - if chip.property("status_key") == key: - chip.setChecked(True) - return - - @Slot(int) - def _select_all_from_status_header(self, section: int) -> None: - if section != COL_STATUS: - return - self.table_view.selectAll() - # The click also dragged the sort indicator onto "#" (the model - # ignores sorting there) — put it back where the data actually is. - self.table_view.horizontalHeader().setSortIndicator( - self.table_model._sort_col, self.table_model._sort_order - ) - - def _selected_samples(self, clicked_row: int) -> list[SampleShortInfo]: - """Selected rows if the clicked row is part of the selection, else - just the clicked row — so right-click on an unselected row acts on it.""" - rows = sorted({i.row() for i in self.table_view.selectionModel().selectedRows()}) - if clicked_row not in rows: - rows = [clicked_row] - return [self.table_model.get_id(r) for r in rows] - - def context_menu(self, position): - index = self.table_view.indexAt(position) - if not index.isValid(): - return - - row = index.row() - sample = self.table_model.get_id(row) - - if sample.location is None: - return - - selected = [s for s in self._selected_samples(row) if s.location is not None] - - menu = QMenu() - count = f" ({len(selected)})" if len(selected) > 1 else "" - add_queue_action = menu.addAction(f"Add to queue{count}") - remove_queue_action = menu.addAction(f"Remove from queue{count}") - menu.addSeparator() - mount_action = menu.addAction("Mount") - # Unmount moved here from the removed bottom-row button — same signal. - unmount_action = menu.addAction("Unmount") - menu.addSeparator() - # Flagging happens by dropping rows on the Flagged chip; this is the - # only way back, so it lives here even though Flag does not. - unflag_action = menu.addAction(f"Unflag{count}") - unflag_action.setEnabled(any(s.db_id in self.table_model.flagged_ids for s in selected)) - - action = menu.exec_(self.table_view.viewport().mapToGlobal(position)) - - if action == mount_action: - self.mount.emit(sample) - elif action == unmount_action: - self.unmount.emit() - elif action == add_queue_action: - self.add_to_queue.emit(SampleShortInfoList(s=selected)) - self.table_view.clearSelection() - elif action == remove_queue_action: - self.remove_from_queue.emit(SampleShortInfoList(s=selected)) - self.table_view.clearSelection() - elif action == unflag_action: - for s in selected: - self.table_model.set_flagged(s.db_id, False) - self.table_view.clearSelection() - - def header_context_menu(self, pos): - header = self.table_view.horizontalHeader() - logical_index = header.logicalIndexAt(pos) - # The "#"/status column is display-only — no filter menus there. - if logical_index < 1: - return - - col_name = self.table_model.header[logical_index] - - menu = QMenu(self) - - # Column-specific preset submenus (existing logic) ... - if logical_index == 1: # Sample name - presets = self.table_model.suggested_prefixes_for_sample_name() - if presets: - prefix_menu = menu.addMenu("Filter by name prefix") - for p in presets: - act = prefix_menu.addAction(p) - act.triggered.connect( - lambda checked=False, vv=p: self.table_model.set_column_filter( - logical_index, vv - ) - ) - elif logical_index == 4: # Location - segs, segpos = self.table_model.suggested_prefixes_for_location() - if segs: - seg_menu = menu.addMenu("Filter by segment (A..F,X,R)") - for s in segs: - act = seg_menu.addAction(s) - act.triggered.connect( - lambda checked=False, vv=s: self.table_model.set_column_filter( - logical_index, vv - ) - ) - if segpos: - sp_menu = menu.addMenu("Filter by segment+position (e.g. B3)") - for sp in segpos: - act = sp_menu.addAction(sp) - act.triggered.connect( - lambda checked=False, vv=sp: self.table_model.set_column_filter( - logical_index, vv - ) - ) - else: - values = self.table_model.unique_values_for_column(logical_index) - if values: - choose_menu = menu.addMenu(f"Choose {col_name}") - for v in values: - act = choose_menu.addAction(v) - act.triggered.connect( - lambda checked=False, vv=v: self.table_model.set_column_filter( - logical_index, vv - ) - ) - - # Manual entry and clear options - set_filter_action = menu.addAction(f"Filter column: {col_name}...") - clear_filter_action = menu.addAction(f"Clear filter: {col_name}") - clear_all_action = menu.addAction("Clear all filters") - - if logical_index == 6: # User - menu.addSeparator() - toggle_all = menu.addAction("Show all pgroups (ignore current p-group)") - toggle_all.setCheckable(True) - toggle_all.setChecked(self.table_model.show_all_pgroups) - - def _toggle_all(): - self.table_model.set_show_all_pgroups(not self.table_model.show_all_pgroups) - - toggle_all.triggered.connect(_toggle_all) - - action = menu.exec_(header.mapToGlobal(pos)) - if action is None: - return - - if action == set_filter_action: - from PySide6.QtWidgets import QInputDialog - - text, ok = QInputDialog.getText(self, "Set filter", f"Filter for '{col_name}':") - if ok: - self.table_model.set_column_filter(logical_index, text) - elif action == clear_filter_action: - self.table_model.set_column_filter(logical_index, None) - elif action == clear_all_action: - self.table_model.clear_all_column_filters() - - @Slot(DAQStatusModel) - def update_daq_status(self, status: DAQStatusModel): - # Mounted state shows as the row highlight only — the "No sample - # mounted" label and Unmount button were dropped; TELL activity text - # lives in the beamline state panel already. - sample = status.sample - if sample is None: - self.table_model.updateCurrentSample(current_puck=None, current_sample=None) - else: - self.table_model.updateCurrentSample( - current_puck=sample.puck_name, current_sample=sample.db_id - ) - - if status.session.current_pgroup is not None: - self._current_pgroup = status.session.current_pgroup - self.table_model.set_default_user_filter(self._current_pgroup) diff --git a/src/aare/gui/panels/zoom_panel.py b/src/aare/gui/panels/zoom_panel.py deleted file mode 100644 index 6ae14f56..00000000 --- a/src/aare/gui/panels/zoom_panel.py +++ /dev/null @@ -1,50 +0,0 @@ -from aarecommon.models.models import DAQStatusModel -from PySide6.QtCore import Signal, Slot -from PySide6.QtWidgets import QGridLayout, QWidget - -from aare.gui.widgets.button_with_payload import ButtonWithPayload -from aare.gui.widgets.title_label import TitleLabel - - -class ZoomPanel(QWidget): - zoom = Signal(float) - - def __init__(self, parent=None): - super().__init__(parent) - - self._zoom = 1.0 - - grid_layout = QGridLayout(self) - self._zoom_settings = [ - {"name": "1.0x", "value": 1}, - {"name": "2.0x", "value": 280}, - {"name": "3.5x", "value": 500}, - {"name": "5.8x", "value": 700}, - {"name": "7.5x", "value": 800}, - {"name": "12.5x", "value": 1000}, - ] - grid_layout.addWidget( - TitleLabel("Zoom", self, collapsible=True, default_collapsed=False), 0, 0, 1, 2 - ) - i = 2 - - self._buttons = [] - for z in self._zoom_settings: - button = ButtonWithPayload(z["name"], {"zoom": z["value"]}) - grid_layout.addWidget(button, int(i / 2), int(i % 2)) - i += 1 - button.pressed.connect(self.set_zoom) - self._buttons.append(button) - - @Slot(dict) - def set_zoom(self, payload: dict): - self.zoom.emit(payload["zoom"]) - - @Slot(DAQStatusModel) - def update_daq_status(self, status: DAQStatusModel): - self._zoom = status.bl.zoom - for z in self._zoom_settings: - if z["value"] == self._zoom: - self._buttons[self._zoom_settings.index(z)].setStyleSheet("font-weight: bold;") - else: - self._buttons[self._zoom_settings.index(z)].setStyleSheet("") diff --git a/src/aare/gui/scan_logic/__init__.py b/src/aare/gui/scan_logic/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/aare/gui/scan_logic/raster_grid_manager.py b/src/aare/gui/scan_logic/raster_grid_manager.py deleted file mode 100644 index 3d5ba110..00000000 --- a/src/aare/gui/scan_logic/raster_grid_manager.py +++ /dev/null @@ -1,983 +0,0 @@ -import math -from enum import Enum - -import numpy as np -from aarecommon.config.beamline import cfg_get, get_jfjoch_url, mx_beamline -from aarecommon.config.logger import setup_logger -from aarecommon.math.coordinate import Coordinate, SmargonCoordinate -from aarecommon.math.find_xtal import compute_crystal_score_array -from aarecommon.math.sample_geometry import SampleGeometryModel -from aarecommon.models.models import DAQStatusModel -from aarecommon.models.raster_grid import ( - CompletedRasterGrid, - CompletedRasterGridElem, - RasterGridRequest, -) -from PySide6.QtCore import QLineF, QObject, QPointF, QRect, QRectF, Qt, Signal, Slot -from PySide6.QtGui import QBrush, QColor, QImage, QPainter, QPen - -from aare.gui.constants import LOGGER_NAME -from aare.gui.styles import RASTER_GRID_LINE, qcolor - -logger = setup_logger(LOGGER_NAME) - - -class RasterGridMetric(Enum): - BKG = 0 - SPOTS = 1 - INDEXING = 2 - PR = 3 # JD: repurposing PR for testing scoring - BFACTOR = 4 - SPOTS_LOW_RES = 5 - RES = 6 - SPOTS_ICE = 7 - SPOTS_INDEXED = 8 - SPOTS_ICE_LOW_RES = 9 - RASTER_SCORE = 10 - - -# Viridis colormap colors (from matplotlib), dark purple -> yellow -_VIRIDIS_COLORS = [ - (68, 1, 84), # Dark purple - (72, 35, 116), - (64, 67, 135), - (52, 94, 141), - (41, 120, 142), - (32, 144, 140), - (34, 167, 132), - (68, 190, 112), - (121, 209, 81), - (189, 223, 38), - (253, 231, 37), # Yellow -] - -# Float (N, 3) lookup table for vectorised colour mapping. -_VIRIDIS_LUT = np.array(_VIRIDIS_COLORS, dtype=np.float64) - - -def viridis_rgb_array(norm: np.ndarray) -> np.ndarray: - """Map an array of normalized values in [0, 1] to (..., 3) uint8 RGB using - the Viridis colormap, vectorised with the same linear interpolation as - float_to_viridis_brush.""" - pos = np.clip(norm, 0.0, 1.0) * (len(_VIRIDIS_LUT) - 1) - lo = np.clip(np.floor(pos).astype(np.intp), 0, len(_VIRIDIS_LUT) - 1) - hi = np.clip(lo + 1, 0, len(_VIRIDIS_LUT) - 1) - t = (pos - lo)[..., None] - c = _VIRIDIS_LUT[lo] * (1.0 - t) + _VIRIDIS_LUT[hi] * t - return np.clip(np.rint(c), 0, 255).astype(np.uint8) - - -def float_to_viridis_brush(value: float, alpha: int = 127) -> QBrush: - """ - Convert float value to a QBrush with Viridis colormap - Args: - value: Float between 0 and 1 - alpha: Transparency (0-255), default 127 for 50% transparency - Returns: - QBrush with corresponding Viridis color - """ - viridis_colors = _VIRIDIS_COLORS - - # Clamp value between 0 and 1 - value = max(0.0, min(1.0, value)) - - # Find the two colors to interpolate between - index = value * (len(viridis_colors) - 1) - i = int(index) - t = index - i - - if i == len(viridis_colors) - 1: - color = viridis_colors[-1] - else: - # Linear interpolation between two adjacent colors - c1 = viridis_colors[i] - c2 = viridis_colors[i + 1] - color = tuple(int(c1[j] + (c2[j] - c1[j]) * t) for j in range(3)) - - return QBrush(QColor(color[0], color[1], color[2], alpha)) - - -def normalize_angle(angle_deg: float) -> float: - normalized_angle = math.fmod(angle_deg + 180, 360) - 180.0 - return normalized_angle - - -class RasterGridManager(QObject): - viewer_track_online = Signal() - - grid_updated = Signal() - - grid_scan = Signal(RasterGridRequest) - grid_scan_auto = Signal(RasterGridRequest) - - grid_scan_size_changed = Signal(int, int, float, float) - completed_grid_updated = Signal() - - image_selected = Signal(str, int) - - omega = Signal(float) - smargon = Signal(SmargonCoordinate) - - def __init__(self, geom: SampleGeometryModel): - super().__init__() - - self._sample_id = -1 - self._beamline = mx_beamline() - self._detector_url = get_jfjoch_url(self._beamline) - - self._beam_size_mm = geom.beam_size_mm - self._geom = geom - - self._metric = RasterGridMetric.RASTER_SCORE - - self._loaded_image_prefix = None - self._loaded_image_index = None - - self._start_point: QPointF = QPointF(0, 0) - self._active_grid: RasterGridRequest = RasterGridRequest( - n_x=0, - n_y=0, - smargon_top_left=self._geom.smargon, - grid_size_mm=Coordinate(x=0.8 * self._beam_size_mm.x, y=0.8 * self._beam_size_mm.y), - omega_deg=self._geom.omega_deg, - exp_time_s=cfg_get( - "daq.data_collection_settings.default_raster_settings.exp_time_s", 0.01 - ), - transmission=cfg_get( - "daq.data_collection_settings.default_raster_settings.transmission", 1.0 - ), - dtz=cfg_get("daq.data_collection_settings.default_raster_settings.dtz", 200.0), - ) - self._completed_grids: list[CompletedRasterGridElem] = [] - - # Cache of pre-rendered heatmap bitmaps, keyed by (id(grid_elem), metric). - # Each entry is (QImage, backing ndarray); the ndarray must be kept alive - # because QImage shares its buffer without copying. Rebuilt only when the - # data or metric changes, not on every repaint (sample move / zoom). - self._heatmap_cache: dict[tuple[int, RasterGridMetric], tuple[QImage, np.ndarray]] = {} - - @property - def active_grid(self) -> RasterGridRequest: - return self._active_grid - - def _is_grid_visible(self, grid: RasterGridRequest): - if ( - grid.smargon_top_left is None - or grid.smargon_top_left.phi_deg is None - or grid.smargon_top_left.chi_deg is None - or self._geom.smargon.phi_deg is None - or self._geom.smargon.chi_deg is None - ): - raise ValueError(f"Cannot compute visibility for {grid}.") - return bool( - grid.visible - and abs(normalize_angle(grid.omega_deg - self._geom.omega_deg)) < 0.2 - and abs(grid.smargon_top_left.phi_deg - self._geom.smargon.phi_deg) < 0.2 - and abs(grid.smargon_top_left.chi_deg - self._geom.smargon.chi_deg) < 0.2 - and grid.n_x > 0 - and grid.n_y > 0 - ) - - def _grid_pixel_geometry( - self, grid: RasterGridRequest - ) -> tuple[float, float, float, float] | None: - if not self._is_grid_visible(grid): - return None - - cell = grid.grid_size_pxl(self._geom) - cell_w = float(cell.x) - cell_h = float(cell.y) - - if cell_w <= 0 or cell_h <= 0: - return None - - start_anchor = grid.start_pxl(self._geom) - start_picture = self._geom.sample_to_picture(start_anchor) - - return float(start_picture.x), float(start_picture.y), cell_w, cell_h - - def _grid_bounds_rect(self, grid: RasterGridRequest) -> QRectF | None: - geo = self._grid_pixel_geometry(grid) - if geo is None: - return None - - start_x, start_y, cell_w, cell_h = geo - return QRectF(start_x, start_y, cell_w * grid.n_x, cell_h * grid.n_y) - - def _visible_index_range( - self, - grid: RasterGridRequest, - visible_rect: QRectF | None, - start_x: float, - start_y: float, - cell_w: float, - cell_h: float, - ) -> tuple[int, int, int, int]: - if visible_rect is None or visible_rect.isEmpty(): - return 0, grid.n_x, 0, grid.n_y - - min_x = max(0, math.floor((visible_rect.left() - start_x) / cell_w) - 1) - max_x = min(grid.n_x, math.ceil((visible_rect.right() - start_x) / cell_w) + 1) - min_y = max(0, math.floor((visible_rect.top() - start_y) / cell_h) - 1) - max_y = min(grid.n_y, math.ceil((visible_rect.bottom() - start_y) / cell_h) + 1) - - return min_x, max_x, min_y, max_y - - @Slot(RasterGridRequest) - def update_active_grid_request(self, grid: RasterGridRequest): - self._active_grid.smargon_top_left = grid.smargon_top_left - self._active_grid.omega_deg = grid.omega_deg - self._active_grid.grid_size_mm = grid.grid_size_mm - self._active_grid.n_x = grid.n_x - self._active_grid.n_y = grid.n_y - self.grid_scan_size_changed.emit( - self._active_grid.n_x, - self._active_grid.n_y, - self._active_grid.grid_size_mm.x, - self._active_grid.grid_size_mm.y, - ) - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - if s.sample is not None and s.sample.db_id != self._sample_id: - self._sample_id = s.sample.db_id - self.clear_completed_grids() - self.clear_active_grid() - if self._beam_size_mm != s.geom.beam_size_mm: - self._beam_size_mm = s.geom.beam_size_mm - self.update_grid_size(0.8 * self._beam_size_mm.x, 0.8 * self._beam_size_mm.y) - self._geom = s.geom - - def resize_active_grid(self, end_point: QPointF): - self.update_active_grid(self._start_point, end_point) - - def update_active_grid(self, start: QPointF, end: QPointF): - delta_x = (end.x() - start.x()) * self._geom.pixel_in_mm - delta_y = (end.y() - start.y()) * self._geom.pixel_in_mm - - self._active_grid.n_x = round(abs(delta_x / self._active_grid.grid_size_mm.x)) - self._active_grid.n_y = round(abs(delta_y / self._active_grid.grid_size_mm.y)) - - c = self._geom.picture_to_sample(Coordinate(x=start.x(), y=start.y())) - - if delta_x < 0: - c.x -= self._active_grid.n_x * self._active_grid.grid_size_mm.x - if delta_y < 0: - c.y -= self._active_grid.n_y * self._active_grid.grid_size_mm.y - - if delta_x < 0 or delta_y < 0: - c_pic = self._geom.sample_to_picture(c) - self._start_point = QPointF(c_pic.x, c_pic.y) - else: - self._start_point = start - - self._active_grid.smargon_top_left = SmargonCoordinate( - sh_mm=self._geom.beamline_to_smargon(c), - phi_deg=self._geom.smargon.phi_deg, - chi_deg=self._geom.smargon.chi_deg, - ) - - self._active_grid.omega_deg = self._geom.omega_deg - self.grid_scan_size_changed.emit( - self._active_grid.n_x, - self._active_grid.n_y, - self._active_grid.grid_size_mm.x, - self._active_grid.grid_size_mm.y, - ) - - def move_active_grid(self, delta: QPointF): - if not self._is_grid_visible(self._active_grid): - return - - delta_pxl = Coordinate(x=delta.x(), y=delta.y()) - delta_mm = self._geom.smargon_nudge(delta_pxl * self._geom.pixel_in_mm) - - self._active_grid.smargon_top_left = SmargonCoordinate( - sh_mm=self._active_grid.smargon_top_left.sh_mm + delta_mm, - phi_deg=self._geom.smargon.phi_deg, - chi_deg=self._geom.smargon.chi_deg, - ) - - @Slot() - def clear_active_grid(self): - self._active_grid.n_x = 0 - self._active_grid.n_y = 0 - self.grid_scan_size_changed.emit( - 0, 0, self._active_grid.grid_size_mm.x, self._active_grid.grid_size_mm.y - ) - - def get_grid_coord(self, grid: RasterGridRequest, point: QPointF) -> tuple[int, int]: - point_bl = self._geom.picture_to_sample(Coordinate(x=point.x(), y=point.y())) - - delta = point_bl - self._geom.smargon_to_beamline(grid.smargon_top_left.sh_mm) - - elem_x = grid.grid_size_mm.x - elem_y = grid.grid_size_mm.y - - cell_x = math.floor(delta.x / elem_x) - cell_y = math.floor(delta.y / elem_y) - - return cell_x, cell_y - - @Slot(QPointF) - def load_image(self, point: QPointF): - for grid in self._completed_grids: - if self._is_grid_visible(grid.request): - n_x = grid.request.n_x - n_y = grid.request.n_y - cell_x, cell_y = self.get_grid_coord(grid.request, point) - - if 0 <= cell_x < n_x and 0 <= cell_y < n_y: - cell = cell_y * n_x + cell_x - - if ( - self._loaded_image_prefix != grid.result.file_prefix - or self._loaded_image_index != grid.result.images[cell].number - ): - self._loaded_image_prefix = grid.result.file_prefix - self._loaded_image_index = grid.result.images[cell].number - logger.debug( - f"Load {grid.result.file_prefix} {grid.result.images[cell].number}" - ) - self.image_selected.emit( - grid.result.file_prefix, grid.result.images[cell].number - ) - # TODO if not in the same PGroup, user can stream from last run only but never load from a file. - # If loading a prior run, this shoudl throw an error, - # if user in same pgroup, load will always be fine. - # self.image_selected.emit(self._detector_url, grid.result.images[cell].number) - - def is_part_of_active_grid(self, point: QPointF) -> bool: - if not self._is_grid_visible(self._active_grid): - return False - point_bl = self._geom.picture_to_sample(Coordinate(x=point.x(), y=point.y())) - - delta = point_bl - self._geom.smargon_to_beamline(self._active_grid.smargon_top_left.sh_mm) - return (0 <= delta.x < self._active_grid.n_x * self._active_grid.grid_size_mm.x) and ( - 0 <= delta.y < self._active_grid.n_y * self._active_grid.grid_size_mm.y - ) - - def is_part_of_completed_grid(self, point: QPointF) -> str | None: - for grid in self._completed_grids: - if self._is_grid_visible(grid.request): - n_x = grid.request.n_x - n_y = grid.request.n_y - cell_x, cell_y = self.get_grid_coord(grid.request, point) - - if 0 <= cell_x < n_x and 0 <= cell_y < n_y: - cell = cell_y * n_x + cell_x - txt = "" - if ( - cell < len(grid.result.images) - and grid.result.images[cell].efficiency == 1.0 - ): - txt += f"Image {grid.result.images[cell].number}
" - - if ( - grid.result.images[cell].bkg is not None - and grid.result.images[cell].bkg >= 0 - ): - txt += f"Background estimate {grid.result.images[cell].bkg:.2f}
" - - if ( - grid.result.images[cell].spots is not None - and grid.result.images[cell].spots >= 0 - ): - txt += f"Spot count {grid.result.images[cell].spots}
" - - if ( - grid.result.images[cell].spots_ice is not None - and grid.result.images[cell].spots_ice >= 0 - ): - txt += f"Spot count (ice) {grid.result.images[cell].spots_ice}
" - - if ( - self.spot_ice_ratio(grid.result.images[cell]) is not None - and self.spot_ice_ratio(grid.result.images[cell]) >= 0 - ): - txt += f"Spot ratio (ice/low res.) {self.spot_ice_ratio(grid.result.images[cell])}
" - - if ( - grid.result.images[cell].spots_low_res is not None - and grid.result.images[cell].spots_low_res >= 0 - ): - txt += f"Spot count (low res.) {grid.result.images[cell].spots_low_res}
" - - if ( - grid.result.images[cell].index is not None - and grid.result.images[cell].index > 0 - and grid.result.images[cell].uc is not None - ): - txt += f"Indexed {grid.result.images[cell].uc.a:.1f} {grid.result.images[cell].uc.b:.1f} {grid.result.images[cell].uc.c:.1f} {grid.result.images[cell].uc.alpha:.1f} {grid.result.images[cell].uc.beta:.1f} {grid.result.images[cell].uc.gamma:.1f}
" - - if ( - grid.result.images[cell].b is not None - and grid.result.images[cell].b >= 0 - ): - txt += f"B-factor {grid.result.images[cell].b:.2f}
" - - if ( - grid.result.images[cell].pr is not None - and grid.result.images[cell].pr >= 0 - ): - txt += f"Profile Radius {grid.result.images[cell].pr:.2f}
" - if ( - grid.result.images[cell].nx is not None - and grid.result.images[cell].ny is not None - ): - score = compute_crystal_score_array(grid.result.images) - txt += f"Raster score {score[grid.result.images[cell].nx, grid.result.images[cell].ny]:.2f}" - - return txt - return None - - @Slot(float, float) - def update_grid_size(self, grid_size_mm_x: float, grid_size_mm_y: float): - if (grid_size_mm_x <= 0) or (grid_size_mm_y <= 0): - raise ValueError("Grid size must be positive") - - self._active_grid.n_x = round( - self._active_grid.n_x * self._active_grid.grid_size_mm.x / grid_size_mm_x - ) - self._active_grid.n_y = round( - self._active_grid.n_y * self._active_grid.grid_size_mm.y / grid_size_mm_y - ) - - self._active_grid.grid_size_mm = Coordinate(x=grid_size_mm_x, y=grid_size_mm_y) - - self.grid_scan_size_changed.emit( - self._active_grid.n_x, - self._active_grid.n_y, - self._active_grid.grid_size_mm.x, - self._active_grid.grid_size_mm.y, - ) - - @Slot() - def run_grid_scan(self): - ag = self._active_grid - grid = RasterGridRequest( - dtz=ag.dtz, - transmission=ag.transmission, - file_prefix=ag.file_prefix, - exp_time_s=ag.exp_time_s, - n_x=ag.n_x, - n_y=ag.n_y, - grid_size_mm=Coordinate(x=ag.grid_size_mm.x, y=ag.grid_size_mm.y), - smargon_top_left=SmargonCoordinate( - sh_mm=Coordinate( - x=ag.smargon_top_left.sh_mm.x, - y=ag.smargon_top_left.sh_mm.y, - z=ag.smargon_top_left.sh_mm.z, - ), - phi_deg=ag.smargon_top_left.phi_deg, - chi_deg=ag.smargon_top_left.chi_deg, - ), - omega_deg=ag.omega_deg, - visible=ag.visible, - ) - self.grid_scan.emit(grid) - self.viewer_track_online.emit() - - @Slot() - def run_grid_scan_auto(self): - ag = self._active_grid - grid = RasterGridRequest( - dtz=ag.dtz, - transmission=ag.transmission, - file_prefix=ag.file_prefix, - exp_time_s=ag.exp_time_s, - n_x=ag.n_x, - n_y=ag.n_y, - grid_size_mm=Coordinate(x=ag.grid_size_mm.x, y=ag.grid_size_mm.y), - smargon_top_left=None, - omega_deg=ag.omega_deg, - visible=ag.visible, - ) - self.grid_scan_auto.emit(grid) - self.viewer_track_online.emit() - - def spot_ice_ratio(self, obj): - if obj.spots_ice is None or obj.spots_low_res is None or obj.spots_low_res <= 0: - return None - else: - return obj.spots_ice / obj.spots_low_res - - def draw_grid(self, painter: QPainter, alpha: int = 127): - if alpha < 0 or alpha > 255: - return - - visible_rect = painter.clipBoundingRect() - if visible_rect.isEmpty(): - visible_rect = QRectF() - - self._draw_grid(painter, self._active_grid, None, alpha, visible_rect) - - for i in self._completed_grids: - match self._metric: - case RasterGridMetric.SPOTS_LOW_RES: - v = [obj.spots_low_res for obj in i.result.images] - case RasterGridMetric.SPOTS: - v = [obj.spots for obj in i.result.images] - case RasterGridMetric.BKG: - v = [obj.bkg for obj in i.result.images] - case RasterGridMetric.INDEXING: - v = [obj.index for obj in i.result.images] - case RasterGridMetric.PR: - v = [obj.index / max(obj.spots_low_res, 1) for obj in i.result.images] - case RasterGridMetric.RASTER_SCORE: - score = compute_crystal_score_array(i.result.images) - v = [ - score[obj.nx, obj.ny] if obj.nx is not None and obj.ny is not None else None - for obj in i.result.images - ] - case RasterGridMetric.BFACTOR: - v = [obj.b for obj in i.result.images] - case RasterGridMetric.RES: - v = [obj.res for obj in i.result.images] - case RasterGridMetric.SPOTS_ICE: - v = [obj.spots_ice for obj in i.result.images] - case RasterGridMetric.SPOTS_ICE_LOW_RES: - v = [self.spot_ice_ratio(obj) for obj in i.result.images] - case RasterGridMetric.SPOTS_INDEXED: - v = [obj.spots_indexed for obj in i.result.images] - self._draw_completed_heatmap(painter, i, v, alpha, visible_rect, (id(i), self._metric)) - - def _invalidate_heatmap_cache(self) -> None: - """Drop all cached heatmap bitmaps. Call whenever the completed-grid data - set or the active metric changes; cheap to rebuild lazily on next paint.""" - self._heatmap_cache.clear() - - def _heatmap_image( - self, cache_key: tuple, grid: RasterGridRequest, values: list[float] | list[int] - ) -> QImage | None: - """Return a cached n_x*n_y heatmap bitmap for this grid, building it once - on a cache miss. One pixel per cell; colours baked at full opacity with - the alpha channel encoding validity (overlay transparency is applied at - blit time via painter opacity, so it never invalidates the cache).""" - cached = self._heatmap_cache.get(cache_key) - if cached is not None: - return cached[0] - - built = self._build_heatmap_image(grid.n_x, grid.n_y, values) - if built is None: - return None - - self._heatmap_cache[cache_key] = built - return built[0] - - def _build_heatmap_image( - self, n_x: int, n_y: int, values: list[float] | list[int] - ) -> tuple[QImage, np.ndarray] | None: - if n_x <= 0 or n_y <= 0: - return None - - count = n_x * n_y - - # Cell values are laid out row-major: idx = x + y * n_x (matches the - # per-cell loop and load_image()/get_grid_coord() hit-testing). - flat = np.array([np.nan if v is None else v for v in values[:count]], dtype=np.float64) - if flat.size < count: - flat = np.concatenate([flat, np.full(count - flat.size, np.nan)]) - - valid = np.isfinite(flat) & (flat >= 0) - if valid.any(): - vmin = float(flat[valid].min()) - vmax = float(flat[valid].max()) - else: - vmin, vmax = 0.0, 1.0 - diff = (vmax - vmin) or 1.0 - - norm = np.clip((flat - vmin) / diff, 0.0, 1.0) - norm[~valid] = 0.0 - - rgba = np.zeros((count, 4), dtype=np.uint8) - rgba[:, :3] = viridis_rgb_array(norm) - rgba[:, 3] = np.where(valid, 255, 0).astype(np.uint8) - - # (n_y rows, n_x cols, RGBA); contiguous so QImage can share the buffer. - rgba = np.ascontiguousarray(rgba.reshape(n_y, n_x, 4)) - image = QImage(rgba.data, n_x, n_y, 4 * n_x, QImage.Format.Format_RGBA8888) - return image, rgba - - def _draw_completed_heatmap( - self, - painter: QPainter, - elem: CompletedRasterGridElem, - values: list[float] | list[int], - alpha: int, - visible_rect: QRectF | None, - cache_key: tuple, - ) -> None: - """Draw a completed grid by blitting its cached heatmap bitmap, scaled to - the current grid bounds. The bounds follow the sample geometry (x/y/z) - and the view transform handles zoom, so a move/zoom only changes the - destination rect - no per-cell repaint.""" - grid = elem.request - if not self._is_grid_visible(grid): - return - if alpha < 0 or alpha > 255: - return - - bounds = self._grid_bounds_rect(grid) - if bounds is None: - return - - if ( - visible_rect is not None - and not visible_rect.isEmpty() - and not bounds.intersects(visible_rect) - ): - return - - image = self._heatmap_image(cache_key, grid, values) - if image is None or image.isNull(): - # Fall back to per-cell rendering if the bitmap could not be built. - self._draw_grid(painter, grid, values, alpha, visible_rect) - return - - painter.save() - painter.setRenderHint(QPainter.RenderHint.Antialiasing, False) - # Nearest-neighbour scaling keeps cells crisp and blocky like the - # original fillRect rendering. - painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform, False) - painter.setOpacity(alpha / 255.0) - painter.drawImage(bounds, image) - painter.setOpacity(1.0) - - painter.setPen( - QPen(qcolor(RASTER_GRID_LINE, min(255, alpha + 88)), 2, Qt.PenStyle.SolidLine) - ) - painter.setBrush(Qt.BrushStyle.NoBrush) - painter.drawRect(bounds) - painter.restore() - - # TODO make sure draw_grid is visualising the grid correctly, correct orientation, correct x/y labelling!!!! - def _draw_grid( - self, - painter: QPainter, - grid: RasterGridRequest, - values: list[float] | list[int] | None = None, - alpha: int = 127, - visible_rect: QRectF | None = None, - ): - if not self._is_grid_visible(grid): - return - if alpha < 0 or alpha > 255: - return - - if values is None and self._draw_active_grid_fast(painter, grid, visible_rect): - return - - geo = self._grid_pixel_geometry(grid) - if geo is None: - return - - start_x, start_y, cell_w, cell_h = geo - bounds = self._grid_bounds_rect(grid) - if bounds is None: - return - - if ( - visible_rect is not None - and not visible_rect.isEmpty() - and not bounds.intersects(visible_rect) - ): - return - - if ( - values is not None - and (cell_w < 3.0 or cell_h < 3.0) - and self._draw_completed_grid_fast(painter, grid, values, alpha, visible_rect) - ): - return - - painter.save() - painter.setRenderHint(QPainter.RenderHint.Antialiasing, False) - - if values is not None: - painter.setPen(Qt.PenStyle.NoPen) - min_value = min((x for x in values if x is not None and not math.isnan(x)), default=0) - max_value = max((x for x in values if x is not None and not math.isnan(x)), default=1) - diff = 1 if min_value == max_value else (max_value - min_value) - else: - painter.setPen(QPen(qcolor(RASTER_GRID_LINE), 2, Qt.PenStyle.SolidLine)) - min_value = 0 - diff = 1 - - min_x, max_x, min_y, max_y = self._visible_index_range( - grid, visible_rect, start_x, start_y, cell_w, cell_h - ) - - for y in range(min_y, max_y): - py = start_y + y * cell_h - - for x in range(min_x, max_x): - px = start_x + x * cell_w - - if values is None: - painter.setBrush(Qt.BrushStyle.NoBrush) - painter.drawRect(QRect(round(px), round(py), round(cell_w), round(cell_h))) - continue - - idx = x + y * grid.n_x - if ( - len(values) <= idx - or values[idx] is None - or math.isnan(values[idx]) - or values[idx] < 0 - ): - continue - - brush = float_to_viridis_brush((values[idx] - min_value) / diff, alpha=alpha) - painter.fillRect(QRectF(px, py, max(1.0, cell_w), max(1.0, cell_h)), brush) - - if values is None: - painter.setBrush(Qt.BrushStyle.NoBrush) - else: - painter.setPen( - QPen(qcolor(RASTER_GRID_LINE, min(255, alpha + 88)), 2, Qt.PenStyle.SolidLine) - ) - painter.setBrush(Qt.BrushStyle.NoBrush) - painter.drawRect(bounds) - - painter.restore() - - def _draw_active_grid_fast( - self, painter: QPainter, grid: RasterGridRequest, visible_rect: QRectF | None - ) -> bool: - geo = self._grid_pixel_geometry(grid) - if geo is None: - return False - - start_x, start_y, cell_w, cell_h = geo - bounds = self._grid_bounds_rect(grid) - if bounds is None: - return False - - if ( - visible_rect is not None - and not visible_rect.isEmpty() - and not bounds.intersects(visible_rect) - ): - return True - - painter.save() - painter.setRenderHint(QPainter.RenderHint.Antialiasing, False) - painter.setPen(QPen(qcolor(RASTER_GRID_LINE), 2, Qt.PenStyle.SolidLine)) - painter.setBrush(Qt.BrushStyle.NoBrush) - - painter.drawRect(bounds) - - min_spacing_px = 4.0 - stride_x = max(1, math.ceil(min_spacing_px / max(cell_w, 1e-9))) - stride_y = max(1, math.ceil(min_spacing_px / max(cell_h, 1e-9))) - - min_ix, max_ix, min_iy, max_iy = self._visible_index_range( - grid, visible_rect, start_x, start_y, cell_w, cell_h - ) - - vertical_lines: list[QLineF] = [] - horizontal_lines: list[QLineF] = [] - - x_start = max(1, min_ix) - x_end = min(grid.n_x, max_ix) - for x in range(x_start, x_end, stride_x): - px = start_x + x * cell_w - vertical_lines.append(QLineF(px, bounds.top(), px, bounds.bottom())) - - y_start = max(1, min_iy) - y_end = min(grid.n_y, max_iy) - for y in range(y_start, y_end, stride_y): - py = start_y + y * cell_h - horizontal_lines.append(QLineF(bounds.left(), py, bounds.right(), py)) - - if vertical_lines: - painter.drawLines(vertical_lines) - if horizontal_lines: - painter.drawLines(horizontal_lines) - - painter.restore() - return True - - def _draw_completed_grid_fast( - self, - painter: QPainter, - grid: RasterGridRequest, - values: list[float] | list[int], - alpha: int, - visible_rect: QRectF | None, - ) -> bool: - geo = self._grid_pixel_geometry(grid) - if geo is None: - return False - - start_x, start_y, cell_w, cell_h = geo - bounds = self._grid_bounds_rect(grid) - if bounds is None: - return False - - if ( - visible_rect is not None - and not visible_rect.isEmpty() - and not bounds.intersects(visible_rect) - ): - return True - - valid_values = [x for x in values if x is not None and not math.isnan(x) and x >= 0] - min_value = min(valid_values, default=0) - max_value = max(valid_values, default=1) - diff = 1 if min_value == max_value else (max_value - min_value) - - min_x, max_x, min_y, max_y = self._visible_index_range( - grid, visible_rect, start_x, start_y, cell_w, cell_h - ) - - min_fill_px = 3.0 - stride_x = max(1, math.ceil(min_fill_px / max(cell_w, 1e-9))) - stride_y = max(1, math.ceil(min_fill_px / max(cell_h, 1e-9))) - - painter.save() - painter.setRenderHint(QPainter.RenderHint.Antialiasing, False) - painter.setPen(Qt.PenStyle.NoPen) - - for y in range(min_y, max_y, stride_y): - py = start_y + y * cell_h - draw_h = max(1.0, cell_h * stride_y) - - for x in range(min_x, max_x, stride_x): - px = start_x + x * cell_w - draw_w = max(1.0, cell_w * stride_x) - - value = self._block_value( - values, grid.n_x, x, min(x + stride_x, grid.n_x), y, min(y + stride_y, grid.n_y) - ) - if value is None: - continue - - brush = float_to_viridis_brush((value - min_value) / diff, alpha=alpha) - painter.fillRect(QRectF(px, py, draw_w, draw_h), brush) - - painter.setPen( - QPen(qcolor(RASTER_GRID_LINE, min(255, alpha + 88)), 2, Qt.PenStyle.SolidLine) - ) - painter.setBrush(Qt.BrushStyle.NoBrush) - painter.drawRect(bounds) - - painter.restore() - return True - - def _block_value( - self, values: list[float] | list[int], grid_nx: int, x0: int, x1: int, y0: int, y1: int - ) -> float | None: - best = None - for y in range(y0, y1): - row_offset = y * grid_nx - for x in range(x0, x1): - idx = row_offset + x - if idx >= len(values): - continue - value = values[idx] - if value is None or math.isnan(value) or value < 0: - continue - if best is None or value > best: - best = float(value) - return best - - @Slot(float) - def update_exposure_time(self, exp_time_s: float): - self._active_grid.exp_time_s = exp_time_s - - @Slot(float) - def update_transmission(self, transmission: float): - self._active_grid.transmission = transmission - - @Slot(float) - def update_dtz(self, dtz: float): - self._active_grid.dtz = dtz - - @Slot(str) - def update_filename(self, filename: str): - self._active_grid.file_prefix = filename - - @Slot(RasterGridMetric) - def metric(self, r: RasterGridMetric): - self._metric = r - self._invalidate_heatmap_cache() - - @Slot() - def clear_completed_grids(self): - self._completed_grids.clear() - self._invalidate_heatmap_cache() - self.completed_grid_updated.emit() - - @Slot(CompletedRasterGrid) - def grid_scan_completed(self, raster_list: CompletedRasterGrid): - last_raster = None - for raster in raster_list.r: - self._completed_grids.append(raster) - last_raster = raster - self._active_grid.n_x = 0 - self._active_grid.n_y = 0 - self._invalidate_heatmap_cache() - if last_raster is not None and last_raster.result.file_prefix is not None: - com = last_raster.centre_of_mass - logger.info(f"COM: {com}") - cell = com.max_image if com else 0 - self.image_selected.emit(self._detector_url, cell) - self.completed_grid_updated.emit() - - @Slot(int, bool) - def completed_grid_scan_toggle_visible(self, row: int, visible: bool): - if 0 <= row < len(self._completed_grids): - self._completed_grids[row].request.visible = visible - self.completed_grid_updated.emit() - - @Slot(int) - def completed_grid_scan_delete(self, row: int): - if 0 <= row < len(self._completed_grids): - del self._completed_grids[row] - self._invalidate_heatmap_cache() - self.completed_grid_updated.emit() - - @Slot(int) - def completed_grid_scan_goto(self, row: int): - if 0 <= row < len(self._completed_grids): - self.omega.emit(self._completed_grids[row].request.omega_deg) - self.smargon.emit( - SmargonCoordinate( - phi_deg=self._completed_grids[row].request.smargon_top_left.phi_deg, - chi_deg=self._completed_grids[row].request.smargon_top_left.chi_deg, - ) - ) - - @Slot(int) - def completed_grid_redo(self, row: int): - if 0 <= row < len(self._completed_grids): - src = self._completed_grids[row].request - self._active_grid.n_x = src.n_x - self._active_grid.n_y = src.n_y - self._active_grid.grid_size_mm = Coordinate(x=src.grid_size_mm.x, y=src.grid_size_mm.y) - self._active_grid.smargon_top_left = SmargonCoordinate( - sh_mm=Coordinate( - x=src.smargon_top_left.sh_mm.x, - y=src.smargon_top_left.sh_mm.y, - z=src.smargon_top_left.sh_mm.z, - ), - phi_deg=src.smargon_top_left.phi_deg, - chi_deg=src.smargon_top_left.chi_deg, - ) - self._active_grid.omega_deg = src.omega_deg - - self._active_grid.visible = True - self._completed_grids[row].request.visible = False - - self.grid_scan_size_changed.emit( - self._active_grid.n_x, - self._active_grid.n_y, - self._active_grid.grid_size_mm.x, - self._active_grid.grid_size_mm.y, - ) - self.completed_grid_updated.emit() - - def get_completed_grids(self) -> list[CompletedRasterGridElem]: - return self._completed_grids diff --git a/src/aare/gui/scan_logic/rotation_scan_manager.py b/src/aare/gui/scan_logic/rotation_scan_manager.py deleted file mode 100644 index 03885c0b..00000000 --- a/src/aare/gui/scan_logic/rotation_scan_manager.py +++ /dev/null @@ -1,17 +0,0 @@ -from aarecommon.config.beamline import get_jfjoch_url, mx_beamline -from aarecommon.models.rotation_scan import CompletedRotationScan -from PySide6.QtCore import QObject, Signal, Slot - - -class RotationScanManager(QObject): - file_ready = Signal(str, int) - - def __init__(self, parent=None): - super().__init__(parent) - self._beamline = mx_beamline() - self._detector_url = get_jfjoch_url(self._beamline) - - @Slot(CompletedRotationScan) - def scan_completed(self, r: CompletedRotationScan): - if r.result.file_prefix is not None: - self.file_ready.emit(self._detector_url, 0) diff --git a/src/aare/gui/scan_logic/sample_mount_logic.py b/src/aare/gui/scan_logic/sample_mount_logic.py deleted file mode 100644 index f4576681..00000000 --- a/src/aare/gui/scan_logic/sample_mount_logic.py +++ /dev/null @@ -1,17 +0,0 @@ -from aarecommon.models.models import DAQStatusModel, SampleShortInfo -from PySide6.QtCore import QObject, Signal, Slot - - -class SampleMountLogic(QObject): - sample_changed = Signal(SampleShortInfo) - - def __init__(self, parent=None): - super().__init__(parent) - self._sample = None - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - if s.sample != self._sample: - self.sample_changed.emit(s.sample) - - self._sample = s.sample diff --git a/src/aare/gui/styles.py b/src/aare/gui/styles.py deleted file mode 100644 index db3dbcd2..00000000 --- a/src/aare/gui/styles.py +++ /dev/null @@ -1,1837 +0,0 @@ -from __future__ import annotations - -from pathlib import Path -from string import Template - -# These string values are the tokens persisted in QSettings("appearance/theme"). -# They were renamed from "original"/"portrait"; MainWindow._restore_theme_settings -# migrates the old tokens so a user's saved theme survives the rename. -THEME_SUNRISE = "sunrise" -THEME_SUNSET = "sunset" -# Sunrise with the sky gradient flattened to its top color — for consoles -# where the gradient banding distracts, and as a plain-background baseline. -THEME_BLUEBIRD = "bluebird" - -# --------------------------------------------------------------------------- -# Color palette. Change values HERE to try a different look — the QSS below -# and the widgets that import these use them everywhere. Every UPPERCASE -# constant is exposed to the QSS templates as $lowercase_name (see _palette), -# so no color literals live inside the stylesheets themselves. -# Any value can be "transparent" (e.g. to hide a border or a fill). -# string.Template ($name) instead of f-strings so the QSS braces stay literal. - -# -- Light theme ------------------------------------------------------------ -BACKGROUND = "#e2e7ee" -# App-wide sunrise-sky gradient (sampled from the reference photo taken at dawn -# near Dawn's house at Windisch: slate blue fading through pale grey-lavender -# into warm cream. Painted once per top-level window (QMainWindow/QDialog) -# while plain child widgets stay transparent, so the window reads as ONE -# continuous sky instead of every widget restarting the gradient. -# Tune the transition point here: -BACKGROUND_GRADIENT_TOP = "#84abd9" # RHEL9 window-frame blue (sampled from screenshot) -BACKGROUND_GRADIENT_MID = "#adccf1" -BACKGROUND_GRADIENT_MID_POS = "0.55" # 0..1 — where the mid stop sits -BACKGROUND_GRADIENT_BOTTOM = "#f8e9c5" -APP_BACKGROUND = ( - "qlineargradient(x1:0, y1:0, x2:0, y2:1," - f" stop:0 {BACKGROUND_GRADIENT_TOP}," - f" stop:{BACKGROUND_GRADIENT_MID_POS} {BACKGROUND_GRADIENT_MID}," - f" stop:1 {BACKGROUND_GRADIENT_BOTTOM})" -) -BANNER = "#a2b7e4" -BANNER_TEXT = "#F8F8FC" # must contrast with BANNER -BANNER_TEXT_SHADOW = "#000000" # soft shadow under banner titles; alpha in TitleLabel -# Banner edge lines (1px left + bottom): each line fades in from transparent, -# peaks at BANNER_EDGE mid-line and fades out at the far end — a soft sheen, -# not a hard rule. BANNER_EDGE is the peak color; "transparent" hides both. -BANNER_EDGE = "#ffffff" -BANNER_EDGE_H = ( # bottom line — fades along the banner width - "qlineargradient(x1:0, y1:0, x2:1, y2:0," - f" stop:0 transparent, stop:0.5 {BANNER_EDGE}, stop:1 transparent)" -) -BANNER_EDGE_V = ( # left line — fades along the banner height - "qlineargradient(x1:0, y1:0, x2:0, y2:1," - f" stop:0 transparent, stop:0.5 {BANNER_EDGE}, stop:1 transparent)" -) -TEXT = "#263043" -SURFACE = "#f2f2f2" # input fields, cards, group boxes - -# Buttons: flat + hairline like the dark theme (the explicit border is what -# switches Qt from bulky native chrome to compact QSS box rendering). -# Half-transparent so the sky gradient shimmers through, same glass idea as -# INPUT_BG — slightly more solid so clickables read as raised faces. -BUTTON_BG = "rgba(255, 255, 255, 50%)" -# Hover: a dark ink tint instead of more white — darkens whatever sky shade -# is behind the button (the dark theme hovers LIGHTER, see DARK_ELEVATED_HOVER). -BUTTON_BG_HOVER = "rgba(76, 79, 105, 18%)" -BUTTON_BORDER = "#c9cfd8" # same tone as FRAME_L3_COLOR, separate knob - -# Spin/combo arrow glyphs: tiny PNGs — this Qt draws neither native glyphs -# nor QSS border-triangles inside styled spin buttons, so image files are -# the only reliable path. Colors live in the PNGs (TEXT / DARK_TEXT at -# generation time); regenerate them if those knobs change. -_GRAPHICS_DIR = Path(__file__).resolve().parent / "graphics" -SPIN_ARROW_UP = (_GRAPHICS_DIR / "spin_arrow_up_light.png").as_posix() -SPIN_ARROW_DOWN = (_GRAPHICS_DIR / "spin_arrow_down_light.png").as_posix() -DARK_SPIN_ARROW_UP = (_GRAPHICS_DIR / "spin_arrow_up_dark.png").as_posix() -DARK_SPIN_ARROW_DOWN = (_GRAPHICS_DIR / "spin_arrow_down_dark.png").as_posix() -# Slider-handle grip lines (3 vertical ticks) — QSS can't draw interior -# lines, so they are tiny PNG assets like the spin arrows above. -SLIDER_GRIP = (_GRAPHICS_DIR / "slider_grip_light.png").as_posix() -DARK_SLIDER_GRIP = (_GRAPHICS_DIR / "slider_grip_dark.png").as_posix() -# Check marks (PRIMARY blue / dusk gold at generation time): -CHECK_MARK = (_GRAPHICS_DIR / "check_mark_light.png").as_posix() -DARK_CHECK_MARK = (_GRAPHICS_DIR / "check_mark_dark.png").as_posix() -# Resize-bar grips: IDLE paints a short (66px) centered bar instead of a -# full-length line — the full idle line read as a wall between panels; the -# hover/drag hint keeps the full-length gradient (see _separator_gradient). -# QSS can't paint a fixed-length centered segment, so PNGs like the arrows -# above; used by BOTH QMainWindow::separator and QSplitter::handle, so this -# is the one place. Colors baked in (SEPARATOR_IDLE / DARK_SEPARATOR_IDLE) -# — regenerate if those knobs change. -GRIP_IDLE_V = (_GRAPHICS_DIR / "resize_grip_v_idle_light.png").as_posix() -GRIP_IDLE_H = (_GRAPHICS_DIR / "resize_grip_h_idle_light.png").as_posix() -DARK_GRIP_IDLE_V = (_GRAPHICS_DIR / "resize_grip_v_idle_dark.png").as_posix() -DARK_GRIP_IDLE_H = (_GRAPHICS_DIR / "resize_grip_h_idle_dark.png").as_posix() - -# Borders (all can be "transparent" to hide the line): -BORDER = "transparent" # main dividers, e.g. the beamline state bar top line -CARD_BORDER = "transparent" # cards / group boxes (Local Contact, automation) - -# -- Box-frame borders by nesting level ------------------------------------- -# One knob per level so the amount of "boxing" is tunable in one place: -# L1: top-level pop-out window edge (painted by PopoutWindow) -# L2: panel frames inside a dock/tab (TELL sample changer, reference -# tools, sample queue) — transparent by default: banner + table -# already delimit the panel, extra boxes read as clutter -# L3: data views (tables, log text) — a light line so scrollable content -# keeps a visible edge -# (The tab-widget pane is a fourth box, already governed by BORDER above.) -FRAME_L1_WIDTH = "0px" # default off — the pop-out reads as one clean surface -FRAME_L1_COLOR = "#bdbdbd" -FRAME_L2_WIDTH = "0px" -FRAME_L2_COLOR = "transparent" -FRAME_L3_WIDTH = "1px" -FRAME_L3_COLOR = "#c9cfd8" - -# Left inset (px, int — used in code, not QSS) for bottom-dock content so its -# left edge lines up with the left-column panels above (Loop centering). -DOCK_CONTENT_LEFT_PAD = 10 - -# Gap (px, int — used in code, not QSS) between a TitleLabel banner and a tab -# bar sitting directly under it (Exp. Config.), so the tabs don't touch the -# banner's bottom edge line. -BANNER_TAB_GAP = 6 - -# Resize lines: the hover rest (SEPARATOR_HINT_DELAY_MS, gate in -# MainWindow.event(); the QSS :hover part picks the one separator) darkens the -# exact separator under the cursor to SEPARATOR_HINT. -# Accessibility (WCAG 1.4.11, >=3:1 non-text contrast): the old -# rgba(168,178,192) fills measured 1.0-1.2:1 against every theme background — -# invisible. Solid slate: idle #47536a >=3.25:1, hover #3f4a5f >=3.74:1 -# against gradient top/mid/bottom and panel white. -SEPARATOR_HINT = "#3f4a5f" -SEPARATOR_IDLE = "#47536a" -SEPARATOR_HINT_DELAY_MS = 66 # int, used in code, not QSS - -# The gutter keeps this full width for the mouse; idle paints only the -# short GRIP_* bar (a full-length idle line read as a wall), hover/drag -# brings back the full-length hint gradient so the grabbed bar reads over -# its whole run. 5px is a first guess — adjust here if the grab target -# feels off. -SEPARATOR_REGION = "5px" -SEPARATOR_SHADOW = "rgba(31, 41, 59, 25%)" - - -def _separator_gradient(line: str, shadow: str, axis: str) -> str: - """Full-length hover/drag hint of a resize gutter: transparent 1px, - shadow 1px, line 2px, shadow 1px — hard gradient stops at 1/5 steps of - SEPARATOR_REGION. axis "x" runs the gradient left->right (an upright - line), "y" top->down (a lying line).""" - x2, y2 = ("1", "0") if axis == "x" else ("0", "1") - return ( - f"qlineargradient(x1:0, y1:0, x2:{x2}, y2:{y2}," - f" stop:0 transparent, stop:0.19 transparent," - f" stop:0.2 {shadow}, stop:0.39 {shadow}," - f" stop:0.4 {line}, stop:0.79 {line}," - f" stop:0.8 {shadow}, stop:1 {shadow})" - ) - - -SEP_HINT_X = _separator_gradient(SEPARATOR_HINT, SEPARATOR_SHADOW, "x") -SEP_HINT_Y = _separator_gradient(SEPARATOR_HINT, SEPARATOR_SHADOW, "y") - -# Theme-switch screenshot cross-fade duration (int ms, used in code). -THEME_FADE_MS = 250 - -# Tab face fill: the selected Dewar/Auxiliary tab AND the unchecked -# All/Queued/Flagged/Measured filter buttons share this background. -TAB_FACE_BG = "#ffffff" - -# Selection highlight (combo popups, menus, list rows, text selections). -# Qt's style palette used to supply its own blue here; now it is the banner -# blue, and THIS is the knob for it. (Table-row selection has its own paler -# knob: SAMPLE_STATUS_SELECTED_BG.) -SELECTION_BG = BANNER -SELECTION_TEXT = "#263043" # same as TEXT — readable on the banner blue - -PRIMARY = "#2563eb" # main action button -PRIMARY_HOVER = "#1d4ed8" -PRIMARY_TEXT = "white" -SECONDARY_BG = "#dfe9fb" -SECONDARY_BG_HOVER = "#d3e1f8" - -# Alert banners (alertKind: error / success / waiting=warning): -# Catppuccin Latte: BG = 15% accent over base, border = 50%, text = 65% over -# Latte text — same recipe as the chips/cards/log blocks below. -ERROR_BG = "#ebcfd9" # red wash -ERROR_BORDER = "#e08097" -ERROR_TEXT = "#a3254a" -SUCCESS_BG = "#d5e5d7" # green wash -SUCCESS_BORDER = "#98c890" -SUCCESS_TEXT = "#448441" -WARNING_BG = "#f1dcd2" # peach wash -WARNING_BORDER = "#f6aa80" -WARNING_TEXT = "#c05d2c" - -# Axis video status + beamline state bar: -STATUS_IDLE_BG = "#d9e2f2" -STATUS_LABEL_TEXT = "#2f3b52" -STATE_TOGGLE_TEXT = "white" # collapse glyph sitting on the BANNER strip -STATE_CURRENT_TEXT = "#1e293b" # same slate as HEADING_TEXT, separate knob -STATE_TELL_TEXT = "#374357" # also the status-bar TELL line - -# -- Sunset (dark) theme: Daemmerung DUSK palette --------------------------- -# Adopted from ~/repos/aaregui2 (focus/theme.py, jdawnduan.com Daemmerung). -# Grouped by ROLE, mirroring the source Palette dataclass, so a later change -# touches one block. The site's translucent glass is flattened to opaque hex -# (this QSS paints widgets opaque); the radial sunset backdrop is NOT -# adopted — it needs the transparent-children scheme the Sunrise theme uses. - -# Surfaces: -DARK_BG = "#15213a" # bg — window backdrop -# Sunset-sky backdrop (reference photo): near-black navy zenith; the fade -# begins at MID_POS (0.55, same as the day theme), runs through the blue -# band low in the window, and the warm glow is squeezed into the last -# stretch below BLUE_POS. Warm tone deliberately dimmer than the photo's -# cream — dusk text is light. Same transparent-children scheme as -# APP_BACKGROUND; set all stops to DARK_BG for a flat backdrop. -DARK_BACKGROUND_GRADIENT_TOP = "#0c1a33" -DARK_BACKGROUND_GRADIENT_MID = "#16294d" # fade onset tone -DARK_BACKGROUND_GRADIENT_MID_POS = "0.55" # 0..1 — where the fade begins -DARK_BACKGROUND_GRADIENT_BLUE = "#2c5f9e" # the blue band -DARK_BACKGROUND_GRADIENT_BLUE_POS = "0.90" # 0..1 — warm glow only below this -DARK_BACKGROUND_GRADIENT_BOTTOM = "#2c5f9e" # the warm glow doesn't seem to fit -DARK_APP_BACKGROUND = ( - "qlineargradient(x1:0, y1:0, x2:0, y2:1," - f" stop:0 {DARK_BACKGROUND_GRADIENT_TOP}," - f" stop:{DARK_BACKGROUND_GRADIENT_MID_POS} {DARK_BACKGROUND_GRADIENT_MID}," - f" stop:{DARK_BACKGROUND_GRADIENT_BLUE_POS} {DARK_BACKGROUND_GRADIENT_BLUE}," - f" stop:1 {DARK_BACKGROUND_GRADIENT_BOTTOM})" -) -DARK_PANEL2 = "#0e1728" # panel2 — deepest opaque: menus, popups, tooltips -DARK_SURFACE = "#1c2b4a" # panel — cards, state panel, scrollbar track -DARK_ELEVATED = "#253148" # glass2 (7% white) flattened — buttons, banners -DARK_ELEVATED_HOVER = "#32405c" # one glass step lighter — button hover -# Half the button glass (7% -> 4% white), translucent so the sky shows -# through: inputs sank to wells, buttons stay raised faces — same -# button-vs-input split the light theme makes with INPUT_BG vs BUTTON_BG. -DARK_INPUT_BG = "rgba(255, 255, 255, 4%)" -# Solid, not transparent: scroll-area viewports don't composite the window -# gradient on the container's X11 and render BLACK instead. Lighter sky-navy -# so tables don't read near-black against the backdrop. -DARK_TABLE_BG = "#263a61" - -# Hairlines — the site's gold line flattened over bg at its three alphas: -DARK_BORDER_FAINT = "#31313b" # border (14%) — input/button edges -DARK_BORDER = "#423a3c" # border2 (22%) — cards, scrollbar handle -DARK_BORDER_STRONG = "#624c3d" # border3 (38%) — emphasized edges - -# Text ramp (bright -> dim): -DARK_TEXT = "#e9edf4" # text — primary -DARK_SUBTEXT = "#aebccd" # subtext — secondary labels, hints -DARK_MUTED = "#7e8ea4" # muted — tertiary, unselected tabs -DARK_OVERLAY = "#66778f" # overlay — disabled text -DARK_DISABLED = "#3c4a66" # disabled — disabled fills - -# Accents — gold is IDENTITY (titles, highlights), blue is ACTION (primary -# buttons); the site keeps the two apart on purpose: -DARK_ACCENT = "#e0913f" # gold -# DARK_ACCENT @70%: 10% measured 1.16:1 on DARK_BG (invisible); 70% blends to -# >=3.74:1 — same WCAG 1.4.11 floor as the light-theme separators. -DARK_SEPARATOR_IDLE = "rgba(224, 145, 63, 70%)" -DARK_SEPARATOR_SHADOW = "rgba(0, 0, 0, 45%)" -DARK_SEP_HINT_X = _separator_gradient(DARK_ACCENT, DARK_SEPARATOR_SHADOW, "x") -DARK_SEP_HINT_Y = _separator_gradient(DARK_ACCENT, DARK_SEPARATOR_SHADOW, "y") -DARK_ACCENT_HOVER = "#eaa253" # accent2 — brighter gold -DARK_ACCENT_FILL = "#89b4fa" # action blue -DARK_ACCENT_FILL_HOVER = "#9ec2fb" # +10% white, derived (site has no step) -DARK_ON_ACCENT = "#1a1320" # text on either accent fill - -# Banner strips (TitleLabel + beamline state title): gold edge sheen that -# fades in/out like the light theme's BANNER_EDGE_H/V. -DARK_BANNER_EDGE = "#e0913f" -DARK_BANNER_EDGE_H = ( - "qlineargradient(x1:0, y1:0, x2:1, y2:0," - f" stop:0 transparent, stop:0.5 {DARK_BANNER_EDGE}, stop:1 transparent)" -) -DARK_BANNER_EDGE_V = ( - "qlineargradient(x1:0, y1:0, x2:0, y2:1," - f" stop:0 transparent, stop:0.5 {DARK_BANNER_EDGE}, stop:1 transparent)" -) - -# Status — border/text full strength, bg = 25% blend over DARK_BG (the dusk -# palette defines no alert backgrounds, so these are computed blends): -DARK_ERROR_BG = "#48374d" # alarm 25% over bg -DARK_ERROR_BORDER = "#e07a85" # alarm -DARK_ERROR_TEXT = "#e07a85" # alarm -DARK_SUCCESS_BG = "#2f4e5d" # green 25% over bg -DARK_SUCCESS_BORDER = "#7dd6c6" # green -DARK_SUCCESS_TEXT = "#7dd6c6" # green -DARK_WARNING_BG = "#473741" # warn (copper) 25% over bg -DARK_WARNING_BORDER = "#dd7a56" # warn -DARK_WARNING_TEXT = "#dd7a56" # warn - -# -- Shared chrome (light-theme widgets) ------------------------------------ -# Extracted from per-widget literals so the whole app is themeable from this -# file. The same hex may appear under two names when the roles differ — -# separate knobs on purpose. -WHITE = "#ffffff" -# ONLY for theme-independent light surfaces (tutorial callout). To "reset" a -# themed label, clear its stylesheet ("") so the theme color applies — a -# hardcoded black reset is invisible in the dark theme. -DEFAULT_TEXT = "#4c4f69" # latte text -NOTE_TEXT = "#5c5f77" # tutorial hints, TELL sample details (latte subtext1) -DIM_TEXT = "#6c6f85" # baton dialog timers (latte subtext0) -HINT_TEXT = "#9ca0b0" # baton dialog fine print (latte overlay0) -HEADING_TEXT = "#4c4f69" # card headings (latte text) -SUBTLE_TEXT = "#5c5f77" # card body text (latte subtext1) -MUTED_TEXT = "#6c6f85" # neutral chip / idle step text (latte subtext0) -# Unselected tab labels: tabs also sit on the sky gradient, where MUTED_TEXT -# is 2.07:1 — under the 4.5:1 WCAG text floor. This slate reads 4.71:1 on the -# gradient top and stays muted next to TEXT. -TAB_IDLE_TEXT = "#2f3b52" -FAINT_TEXT = "#8c8fa1" # pending/skipped step text (latte overlay1) -SHADOW = "#000000" # drop shadows & tutorial scrim; alpha stays at call site - -# -- Semantic action colors ------------------------------------------------- -GO_TEXT = "#40a02b" # green start/run/measure button text -ABORT_TEXT = "#d20f39" # abort button text (red) -ALERT_TEXT = "#d20f39" # out-of-range motor labels (red) -PATH_WARN_TEXT = "#e64553" # file-exists warning in path panel (maroon) -DANGER_ACCENT = "#e64553" # invalid p-group border + message text (maroon) - -# -- Status chips (local contact status) — "good" reuses SUCCESS_BG/TEXT ---- -CHIP_WARN_BG = "#ede2d5" # yellow wash -CHIP_WARN_TEXT = "#ac7838" -CHIP_BAD_BG = "#ebcfd9" # red wash -CHIP_BAD_TEXT = "#a3254a" -CHIP_NEUTRAL_BG = "#e6e9ef" # latte mantle; text uses MUTED_TEXT -CHIP_INFO_BG = "#d0dcf5" # blue wash -CHIP_INFO_TEXT = "#2e5ec4" - -# -- Status cards (beamline recovery, local contact error frame) ------------ -WARN_CARD_BORDER = "#e9cea9" # yellow border -BAD_CARD_BORDER = "#e5a2b3" # red border -INFO_CARD_BG = "#d0dcf5" # blue wash -INFO_CARD_BORDER = "#a6c0f5" -PENDING_CARD_BG = "#ede2d5" # yellow wash -PENDING_CARD_BORDER = "#e9cea9" - -# -- Log panel -------------------------------------------------------------- -LOG_BORDER = "#8c8fa1" # latte overlay1 -LOG_PANEL_BG = "#ecdae2" # faint red wash -LOG_ERROR_BG = "#ebcfd9" -LOG_ERROR_BORDER = "#e08097" -LOG_WARN_BG = "#ede2d5" -LOG_WARN_BORDER = "#e7c089" -LOG_SUCCESS_BG = "#d5e5d7" -LOG_SUCCESS_BORDER = "#98c890" -LOG_INFO_BG = "#d0dcf5" -LOG_INFO_BORDER = "#86acf5" - -# -- Automation panel + progress steps -------------------------------------- -AUTOMATION_TITLE_TEXT = "#4c4f69" # latte text -AUTOMATION_HINT_TEXT = "#5c5f77" # latte subtext1 -STEP_RUNNING_TEXT = "#1e66f5" # latte blue — same as PRIMARY, separate knob -STEP_SUCCESS_TEXT = "#40a02b" # green -STEP_FAILED_TEXT = "#d20f39" # red -STEP_PAUSED_TEXT = "#c05d2c" # peach ink -STEP_DONE_BG = "#d5e5d7" # green wash -STEP_DONE_TEXT = "#448441" -STEP_DONE_BORDER = "#b2d5ae" -STEP_ACTIVE_BG = "#d0dcf5" # blue wash -STEP_ACTIVE_TEXT = "#2e5ec4" -STEP_ACTIVE_BORDER = "#a6c0f5" -STEP_FAILED_BG = "#ebcfd9" # red wash -STEP_FAILED_BORDER = "#e5a2b3" -STEP_PAUSED_BG = "#f1dcd2" # peach wash -STEP_PAUSED_BORDER = "#f4c0a3" -STEP_IDLE_BG = "#eff1f5" # latte base -STEP_IDLE_BORDER = "#dce0e8" # latte crust - -# -- Baton request dialog --------------------------------------------------- -# Hover/pressed are the accent mixed 12%/24% toward Latte text. -BATON_OK_BG = "#40a02b" # green -BATON_OK_HOVER = "#419632" -BATON_OK_PRESSED = "#438d3a" -BATON_DANGER_BG = "#d20f39" # red -BATON_DANGER_HOVER = "#c2173f" -BATON_DANGER_PRESSED = "#b21e45" -BATON_WARN = "#fe640b" # peach -BATON_INFO = "#1e66f5" # blue -LIGHT_BORDER = "#bcc0cc" # latte surface1 -PROGRESS_TRACK_BG = "#e6e9ef" # latte mantle - -# -- Splash screen ---------------------------------------------------------- -SPLASH_BG = "#dce0e8" # latte crust (progress-bar track) -SPLASH_BORDER = "#bcc0cc" # latte surface1 -SPLASH_ACCENT = "#1e66f5" # latte blue -SPLASH_TEXT = "#4c4f69" # latte text — bar % and loading message - -# -- Numeric inputs --------------------------------------------------------- -# Translucent, not solid white: the sky gradient shimmers through the field -# while text stays on a light ground. Raise the % for a more solid face. -# Why 16%: half of BUTTON_BG's 50% — at 33% inputs read as clickable button -# faces; the deeper glass keeps them visually distinct as wells, not buttons. -INPUT_BG = "rgba(255, 255, 255, 16%)" -INPUT_INVALID_BG = "#e9c4cf" # red 20% over latte base -INPUT_DISABLED_BG = "#e6e9ef" # latte mantle -INPUT_DISABLED_INVALID_BG = "#ecdae2" # faint red wash -# Motor batch-move states (MotorMoveGroup "movestate" dynamic property): -# staged-but-not-sent target vs motor in motion — see motor_move_group.py. -INPUT_PENDING_BG = "#f2cdba" # peach 25% over latte base -INPUT_MOVING_BG = "#c3ddc3" # green 25% over latte base -DARK_INPUT_PENDING_BG = "#473741" # warn (copper) 25% over bg -DARK_INPUT_MOVING_BG = "#2f4e5d" # green 25% over bg - -# -- Status bar flags (Catppuccin Latte) ------------------------------------ -STATUS_OK = "#40a02b" # closed / idle / owned / tell ok (green) -STATUS_ALERT = "#d20f39" # open / busy / other-owner / hot cryo (red) -STATUS_WARN = "#fe640b" # baton waiting / warming cryo / tell busy (peach) -STATUS_INFO = "#1e66f5" # cold cryo (blue) -STATUS_VACANT = "#df8e1d" # baton vacant (yellow) -STATUS_REQUEST = "#04a5e5" # baton request (sky) -# Dark variants (Catppuccin Mocha) — the latte values above sink into the -# sunset sky. Painted in code per DAQ tick, so status_colors(theme) hands -# them out — same pattern as state_colors below. -DARK_STATUS_OK = "#a6e3a1" # mocha green -DARK_STATUS_ALERT = "#f38ba8" # mocha red -DARK_STATUS_WARN = "#fab387" # mocha peach -DARK_STATUS_INFO = "#89b4fa" # mocha blue -DARK_STATUS_VACANT = "#f9e2af" # mocha yellow -DARK_STATUS_REQUEST = "#89dceb" # mocha sky -DARK_STATE_TELL_TEXT = "#bac2de" # mocha subtext1 — status-bar TELL idle line - - -def status_colors(theme: str) -> dict[str, str]: - """Status-bar flag colors for the given theme (painted in code).""" - if theme == THEME_SUNSET: - return { - "ok": DARK_STATUS_OK, - "alert": DARK_STATUS_ALERT, - "warn": DARK_STATUS_WARN, - "info": DARK_STATUS_INFO, - "vacant": DARK_STATUS_VACANT, - "request": DARK_STATUS_REQUEST, - "tell": DARK_STATE_TELL_TEXT, - } - return { - "ok": STATUS_OK, - "alert": STATUS_ALERT, - "warn": STATUS_WARN, - "info": STATUS_INFO, - "vacant": STATUS_VACANT, - "request": STATUS_REQUEST, - "tell": STATE_TELL_TEXT, - } - - -# -- Beamline state panel --------------------------------------------------- -# The panel paints these in code per DAQ tick (data-driven), so it asks -# state_colors(theme) below instead of QSS. Light values unchanged; dark -# values are Catppuccin Mocha so they stay readable on the sunset sky. -STATE_AVAILABLE = "#ed8936" -STATE_UNAVAILABLE = "#8c96a5" -STATE_MSG_ERROR = "#c81e1e" -STATE_MSG_INFO = "#005caa" -DARK_STATE_AVAILABLE = "#fab387" # mocha peach -DARK_STATE_UNAVAILABLE = "#7f849c" # mocha overlay1 -DARK_STATE_MSG_ERROR = "#f38ba8" # mocha red -DARK_STATE_MSG_INFO = "#89b4fa" # mocha blue - - -def state_colors(theme: str) -> dict[str, str]: - """Beamline-state text colors for the given theme.""" - if theme == THEME_SUNSET: - return { - "available": DARK_STATE_AVAILABLE, - "unavailable": DARK_STATE_UNAVAILABLE, - "error": DARK_STATE_MSG_ERROR, - "info": DARK_STATE_MSG_INFO, - } - return { - "available": STATE_AVAILABLE, - "unavailable": STATE_UNAVAILABLE, - "error": STATE_MSG_ERROR, - "info": STATE_MSG_INFO, - } - - -# -- Sample tables + raster grid -------------------------------------------- -SAMPLE_ROW_ACTIVE_BG = "#ff6600" -# mounted/current-sample row (VO & CY want to change this color to different than active one) -SAMPLE_ROW_QUEUED_BG = "#c4c3d0" -SAMPLE_ROW_HIGHLIGHT_BG = "#d8e4fd" -RASTER_GRID_LINE = "#729fcf" -TABLE_SHADE_BG = "#e0e0e0" - -# -- Sample status row tints (dewar/queue view) ----------------------------- -# Status colors now fill the rounded dot in the table's status column; rows -# themselves alternate WHITE / SAMPLE_ROW_ALT_BG. Tune the palette here. -SAMPLE_ROW_ALT_BG = "#eef1f5" # staggered row grey (alternates with white) -SAMPLE_STATUS_QUEUED_BG = "#ffe4c4" # pale orange — waiting in the automation queue -SAMPLE_STATUS_FLAGGED_BG = "#ffd9d9" # pale red — automation failed on this sample -SAMPLE_STATUS_MEASURED_BG = "#dcf2e0" # pale green — already has collected data -SAMPLE_STATUS_SELECTED_BG = "#84abd9" # pale blue — table selection highlight -# Fixed ink on the pastel tints above: the tints stay light in BOTH themes, -# so theme-following text (white in Sunset) would vanish on them. Models -# return this as ForegroundRole wherever they return a tint. -SAMPLE_STATUS_TEXT = "#263043" - -# -- Camera / video overlay (painter colors, alpha at call site) ------------ -# Palette: Catppuccin Latte (light flavor) — softer than the old pure-RGB set. -BEAM_OPEN = "#40a02b" # beam marker: shutter open (green) -BEAM_IDLE = "#fe640b" # beam marker: idle (peach) -BEAM_BUSY = "#d20f39" # beam marker: busy (red) -BEAM_MARKING = "#8839ef" # beam marker: marking mode (mauve) -MARKER_GREEN = "#40a02b" # loop-centering click marker (green) -PATH_START = "#40a02b" # raster path gradient start + start circle (green) -PATH_END = "#d20f39" # raster path gradient end + end circle (red) -LEGEND_BG = "#eff1f5" # base -LEGEND_TEXT = "#4c4f69" # text -TOOLTIP_TEXT = "#4c4f69" # camera coords tooltip pen — NOT the QToolTip popup -SCALE_BAR_GREY = "#8c8fa1" # hover HUD scale bar (Latte overlay1 grey) -MARK_TOOLTIP_GOLD = "#df8e1d" # yellow -MARK_TOOLTIP_ORANGE = "#fe640b" # peach -MARK_TOOLTIP_RED = "#d20f39" # red -MARK_BADGE_BG = "#fe640b" # peach - -# Prediction class overlay colors. The old pure-green vs CSS-green split -# between chart and overlay collapses to the single Latte green. -CLASS_COLORS = { - "pin": "#d20f39", # red - "loop_all": "#40a02b", # green - "loop_face": "#df8e1d", # yellow - "crystal": "#1e66f5", # blue - "needle": "#ea76cb", # pink - "ice": "#04a5e5", # sky -} -CHART_CLASS_COLORS = { - "Pin": "#d20f39", - "Loop_all": "#40a02b", - "Loop_face": "#df8e1d", - "Crystal": "#1e66f5", - "Needle": "#ea76cb", - "Ice": "#04a5e5", -} -TARGET_COLORS = {"Cyan": "#04a5e5", "Dark Blue": "#1e66f5", "Dark Red": "#e64553"} -BOOKMARK_COLORS = { - "red": "#d20f39", - "green": "#40a02b", - "blue": "#1e66f5", - "indigo": "#8839ef", # mauve - "lime": "#179299", # teal — Latte has one green; teal keeps the pair distinct -} - -# -- Busy overlay (per-source color coding) --------------------------------- -# Catppuccin Latte accents; BORDER/DOT are 25%/20% mixes toward Latte base. -BUSY_YELLOW = "#df8e1d" # yellow -BUSY_YELLOW_BORDER = "#ebd8bf" -BUSY_YELLOW_DOT = "#ecddca" -BUSY_YELLOW_TEXT_DARK = "#4c4f69" # text -BUSY_PURPLE = "#8839ef" # mauve -BUSY_PURPLE_BORDER = "#d5c3f4" -BUSY_PURPLE_DOT = "#daccf4" -BUSY_RED_BADGE = "#d20f39" # red -BUSY_RED_FILL = "#d20f39" # red -BUSY_RED_BORDER = "#e8b8c6" -BUSY_RED_DOT = "#e9c4cf" -BUSY_ORANGE = "#fe640b" # peach -BUSY_ORANGE_BORDER = "#f3ceba" -BUSY_ORANGE_DOT = "#f2d5c6" -BUSY_BLUE = "#1e66f5" # blue -BUSY_BLUE_BORDER = "#bbcef5" -BUSY_BLUE_DOT = "#c5d5f5" -BUSY_PSI_RED = "#e64553" # maroon — closest Latte to the PSI brand red -BUSY_PSI_RED_BORDER = "#edc6cc" -BUSY_PSI_RED_DOT = "#edcfd5" - -# -- Charts (prediction metrics, target stability, fluorescence) ------------ -# Catppuccin Latte; PALE variants are 35% mixes toward Latte base. -CHART_BLUE = "#1e66f5" # blue -CHART_BLUE_LIGHT = "#04a5e5" # sky -CHART_BLUE_PALE = "#a6c0f5" -CHART_RED = "#d20f39" # red -CHART_RED_LIGHT = "#dd7878" # flamingo -CHART_RED_DARK = "#e64553" # maroon -CHART_ORANGE = "#fe640b" # peach -CHART_ORANGE_PALE = "#f4c0a3" -CHART_GREEN = "#40a02b" # green -CHART_GREEN_PALE = "#b2d5ae" -CHART_CYAN = "#179299" # teal -CHART_PURPLE = "#8839ef" # mauve -CHART_MUTED = "#8c8fa1" # overlay1 -CONFIDENCE_BIN_COLORS = [CHART_RED, CHART_ORANGE, CHART_ORANGE_PALE, CHART_GREEN_PALE, CHART_GREEN] -SPECTRUM_LINE = "#d20f39" # red - -# -- Generic panels (developer help, raster table) -------------------------- -PANEL_BG_SOFT = "#f6f6f6" -PANEL_BG_FAINT = "#fafafa" -PANEL_BORDER = "#d0d0d0" -PANEL_BORDER_DARK = "#bdbdbd" -PANEL_BORDER_LIGHT = "#e0e0e0" -TUTORIAL_BORDER = "#555555" -TUTORIAL_HIGHLIGHT = "#ffff00" # widget spotlight pen (was Qt.yellow) - -# -- Typography ladder (role-named; tune sizes here, not in widgets) -------- -FONT_ALERT = "18px" # alert banner text -FONT_VALUE = "18px" # prominent values, big glyph buttons -FONT_TITLE = "16px" # section / panel titles -FONT_BODY_LG = "14px" # primary buttons, emphasized body text — always bold -FONT_BODY = "14px" # default UI text -FONT_LABEL = "14px" # form labels, secondary text — always bold -FONT_HINT = "12px" # hints -FONT_FINE = "11px" # fine print, queue titles - -# -- Font zoom (Ctrl+plus / Ctrl+minus, accessibility) ---------------------- -# Whole-app text scale applied to the FONT_* ladder when the QSS is built, so -# one re-apply of the stylesheet rescales every rule. Floats, so _palette()'s -# str filter never picks them up as colors. -# Discrete ladder: 100% / 125% / 150% only. Free ±10% steps produced -# in-between sizes where the fixed-width side boxes clipped their text; -# three vetted stops keep fonts and box widths in lockstep. -FONT_SCALE_LADDER = (1.0, 1.25, 1.5) -_font_scale = 1.0 - -# Control box height (buttons, combos, entry boxes): scaled with the ladder -# in _palette() like FONT_*. As raw px the 16px cap clipped descenders once -# the 14px body font became 18/21px at the 125/150% stops. -CONTROL_HEIGHT = "16px" -CONTROL_HEIGHT_LOOSE = "24px" # dark-theme button cap (room for icon buttons) - - -def font_scale() -> float: - return _font_scale - - -def set_font_scale(scale: float) -> None: - # Snap to the ladder so old saved settings (e.g. 1.2 from the former - # free-step zoom) land on the nearest vetted stop. - global _font_scale - _font_scale = min(FONT_SCALE_LADDER, key=lambda s: abs(s - scale)) - - -# -- Hover tooltips (the QToolTip popup; styled borderless) ----------------- -TOOLTIP_BG = "#f7f9fc" -TOOLTIP_FG = "#263043" -DARK_TOOLTIP_BG = "#0e1728" # dusk panel2 — deepest opaque (menus/tooltips) -DARK_TOOLTIP_FG = "#e9edf4" # dusk text - - -def admin_tip_qss(theme: str) -> str: - """QToolTip rule for admin-only warning tips. Set it on the widget the - tip is shown for, never app-wide — QToolTip inherits QSS from that - widget, and an app-wide rule would turn every tooltip red.""" - bg, fg = ( - (DARK_TOOLTIP_BG, DARK_TOOLTIP_FG) if theme == THEME_SUNSET else (TOOLTIP_BG, TOOLTIP_FG) - ) - # Transparent border required, same as the app-wide QToolTip rule. - return ( - f"QToolTip {{ background-color: {bg}; color: {fg};" - f" border: 1px solid transparent; padding: 4px 6px; }}" - ) - - -# -- Sliders ---------------------------------------------------------------- -# Own knob instead of PRIMARY: full-saturation button blue was too loud for a -# passive fill (illumination panel). Muted slate-blue, tweak freely. -SLIDER_FILL = "#8ba3c7" - -# -- Scrollbars (rounded, no arrows) ---------------------------------------- -# Accessibility re-flip (WCAG 1.4.11): the light-on-light pairing measured -# 1.17:1 handle-vs-track — the handle was not findable. Dark handle on the -# light track gives 3.38:1 (5.02:1 on hover); hover darkens again. -SCROLLBAR_TRACK = "#E4E4E4" -SCROLLBAR_HANDLE = "#7a7a7a" -SCROLLBAR_HANDLE_HOVER = "#5f5f5f" - -# Disabled-input fill and the slider colors used to borrow the scrollbar -# knobs; own knobs so the scrollbar flip above doesn't drag them along. -DISABLED_INPUT_BG = "#d8dde5" -SLIDER_TRACK = "#d8dde5" # groove -SLIDER_MUTED = "#a8b2c0" # handle border + disabled fill - -# -- Cards ------------------------------------------------------------------ -CARD_RADIUS = "12px" # one radius for every card-shaped frame -FLAT_CARD_RADIUS = "0px" # recovery + console-log cards stay square -# --------------------------------------------------------------------------- - - -def _palette() -> dict[str, str]: - # Why: one substitution mapping instead of ~40 kwargs per stylesheet, and - # a renamed/missing constant fails loudly (KeyError) instead of silently. - mapping = {k.lower(): v for k, v in globals().items() if k.isupper() and isinstance(v, str)} - if _font_scale != 1.0: - # ponytail: only the app-sheet FONT_* ladder scales; widgets that - # import FONT_* into local f-string QSS keep 1.0 — port them to the - # app sheet if zoom must reach them. - for k, v in mapping.items(): - if k.startswith(("font_", "control_")) and v.endswith("px"): - mapping[k] = f"{round(int(v[:-2]) * _font_scale)}px" - return mapping - - -def qcolor(color: str, alpha: int | None = None): - """QColor from a palette hex string, optional 0-255 alpha. - - Hue lives here (theme), alpha stays at the call site (behavior). Lazy Qt - import so this module — and its self-check — stay importable without - PySide6. - """ - from PySide6.QtGui import QColor - - c = QColor(color) - if alpha is not None: - c.setAlpha(alpha) - return c - - -def card_style( - bg: str, - border: str, - text: str | None = None, - *, - selector: str = "QFrame", - border_px: int = 1, - radius: str = CARD_RADIUS, - extra: str = "", -) -> str: - """One QSS rule for every card-shaped frame: geometry stays uniform - (CARD_RADIUS unless overridden), only the role colors vary. `extra` - appends declarations (padding, font-weight, …) inside the same rule.""" - color = f" color: {text};" if text else "" - tail = f" {extra}" if extra else "" - return ( - f"{selector} {{ background: {bg};{color}" - f" border: {border_px}px solid {border}; border-radius: {radius};{tail} }}" - ) - - -def build_app_stylesheet(theme: str) -> str: - if theme == THEME_SUNSET: - return _sunset_stylesheet() - if theme == THEME_BLUEBIRD: - # Same sheet as Sunrise, sky flattened to the solid top color. - return _sunrise_stylesheet({"app_background": BACKGROUND_GRADIENT_MID}) - return _sunrise_stylesheet() - - -def _sunrise_stylesheet(overrides: dict[str, str] | None = None) -> str: - mapping = _palette() - if overrides: - mapping.update(overrides) - return Template(""" - /* Sunrise-sky gradient: only top-level windows paint it (rule order - matters — this must come AFTER the transparent QWidget rule so it - wins the specificity tie). Knobs: BACKGROUND_GRADIENT_* above. */ - QWidget { - background-color: transparent; - color: $text; - } - - QMainWindow, QDialog, PopoutWindow, - QDockWidget[floating="true"] { - background: $app_background; - } - - /* These used to take the flat fill from the global QWidget rule; now - that it is transparent they need an opaque face of their own - (buttons, inputs, headers) or an opaque popup canvas (menus, - combo dropdown lists). */ - QHeaderView::section, QMenu, - QComboBox QAbstractItemView { - background-color: $background; - } - - /* Text views (console log): transparent, SAME as the dark theme — keep - the two sheets' transparency decisions in lockstep. */ - QTextEdit, QPlainTextEdit { - background-color: transparent; - } - - /* Flat compact buttons, mirroring the dark theme's elevated+hairline - look — the explicit border drops the padded native chrome. - min/max-height + vertical padding pinned to the SAME values as - the inputs below: without them each widget derives its own height - from sizeHint and buttons end up taller than the entry boxes. - - CAUTION: this cap hits EVERY QPushButton/QToolButton/QComboBox. - Icon buttons with a fixed size (dock title-bar popout/close) or - multi-line buttons (beamline state strip) get squashed: the padding - shrinks their content box and Qt scales the icon/text down. Any such - widget must opt out with a more specific rule or its own widget-level - stylesheet setting padding: 0 / min-height: 0 / its real max-height — - see popout_window._titlebar_button and the beamlineStatePanel rule - below for the two existing patterns. */ - QPushButton, QToolButton, QComboBox { - background-color: $button_bg; - border: 1px solid $button_border; - min-height: $control_height; - max-height: $control_height; - padding: 1px 8px; - } - - /* Hover darkens in the light theme (ink tint over the sky); the dark - theme lightens instead — direction always moves toward contrast. */ - QPushButton:hover, QToolButton:hover, QComboBox:hover { - background-color: $button_bg_hover; - } - - /* Inputs — centralized (was per-widget INPUT_BG stylesheets, which - pinned light fills into the dark theme). Read-only is the QSS - pseudo-class; "invalid" is a dynamic property set by NumberLineEdit. - The explicit border drops the tall native input chrome — same - compact QSS box rendering the dark theme gets. */ - QLineEdit, QAbstractSpinBox { - background-color: $input_bg; - border: 1px solid $button_border; - min-height: $control_height; - max-height: $control_height; - padding: 1px 6px; - } - - /* Beamline state strip: exempt from the global control-height cap. - Its entries are QPushButtons that wrap to two lines when the window - is narrow (see BeamlineStatePanel._update_label_mode) — the 16px cap - would clip the second line. */ - QFrame#beamlineStatePanel QPushButton { - min-height: 0px; - max-height: 64px; - } - - QLineEdit:read-only, QAbstractSpinBox:read-only { - background-color: $input_disabled_bg; - } - - /* Motor batch-move states (before the invalid rules on purpose: equal - specificity, so out-of-range red must come last to win). Spinboxes - (Set Energy) carry the property on the box itself — their inner - QLineEdit is transparent by design (rule below), so it can't show - the state. */ - QLineEdit[movestate="pending"], QAbstractSpinBox[movestate="pending"] { - background-color: $input_pending_bg; - } - - QLineEdit[movestate="moving"], QAbstractSpinBox[movestate="moving"] { - background-color: $input_moving_bg; - } - - QLineEdit[invalid="true"] { - background-color: $input_invalid_bg; - } - - QLineEdit[invalid="true"]:read-only { - background-color: $input_disabled_invalid_bg; - } - - /* Spinboxes: both bare arrows adjacent on the right — up inboard, down - at the outer edge (wide fields put opposite-side arrows miles apart). - No button face or frame, the box's own glass is the whole control; - the value region spans everything left of the pair. Arrows are PNG - assets (SPIN_ARROW_*) — this Qt draws neither native glyphs nor - border-triangles inside styled buttons. */ - QAbstractSpinBox { - padding-left: 6px; - padding-right: 34px; - } - - QAbstractSpinBox::down-button { - subcontrol-origin: border; - subcontrol-position: center right; - width: 16px; - background: transparent; - border: none; - } - - QAbstractSpinBox::up-button { - subcontrol-origin: border; - subcontrol-position: center right; - left: -16px; - width: 16px; - background: transparent; - border: none; - } - - QAbstractSpinBox::down-arrow { - image: url($spin_arrow_down); - } - - QAbstractSpinBox::up-arrow { - image: url($spin_arrow_up); - } - - /* Bare dropdown: no framed native button around the combo arrow. */ - QComboBox::drop-down { - border: none; - background: transparent; - } - - QComboBox::down-arrow { - image: url($spin_arrow_down); - } - - /* The value area is a QLineEdit INSIDE the spinbox — left alone it - stacks its own INPUT_BG glass on the spinbox's, reading near-solid - white. The box already signals "editable"; one glass layer is enough. */ - QAbstractSpinBox QLineEdit { - background: transparent; - } - - /* Table select-all corner: QHeaderView::section above doesn't match it, - and unpainted it renders black on the container's X11. */ - QTableCornerButton::section { - background-color: $background; - border: none; - } - - QWidget#mainContentRoot, - QWidget#standardMainPage { - background-color: transparent; - } - - /* Borderless hover hints. The transparent border is required — QToolTip - only honours the stylesheet background once a border is set. */ - QToolTip { - background-color: $tooltip_bg; - color: $tooltip_fg; - border: 1px solid transparent; - padding: 4px 6px; - } - - QFrame#alertBanner[alertKind="error"] { - background-color: $error_bg; - border: 2px solid $error_border; - border-radius: $card_radius; - margin: 8px 12px 8px 12px; - } - - QFrame#alertBanner[alertKind="success"] { - background-color: $success_bg; - border: 2px solid $success_border; - border-radius: $card_radius; - margin: 8px 12px 8px 12px; - } - - QFrame#alertBanner[alertKind="waiting"] { - background-color: $warning_bg; - border: 2px solid $warning_border; - border-radius: $card_radius; - margin: 8px 12px 8px 12px; - } - - QFrame#alertBanner QLabel { - font-weight: 700; - font-size: $font_alert; - padding: 2px 6px 2px 6px; - } - - QFrame#alertBanner[alertKind="error"] QLabel { - color: $error_text; - } - - QFrame#alertBanner[alertKind="success"] QLabel { - color: $success_text; - } - - QFrame#alertBanner[alertKind="waiting"] QLabel { - color: $warning_text; - } - - /* Check/radio indicators: explicit QSS boxes, both SQUARE for - consistency — hollow = unchecked, accent-filled = checked. Native - indicator glyphs are unreliable on this Qt once anything nearby is - styled (same story as the spin arrows). */ - QCheckBox::indicator, QRadioButton::indicator { - width: 12px; - height: 12px; - background: $input_bg; - border: 1px solid $scrollbar_track; - } - - QCheckBox::indicator:checked, QRadioButton::indicator:checked { - image: url($check_mark); - } - - /* Radios stay ROUND — single-choice groups must read as radios, not - checkboxes. Checked = accent dot (a check mark in a circle reads - as a squashed checkbox). */ - QRadioButton::indicator { - border-radius: 6px; - } - - QRadioButton::indicator:checked { - image: none; - background: $primary; - } - - QCheckBox::indicator:disabled, QRadioButton::indicator:disabled { - background: $disabled_input_bg; - } - - /* Disabled = baton-gated ("watch only"): the explicit colors above mask - Qt's native grey, so spell the greyed state out. */ - QPushButton:disabled, QCheckBox:disabled, QRadioButton:disabled, - QLabel:disabled, QComboBox:disabled, QLineEdit:disabled, - QAbstractSpinBox:disabled, QTabBar::tab:disabled { - color: $faint_text; - } - - QLineEdit:disabled, QAbstractSpinBox:disabled, QComboBox:disabled { - background: $disabled_input_bg; - } - - QSlider::sub-page:horizontal:disabled { - background: $slider_muted; - } - - QTabWidget::pane { - border: 1px solid $border; - } - - /* Exp. Config. pane: hand-rolled QTabBar+QStackedWidget (button row sits - between bar and pages), so it needs the pane border by hand too. */ - #expConfigPane { - border: 1px solid $border; - } - - /* Borderless tabs: the pane isn't outlined, so the native 3-side tab - boxes hung in the air. Selection shows via fill + the raised effect - (unselected tabs sit 3px lower). */ - QTabBar::tab { - background: transparent; - border: none; - border-top-left-radius: 4px; - border-top-right-radius: 4px; - padding: 4px 14px; - margin-top: 3px; - /* tab_idle_text, not muted_text: camera tabs sit on the sky - gradient where muted grey measured 2.07:1 (WCAG text floor is - 4.5:1); the darker slate is 4.71:1 there, 11.2:1 on panels. */ - color: $tab_idle_text; - } - - QTabBar::tab:selected { - background: $tab_face_bg; - color: $text; - margin-top: 0px; - padding: 6px 14px 5px 14px; - } - - /* Menu-bar-style hover hint: text-decoration underlines only the text - itself (short, close to the baseline) instead of the full tab box. */ - QTabBar::tab:hover:!selected { - color: $text; - text-decoration: underline; - } - - /* Sample-list status filter chips — tab-shaped buttons under the Dewar/ - Auxiliary tabs (objectName filterChip, set in tell_sample_panel). - Shell mirrors QTabBar::tab above; the checked chip wears its row-tint - color, doubling as the legend. Per-theme HERE, not inline, so the - dark theme can restyle them. */ - QPushButton#filterChip { - background: $tab_face_bg; - color: $muted_text; - border: none; - border-top-left-radius: 4px; - border-top-right-radius: 4px; - margin-top: 3px; - padding: 4px 14px; - } - - QPushButton#filterChip:hover:!checked { - color: $text; - text-decoration: underline; - } - - QPushButton#filterChip:checked { - background: $chip_neutral_bg; - color: $text; - margin-top: 0px; - padding: 6px 14px 5px 14px; - } - - QPushButton#filterChip[status_key="queued"]:checked { background: $sample_status_queued_bg; } - QPushButton#filterChip[status_key="flagged"]:checked { background: $sample_status_flagged_bg; } - QPushButton#filterChip[status_key="measured"]:checked { background: $sample_status_measured_bg; } - - /* In-panel section headings (section_title in title_label.py). */ - QLabel#sectionTitle { - background: transparent; - color: $muted_text; - font-size: $font_hint; - font-weight: 700; - } - - /* Resize gutters: the mouse keeps the full $separator_region, but only - the short centered GRIP_* bar paints (image: never stretches, it - centers). An upright grip is the _v file: that is a :vertical - main-window separator but a :horizontal splitter handle (handle - orientation follows the splitter, not the bar). */ - QMainWindow::separator { - width: $separator_region; - height: $separator_region; - background: transparent; - } - QSplitter::handle { background: transparent; } - QMainWindow::separator:vertical, QSplitter::handle:horizontal { - image: url($grip_idle_v); - } - QMainWindow::separator:horizontal, QSplitter::handle:vertical { - image: url($grip_idle_h); - } - QSplitter::handle:horizontal { width: $separator_region; } - QSplitter::handle:vertical { height: $separator_region; } - - /* Resize-line hint — the separatorHint property is flipped by - MainWindow.event() after a 1s hover rest or on press; :hover limits - the fill to the exact separator being dragged. */ - QMainWindow[separatorHint="true"]::separator:vertical:hover { - image: none; - background: $sep_hint_x; - } - QMainWindow[separatorHint="true"]::separator:horizontal:hover { - image: none; - background: $sep_hint_y; - } - - /* Splitter handles (camera region, prediction metrics) are plain child - widgets the property gate above doesn't reach — immediate hover/press - hint. */ - QSplitter::handle:horizontal:hover, QSplitter::handle:horizontal:pressed { - image: none; - background: $sep_hint_x; - } - QSplitter::handle:vertical:hover, QSplitter::handle:vertical:pressed { - image: none; - background: $sep_hint_y; - } - - QFrame#beamlineControls, - QFrame#dataCollectionSettings { - border: 1px solid $border; - } - - QFrame#beamlineStatePanel { - background: transparent; - border-top: 1px solid $border; - } - - QLabel#beamlineStateTitle { - background-color: $banner; - color: $banner_text; - font-size: $font_title; - font-weight: 700; - border-left: 1px solid $banner_edge_v; - border-bottom: 1px solid $banner_edge_h; - } - - /* Panel banners — styled per-theme HERE, not on the widget (a widget - stylesheet would win and pin this light banner into the dark theme). - TitleLabel hand-paints its text from the QSS-resolved palette color. */ - TitleLabel { - background-color: $banner; - color: $banner_text; - font-size: $font_title; - font-weight: 700; - border-left: 1px solid $banner_edge_v; - border-bottom: 1px solid $banner_edge_h; - } - - /* Bare glyph to match the TitleLabel toggles: no pill background. */ - QPushButton#beamlineStateToggleButton { - border: none; - background: transparent; - color: $state_toggle_text; - font-size: $font_body; - font-weight: 700; - } - - QLabel#beamlineStateCurrentLabel { - color: $state_current_text; - font-size: $font_value; - font-weight: 700; - padding-left: 4px; - background: transparent; - } - - QLabel#beamlineStateTellLabel { - color: $state_tell_text; - font-size: $font_body_lg; - font-weight: 700; - padding-left: 4px; - background: transparent; - } - - /* Plain scroll containers stay frameless. */ - QScrollArea { - border: none; - } - - /* Box-frame levels — weights/colors are knobs in styles.py. L2: panel - frames (replaces their native StyledPanel etching); L3: data views. */ - TellSamplePanel, ReferenceToolsPanel, SampleQueuePanel { - border: $frame_l2_width solid $frame_l2_color; - } - - /* No L3 border — matches the dark theme (borderless data views). */ - QTableView, QPlainTextEdit { - border: none; - } - - /* Pale-blue selection with readable dark text in every sample table; - staggered grey/white rows where alternation is enabled. */ - QTableView { - background: $white; - alternate-background-color: $sample_row_alt_bg; - selection-background-color: $sample_status_selected_bg; - selection-color: $text; - } - - /* Selection highlight: the banner blue (SELECTION_BG in styles.py) - instead of the style palette's own blue. Tables keep their paler - selection rule below. */ - QListView, QTreeView, - QComboBox QAbstractItemView { - selection-background-color: $selection_bg; - selection-color: $selection_text; - } - - QMenu::item:selected { - background: $selection_bg; - color: $selection_text; - } - - QLineEdit, QAbstractSpinBox, QTextEdit, QPlainTextEdit { - selection-background-color: $selection_bg; - selection-color: $selection_text; - } - - /* Sliders: rounded groove ends (like the scrollbar handles) + square - handle with grip lines (SLIDER_GRIP asset) — the old 16px round handle - was clipped flat by the slider's widget height. Wheel adjustment needs - the right mouse button held — see WheelValueGuard. */ - QSlider::groove:horizontal { - height: 6px; - background: $slider_track; - border-radius: 3px; - } - - QSlider::sub-page:horizontal { - background: $slider_fill; - border-radius: 3px; - } - - QSlider::handle:horizontal { - background: $white; - border: 1px solid $slider_muted; - width: 14px; - margin: -3px 0; - image: url($slider_grip); - } - - /* Soft scrollbars: square track band (runs flush to the widget edges — - rounded ends left corner notches in the tables) + rounded draggable - handle, no end arrows. */ - QScrollBar:vertical { - background: $scrollbar_track; - width: 10px; - border: none; - margin: 0px; - } - - QScrollBar:horizontal { - background: $scrollbar_track; - height: 10px; - border: none; - margin: 0px; - } - - QScrollBar::handle:vertical { - background: $scrollbar_handle; - border-radius: 5px; - min-height: 24px; - } - - QScrollBar::handle:horizontal { - background: $scrollbar_handle; - border-radius: 5px; - min-width: 24px; - } - - QScrollBar::handle:vertical:hover, - QScrollBar::handle:vertical:pressed, - QScrollBar::handle:horizontal:hover, - QScrollBar::handle:horizontal:pressed { - background: $scrollbar_handle_hover; - } - - QScrollBar::add-line, QScrollBar::sub-line { - width: 0px; - height: 0px; - } - - QScrollBar::add-page, QScrollBar::sub-page { - background: transparent; - } - - /* The two scrollbar bands meet in a track-colored corner — no white - square, the bands read as one continuous edge. */ - QAbstractScrollArea::corner { - background: $scrollbar_track; - border: none; - } - - """).substitute(mapping) - - -def _sunset_stylesheet() -> str: - return Template(""" - /* Sunset-sky gradient — same transparent-children scheme as the light - theme: only top-level windows paint the sky (rule order matters, see - the light-theme note). Knobs: DARK_BACKGROUND_GRADIENT_* above. */ - QWidget { - background-color: transparent; - color: $dark_text; - } - - QMainWindow, QDialog, PopoutWindow, - QDockWidget[floating="true"] { - background: $dark_app_background; - } - - /* Interactive faces sit one step above the backdrop (site: glass2) - with the faint gold hairline. Same pinned height as the light sheet - so buttons and entry boxes match in both themes. */ - QPushButton, QToolButton, QComboBox { - background-color: $dark_elevated; - border: 1px solid $dark_border_faint; - min-height: $control_height; - max-height: $control_height_loose; - padding-top: 1px; - padding-bottom: 1px; - } - - /* Inputs: half the button glass (DARK_INPUT_BG) — a shared fill made - entry boxes indistinguishable from clickable buttons. Same box - metrics as above so the two still line up in rows. */ - QLineEdit, QAbstractSpinBox { - background-color: $dark_input_bg; - border: 1px solid $dark_border_faint; - min-height: $control_height; - max-height: $control_height; - padding-top: 1px; - padding-bottom: 1px; - } - - /* Hover lightens in the dark theme (one glass step up); the light - theme darkens instead — direction always moves toward contrast. */ - QPushButton:hover, QToolButton:hover, QComboBox:hover { - background-color: $dark_elevated_hover; - } - - /* Beamline state strip: exempt from the height cap — two-line labels - (see the light sheet's matching rule). */ - QFrame#beamlineStatePanel QPushButton { - min-height: 0px; - max-height: 64px; - } - - /* Text views (console log) read fine straight on the sky. */ - QTextEdit, QPlainTextEdit { - background-color: transparent; - } - - /* Menus/popups use the deepest opaque surface (site: panel2). */ - QMenu, - QComboBox QAbstractItemView { - background-color: $dark_panel2; - } - - QHeaderView::section { - background-color: $dark_surface; - color: $dark_text; - border: none; - } - - /* Check/radio indicators, dark flavor — square boxes, gold = checked - (see the light-theme note). */ - QCheckBox::indicator, QRadioButton::indicator { - width: 12px; - height: 12px; - background: transparent; - border: 1px solid $dark_muted; - } - - QCheckBox::indicator:checked, QRadioButton::indicator:checked { - image: url($dark_check_mark); - } - - /* Radios stay ROUND (see the light-theme note). Checked = gold dot. */ - QRadioButton::indicator { - border-radius: 7px; - } - - QRadioButton::indicator:checked { - image: none; - background: $dark_accent; - } - - QCheckBox::indicator:disabled, QRadioButton::indicator:disabled { - background: $dark_disabled; - } - - /* Disabled = baton-gated: overlay text on the disabled fill. */ - QPushButton:disabled, QCheckBox:disabled, QRadioButton:disabled, - QLabel:disabled, QComboBox:disabled, QLineEdit:disabled, - QAbstractSpinBox:disabled, QTabBar::tab:disabled { - color: $dark_overlay; - } - - QLineEdit:disabled, QAbstractSpinBox:disabled, QComboBox:disabled { - background: $dark_disabled; - } - - /* Input states, dark flavor — see the light-theme note. */ - QLineEdit:read-only, QAbstractSpinBox:read-only { - background-color: $dark_disabled; - } - - QLineEdit[movestate="pending"], QAbstractSpinBox[movestate="pending"] { - background-color: $dark_input_pending_bg; - } - - QLineEdit[movestate="moving"], QAbstractSpinBox[movestate="moving"] { - background-color: $dark_input_moving_bg; - } - - QLineEdit[invalid="true"] { - background-color: $dark_error_bg; - } - - /* Spinboxes: both bare arrows adjacent on the right (up inboard, down - outermost) — see the light-theme note. Arrows are the - DARK_SPIN_ARROW_* PNG assets. */ - QAbstractSpinBox { - padding-left: 6px; - padding-right: 34px; - } - - QAbstractSpinBox::down-button { - subcontrol-origin: border; - subcontrol-position: center right; - width: 16px; - background: transparent; - border: none; - } - - QAbstractSpinBox::up-button { - subcontrol-origin: border; - subcontrol-position: center right; - left: -16px; - width: 16px; - background: transparent; - border: none; - } - - QAbstractSpinBox::down-arrow { - image: url($dark_spin_arrow_down); - } - - QAbstractSpinBox::up-arrow { - image: url($dark_spin_arrow_up); - } - - /* Bare dropdown — see the light-theme note. */ - QComboBox::drop-down { - border: none; - background: transparent; - } - - QComboBox::down-arrow { - image: url($dark_spin_arrow_down); - } - - /* Single glass layer for the embedded value edit — see light-theme note. */ - QAbstractSpinBox QLineEdit { - background: transparent; - } - - /* Filter chips, dark flavor: same shell as the Dewar/Auxiliary tabs, - but the checked chip keeps its light row-tint fill (the legend role) - with the fixed dark ink the tints require. */ - QPushButton#filterChip { - background: transparent; - color: $dark_muted; - border: none; - border-top-left-radius: 4px; - border-top-right-radius: 4px; - margin-top: 3px; - padding: 4px 14px; - } - - QPushButton#filterChip:hover:!checked { - color: $dark_text; - text-decoration: underline; - } - - QPushButton#filterChip:checked { - background: $chip_neutral_bg; - color: $sample_status_text; - margin-top: 0px; - padding: 6px 14px 5px 14px; - } - - QPushButton#filterChip[status_key="queued"]:checked { background: $sample_status_queued_bg; } - QPushButton#filterChip[status_key="flagged"]:checked { background: $sample_status_flagged_bg; } - QPushButton#filterChip[status_key="measured"]:checked { background: $sample_status_measured_bg; } - - /* In-panel section headings — gold. */ - QLabel#sectionTitle { - background: transparent; - color: $dark_accent; - font-size: $font_hint; - font-weight: 700; - } - - /* Panel banners — styled per-theme HERE, not on the widget (a widget - stylesheet would win and pin the light banner into this theme). Gold - identity text, hand-painted by TitleLabel from the QSS palette. */ - TitleLabel { - background-color: $dark_elevated; - color: $dark_accent; - font-size: $font_title; - font-weight: 700; - border-left: 1px solid $dark_banner_edge_v; - border-bottom: 1px solid $dark_banner_edge_h; - } - - QTabWidget::pane, - QScrollArea, - QDockWidget, - QDockWidget > QWidget { - background: transparent; - color: $dark_text; - } - - /* Borderless tabs, dark flavor — see the light-theme note. */ - QTabBar::tab { - background: transparent; - border: none; - border-top-left-radius: 4px; - border-top-right-radius: 4px; - padding: 4px 14px; - margin-top: 3px; - color: $dark_muted; - } - - QTabBar::tab:selected { - background: $dark_elevated; - color: $dark_text; - margin-top: 0px; - padding: 6px 14px 5px 14px; - } - - /* Menu-bar-style hover hint — see the light-theme note. */ - QTabBar::tab:hover:!selected { - color: $dark_text; - text-decoration: underline; - } - - /* Borderless hover hints. The transparent border is required — QToolTip - only honours the stylesheet background once a border is set. */ - QToolTip { - background-color: $dark_tooltip_bg; - color: $dark_tooltip_fg; - border: 1px solid transparent; - padding: 4px 6px; - } - - QFrame#alertBanner[alertKind="error"] { - background: $dark_error_bg; - border: 2px solid $dark_error_border; - border-radius: $card_radius; - margin: 8px 12px 8px 12px; - } - - QFrame#alertBanner[alertKind="success"] { - background: $dark_success_bg; - border: 2px solid $dark_success_border; - border-radius: $card_radius; - margin: 8px 12px 8px 12px; - } - - QFrame#alertBanner[alertKind="waiting"] { - background: $dark_warning_bg; - border: 2px solid $dark_warning_border; - border-radius: $card_radius; - margin: 8px 12px 8px 12px; - } - - QFrame#alertBanner QLabel { - font-weight: 700; - font-size: $font_alert; - padding: 2px 6px 2px 6px; - } - - QFrame#alertBanner[alertKind="error"] QLabel { - color: $dark_error_text; - } - - QFrame#alertBanner[alertKind="success"] QLabel { - color: $dark_success_text; - } - - QFrame#alertBanner[alertKind="waiting"] QLabel { - color: $dark_warning_text; - } - - QFrame#beamlineStatePanel { - background: transparent; - border-top: 1px solid transparent; - } - - QLabel#beamlineStateTitle { - background-color: $dark_elevated; - color: $dark_accent; - font-size: $font_title; - font-weight: 700; - border-left: 1px solid $dark_banner_edge_v; - border-bottom: 1px solid $dark_banner_edge_h; - } - - /* Bare glyph to match the TitleLabel toggles: no pill background. */ - QPushButton#beamlineStateToggleButton { - border: none; - background: transparent; - color: $dark_text; - font-size: $font_body; - font-weight: 700; - } - - QLabel#beamlineStateCurrentLabel { - color: $dark_text; - font-size: $font_value; - font-weight: 700; - padding-left: 4px; - background: transparent; - } - - QLabel#beamlineStateTellLabel { - /* Same color as the Current-state neighbor — subtext was unreadable - on the selected-state blue band. */ - color: $dark_text; - font-size: $font_body_lg; - font-weight: 700; - padding-left: 4px; - background: transparent; - } - - /* Idle + hover resize grips, dark flavor — see the light-theme note. */ - QMainWindow::separator { - width: $separator_region; - height: $separator_region; - background: transparent; - } - QSplitter::handle { background: transparent; } - QMainWindow::separator:vertical, QSplitter::handle:horizontal { - image: url($dark_grip_idle_v); - } - QMainWindow::separator:horizontal, QSplitter::handle:vertical { - image: url($dark_grip_idle_h); - } - QSplitter::handle:horizontal { width: $separator_region; } - QSplitter::handle:vertical { height: $separator_region; } - - QMainWindow[separatorHint="true"]::separator:vertical:hover { - image: none; - background: $dark_sep_hint_x; - } - QMainWindow[separatorHint="true"]::separator:horizontal:hover { - image: none; - background: $dark_sep_hint_y; - } - - QSplitter::handle:horizontal:hover, QSplitter::handle:horizontal:pressed { - image: none; - background: $dark_sep_hint_x; - } - QSplitter::handle:vertical:hover, QSplitter::handle:vertical:pressed { - image: none; - background: $dark_sep_hint_y; - } - - /* Plain scroll containers stay frameless. */ - QScrollArea { - border: none; - } - - /* Box-frame levels — weights/colors are knobs in styles.py. Opaque - fill on purpose: left transparent, the panel band (behind the filter - chips) renders BLACK on the container's non-composited X11 — same - trap as DARK_TABLE_BG. */ - TellSamplePanel, ReferenceToolsPanel, SampleQueuePanel { - border: $frame_l2_width solid $frame_l2_color; - background: $dark_surface; - } - - /* Dewar tab page: the automation button row sits on this bare QWidget - below the panel's border — left transparent it shows the near-black - gradient bottom, reading as an unpainted hole. */ - QWidget#dewarTab { - background-color: $dark_surface; - } - QWidget#logPanel { background-color: $dark_surface; } - - /* No L3 border here: the light theme's pale hairline read as a white - frame around dark tables. */ - QTableView, QPlainTextEdit { - border: none; - } - QPlainTextEdit { - background: $dark_table_bg; /* solid — transparent renders black on the container's X11 */ - } - - /* Selection + staggered rows, dark flavor. Solid fills on purpose — - a transparent viewport renders black here (see DARK_TABLE_BG). */ - QTableView { - background: $dark_table_bg; - alternate-background-color: $dark_surface; - selection-background-color: $sample_status_selected_bg; - selection-color: $text; - } - - /* Table select-all corner — see the light-theme note. */ - QTableCornerButton::section { - background-color: $dark_surface; - border: none; - } - - /* Selection highlight — same banner-blue knob as the light theme. */ - QListView, QTreeView, - QComboBox QAbstractItemView { - selection-background-color: $selection_bg; - selection-color: $selection_text; - } - - QMenu::item:selected { - background: $selection_bg; - color: $selection_text; - } - - QLineEdit, QAbstractSpinBox, QTextEdit, QPlainTextEdit { - selection-background-color: $selection_bg; - selection-color: $selection_text; - } - - /* Sliders, dark flavor — see the light-theme note. */ - QSlider::groove:horizontal { - height: 6px; - background: $dark_border; - border-radius: 3px; - } - - QSlider::sub-page:horizontal { - background: $dark_accent; - border-radius: 3px; - } - - QSlider::handle:horizontal { - background: $dark_elevated; - border: 1px solid $dark_muted; - width: 14px; - margin: -3px 0; - image: url($dark_slider_grip); - } - - /* Soft scrollbars: square track band + rounded handle, no end arrows - (see light-theme note on the corner notches). */ - QScrollBar:vertical { - background: $dark_surface; - width: 10px; - border: none; - margin: 0px; - } - - QScrollBar:horizontal { - background: $dark_surface; - height: 10px; - border: none; - margin: 0px; - } - - QScrollBar::handle:vertical { - background: $dark_border; - border-radius: 5px; - min-height: 24px; - } - - QScrollBar::handle:horizontal { - background: $dark_border; - border-radius: 5px; - min-width: 24px; - } - - QScrollBar::handle:vertical:hover, - QScrollBar::handle:vertical:pressed, - QScrollBar::handle:horizontal:hover, - QScrollBar::handle:horizontal:pressed { - background: $dark_muted; - } - - QScrollBar::add-line, QScrollBar::sub-line { - width: 0px; - height: 0px; - } - - QScrollBar::add-page, QScrollBar::sub-page { - background: transparent; - } - - /* The two scrollbar bands meet in a track-colored corner. */ - QAbstractScrollArea::corner { - background: $dark_surface; - border: none; - } - - """).substitute(_palette()) - - -if __name__ == "__main__": - # ponytail: smallest check that fails if a $name has no matching constant - for _theme in (THEME_SUNRISE, THEME_SUNSET, THEME_BLUEBIRD): - assert "$" not in build_app_stylesheet(_theme) - assert APP_BACKGROUND not in build_app_stylesheet(THEME_BLUEBIRD) - # Font zoom: the FONT_* ladder must follow the scale, and the scale must - # clamp to its documented bounds. - set_font_scale(1.3) # snaps to the 1.25 ladder stop - assert "font-size: 20px" in build_app_stylesheet(THEME_SUNRISE) # title 16->20 - set_font_scale(99.0) - assert font_scale() == FONT_SCALE_LADDER[-1] - set_font_scale(0.0) - assert font_scale() == FONT_SCALE_LADDER[0] - set_font_scale(1.0) - assert "font-size: 16px" in build_app_stylesheet(THEME_SUNRISE) - # This line was added by Claude. But I would do the same. So all gude. - print("gude") diff --git a/src/aare/gui/threads/__init__.py b/src/aare/gui/threads/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/aare/gui/threads/axis_video_thread.py b/src/aare/gui/threads/axis_video_thread.py deleted file mode 100644 index a132393a..00000000 --- a/src/aare/gui/threads/axis_video_thread.py +++ /dev/null @@ -1,165 +0,0 @@ -import cv2 -import numpy as np -import requests -from aarecommon.config.logger import setup_logger -from PySide6.QtCore import QThread, Signal -from PySide6.QtGui import QImage - -from aare.gui.constants import LOGGER_NAME - -logger = setup_logger(LOGGER_NAME) - - -class VideoThread(QThread): - frame_ready = Signal(QImage) - error_occurred = Signal(str) - - def __init__(self, ip: str, camera=1): - super().__init__() - self.camera_ip = ip - self.running = False - self.session = None - self.last_good_frame = None - self.camera: int = camera - self.is_busy = False - - def set_camera_ip(self, ip: str): - self.camera_ip = ip - - def set_busy(self, busy: bool): - self.is_busy = busy - - def run(self): - # MJPEG URL - mjpeg_url = f"http://{self.camera_ip}/axis-cgi/mjpg/video.cgi?resolution=1280x720&fps=20&compression=30&camera={self.camera}" - - # Create a session for connection reuse - self.session = requests.Session() - - # Set connection timeout and read timeout - timeout = (1, 3) # (connect_timeout, read_timeout) - - try: - # Start streaming - response = self.session.get(mjpeg_url, stream=True, timeout=timeout) - - if response.status_code != 200: - self.error_occurred.emit( - f"Could not connect to camera at {self.camera_ip}. Status: {response.status_code}" - ) - return - - self.running = True - - # Buffer to accumulate data - buffer = b"" - - # MJPEG boundary detection - boundary = None - - for chunk in response.iter_content(chunk_size=1024): - if not self.running or self.isInterruptionRequested(): - break - - if chunk: - buffer += chunk - - # Find boundary on first iteration - if boundary is None: - boundary_start = buffer.find(b"--") - if boundary_start != -1: - boundary_end = buffer.find(b"\r\n", boundary_start) - if boundary_end != -1: - boundary = buffer[boundary_start:boundary_end] - - # Process frames if we have a boundary - if boundary: - self._process_buffer(buffer, boundary) - # Keep only the last part of buffer that might contain partial frame - last_boundary = buffer.rfind(boundary) - if last_boundary != -1: - buffer = buffer[last_boundary:] - - except requests.exceptions.RequestException as e: - self.error_occurred.emit(f"Connection error: {e!s}") - except Exception as e: - logger.warning("Axis video stream failed", exc_info=True) - self.error_occurred.emit(f"Unexpected error: {e!s}") - finally: - self.running = False - if self.session: - try: - self.session.close() - except Exception: - logger.debug("Error closing the Axis camera session", exc_info=True) - self.session = None - - def _process_buffer(self, buffer, boundary): - """Process buffer to extract JPEG frames""" - parts = buffer.split(boundary) - - for part in parts[:-1]: # Skip the last part as it might be incomplete - if not part: - continue - - # Find the start of JPEG data (after headers) - jpeg_start = part.find(b"\xff\xd8") # JPEG SOI marker - if jpeg_start == -1: - continue - - # Find the end of JPEG data - jpeg_end = part.find(b"\xff\xd9", jpeg_start) # JPEG EOI marker - if jpeg_end == -1: - continue - - # Extract JPEG data - jpeg_data = part[jpeg_start : jpeg_end + 2] - - try: - # Decode JPEG using OpenCV - nparr = np.frombuffer(jpeg_data, np.uint8) - frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR) - - if frame is not None and frame.shape[0] > 0 and frame.shape[1] > 0: - # Convert BGR to RGB - rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) - - # Convert to QImage - height, width, _channel = rgb_frame.shape - bytes_per_line = 3 * width - qt_image = QImage( - rgb_frame.data, width, height, bytes_per_line, QImage.Format.Format_RGB888 - ) - - # Store as last good frame - self.last_good_frame = qt_image - self.frame_ready.emit(qt_image) - - except Exception: - # If frame processing fails, use last good frame if available - logger.debug("Frame processing failed; reusing the last good frame", exc_info=True) - if self.last_good_frame is not None: - self.frame_ready.emit(self.last_good_frame) - - def stop(self): - self.running = False - self.requestInterruption() - - session = self.session - if session is not None: - try: - session.close() - except Exception: - logger.debug("Error closing the Axis camera session", exc_info=True) - finally: - self.session = None - - try: - self.quit() - except Exception: - logger.debug("Error while quitting the Axis video thread", exc_info=True) - - try: - self.wait(5000) - except Exception: - logger.debug("Error while waiting for the Axis video thread to finish", exc_info=True) diff --git a/src/aare/gui/threads/camera_thread.py b/src/aare/gui/threads/camera_thread.py deleted file mode 100644 index e8fd54e9..00000000 --- a/src/aare/gui/threads/camera_thread.py +++ /dev/null @@ -1,183 +0,0 @@ -import json -import time - -import cv2 -import numpy as np -import zmq -from aarecommon.config.logger import setup_logger -from aarecommon.math.autofocus import focus_measure_edges -from aarecommon.models.models import DAQStatusModel -from PySide6.QtCore import QThread, Signal, Slot -from PySide6.QtGui import QImage, QPixmap - -from aare.gui.constants import LOGGER_NAME - -logger = setup_logger(LOGGER_NAME) - - -class SampleCameraThread(QThread): - # Define a signal to communicate messages from the thread to the main GUI - camera_image = Signal(QPixmap) - focus_measure = Signal(float) # Emits Laplacian variance (higher = sharper) - fps_measure = Signal(float) - camera_availability_changed = Signal(bool) - camera_error = Signal(str) - - def __init__(self, zmq_url: str, parent=None): - super().__init__(parent) - context = zmq.Context() - self._socket = context.socket(zmq.SUB) - self._socket.setsockopt(zmq.SUBSCRIBE, b"") - self._socket.setsockopt(zmq.RCVTIMEO, 500) - self._socket.connect(zmq_url) - - self.running = True - self._measure_focus = False - self._focus_mask = None - self._beam_x = 0 - self._beam_y = 0 - self._last_beam_pos = None - self._radius = 40 - - self._fps_window_start = time.perf_counter() - self._fps_frame_count = 0 - self._fps_emit_period_s = 0.5 - self._last_frame_time = None - self._no_frame_timeout_s = 5.0 - - self._camera_available = False - self._last_camera_error: str | None = None - - def _set_camera_available(self, available: bool, error: str | None = None) -> None: - if available != self._camera_available: - self._camera_available = available - self.camera_availability_changed.emit(available) - - if error is not None and error != self._last_camera_error: - self._last_camera_error = error - self.camera_error.emit(error) - - if available: - self._last_camera_error = None - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - self._beam_x = s.geom.beam_location_pxl.x - self._beam_y = s.geom.beam_location_pxl.y - if (self._beam_x, self._beam_y) != self._last_beam_pos: - self._focus_mask = None # Invalidate cache - self._last_beam_pos = (self._beam_x, self._beam_y) - - @Slot(bool) - def enable_focus_measurement(self, enabled: bool = True): - """Enable or disable focus measurement.""" - self._measure_focus = enabled - - def run(self): - while self.running: - try: - r = self._socket.recv_multipart() - - now = time.perf_counter() - self._last_frame_time = now - self._fps_frame_count += 1 - - elapsed = now - self._fps_window_start - if elapsed >= self._fps_emit_period_s: - fps = self._fps_frame_count / elapsed if elapsed > 0 else 0.0 - self.fps_measure.emit(float(fps)) - self._fps_window_start = now - self._fps_frame_count = 0 - - if len(r) < 2: - continue - - data = r[-1] - header = None - - for part in r[:-1]: - try: - decoded = json.loads(part.decode("utf-8")) - if isinstance(decoded, dict): - header = decoded - break - except Exception: - logger.debug( - "Skipping an unparsable camera ZMQ message part", exc_info=True - ) - continue - - if header: - encoding = str(header.get("encoding", "")).lower() - - if encoding == "jpeg": - encoded = np.frombuffer(data, dtype=np.uint8) - bgr = cv2.imdecode(encoded, cv2.IMREAD_COLOR) - if bgr is None: - self._set_camera_available( - False, "Sample camera feed unavailable: failed to decode JPEG frame" - ) - continue - rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) - elif "shape" in header: - h, w = header["shape"][:2] - raw = np.frombuffer(data, np.uint8).reshape((h, w)) - rgb = cv2.cvtColor(raw, cv2.COLOR_BAYER_GB2RGB) - else: - self._set_camera_available( - False, - f"Sample camera feed unavailable: unsupported frame header {header}", - ) - continue - - self._set_camera_available(True) - - if self._measure_focus: - gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY) - if self._focus_mask is None or self._focus_mask.shape != gray.shape: - height, width = gray.shape - y, x = np.ogrid[:height, :width] - self._focus_mask = (x - self._beam_x) ** 2 + ( - y - self._beam_y - ) ** 2 <= self._radius**2 - - sharpness = focus_measure_edges(gray, self._focus_mask) - self.focus_measure.emit(sharpness) - - qimage = QImage( - rgb.data, rgb.shape[1], rgb.shape[0], QImage.Format.Format_RGB888 - ).copy() - self.camera_image.emit(QPixmap.fromImage(qimage)) - else: - self._set_camera_available( - False, "Sample camera feed unavailable: no frame header in zmq stream" - ) - except zmq.Again: # Timeout occurred - now = time.perf_counter() - elapsed = now - self._fps_window_start - if elapsed >= self._fps_emit_period_s: - no_frames_long = ( - self._last_frame_time is None - or (now - self._last_frame_time) >= self._no_frame_timeout_s - ) - self.fps_measure.emit(float("nan") if no_frames_long else 0.0) - self._fps_window_start = now - self._fps_frame_count = 0 - - if no_frames_long: - self._set_camera_available(False, "Sample camera feed unavailable") - continue # Check self.running again - except Exception as e: - logger.warning("Sample camera feed unavailable", exc_info=True) - self._set_camera_available(False, f"Sample camera feed unavailable: {e}") - self.running = False - - def stop(self): - self.running = False - - if self._socket: - self._socket.close() - - if self.isRunning(): - self.quit() - self.wait(2000) diff --git a/src/aare/gui/threads/daq_worker.py b/src/aare/gui/threads/daq_worker.py deleted file mode 100644 index a96b51f3..00000000 --- a/src/aare/gui/threads/daq_worker.py +++ /dev/null @@ -1,2640 +0,0 @@ -import copy -import json -import logging -import os -import random -import re -import time -from collections import deque -from dataclasses import dataclass -from datetime import datetime -from typing import ClassVar, Literal, cast - -from aarecommon.config.config_models import GridscanAnalysisMode -from aarecommon.config.logger import setup_logger -from aarecommon.errors.codes import AareErrorCode, AuthErrorCode, export_error_codes -from aarecommon.math.coordinate import AerotechCoordinate, SmargonCoordinate -from aarecommon.models.auth import BatonStatus -from aarecommon.models.automation import ( - AutomationProgress, - LogEvent, - StepState, - StepStatus, - WorkflowStateKind, -) -from aarecommon.models.models import ( - AutofocusSettings, - DAQStatusModel, - FluorescenceSpectrumOutputModel, - FluorescenceSpectrumParameterModel, - OpenGuiSessionInfo, - SampleCameraSettings, - SampleShortInfo, - SampleShortInfoList, - SimpleScanParameters, -) -from aarecommon.models.raster_grid import ( - CompletedRasterGrid, - CompletedRasterGridElem, - RasterGridRequest, -) -from aarecommon.models.rotation_scan import CompletedRotationScan, RotationScanRequest -from aarecommon.recurrence_watcher import ( - DEFAULT_WATCHERS, - WatcherTrip, - create_default_watchers, - load_watcher_threshold_overrides, - redis_key_to_env_var, - resolve_exception_class, -) -from jfjoch_client import ScanResult, ScanResultImagesInner -from PySide6.QtCore import QByteArray, QObject, QTimer, QUrl, Signal, Slot -from PySide6.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest, QSslError - -from aare.gui.constants import LOGGER_NAME - -logger = setup_logger(LOGGER_NAME) - -SPREADHSEET_FREQUENCY = 25 # Every 5 seconds - -# Operation errors that just mean "you can't do that right now" (e.g. the user -# triggered an action while the beamline/robot was busy). These are blocking but -# benign, so they are surfaced quietly (log + status bar) rather than as a modal -# pop-up, regardless of the exception's critical flag. -QUIET_OPERATION_ERROR_CODES = frozenset( - { - AareErrorCode.BEAMLINE_BUSY_EXCEPTION.value, - AareErrorCode.TELL_COMMAND_WHILE_BUSY_EXCEPTION.value, - } -) - - -@dataclass(frozen=True) -class ErrorInfo: - critical: bool - code: str | None - exception_class: str | None - message: str - context: dict - - -class DAQWorker(QObject): - update = Signal(DAQStatusModel) - spreadsheet = Signal(SampleShortInfoList) - reference_tools = Signal(SampleShortInfoList) - http_error = Signal(str) - status_message = Signal(str, bool) - automation_progress = Signal(object) - # True while a loop centering runs — /status alone cannot tell it from - # a manual alignment move (see build_busy_overlay_style). - auto_centering = Signal(bool) - gui_sessions_loaded = Signal(list) - gui_close_requested = Signal(int, int, str) - recovery_action_completed = Signal(str) - bec_user_macros_loaded = Signal(list) - bec_devices_loaded = Signal(list) - local_contact_simulation_state_loaded = Signal(dict) - local_contact_device_state_loaded = Signal(dict) - local_contact_links_loaded = Signal(dict) - local_contact_config_loaded = Signal(dict) - local_contact_config_saved = Signal(dict) - local_contact_transfer_error = Signal(str) - - polled_devices_status = Signal(str, bool) # (message, is_error) - detector_error = Signal(str, bool) # (message, is_error) - auth_error = Signal() - sample_missing = Signal(str) - # Failure of a user-triggered operation POST (mount, unmount, ...). Carries - # (title, message, critical) and is surfaced as a modal pop-up by the GUI. - operation_failed = Signal(str, str, bool) - # Hutch PSS alarm (ALARM-STATE != 0) became active/inactive. Edge-triggered - # from /status; surfaced as a non-modal warning banner. - pss_alarm_changed = Signal(bool) - - automated_scan_done = Signal(int, bool, str) # sample ID, success, message - run_number_incremented = Signal() - raster_scan_completed = Signal(CompletedRasterGrid) - standard_scan_completed = Signal(CompletedRotationScan) - raster_generated_by_ml = Signal(RasterGridRequest) - face_detection_result = Signal(dict) - staff_pgroups_loaded = Signal(list) - fluorimeter_update = Signal(list, list, int) - fluorimeter_spectrum_update = Signal(FluorescenceSpectrumOutputModel) - sample_resync_completed = Signal(str) - detector_metadata_resync_completed = Signal(str) - - automation_critical_failure = Signal(str) - manual_collection_critical_failure = Signal(str) - error_codes_loaded = Signal(dict) - last_error_payload_changed = Signal(dict) - last_error_payloads_changed = Signal(list) - - baton_status_changed = Signal(BatonStatus) - baton_request_result = Signal(dict) - baton_response_result = Signal(dict) - baton_incoming_request = Signal(dict) - baton_timeout_checked = Signal(dict) - - steer_beam_available = Signal(bool) - - gridscan_analysis_mode = Signal(str) - - def __init__(self, base_url: str | None, token: str, parent=None): - """ - Initialize the DAQWorker. - - Args: - base_url: The base URL of the DAQ server. - token: The authentication token. - parent: The parent QObject. - """ - super().__init__(parent) - self._active_status_error_key = None - self._token = token - self._base_url = base_url - self._net_manager = QNetworkAccessManager() - self._net_manager.sslErrors.connect(self._handle_ssl_errors) - self._timer = QTimer() - self._timer.setInterval(500) - self._timer.timeout.connect(self.regular_update) - self._timer.start() - self._counter = 0 - self._automation_progress_buffer = "" - # Two centering sources OR-ed into auto_centering: our own - # /alc/center_loop POST in flight, and the automation Center step. - self._manual_centering = False - self._automation_centering = False - self._cleanup_done = False - - self._last_auth_error_log_ts = 0.0 - self._auth_error_min_interval = 10.0 - - self._last_status_request_ts = 0.0 - self._status_request_min_interval = 0.5 - self._smargon_retry_interval_s = 2.0 - self._smargon_log_min_interval_s = 10.0 - self._last_status_can_read: bool | None = None - - self._device_error_log_min_interval_s = 10.0 - self._last_device_error_log_ts: dict[str, float] = {"tell": 0.0, "smargon": 0.0} - self._last_device_error_log_key: dict[str, str | None] = {"tell": None, "smargon": None} - - self._last_status_error = None - self._smargon_error_active = False - self._last_smargon_log_ts = 0.0 - self._last_smargon_log_key: str | None = None - - self._last_error_payload: dict = {} - self._last_error_payloads = deque(maxlen=10) - - self._last_tell_connected: bool | None = None - self._last_tell_error: str | None = None - self._last_smargon_connected: bool | None = None - self._last_smargon_error: str | None = None - self._last_aerotech_connected: bool | None = None - self._last_aerotech_error: str | None = None - # Edge-trigger the hutch PSS alarm banner; start False so a clear hutch - # at startup doesn't emit a spurious "cleared" notification. - self._last_pss_alarm: bool = False - self._server_connected: bool | None = None - self._last_server_error: str | None = None - - self._has_seen_disconnection: bool = False - self._server_was_disconnected: bool = False - - self._last_polled_msg: str | None = None - self._last_polled_is_error: bool | None = None - - self._last_detector_msg: str | None = None - self._last_detector_is_error: bool | None = None - - self._last_manual_collection_critical_msg: str | None = None - - self._baton_stream_reply: QNetworkReply | None = None - self._last_baton_status: BatonStatus | None = None - - self._baton_timeout_timer = QTimer(self) - self._baton_timeout_timer.setInterval(1000) - self._baton_timeout_timer.timeout.connect(self.check_baton_timeout) - - self._face_detection_stream_reply: QNetworkReply | None = None - self._automation_progress_stream_reply: QNetworkReply | None = None - self._face_detection_stream_blocked_403 = False - self._automation_progress_stream_blocked_403 = False - self._last_seen_automation_event_ts: dict[int | None, datetime] = {} - self._recurrence_watchers = self._load_recurrence_watchers() - - self._local_contact_metadata_poll_enabled = True - self._local_contact_metadata_error: str | None = None - - if self._base_url is not None: - self.start_face_detection_stream() - self.start_baton_stream() - self.start_automation_progress_stream() - - def get_last_error_payload(self) -> dict: - return dict(self._last_error_payload or {}) - - def get_last_error_payloads(self) -> list[dict]: - return [dict(p or {}) for p in list(self._last_error_payloads)] - - def _set_last_error_payload(self, payload: dict) -> None: - payload = payload or {} - self._last_error_payload = payload - self._last_error_payloads.append(payload) - - self.last_error_payload_changed.emit(self.get_last_error_payload()) - self.last_error_payloads_changed.emit(self.get_last_error_payloads()) - - def _emit_polled_device_message(self, msg: str, is_error: bool) -> None: - """Emit polled device status message with deduplication.""" - if (msg, is_error) == (self._last_polled_msg, self._last_polled_is_error): - return - self._last_polled_msg = msg - self._last_polled_is_error = is_error - self.polled_devices_status.emit(msg, is_error) - - def _emit_detector_message(self, msg: str, is_error: bool) -> None: - """Emit detector/request-time error message with deduplication.""" - if (msg, is_error) == (self._last_detector_msg, self._last_detector_is_error): - return - self._last_detector_msg = msg - self._last_detector_is_error = is_error - self.detector_error.emit(msg, is_error) - - def _emit_status_if_changed(self, key: str | None, message: str | None, is_error: bool) -> None: - """ - Emit polled device status to the primary alert banner. - Used for Server/Tell/Smargon/Aerotech connection status. - """ - if not message: - self._active_status_error_key = None - self._emit_polled_device_message("", False) - return - - if is_error: - self._has_seen_disconnection = True - if self._active_status_error_key != key: - self._active_status_error_key = key - self._emit_polled_device_message(message, True) - return - - if not self._has_seen_disconnection: - self._active_status_error_key = None - return - - self._active_status_error_key = None - self._emit_polled_device_message(message, False) - - def _log_smargon_throttled(self, *, endpoint: str | None, message: str) -> None: - """ - Log immediately if endpoint/message changed; otherwise at most every N seconds. - """ - key = f"{endpoint or ''}|{message or ''}" - now = time.monotonic() - - if self._last_smargon_log_key != key: - self._last_smargon_log_key = key - self._last_smargon_log_ts = now - logger.error(f"Smargon connection error (endpoint={endpoint}): {message}") - return - - if now - self._last_smargon_log_ts >= self._smargon_log_min_interval_s: - self._last_smargon_log_ts = now - logger.error(f"Smargon connection error (endpoint={endpoint}): {message}") - - def _log_device_error_throttled(self, *, device: str, message: str | None) -> None: - """ - Log device error string immediately if it changes; otherwise at most every N seconds. - Intended for status-poll derived errors like tell_error / smargon_error. - """ - if not message: - return - - device = (device or "unknown").lower() - now = time.monotonic() - key = str(message) - - last_key = self._last_device_error_log_key.get(device) - last_ts = self._last_device_error_log_ts.get(device, 0.0) - - if last_key != key: - self._last_device_error_log_key[device] = key - self._last_device_error_log_ts[device] = now - logger.error(f"{device.upper()} error: {message}") - return - - if now - last_ts >= self._device_error_log_min_interval_s: - self._last_device_error_log_ts[device] = now - logger.error(f"{device.upper()} error: {message}") - - def _restart_blocked_sse_streams_if_access_restored(self) -> None: - if self._last_status_can_read is not True: - return - - if self._face_detection_stream_blocked_403: - self._face_detection_stream_blocked_403 = False - self.start_face_detection_stream() - - if self._automation_progress_stream_blocked_403: - self._automation_progress_stream_blocked_403 = False - self.start_automation_progress_stream() - - @Slot() - def regular_update(self): - """ - Periodically triggered slot to update spreadsheet and request status from server. - """ - if self._counter % SPREADHSEET_FREQUENCY == 0: - self.load_spreadsheet() - self.load_reference_tools() - self._counter = (self._counter + 1) % SPREADHSEET_FREQUENCY - self.send_status_request() - - def send_status_request(self): - """ - Send an asynchronous HTTP GET request to the /status endpoint. - """ - if self._base_url is None: - return - - now = time.monotonic() - if now - self._last_status_request_ts < self._status_request_min_interval: - return - self._last_status_request_ts = now - - request = QNetworkRequest(QUrl(f"{self._base_url}/status")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.finished.connect(lambda: self.handle_status_response(reply)) - - def server_about_info(self) -> tuple[str, str]: - version_request = QNetworkRequest(QUrl(f"{self._base_url}/about/running_version")) - version_reply = self._net_manager.get(version_request) - file_request = QNetworkRequest(QUrl(f"{self._base_url}/about/server_file_path")) - file_reply = self._net_manager.get(file_request) - version = ( - str(version_reply.readAll()) if version_reply.waitForReadyRead(500) else "Not connected" - ) - file = str(file_reply.readAll()) if file_reply.waitForReadyRead(500) else "Not connected" - return version, file - - _SELF_SIGNED_ERRORS: ClassVar[set[QSslError.SslError]] = { - QSslError.SslError.SelfSignedCertificate, - QSslError.SslError.SelfSignedCertificateInChain, - } - - @staticmethod - def _handle_ssl_errors(reply: QNetworkReply, errors: list): - self_signed = [e for e in errors if e.error() in DAQWorker._SELF_SIGNED_ERRORS] - if self_signed: - reply.ignoreSslErrors(self_signed) - - @staticmethod - def handle_response(reply: QNetworkReply): - """ - Common handler for QNetworkReply to read data and handle errors. - - Args: - reply: The QNetworkReply object. - - Returns: - The response data as a UTF-8 string. - - Raises: - RuntimeError: If the reply contains a network error. - """ - if reply.error() == QNetworkReply.NetworkError.NoError: - response_data = reply.readAll().data().decode("utf-8") - reply.deleteLater() - return response_data - else: - reply.deleteLater() - logger.error(f"Error in response: {reply.errorString()}") - raise RuntimeError(reply.errorString()) - - def _compose_device_status_message( - self, - *, - tell_conn: bool, - smargon_conn: bool, - aerotech_conn: bool, - tell_changed: bool, - smargon_changed: bool, - aerotech_changed: bool, - ) -> tuple[str | None, str | None, bool]: - disconnected: list[str] = [] - restored: list[str] = [] - - if not tell_conn: - disconnected.append("TELL") - elif tell_changed: - restored.append("TELL") - - if not smargon_conn: - disconnected.append("Smargon") - elif smargon_changed: - restored.append("Smargon") - - if not aerotech_conn: - disconnected.append("Aerotech") - elif aerotech_changed: - restored.append("Aerotech") - - if disconnected: - if len(disconnected) == 3: - return ("all-devices-down", "TELL, Smargon, and Aerotech disconnected.", True) - if len(disconnected) == 2: - return ( - "+".join(sorted(d.lower() for d in disconnected)) + "-down", - f"{disconnected[0]} and {disconnected[1]} disconnected.", - True, - ) - device = disconnected[0] - return (f"{device.lower()}-down", f"{device} disconnected.", True) - - if restored: - if len(restored) == 3: - return (None, "TELL, Smargon, and Aerotech reconnected.", False) - if len(restored) == 2: - return (None, f"{restored[0]} and {restored[1]} reconnected.", False) - return (None, f"{restored[0]} reconnected.", False) - - return (None, None, False) - - @Slot(QNetworkReply) - def handle_status_response(self, reply: QNetworkReply): - """ - Handle the server's response to a status request. - - Args: - reply: The QNetworkReply object. - """ - try: - response_data = self.handle_response(reply) - parsed_response = DAQStatusModel.model_validate_json(response_data) - self.update.emit(parsed_response) - - pss_alarm = bool(getattr(getattr(parsed_response, "bl", None), "pss_alarm", False)) - if pss_alarm != self._last_pss_alarm: - self._last_pss_alarm = pss_alarm - self.pss_alarm_changed.emit(pss_alarm) - - self._last_status_can_read = True - self._restart_blocked_sse_streams_if_access_restored() - - # Handle server reconnection - show "Server reconnected" not device messages - if self._server_connected is False and self._has_seen_disconnection: - self._emit_status_if_changed(None, "Server reconnected.", False) - # Reset device states so we don't also emit device reconnection messages - self._last_tell_connected = None - self._last_smargon_connected = None - self._last_aerotech_connected = None - self._server_was_disconnected = False - - self._server_connected = True - self._last_server_error = None - - smargon_conn = bool(getattr(parsed_response, "smargon_connected", True)) - smargon_err = getattr(parsed_response, "smargon_error", None) - tell_conn = bool(getattr(parsed_response, "tell_connected", True)) - tell_err = getattr(parsed_response, "tell_error", None) - aerotech_conn = bool(getattr(parsed_response, "aerotech_connected", True)) - aerotech_err = getattr(parsed_response, "aerotech_error", None) - - tell_err_text = None if tell_err is None else str(tell_err).strip() - smargon_err_text = None if smargon_err is None else str(smargon_err).strip() - aerotech_err_text = None if aerotech_err is None else str(aerotech_err).strip() - - # Skip device status processing if we just reconnected from server down - # (we already showed "Server reconnected") - if ( - self._last_tell_connected is None - and self._last_smargon_connected is None - and self._last_aerotech_connected is None - ): - # First status after startup or server reconnect - just record states, don't emit - self._last_tell_connected = tell_conn - self._last_smargon_connected = smargon_conn - self._last_aerotech_connected = aerotech_conn - self._last_tell_error = tell_err_text - self._last_smargon_error = smargon_err_text - self._last_aerotech_error = aerotech_err_text - return - - tell_changed = ( - self._last_tell_connected != tell_conn or self._last_tell_error != tell_err_text - ) - smargon_changed = ( - self._last_smargon_connected != smargon_conn - or self._last_smargon_error != smargon_err_text - ) - aerotech_changed = ( - self._last_aerotech_connected != aerotech_conn - or self._last_aerotech_error != aerotech_err_text - ) - - self._last_tell_connected = tell_conn - self._last_smargon_connected = smargon_conn - self._last_aerotech_connected = aerotech_conn - self._last_tell_error = tell_err_text - self._last_smargon_error = smargon_err_text - self._last_aerotech_error = aerotech_err_text - - status_key, status_msg, is_error = self._compose_device_status_message( - tell_conn=tell_conn, - smargon_conn=smargon_conn, - aerotech_conn=aerotech_conn, - tell_changed=tell_changed, - smargon_changed=smargon_changed, - aerotech_changed=aerotech_changed, - ) - self._emit_status_if_changed(status_key, status_msg, is_error) - - if not tell_conn: - self._log_device_error_throttled(device="tell", message=tell_err) - if not smargon_conn: - self._log_device_error_throttled(device="smargon", message=smargon_err) - if not aerotech_conn: - self._log_device_error_throttled(device="aerotech", message=aerotech_err) - - except Exception as e: - status = None - err_msg = str(e) - - try: - status = reply.attribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute) - raw_body = reply.readAll().data().decode("utf-8") - if raw_body: - body_json = json.loads(raw_body) - if isinstance(body_json, dict): - err_msg = body_json.get("message") or body_json.get("detail") or err_msg - if body_json.get("code") == "AEROTECH_UNAVAILABLE": - extra = body_json.get("extra") or {} - if isinstance(extra, dict): - aerotech_detail = extra.get("message") - if aerotech_detail: - err_msg = aerotech_detail - except Exception: - logger.exception("Exception reading status response") - - if status == 403: - self._last_status_can_read = False - elif status is not None: - self._last_status_can_read = None - - if status == 503: - if self._server_connected is not False: - self._has_seen_disconnection = True - self._server_was_disconnected = True - self._emit_status_if_changed( - "server-down", f"Aerotech unavailable: {err_msg}", True - ) - else: - if self._server_connected is not False: - self._has_seen_disconnection = True - self._server_was_disconnected = True - self._emit_status_if_changed( - "server-down", "Server disconnected. Reconnecting...", True - ) - - self._server_connected = False - self._last_server_error = err_msg - self._last_tell_connected = None - self._last_smargon_connected = None - self._last_aerotech_connected = None - - logger.exception("Exception from status response") - - @Slot(QNetworkReply) - def handle_spreadsheet_response(self, reply: QNetworkReply): - try: - response_data = self.handle_response(reply) - parsed_response = SampleShortInfoList.model_validate_json(response_data) - self.spreadsheet.emit(parsed_response) - except Exception as e: - logger.exception("Exception from spreadsheet response") - self.http_error.emit(str(e)) - - @Slot(QNetworkReply) - def handle_reference_tools_response(self, reply: QNetworkReply): - # not accumulate errors from reference tools, just log them - if reply.error() != QNetworkReply.NetworkError.NoError: - logger.debug(f"Reference tools request failed: {reply.errorString()}") - reply.deleteLater() - return - try: - response_data = self.handle_response(reply) - parsed_response = SampleShortInfoList.model_validate_json(response_data) - self.reference_tools.emit(parsed_response) - except Exception: - # demote reference tool exception to debug - logger.debug("Exception from reference tools response", exc_info=True) - - def handle_req_response(self, reply: QNetworkReply): - if reply.error() != QNetworkReply.NetworkError.NoError: - status, err_details, body_json = self._extract_reply_error_details(reply) - error_info = self._classify_reply_error(status, err_details, body_json) - - raw_body = "" - try: - raw_body = reply.readAll().data().decode("utf-8") - except Exception: - logger.debug("Could not read the raw reply body", exc_info=True) - - try: - url = reply.request().url().toString() - except Exception: - logger.debug("Could not read the request URL", exc_info=True) - url = "" - - net_err = reply.error() - net_err_name = getattr(net_err, "name", None) - net_err_value = getattr(net_err, "value", None) - - self._set_last_error_payload( - { - "url": url, - "http_status": int(status) if status is not None else None, - "network_error": net_err_name or str(net_err), - "network_error_value": int(net_err_value) - if isinstance(net_err_value, int) - else None, - "error_string": str(reply.errorString()), - "body_raw": raw_body, - "body_json": body_json, - } - ) - - if self._is_auth_error_code(error_info.code) or status == 401: - now = time.monotonic() - if now - self._last_auth_error_log_ts > self._auth_error_min_interval: - logger.error(f"{error_info.message}: baton taken by another user") - self._last_auth_error_log_ts = now - self.auth_error.emit() - elif status in (404, 410, 417): - self.sample_missing.emit(error_info.message) - elif error_info.code in QUIET_OPERATION_ERROR_CODES: - pass - else: - logger.error(f"{error_info.message}") - title = self._operation_error_title(error_info.exception_class) - self.operation_failed.emit(title, error_info.message, error_info.critical) - - reply.deleteLater() - - @staticmethod - def _operation_error_title(exception_class: str | None) -> str: - """Human-friendly dialog title from an exception class name. - - ``MountingFailed`` -> ``"Mounting Failed"``; falls back to - ``"Operation Failed"`` when the class is unknown. - """ - if not exception_class: - return "Operation Failed" - spaced = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", " ", exception_class) - spaced = spaced.replace("Exception", "Error").strip() - return spaced or "Operation Failed" - - def _handle_sample_resync_response(self, reply: QNetworkReply): - try: - response_data = self.handle_response(reply) - payload = json.loads(response_data) if response_data else {} - message = str(payload.get("message") or "TELL sample cache resynced.") - logger.info(message) - self.status_message.emit(message, False) - self.sample_resync_completed.emit(message) - self.send_status_request() - except Exception as e: - logger.exception("Sample resync failed") - self.http_error.emit(str(e)) - - def _handle_detector_metadata_resync_response(self, reply: QNetworkReply): - try: - response_data = self.handle_response(reply) - payload = json.loads(response_data) if response_data else {} - message = str(payload.get("message") or "Hardware metadata cache resynced.") - logger.info(message) - self.status_message.emit(message, False) - self.detector_metadata_resync_completed.emit(message) - self.send_status_request() - self.load_local_contact_device_state() - except Exception as e: - logger.exception("Hardware metadata resync failed") - self.http_error.emit(str(e)) - - def _handle_recovery_action_response(self, reply: QNetworkReply, default_message: str): - try: - response_data = self.handle_response(reply) - payload = json.loads(response_data) if response_data else {} - if not isinstance(payload, dict): - message = str(payload) - else: - message = str(payload.get("message") or default_message) - logger.info(message) - self.status_message.emit(message, False) - self.recovery_action_completed.emit(message) - self.send_status_request() - except Exception as e: - logger.exception("Recovery action failed") - self.http_error.emit(str(e)) - - def _emit_placeholder_local_contact_action(self, action_name: str) -> None: - message = f"{action_name}: This hasn't been connected yet." - logger.info(message) - self.status_message.emit(message, False) - - def generic_post(self, url: str, body: str = ""): - """ - Send a generic HTTP POST request to the server. - - Args: - url: The relative URL (endpoint). - body: The request body string. - """ - if self._base_url is None: - logger.info(f"POST /{url}: {body}") - return None - - request = QNetworkRequest(QUrl(f"{self._base_url}/{url}")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - if str: - request.setRawHeader(b"Content-Type", b"application/json") - reply = self._net_manager.post(request, QByteArray(body.encode("utf-8"))) - reply.finished.connect(lambda: self.handle_req_response(reply)) - return reply - - def generic_put(self, url: str, body: str = ""): - """ - Send a generic HTTP PUT request to the server. - - Args: - url: The relative URL (endpoint). - body: The request body string. - """ - if self._base_url is None: - logger.info(f"PUT /{url}: {body}") - return - request = QNetworkRequest(QUrl(f"{self._base_url}/{url}")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - if str: - request.setRawHeader(b"Content-Type", b"application/json") - reply = self._net_manager.put(request, QByteArray(body.encode("utf-8"))) - reply.finished.connect(lambda: self.handle_req_response(reply)) - - def generic_delete(self, url: str): - """ - Send a generic HTTP DELETE request to the server. - - Args: - url: The relative URL (endpoint). - """ - if self._base_url is None: - logger.info(f"DELETE /{url}") - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/{url}")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.deleteResource(request) - reply.finished.connect(lambda: self.handle_req_response(reply)) - - @Slot(float) - def set_omega(self, f: float): - self.generic_put(f"beamline/omega?val={f:.3f}") - - @Slot(float) - def set_omega_rel(self, f: float): - self.generic_put(f"beamline/omega_rel?val={f:.3f}") - - @Slot(float) - def zoom(self, f: float): - self.generic_put(f"beamline/zoom?val={f:.3f}") - - @Slot() - def mono_pitch_scan(self): - self.generic_post("beamline/mono_pitch_scan") - - @Slot() - def steer_beam(self): - self.generic_post("beamline/steer_beam") - - def update_steer_beam_available(self): - """Check if beam steering is supported by the server. The result is emitted from DaqWorker.steer_beam_available when ready""" - if self._base_url is None: - return False - request = QNetworkRequest(QUrl(f"{self._base_url}/beamline/steer_beam_available")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.finished.connect(lambda: self._update_steer_beam_available(reply)) - - def _update_steer_beam_available(self, reply: QNetworkReply): - self.steer_beam_available.emit(json.loads(bytes(reply.readAll().data()))) - - @Slot(float) - def change_energy(self, value: float): - self.generic_put(f"beamline/change_energy?value={value:.3f}") - - @Slot(int) - def front_light(self, v: int): - self.generic_put(f"beamline/front_light?val={v:d}") - - @Slot(int) - def back_light(self, v: int): - self.generic_put(f"beamline/back_light?val={v:d}") - - @Slot() - def close_shutter(self): - self.generic_post("beamline/shutter?val=false") - - @Slot() - def open_shutter(self): - self.generic_post("beamline/shutter?val=true") - - @Slot() - def center_loop(self): - # The endpoint blocks server-side until centering ends, so the reply - # doubles as the "done" edge for the camera overlay. - reply = self.generic_post("alc/center_loop") - if reply is None: - return - self._set_centering(manual=True) - reply.finished.connect(lambda: self._set_centering(manual=False)) - - def _set_centering(self, *, manual: bool | None = None, automation: bool | None = None): - if manual is not None: - self._manual_centering = manual - if automation is not None: - self._automation_centering = automation - self.auto_centering.emit(self._manual_centering or self._automation_centering) - - @Slot() - def force_session(self): - self.generic_post("access/force_current_session") - - @Slot() - def end_session(self): - self.generic_post("access/end_session") - - @Slot() - def dewar_exchange(self): - self.generic_post("state/dewar_exchange") - - @Slot() - def sample_exchange(self): - self.generic_post("state/sample_exchange") - - @Slot() - def sample_alignment(self): - self.generic_post("state/sample_alignment") - - @Slot() - def beam_location(self): - self.generic_post("state/beam_location") - - @Slot() - def beamstop_alignment(self): - self.generic_post("state/beamstop_alignment") - - @Slot() - def flux_measurement(self): - self.generic_post("state/flux_measurement") - - @Slot() - def data_collection(self): - self.generic_post("state/data_collection") - - @Slot() - def robot_sample_exchange(self): - self.generic_post("state/robot_sample_exchange") - - @Slot() - def xray_fluorescence(self): - self.generic_post("state/xray_fluorescence") - - @Slot() - def xtal_snapshot(self): - self.generic_post("state/xtal_snapshot") - - @Slot(str) - def force_clear_busy(self, confirmation_code: str): - if self._base_url is None: - logger.info("POST /state/force_clear_busy") - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/state/force_clear_busy")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - body = json.dumps({"confirmation_code": confirmation_code}) - reply = self._net_manager.post(request, QByteArray(body.encode("utf-8"))) - reply.finished.connect( - lambda: self._handle_recovery_action_response(reply, "Beamline busy flag cleared.") - ) - - @Slot(str) - def take_over_beamline(self, confirmation_code: str): - if self._base_url is None: - logger.info("POST /access/take_over_beamline") - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/access/take_over_beamline")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - body = json.dumps({"confirmation_code": confirmation_code}) - reply = self._net_manager.post(request, QByteArray(body.encode("utf-8"))) - reply.finished.connect( - lambda: self._handle_recovery_action_response(reply, "Beamline session taken over.") - ) - - @Slot(str) - def force_maintenance_state(self, confirmation_code: str): - if self._base_url is None: - logger.info("POST /recovery/force_maintenance_state") - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/recovery/force_maintenance_state")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - body = json.dumps({"confirmation_code": confirmation_code}) - reply = self._net_manager.post(request, QByteArray(body.encode("utf-8"))) - reply.finished.connect( - lambda: self._handle_recovery_action_response( - reply, "Beamline recovered to Maintenance." - ) - ) - - @Slot(str) - def recovery_unmount_sample(self, confirmation_code: str): - if self._base_url is None: - logger.info("POST /recovery/unmount_sample") - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/recovery/unmount_sample")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - body = json.dumps({"confirmation_code": confirmation_code}) - reply = self._net_manager.post(request, QByteArray(body.encode("utf-8"))) - reply.finished.connect( - lambda: self._handle_recovery_action_response(reply, "Recovery unmount completed.") - ) - - @Slot(str) - def set_pgroup(self, val: str): - if val == "": - self.generic_delete("access/pgroup") - else: - self.generic_put(f"access/pgroup?val={val}") - self._face_detection_stream_blocked_403 = False - self._automation_progress_stream_blocked_403 = False - self.send_status_request() - self.start_face_detection_stream() - self.start_automation_progress_stream() - - @Slot(QNetworkReply) - def _handle_all_pgroups_response(self, reply: QNetworkReply): - try: - response_data = self.handle_response(reply) - import json - - arr = json.loads(response_data) if response_data else [] - if not isinstance(arr, list): - raise TypeError("Invalid all_pgroups payload") - # Ensure list[str] - out = [str(x) for x in arr if isinstance(x, (str, int))] - self.staff_pgroups_loaded.emit(out) - except Exception as e: - logger.exception("Exception from all_pgroups response") - self.http_error.emit(str(e)) - - @Slot() - def get_all_pgroups(self): - logger.debug("PUT /access/all_pgroups") - if self._base_url is None: - self.staff_pgroups_loaded.emit([]) - return - request = QNetworkRequest(QUrl(f"{self._base_url}/access/all_pgroups")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - reply = self._net_manager.put(request, QByteArray(b"")) - reply.finished.connect(lambda: self._handle_all_pgroups_response(reply)) - - @Slot(SampleCameraSettings) - def samcam_settings(self, s: SampleCameraSettings): - self.generic_put("beamline/samcam", s.model_dump_json()) - - @Slot(AutofocusSettings) - def autofocus(self, f: AutofocusSettings): - self.generic_post("samcam/autofocus", f.model_dump_json()) - - @Slot(SmargonCoordinate) - def move_smargon(self, coord: SmargonCoordinate): - self.generic_put("beamline/smargon", coord.model_dump_json()) - - def handle_rotation_scan_response(self, reply: QNetworkReply): - try: - # Check for HTTP errors first - if reply.error() != QNetworkReply.NetworkError.NoError: - status, err_msg, body_json = self._extract_reply_error_details(reply) - - if self._is_detector_state_failure_message(err_msg): - self._emit_detector_message(f"JFJoch: {err_msg}", is_error=True) - else: - code = body_json.get("code", "") if isinstance(body_json, dict) else "" - if code == AareErrorCode.JF_JOCH_COMMUNICATION_ERROR or status == 503: - self._emit_detector_message(f"JFJoch: {err_msg}", is_error=True) - - if self._is_critical_detector_failure(status, body_json, err_msg): - critical_msg = ( - "Manual collection stopped because there is an error with the detector. " - "Please call your local contact.\n\n" - f"Details: {err_msg}" - ) - self._emit_detector_message( - f"Detector error during manual collection: {err_msg}", is_error=True - ) - self._emit_manual_collection_critical_failure(critical_msg) - - short_msg = ( - err_msg.split("input':", 1)[0].strip() if "input':" in err_msg else err_msg - ) - logger.error(f"Rotation scan failed: {short_msg}") - self.http_error.emit(short_msg) - reply.deleteLater() - return - - response_data = self.handle_response(reply) - parsed_response = CompletedRotationScan.model_validate_json(response_data) - self.standard_scan_completed.emit(parsed_response) - except Exception as e: - logger.exception("Exception from rotation scan response") - self.http_error.emit(str(e)) - finally: - reply.deleteLater() - - @Slot(RotationScanRequest) - def standard_scan(self, r: RotationScanRequest): - """ - Trigger a standard rotation scan. - - Args: - r: The RotationScanRequest object. - """ - self.run_number_incremented.emit() - - request = QNetworkRequest(QUrl(f"{self._base_url}/scan/rotation")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - body = r.model_dump_json() - reply = self._net_manager.post(request, QByteArray(body.encode("utf-8"))) - reply.finished.connect(lambda: self.handle_rotation_scan_response(reply)) - - def handle_raster_scan_response(self, reply: QNetworkReply): - try: - # Check for HTTP errors first - if reply.error() != QNetworkReply.NetworkError.NoError: - status, err_msg, body_json = self._extract_reply_error_details(reply) - - if self._is_detector_state_failure_message(err_msg): - self._emit_detector_message(f"JFJoch: {err_msg}", is_error=True) - else: - code = body_json.get("code", "") if isinstance(body_json, dict) else "" - if code == AareErrorCode.JF_JOCH_COMMUNICATION_ERROR or status == 503: - self._emit_detector_message(f"JFJoch: {err_msg}", is_error=True) - - if self._is_critical_detector_failure(status, body_json, err_msg): - critical_msg = ( - "Manual collection stopped because there is an error with the detector. " - "Please call your local contact.\n\n" - f"Details: {err_msg}" - ) - self._emit_detector_message( - f"Detector error during manual collection: {err_msg}", is_error=True - ) - self._emit_manual_collection_critical_failure(critical_msg) - - logger.error(f"Raster scan failed: {err_msg}") - self.http_error.emit(err_msg) - reply.deleteLater() - return - - response_data = self.handle_response(reply) - parsed_response = CompletedRasterGrid.model_validate_json(response_data) - self.raster_scan_completed.emit(parsed_response) - except Exception as e: - logger.exception("Exception from raster scan response") - self.http_error.emit(str(e)) - finally: - reply.deleteLater() - - @Slot(RasterGridRequest) - def raster_scan(self, r: RasterGridRequest): - """ - Trigger a raster scan. - - Args: - r: The RasterGridRequest object. - """ - self.run_number_incremented.emit() - if self._base_url is None: - logger.info(f"POST /scan/raster: {r.model_dump_json()}") - image_number = r.get_image_number() - new_copy = copy.deepcopy(r) - - images = [] - - for i in range(image_number): - images.append( - ScanResultImagesInner( - number=i, - efficiency=1.0, - bkg=random.gauss(3.0, 0.1), - spots=random.randint(0, 250), - index=random.randint(0, 1), - b=random.uniform(15.0, 80.0), - ) - ) - raster_elem = CompletedRasterGridElem( - request=new_copy, - result=ScanResult(file_prefix=r.file_prefix, images=images), - centre_of_mass=None, - ) - reply = CompletedRasterGrid(r=[raster_elem]) - self.raster_scan_completed.emit(reply) - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/scan/raster?auto_center=false")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - body = r.model_dump_json() - reply = self._net_manager.post(request, QByteArray(body.encode("utf-8"))) - reply.finished.connect(lambda: self.handle_raster_scan_response(reply)) - - @Slot(RasterGridRequest) - def raster_scan_auto(self, r: RasterGridRequest): - """ - Trigger an automated raster scan. - - Args: - r: The RasterGridRequest object. - """ - self.run_number_incremented.emit() - if self._base_url is None: - logger.info(f"POST /scan/raster: {r.model_dump_json()}") - image_number = r.get_image_number() - new_copy = copy.deepcopy(r) - - images = [] - for i in range(image_number): - images.append( - ScanResultImagesInner( - number=i, - efficiency=1.0, - bkg=random.gauss(3.0, 0.1), - spots=random.randint(0, 250), - index=random.randint(0, 1), - b=random.uniform(15.0, 80.0), - ) - ) - raster_elem = CompletedRasterGridElem( - request=new_copy, - result=ScanResult(file_prefix=r.file_prefix, images=images), - centre_of_mass=None, - ) - reply = CompletedRasterGrid(r=[raster_elem]) - self.raster_scan_completed.emit(reply) - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/scan/raster?auto_center=true")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - body = r.model_dump_json() - reply = self._net_manager.post(request, QByteArray(body.encode("utf-8"))) - reply.finished.connect(lambda: self.handle_raster_scan_response(reply)) - - @Slot() - def load_spreadsheet(self): - if self._base_url is None: - # TODO: log spam. This (and load_reference_tools) fires every - # SPREADHSEET_FREQUENCY cycle (~12.5s) while base_url is None, - # logging a GET it never actually sends -> two INFO lines every - # poll. Fix by demoting to logger.debug, or log once on the - # None->set edge rather than on every poll. - logger.info("GET /sample/spreadsheet") - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/sample/spreadsheet")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.finished.connect(lambda: self.handle_spreadsheet_response(reply)) - - @Slot() - def load_reference_tools(self): - if self._base_url is None: - logger.info("GET /sample/reference_tools") - return - request = QNetworkRequest(QUrl(f"{self._base_url}/sample/reference_tools")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.finished.connect(lambda: self.handle_reference_tools_response(reply)) - - def _emit_manual_collection_critical_failure(self, msg: str) -> None: - if not msg: - return - if msg == self._last_manual_collection_critical_msg: - return - self._last_manual_collection_critical_msg = msg - self.manual_collection_critical_failure.emit(msg) - - @staticmethod - def _load_recurrence_watchers(): - beamline = os.getenv("AARE_BEAMLINE", "default") - watcher_names = [name for name, *_ in DEFAULT_WATCHERS] - overrides = load_watcher_threshold_overrides( - beamline=beamline, - watcher_names=watcher_names, - get_value=lambda k: os.getenv(redis_key_to_env_var(k)), - ) - return create_default_watchers(overrides) - - def _reset_recurrence_watchers(self) -> None: - for watcher in self._recurrence_watchers: - watcher.reset() - - def _observe_recurrence(self, exception_class_name: str | None) -> WatcherTrip | None: - exception_class = resolve_exception_class(exception_class_name) - for watcher in self._recurrence_watchers: - trip = watcher.maybe_trip(exception_class) - if trip is not None: - return trip - return None - - def _emit_watcher_trip(self, trip: WatcherTrip) -> None: - message = trip.message() - logger.critical(message) - self.http_error.emit(message) - self.automation_critical_failure.emit(message) - - @staticmethod - def _extract_reply_error_details(reply: QNetworkReply) -> tuple[int | None, str, dict | None]: - status = reply.attribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute) - err_msg = reply.errorString() - body_json = None - - try: - raw_body = reply.readAll().data().decode("utf-8") - if raw_body: - try: - parsed = json.loads(raw_body) - if isinstance(parsed, dict): - body_json = parsed - err_msg = ( - parsed.get("message") - or parsed.get("detail") - or parsed.get("error") - or raw_body - ) - else: - err_msg = raw_body - except Exception: - logger.debug("Could not parse the error body as JSON", exc_info=True) - err_msg = raw_body - except Exception: - logger.debug("Could not extract error details from the reply body", exc_info=True) - - return status, str(err_msg), body_json - - @staticmethod - def _is_critical(body_json: dict | None) -> bool: - if not isinstance(body_json, dict): - return True - return bool(body_json.get("critical", True)) - - @staticmethod - def _classify_reply_error( - status: int | None, err_msg: str, body_json: dict | None - ) -> ErrorInfo: - code = body_json.get("code") if isinstance(body_json, dict) else None - exception_class = body_json.get("exception_class") if isinstance(body_json, dict) else None - context = body_json.get("context") if isinstance(body_json, dict) else {} - if not isinstance(context, dict): - context = {} - return ErrorInfo( - critical=DAQWorker._is_critical(body_json), - code=str(code) if code is not None else None, - exception_class=str(exception_class) if exception_class is not None else None, - message=str(err_msg or ""), - context=context, - ) - - @staticmethod - def _is_auth_error_code(code: str | None) -> bool: - if code is None: - return False - try: - return code in {item.value for item in AuthErrorCode} - except Exception: - logger.debug("Could not classify the reply as an auth error", exc_info=True) - return False - - @staticmethod - def _is_detector_state_failure_message(message: str | None) -> bool: - text = str(message or "").lower() - return ( - "daq state error" in text - or "must be idle to start measurement" in text - or "must be idle" in text - ) - - @staticmethod - def _is_critical_detector_failure( - status: int | None, body_json: dict | None = None, err_msg: str | None = None - ) -> bool: - try: - status_int = int(status) if status is not None else None - except Exception: - logger.debug("Could not read the reply status code", exc_info=True) - status_int = None - - code = None - if isinstance(body_json, dict): - code = body_json.get("code") - - text = str(err_msg or "").lower() - - if status_int == 500: - return True - - if ( - code == AareErrorCode.JF_JOCH_COMMUNICATION_ERROR - and status_int is not None - and 500 <= status_int < 600 - ): - return True - - return bool( - "daq state error" in text - or "must be idle to start measurement" in text - or "must be idle" in text - ) - - def handle_auto_scan_response(self, reply, sample_id: int): - if reply.error() == QNetworkReply.NetworkError.NoError: - resp = reply.readAll().data().decode("utf-8") - logger.info(f"Sample time {resp} s") - self._reset_recurrence_watchers() - self.automated_scan_done.emit(sample_id, True, "") - else: - status, err_str, body_json = self._extract_reply_error_details(reply) - error_info = self._classify_reply_error(status, err_str, body_json) - watcher_trip = self._observe_recurrence(error_info.exception_class) - - if self._is_detector_state_failure_message(error_info.message): - self._emit_detector_message(f"JFJoch: {error_info.message}", is_error=True) - - if self._is_auth_error_code(error_info.code) or status == 401: - logger.error(f"Error in auto scan: {error_info.message}") - self.automated_scan_done.emit(sample_id, False, "Authentication Error") - self.auth_error.emit() - elif status == 404: - self.sample_missing.emit(error_info.message) - self.automated_scan_done.emit(sample_id, False, "Missing") - elif status == 410: - self.sample_missing.emit(error_info.message) - self.automated_scan_done.emit(sample_id, False, "Warning") - elif status == 417: - self.sample_missing.emit(error_info.message) - self.automated_scan_done.emit(sample_id, False, "Critical") - elif watcher_trip is not None: - self.automated_scan_done.emit(sample_id, False, "Critical") - self._emit_watcher_trip(watcher_trip) - elif error_info.critical: - logger.critical(f"Critical automation failure: {error_info.message}") - self.http_error.emit(error_info.message) - self.automated_scan_done.emit(sample_id, False, "Critical") - self.automation_critical_failure.emit(error_info.message) - else: - logger.error(f"Error in auto scan: {error_info.message}") - self.http_error.emit(error_info.message) - self.automated_scan_done.emit(sample_id, False, error_info.message) - reply.deleteLater() - - @Slot(SampleShortInfo) - def automated_scan(self, s: SampleShortInfo): - """ - Trigger a fully automated scan sequence for a sample. - - Args: - s: The SampleShortInfo object. - """ - if self._base_url is None: - logger.info(f"POST /scan/auto: {s.model_dump_json()}") - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/scan/auto")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - body = s.model_dump_json() - reply = self._net_manager.post(request, QByteArray(body.encode("utf-8"))) - reply.finished.connect(lambda: self.handle_auto_scan_response(reply, s.db_id)) - - @Slot(SimpleScanParameters) - def smart_params(self, p: SimpleScanParameters): - if self._base_url is None: - logger.info(f"POST /scan/smart_params: {p.model_dump_json()}") - return - self.generic_post("scan/smart_params", p.model_dump_json()) - - @Slot(AerotechCoordinate) - def abr_tweak(self, c: AerotechCoordinate): - self.generic_post("beamline/tweak_abr_meas_pos", c.model_dump_json()) - - @Slot() - def abr_save(self): - self.generic_post("beamline/save_abr_meas_pos") - - @Slot() - def abr_goto_meas(self): - self.generic_post("beamline/goto_abr_meas_pos") - - @Slot(float, float) - def beam_mark_add(self, x: float, y: float): - self.generic_post(f"beam_mark/add?x={x}&y={y}") - - @Slot() - def beam_mark_clear(self): - self.generic_post("beam_mark/clear") - - @Slot(float, float) - def beam_center(self, x: float, y: float): - self.generic_post(f"beamline/beam_center?x={x}&y={y}") - - @Slot(float, float) - def beam_size_mm(self, x: float, y: float): - self.generic_post(f"beamline/beam_size_mm?x={x}&y={y}") - - @Slot() - def resync_sample(self): - if self._base_url is None: - logger.info("POST /sample/resync") - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/sample/resync")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - reply = self._net_manager.post(request, QByteArray(b"")) - reply.finished.connect(lambda: self._handle_sample_resync_response(reply)) - - @Slot() - def resync_local_contact_detector_metadata(self): - if self._base_url is None: - logger.info("POST /local_contact/resync/detector_metadata") - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/local_contact/resync/detector_metadata")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - reply = self._net_manager.post(request, QByteArray(b"")) - reply.finished.connect(lambda: self._handle_detector_metadata_resync_response(reply)) - - @Slot(float) - def anneal(self, time_s: float): - self.generic_post(f"beamline/anneal?time_s={time_s:.1f}") - - @Slot() - def unmount_then_park_and_dry(self): - self.generic_post("sample/unmount_then_park_and_dry") - - @Slot() - def park_and_dry(self): - self.generic_post("tell/park_and_dry") - - @Slot() - def tell_dry(self): - self.generic_post("tell/dry") - - @Slot() - def tell_toggle_blower(self): - self.generic_post("tell/toggle_blower") - - def _disable_local_contact_metadata_polling(self, message: str) -> None: - if ( - self._local_contact_metadata_poll_enabled is False - and self._local_contact_metadata_error == message - ): - return - self._local_contact_metadata_poll_enabled = False - self._local_contact_metadata_error = message - logger.error(f"Disabling Local Contact metadata polling: {message}") - self.local_contact_transfer_error.emit(message) - - def _build_local_contact_error_message( - self, context: str, reply: QNetworkReply, exc: Exception - ) -> str: - status = reply.attribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute) - try: - url = reply.request().url().toString() - except Exception: - logger.debug("Could not read the request URL", exc_info=True) - url = "unknown-url" - - return f"{context}\n\nURL: {url}\nHTTP status: {status}\nError: {exc}" - - @Slot() - def load_local_contact_simulation_state(self): - if not self._local_contact_metadata_poll_enabled: - return - - if self._base_url is None: - self.local_contact_simulation_state_loaded.emit( - { - "bec": False, - "detector": False, - "tell": False, - "aerotech": False, - "smargon": False, - } - ) - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/local_contact/simulation_state")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.finished.connect(lambda: self._handle_local_contact_simulation_state_response(reply)) - - def _handle_local_contact_simulation_state_response(self, reply: QNetworkReply): - try: - response_data = self.handle_response(reply) - payload = json.loads(response_data) if response_data else {} - if not isinstance(payload, dict): - raise TypeError("Invalid local contact simulation state payload") - self.local_contact_simulation_state_loaded.emit(payload) - except Exception as e: - logger.warning("Local Contact simulation state request failed", exc_info=True) - message = self._build_local_contact_error_message( - "Error transferring information from DAQ while loading Local Contact simulation state.", - reply, - e, - ) - self._disable_local_contact_metadata_polling(message) - - @Slot() - def load_local_contact_device_state(self): - if not self._local_contact_metadata_poll_enabled: - return - - if self._base_url is None: - self.local_contact_device_state_loaded.emit({}) - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/local_contact/device_state")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.finished.connect(lambda: self._handle_local_contact_device_state_response(reply)) - - def _handle_local_contact_device_state_response(self, reply: QNetworkReply): - try: - response_data = self.handle_response(reply) - payload = json.loads(response_data) if response_data else {} - if not isinstance(payload, dict): - raise TypeError("Invalid local contact device state payload") - self.local_contact_device_state_loaded.emit(payload) - except Exception as e: - logger.warning("Local Contact device state request failed", exc_info=True) - message = self._build_local_contact_error_message( - "Error transferring information from DAQ while loading Local Contact device state.", - reply, - e, - ) - self._disable_local_contact_metadata_polling(message) - - @Slot() - def load_local_contact_links(self): - if not self._local_contact_metadata_poll_enabled: - return - - if self._base_url is None: - self.local_contact_links_loaded.emit({}) - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/local_contact/links")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.finished.connect(lambda: self._handle_local_contact_links_response(reply)) - - def _handle_local_contact_links_response(self, reply: QNetworkReply): - try: - response_data = self.handle_response(reply) - payload = json.loads(response_data) if response_data else {} - if not isinstance(payload, dict): - raise TypeError("Invalid local contact links payload") - self.local_contact_links_loaded.emit(payload) - except Exception as e: - logger.warning("Local Contact links request failed", exc_info=True) - message = self._build_local_contact_error_message( - "Error transferring information from DAQ while loading Local Contact links.", - reply, - e, - ) - self._disable_local_contact_metadata_polling(message) - - @Slot() - def load_local_contact_config(self): - if self._base_url is None: - self.local_contact_config_loaded.emit( - { - "mount_to_center_sleep_s": 0.0, - "line_scan_loop_face_y_padding_fraction_each_side": 0.5, - "line_scan_loop_all_y_padding_fraction_each_side": 0.5, - } - ) - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/local_contact/config")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.finished.connect(lambda: self._handle_local_contact_config_response(reply)) - - def _handle_local_contact_config_response(self, reply: QNetworkReply): - try: - response_data = self.handle_response(reply) - payload = json.loads(response_data) if response_data else {} - if not isinstance(payload, dict): - raise TypeError("Invalid local contact config payload") - self.local_contact_config_loaded.emit(payload) - except Exception as e: - message = ( - "Error transferring information from DAQ while loading Local Contact config.\n\n" - f"{e}" - ) - logger.exception(message) - self.local_contact_transfer_error.emit(message) - - @Slot(dict) - def set_local_contact_config(self, payload: dict): - if self._base_url is None: - self.local_contact_config_saved.emit(payload) - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/local_contact/config")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - body = QByteArray(json.dumps(payload).encode("utf-8")) - reply = self._net_manager.put(request, body) - reply.finished.connect(lambda: self._handle_set_local_contact_config_response(reply)) - - def _handle_set_local_contact_config_response(self, reply: QNetworkReply): - try: - response_data = self.handle_response(reply) - payload = json.loads(response_data) if response_data else {} - if not isinstance(payload, dict): - raise TypeError("Invalid local contact config response") - self.local_contact_config_saved.emit(payload) - self.local_contact_config_loaded.emit(payload) - self.status_message.emit("Local Contact config saved.", False) - except Exception as e: - message = ( - f"Error transferring information from DAQ while saving Local Contact config.\n\n{e}" - ) - logger.exception(message) - self.local_contact_transfer_error.emit(message) - - def refresh_gridscan_analysis_mode(self): - request = QNetworkRequest(QUrl(f"{self._base_url}/local_contact/gridscan_analysis_mode")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.finished.connect( - lambda: self.gridscan_analysis_mode.emit(self.handle_response(reply)) - ) - - def set_gridscan_analysis_mode(self, value: GridscanAnalysisMode): - request = QNetworkRequest( - QUrl(f"{self._base_url}/local_contact/gridscan_analysis_mode?val={value!s}") - ) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - body = QByteArray(str(value).encode("utf-8")) - reply = self._net_manager.put(request, body) - reply.finished.connect(lambda: self.refresh_gridscan_analysis_mode()) - - @Slot(str, bool) - def set_local_contact_simulation(self, device: str, enabled: bool): - self.generic_post(f"local_contact/simulate/{device}?enabled={str(enabled).lower()}") - - @Slot(str) - def restart_local_contact_device(self, device: str): - self.generic_post(f"local_contact/restart/{device}") - - @Slot() - def bec_load_user_macros(self): - self.generic_post("bec/load_user_macros") - - @Slot() - def bec_list_all_user_macros(self): - if self._base_url is None: - logger.info("GET /bec/user_macros") - self.bec_user_macros_loaded.emit([]) - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/bec/user_macros")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.finished.connect(lambda: self._handle_bec_user_macros_response(reply)) - - def _handle_bec_user_macros_response(self, reply: QNetworkReply): - try: - response_data = self.handle_response(reply) - payload = json.loads(response_data) if response_data else [] - if not isinstance(payload, list): - raise TypeError("Invalid BEC user macros payload") - self.bec_user_macros_loaded.emit([str(item) for item in payload]) - except Exception as e: - logger.exception("Failed to list BEC user macros") - self.http_error.emit(str(e)) - - @Slot() - def bec_list_all_devices(self): - if self._base_url is None: - logger.info("GET /bec/devices") - self.bec_devices_loaded.emit([]) - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/bec/devices")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.finished.connect(lambda: self._handle_bec_devices_response(reply)) - - def _handle_bec_devices_response(self, reply: QNetworkReply): - try: - response_data = self.handle_response(reply) - payload = json.loads(response_data) if response_data else [] - if not isinstance(payload, list): - raise TypeError("Invalid BEC devices payload") - self.bec_devices_loaded.emit([str(item) for item in payload]) - except Exception as e: - logger.exception("Failed to list BEC devices") - self.http_error.emit(str(e)) - - @Slot(str) - def bec_reinitialise_planner_and_position_devices(self, method: str = "auto"): - self.generic_post(f"bec/reinitialise_planner_and_position_devices?method={method}") - - @Slot() - def bec_save_current_bs_pos(self): - self.generic_post("bec/save_current_bs_pos") - - @Slot() - def bec_save_current_collimator_pos(self): - self.generic_post("bec/save_current_collimator_pos") - - @Slot() - def bec_save_current_aerotech_position(self): - self.generic_post("bec/save_current_aerotech_position") - - @Slot() - def initialise_smargon(self): - self.generic_post("smargon/initialize") - - @Slot() - def save_beam_location_camera_setting(self): - self.generic_post("beamline/save_beam_location_camera_setting") - - @Slot() - def initialize_aerotech(self): - logger.info("initisalisation does not initisalise aareSCAN but runs homing script") - self.generic_post("aerotech/initialize") - - @Slot() - def initialize_detector(self): - self.generic_post("detector/initialize") - - @Slot() - def unmount(self): - self.generic_post("sample/unmount") - - @Slot(SampleShortInfo) - def mount(self, s: SampleShortInfo, reference: bool = False): - self.generic_post(f"sample/mount?dbid={s.db_id}&reference={reference}") - - @Slot(SampleShortInfo) - def sample_manual(self, s: SampleShortInfo): - self.generic_post("sample/manual", s.model_dump_json()) - - @Slot() - def cancel(self): - self.generic_post("scan/cancel") - - def handle_ml_box_response(self, reply): - try: - response_data = self.handle_response(reply) - if response_data != "": - parsed_response = RasterGridRequest.model_validate_json(response_data) - self.raster_generated_by_ml.emit(parsed_response) - except Exception as e: - logger.exception("Error in ml box") - self.http_error.emit(str(e)) - - @Slot() - def ml_bounding_box(self): - """ - Request an ML-based bounding box for the current sample. - """ - if self._base_url is None: - logger.info("POST /alc/ml_bounding_box") - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/alc/ml_bounding_box")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.post(request, QByteArray(b"")) - reply.finished.connect(lambda: self.handle_ml_box_response(reply)) - - def _handle_face_detection_response(self, reply: QNetworkReply): - try: - if reply.error() != QNetworkReply.NetworkError.NoError: - logger.error(f"Error in face detection: {reply.errorString()}") - raise RuntimeError(reply.errorString()) - payload = reply.readAll().data().decode("utf-8") or "{}" - import json - - data = json.loads(payload) - self.face_detection_result.emit(data) - except Exception as e: - logger.exception("Error in face detection") - self.http_error.emit(str(e)) - finally: - reply.deleteLater() - - def _read_face_detection_stream(self, reply: QNetworkReply): - try: - chunk = reply.readAll().data().decode("utf-8") - for line in chunk.splitlines(): - if line.startswith("data:"): - payload = line[5:].strip() - if payload: - data = json.loads(payload) - self.face_detection_result.emit(data) - except Exception: - logger.exception("Face detection stream parse error") - - def _restart_face_detection_stream(self): - reply = self._face_detection_stream_reply - self._face_detection_stream_reply = None - - status = None - if reply is not None: - try: - status = reply.attribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute) - except Exception: - logger.debug("Could not read the face detection stream status", exc_info=True) - status = None - - if status == 403: - self._face_detection_stream_blocked_403 = True - logger.info( - "Face detection SSE access denied; waiting for access change before retrying." - ) - return - - if self._base_url is not None: - QTimer.singleShot(1000, self.start_face_detection_stream) - - @staticmethod - def _parse_automation_progress(progress_payload: dict) -> AutomationProgress: - steps: list[StepState] = [] - events: list[LogEvent] = [] - - step_aliases = { - "final": WorkflowStateKind.FINAL, - "Paused/Finished": WorkflowStateKind.FINAL, - } - - for raw_step in progress_payload.get("steps", []): - raw_kind = raw_step.get("step") - raw_status = raw_step.get("status", StepStatus.PENDING.value) - raw_message = raw_step.get("message", "") - - step_kind = step_aliases.get(raw_kind) - if step_kind is None: - step_kind = WorkflowStateKind(raw_kind) - - step_status = StepStatus(raw_status) - steps.append( - StepState( - step=step_kind, - status=step_status, - message=str(raw_message or ""), - started_at=raw_step.get("started_at"), - completed_at=raw_step.get("completed_at"), - error_code=raw_step.get("error_code"), - ) - ) - - for raw_event in progress_payload.get("events", []): - raw_ts = raw_event.get("ts") - if isinstance(raw_ts, str) and raw_ts: - ts = datetime.fromisoformat(raw_ts) - elif isinstance(raw_ts, datetime): - ts = raw_ts - else: - continue - - raw_level = str(raw_event.get("level", "INFO")).upper() - if raw_level not in {"INFO", "WARNING", "ERROR"}: - raw_level = "INFO" - level = cast(Literal["INFO", "WARNING", "ERROR"], raw_level) - - events.append( - LogEvent( - ts=ts, - level=level, - code=str(raw_event.get("code", "UNKNOWN")), - exception_class=raw_event.get("exception_class"), - message=str(raw_event.get("message", "")), - sample_id=raw_event.get("sample_id"), - context=dict(raw_event.get("context") or {}), - ) - ) - - return AutomationProgress( - current_step=progress_payload.get("current_step"), - steps=steps, - events=events, - finished=bool(progress_payload.get("finished", False)), - success=progress_payload.get("success"), - samples_in_queue=int(progress_payload.get("samples_in_queue", 0) or 0), - avg_time_per_sample=float(progress_payload.get("avg_time_per_sample", 0.0) or 0.0), - current_sample_name=str(progress_payload.get("current_sample_name") or ""), - ) - - @staticmethod - def _log_level_for_event(level: str) -> int: - return {"ERROR": logging.ERROR, "WARNING": logging.WARNING, "INFO": logging.INFO}.get( - str(level).upper(), logging.INFO - ) - - def _emit_automation_progress_events(self, progress: AutomationProgress) -> None: - for event in progress.events: - sample_id = event.sample_id - last_seen = self._last_seen_automation_event_ts.get(sample_id) - if last_seen is not None and event.ts <= last_seen: - continue - - self._last_seen_automation_event_ts[sample_id] = event.ts - logger.log( - self._log_level_for_event(event.level), - event.message, - extra={ - "code": event.code, - "exception_class": event.exception_class, - "sample_id": event.sample_id, - **dict(event.context or {}), - }, - ) - watcher_trip = self._observe_recurrence(event.exception_class) - if watcher_trip is not None: - self._emit_watcher_trip(watcher_trip) - - def _handle_automation_progress_event(self, payload: str) -> None: - if not payload: - return - - logger.info(f"[automation_progress raw] {payload}") - outer = json.loads(payload) - progress_payload = outer.get("progress") - if progress_payload is None: - logger.info("[automation_progress raw] no progress payload in SSE event") - return - - progress = self._parse_automation_progress(progress_payload) - self.automation_progress.emit(progress) - self._emit_automation_progress_events(progress) - self._set_centering( - automation=not progress.finished - and any( - step.step == WorkflowStateKind.LOOP_CENTRE and step.status == StepStatus.RUNNING - for step in progress.steps - ) - ) - - current = progress.current_step or "Idle" - if progress.finished: - if progress.success is True: - logger.info(f"Automation progress: {current} - finished successfully") - elif progress.success is False: - logger.info(f"Automation progress: {current} - finished with error") - else: - logger.info(f"Automation progress: {current} - finished") - else: - logger.info(f"Automation progress: {current}") - - def _process_automation_progress_buffer(self) -> None: - while "\n\n" in self._automation_progress_buffer: - event_data, self._automation_progress_buffer = self._automation_progress_buffer.split( - "\n\n", 1 - ) - - data_lines: list[str] = [] - for line in event_data.splitlines(): - if line.startswith("data:"): - data_lines.append(line[5:].lstrip()) - - if not data_lines: - continue - - payload = "\n".join(data_lines) - self._handle_automation_progress_event(payload) - - def _read_automation_progress_stream(self, reply: QNetworkReply): - try: - chunk = reply.readAll().data().decode("utf-8") - if not chunk: - return - - self._automation_progress_buffer += chunk - self._process_automation_progress_buffer() - except Exception: - logger.exception("Automation progress stream parse error") - - def _restart_automation_progress_stream(self): - reply = self._automation_progress_stream_reply - self._automation_progress_stream_reply = None - self._automation_progress_buffer = "" - - status = None - if reply is not None: - try: - status = reply.attribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute) - except Exception: - logger.debug("Could not read the automation progress stream status", exc_info=True) - status = None - - if status == 403: - self._automation_progress_stream_blocked_403 = True - logger.info( - "Automation progress SSE access denied; waiting for access change before retrying." - ) - return - - if self._base_url is not None: - QTimer.singleShot(1000, self.start_automation_progress_stream) - - def start_automation_progress_stream(self): - if self._base_url is None: - return - - if self._automation_progress_stream_reply is not None: - return - - if self._automation_progress_stream_blocked_403: - return - - self._automation_progress_buffer = "" - - request = QNetworkRequest(QUrl(f"{self._base_url}/sse/automation_progress")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.readyRead.connect(lambda: self._read_automation_progress_stream(reply)) - reply.finished.connect(self._restart_automation_progress_stream) - self._automation_progress_stream_reply = reply - - def start_face_detection_stream(self): - if self._base_url is None: - return - - if self._face_detection_stream_reply is not None: - return - - if self._face_detection_stream_blocked_403: - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/sse/face_detection")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.readyRead.connect(lambda: self._read_face_detection_stream(reply)) - reply.finished.connect(self._restart_face_detection_stream) - self._face_detection_stream_reply = reply - - @Slot() - def face_detection(self, steps: int, step_size: int): - """ - Trigger the face detection procedure. - - Args: - steps: Number of rotation steps. - step_size: Degrees per step. - """ - if self._base_url is None: - logger.info(f"POST /face_detection/run?steps={steps}&step_size={step_size}") - return - - request = QNetworkRequest( - QUrl(f"{self._base_url}/face_detection/run?steps={steps}&step_size={step_size}") - ) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - reply = self._net_manager.post(request, QByteArray(b"")) - reply.finished.connect(lambda: self._handle_face_detection_response(reply)) - - @Slot() - def fluorimeter_start(self): - self.generic_post("fluorimeter/start") - - @Slot() - def fluorimeter_start_erase(self): - self.generic_post("fluorimeter/start?erase=true") - - @Slot() - def fluorimeter_stop(self): - self.generic_post("fluorimeter/stop") - - def _handle_fluorimeter_data(self, reply: QNetworkReply, emit_status: bool = False): - try: - response_data = self.handle_response(reply) - import json - - data = json.loads(response_data) if response_data else [] - if emit_status: - # fetch status and bkg in parallel (simple sequential here) - status_req = QNetworkRequest(QUrl(f"{self._base_url}/fluorimeter/status")) - status_req.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - status_reply = self._net_manager.get(status_req) - status_reply.finished.connect( - lambda: self._handle_fluorimeter_status_and_emit(data, status_reply) - ) - else: - self.fluorimeter_update.emit(data, [], -1) - except Exception as e: - logger.exception("Fluorimeter data error") - self.http_error.emit(str(e)) - - def _handle_fluorimeter_status_and_emit(self, data, status_reply: QNetworkReply): - try: - s_payload = self.handle_response(status_reply) - s = int(s_payload) if s_payload not in ("", "null") else -1 - b_req = QNetworkRequest(QUrl(f"{self._base_url}/fluorimeter/background")) - b_req.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - b_reply = self._net_manager.get(b_req) - b_reply.finished.connect(lambda: self._emit_fluorimeter_with_bkg(data, s, b_reply)) - except Exception as e: - logger.exception("Fluorimeter status error") - self.http_error.emit(str(e)) - - def _emit_fluorimeter_with_bkg(self, data, s, b_reply: QNetworkReply): - try: - bkg_json = self.handle_response(b_reply) - import json - - bkg = json.loads(bkg_json) if bkg_json else [] - self.fluorimeter_update.emit(data, bkg, s) - except Exception as e: - logger.exception("Fluorimeter background error") - self.http_error.emit(str(e)) - - @Slot() - def fluorimeter_spectrum(self, f: FluorescenceSpectrumParameterModel): - if self._base_url is None: - return - req = QNetworkRequest(QUrl(f"{self._base_url}/fluorimeter/spectrum")) - req.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - req.setRawHeader(b"Content-Type", b"application/json") - body = f.model_dump_json() - reply = self._net_manager.post(req, QByteArray(body.encode("utf-8"))) - reply.finished.connect(lambda: self._handle_fluorimeter_spectrum(reply)) - - def _handle_fluorimeter_spectrum(self, reply: QNetworkReply): - try: - response_data = self.handle_response(reply) - parsed_response = FluorescenceSpectrumOutputModel.model_validate_json(response_data) - self.fluorimeter_spectrum_update.emit(parsed_response) - except Exception as e: - logger.exception("Exception from fluorimeter spectrum") - self.http_error.emit(str(e)) - - @Slot() - def fluorimeter_request_snapshot(self): - if self._base_url is None: - return - req = QNetworkRequest(QUrl(f"{self._base_url}/fluorimeter/data")) - req.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(req) - reply.finished.connect(lambda: self._handle_fluorimeter_data(reply, emit_status=True)) - - # Optional: SSE listener for live updates - def start_fluorimeter_stream(self): - if self._base_url is None: - return - request = QNetworkRequest(QUrl(f"{self._base_url}/sse/fluorimeter")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.readyRead.connect(lambda: self._read_fluorimeter_stream(reply)) - reply.finished.connect(lambda: reply.deleteLater()) - - def _read_fluorimeter_stream(self, reply: QNetworkReply): - try: - chunk = reply.readAll().data().decode("utf-8") - for line in chunk.splitlines(): - if line.startswith("data:"): - payload = line[5:].strip() - if payload: - obj = json.loads(payload) - data = obj.get("data") or [] - bkg = obj.get("background") or [] - status = obj.get("status", -1) - self.fluorimeter_update.emit(data, bkg, status) - except Exception: - logger.exception("SSE parse error") - - @staticmethod - def _flatten_error_codes_payload(obj: dict) -> dict[str, str]: - """ - Accept either: - - flat: {"INVALID_TOKEN": "INVALID_TOKEN"} - - grouped: {"AuthErrorCode": {"INVALID_TOKEN": "INVALID_TOKEN"}, "AareErrorCode": {...}} - - Output is always flat strings, using 'Group.KEY' for grouped input. - """ - out: dict[str, str] = {} - for k, v in (obj or {}).items(): - if isinstance(v, dict): - group = str(k) - for kk, vv in v.items(): - out[f"{group}.{kk!s}"] = str(vv) - else: - out[str(k)] = str(v) - return out - - @Slot() - def get_error_codes(self) -> None: - """ - Fetch server error codes registry for developer/help UI. - Emits error_codes_loaded(dict). - - Server default is grouped. We flatten grouped payloads for existing UI. - """ - if self._base_url is None: - self.error_codes_loaded.emit(export_error_codes()) - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/meta/error-codes")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.finished.connect(lambda: self._handle_error_codes_response(reply)) - - def _retry_error_codes_legacy(self) -> None: - request = QNetworkRequest(QUrl(f"{self._base_url}/meta/error-codes/flat")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.finished.connect(lambda: self._handle_error_codes_response(reply)) - - @Slot(QNetworkReply) - def _handle_error_codes_response(self, reply: QNetworkReply) -> None: - try: - status = reply.attribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute) - - try: - url = reply.request().url().toString() - except Exception: - logger.debug("Could not read the request URL", exc_info=True) - url = "" - - if int(status) == 404 and url.endswith("/meta/error-codes"): - reply.deleteLater() - logger.error("Error codes not found on server.") - return - - payload = self.handle_response(reply) - obj = json.loads(payload) if payload else {} - if not isinstance(obj, dict): - raise TypeError("Invalid error-codes payload (expected JSON object)") - out = self._flatten_error_codes_payload(obj) - self.error_codes_loaded.emit(out) - except Exception as e: - logger.exception("Failed to load error codes") - self.http_error.emit(str(e)) - - @Slot(str, str) - def send_screenshot_db(self, filename: str = "", message: str = ""): - if self._base_url is None: - logger.info(f"POST /samcam/send_screenshot_db?filename={filename}&message={message}") - return - - from urllib.parse import quote - - query = [] - filename = filename.strip() - message = message.strip() - - if filename: - query.append(f"filename={quote(filename)}") - if message: - query.append(f"message={quote(message)}") - - suffix = f"?{'&'.join(query)}" if query else "" - self.generic_post(f"samcam/send_screenshot_db{suffix}") - - def start_baton_stream(self): - """Start SSE stream for baton status updates.""" - if self._base_url is None: - return - - if self._baton_stream_reply is not None: - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/sse/baton")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.readyRead.connect(lambda: self._read_baton_stream(reply)) - reply.finished.connect(self._restart_baton_stream) - self._baton_stream_reply = reply - - def _restart_baton_stream(self): - self._baton_stream_reply = None - if self._base_url is not None: - QTimer.singleShot(1000, self.start_baton_stream) - - def _read_baton_stream(self, reply: QNetworkReply): - try: - chunk = reply.readAll().data().decode("utf-8") - for line in chunk.splitlines(): - if line.startswith("data:"): - payload = line[5:].strip() - if payload: - status = BatonStatus.model_validate_json(payload) - - if status.you_have_pending_request: - if not self._baton_timeout_timer.isActive(): - self._baton_timeout_timer.start() - else: - if self._baton_timeout_timer.isActive(): - self._baton_timeout_timer.stop() - - if status.incoming_request and ( - self._last_baton_status is None - or not self._last_baton_status.incoming_request - ): - self.baton_incoming_request.emit( - { - "requester": status.pending_request.requester_username - if status.pending_request - else "Unknown", - "timeout": status.pending_request.timeout_seconds - if status.pending_request - else 30, - } - ) - - self._last_baton_status = status - self.baton_status_changed.emit(status) - except Exception: - logger.exception("Baton stream parse error") - - @Slot() - def request_baton(self): - """ - Request the baton to gain write access to the beamline. - """ - if self._base_url is None: - logger.info("POST /baton/request") - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/baton/request")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - reply = self._net_manager.post(request, QByteArray(b"")) - reply.finished.connect(lambda: self._handle_baton_request_response(reply)) - - def _handle_baton_request_response(self, reply: QNetworkReply): - try: - response_data = self.handle_response(reply) - result = json.loads(response_data) if response_data else {} - self.baton_request_result.emit(result) - - if result.get("granted"): - self.status_message.emit("Baton acquired", False) - self.send_status_request() - self._restart_blocked_sse_streams_if_access_restored() - elif result.get("pending"): - self.status_message.emit( - f"Request sent - waiting for response ({result.get('timeout_seconds', 30)}s timeout)", - False, - ) - elif result.get("error"): - self.status_message.emit(result.get("message", "Request failed"), True) - except Exception as e: - logger.exception("Baton request failed") - self.http_error.emit(str(e)) - - @Slot(bool) - def respond_to_baton_request(self, accept: bool): - """ - Respond to an incoming baton request from another user. - - Args: - accept: True to grant the baton, False to refuse. - """ - if self._base_url is None: - logger.info(f"POST /baton/respond?accept={accept}") - return - - request = QNetworkRequest( - QUrl(f"{self._base_url}/baton/respond?accept={str(accept).lower()}") - ) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - reply = self._net_manager.post(request, QByteArray(b"")) - reply.finished.connect(lambda: self._handle_baton_response_result(reply)) - - def _handle_baton_response_result(self, reply: QNetworkReply): - try: - response_data = self.handle_response(reply) - result = json.loads(response_data) if response_data else {} - self.baton_response_result.emit(result) - - if result.get("accepted") or result.get("refused"): - self.send_status_request() - self.check_baton_timeout() - self.start_baton_stream() - self._restart_blocked_sse_streams_if_access_restored() - except Exception as e: - logger.exception("Baton response failed") - self.http_error.emit(str(e)) - - @Slot() - def release_baton(self): - """Release the baton voluntarily.""" - self.generic_post("baton/release") - - @Slot() - def cancel_baton_request(self): - """Cancel your pending baton request.""" - self.generic_post("baton/cancel") - - @Slot() - def check_baton_timeout(self): - """Poll to check if timeout has been reached.""" - if self._base_url is None: - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/baton/check_timeout")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.finished.connect(lambda: self._handle_baton_timeout_response(reply)) - - def _handle_baton_timeout_response(self, reply: QNetworkReply): - try: - response_data = self.handle_response(reply) - result = json.loads(response_data) if response_data else {} - self.baton_timeout_checked.emit(result) - - if result.get("granted") or result.get("queued") or result.get("refused"): - self.send_status_request() - self.start_baton_stream() - self._restart_blocked_sse_streams_if_access_restored() - except Exception as e: - logger.exception("Baton timeout check failed") - self.http_error.emit(str(e)) - - def release_baton_on_close(self): - """Backward-compatible fallback.""" - self.end_session_on_close() - - def end_session_on_close(self): - """ - End the GUI session when the window is closed. - - This is preferred over only releasing the baton because the backend can: - - remove the Redis GUI session entry immediately - - clear the active beamline session if this GUI owns it - """ - try: - if hasattr(self, "_baton_timeout_timer") and self._baton_timeout_timer is not None: - self._baton_timeout_timer.stop() - - self.end_session() - - from PySide6.QtCore import QEventLoop, QTimer - - loop = QEventLoop() - QTimer.singleShot(500, loop.quit) - loop.exec() - - logger.info("End session requested on GUI close") - except Exception as e: - logger.warning(f"Error ending session on close: {e}", exc_info=True) - - def _handle_gui_sessions_response(self, reply: QNetworkReply): - try: - response_data = self.handle_response(reply) - payload = json.loads(response_data) if response_data else [] - sessions = [OpenGuiSessionInfo.model_validate(item) for item in payload] - self.gui_sessions_loaded.emit(sessions) - except Exception as e: - logger.exception("Failed to load GUI sessions") - self.http_error.emit(str(e)) - - @Slot() - def load_gui_sessions(self): - if self._base_url is None: - self.gui_sessions_loaded.emit([]) - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/admin/gui_sessions")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.get(request) - reply.finished.connect(lambda: self._handle_gui_sessions_response(reply)) - - @Slot(int, int) - def request_gui_close(self, session_id: int, grace_seconds: int = 60): - if self._base_url is None: - logger.info( - f"POST /admin/gui_sessions/{session_id}/request_close?grace_seconds={grace_seconds}" - ) - return - - request = QNetworkRequest( - QUrl( - f"{self._base_url}/admin/gui_sessions/{session_id}/request_close?grace_seconds={grace_seconds}" - ) - ) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - reply = self._net_manager.post(request, QByteArray(b"")) - reply.finished.connect(lambda: self._handle_gui_session_mutation_response(reply)) - - @Slot(int) - def force_remove_gui_session(self, session_id: int): - if self._base_url is None: - logger.info(f"DELETE /admin/gui_sessions/{session_id}") - return - - request = QNetworkRequest(QUrl(f"{self._base_url}/admin/gui_sessions/{session_id}")) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - reply = self._net_manager.deleteResource(request) - reply.finished.connect(lambda: self._handle_gui_session_mutation_response(reply)) - - def _handle_gui_session_mutation_response(self, reply: QNetworkReply): - try: - if reply.error() != QNetworkReply.NetworkError.NoError: - self.handle_req_response(reply) - self.load_gui_sessions() - return - - _ = self.handle_response(reply) - self.load_gui_sessions() - except Exception as e: - logger.exception("GUI session mutation failed") - self.http_error.emit(str(e)) - self.load_gui_sessions() - - @Slot(int) - def report_gui_interaction(self, session_id: int): - if self._base_url is None: - return - - request = QNetworkRequest( - QUrl(f"{self._base_url}/admin/gui_sessions/{session_id}/interaction") - ) - request.setRawHeader(b"Authorization", f"Bearer {self._token}".encode()) - request.setRawHeader(b"Content-Type", b"application/json") - reply = self._net_manager.post(request, QByteArray(b"")) - reply.finished.connect(lambda: reply.deleteLater()) - - def cleanup(self) -> None: - if getattr(self, "_cleanup_done", False): - return - self._cleanup_done = True - - try: - if hasattr(self, "_baton_timeout_timer") and self._baton_timeout_timer is not None: - self._baton_timeout_timer.stop() - except Exception as e: - logger.warning(f"Failed to stop _baton_timeout_timer: {e}", exc_info=True) - - try: - if hasattr(self, "_timer") and self._timer is not None: - self._timer.stop() - except Exception as e: - logger.warning(f"Failed to stop __timer: {e}", exc_info=True) - - for attr_name in ( - "_baton_stream_reply", - "_face_detection_stream_reply", - "_automation_progress_stream_reply", - ): - reply = getattr(self, attr_name, None) - if reply is None: - continue - - try: - reply.abort() - except Exception as e: - logger.warning(f"Failed to abort {attr_name}: {e}", exc_info=True) - - try: - reply.deleteLater() - except Exception as e: - logger.warning(f"Failed to delete {attr_name}: {e}", exc_info=True) - - setattr(self, attr_name, None) - - self._face_detection_stream_blocked_403 = False - self._automation_progress_stream_blocked_403 = False - self._automation_progress_buffer = "" diff --git a/src/aare/gui/threads/jfjoch_viewer.py b/src/aare/gui/threads/jfjoch_viewer.py deleted file mode 100644 index 102ef3b0..00000000 --- a/src/aare/gui/threads/jfjoch_viewer.py +++ /dev/null @@ -1,81 +0,0 @@ -from aarecommon.config.beamline import get_jfjoch_url, mx_beamline -from aarecommon.config.logger import setup_logger -from PySide6.QtCore import QObject, Slot -from PySide6.QtDBus import QDBusConnection, QDBusInterface - -from aare.gui.constants import LOGGER_NAME - -logger = setup_logger(LOGGER_NAME) - - -class JFJochDBusClient(QObject): - def __init__(self): - super().__init__() - - self._session_bus = QDBusConnection.sessionBus() - self._interface = None - self._dbus_available = False - - self._beamline = mx_beamline() - try: - self._detector_url = get_jfjoch_url(self._beamline) - except ValueError: - self._detector_url = None - - try: - self._session_bus = QDBusConnection.sessionBus() - if self._session_bus.isConnected(): - self._dbus_available = True - print("D-Bus session bus connected") - else: - print("D-Bus not available") - - except Exception: - logger.warning("D-Bus not available", exc_info=True) - - def _ensure_interface(self): - """Ensure we have a valid interface, creating one if needed.""" - if not self._dbus_available: - print("D-Bus not available, cannot connect to JFJoch viewer") - return False - - if self._interface is None or not self._interface.isValid(): - if not self._session_bus.isConnected(): - print("Session bus not connected") - return False - - self._interface = QDBusInterface( - "ch.psi.jfjoch_viewer", # Service name - "/", # Object path - "ch.psi.jfjoch_viewer", # Interface name - self._session_bus, - ) - - if not self._interface.isValid(): - print("Service 'ch.psi.jfjoch_viewer' not available") - return False - - return True - - @Slot(str, int) - def load_image(self, name: str, number: int): - if not self._dbus_available: - print("D-Bus not available, cannot load image in JFJoch viewer") - return - - if name.startswith("http://"): - path = name - else: - path = "/sls/mx/data/" + name + "_master.h5" - print(f"Load dataset: {path} image: {number}") - if self._ensure_interface(): - self._interface.call("LoadFile", path, number, 1) - - @Slot() - def load_online(self): - if not self._dbus_available: - print("D-Bus not available, cannot load online data in JFJoch viewer") - return - - if self._ensure_interface(): - self._interface.call("LoadFile", self._detector_url, -1, 1) diff --git a/src/aare/gui/threads/prediction_subscriber.py b/src/aare/gui/threads/prediction_subscriber.py deleted file mode 100644 index e5c40980..00000000 --- a/src/aare/gui/threads/prediction_subscriber.py +++ /dev/null @@ -1,333 +0,0 @@ -import json -import time - -import cv2 -import numpy as np -import zmq -from aarecommon.config.logger import setup_logger -from aarecommon.math.autofocus import focus_measure_edges -from aarecommon.models.models import DAQStatusModel -from PySide6.QtCore import QThread, Signal, Slot -from PySide6.QtGui import QImage - -from aare.gui.constants import LOGGER_NAME - -logger = setup_logger(LOGGER_NAME) - - -class PredictionSubscriber(QThread): - prediction = Signal(dict) - target_point = Signal(dict) - image = Signal(QImage) - focus_measure = Signal(float) - fps_measure = Signal(float) - camera_availability_changed = Signal(bool) - camera_error = Signal(str) - - #: How many frames may sit unpainted in the GUI event queue (see _emit_image). - MAX_FRAMES_IN_FLIGHT = 2 - - def __init__(self, pred_zmq_url: str, topic: bytes | str = b"", parent=None): - super().__init__(parent) - self._ctx = zmq.Context() - self._sock = self._ctx.socket(zmq.SUB) - self._sock.setsockopt(zmq.RCVTIMEO, 500) - self._sock.setsockopt(zmq.LINGER, 0) - # Cap the backlog the socket may hold. Both must be set before connect() - # to take effect on the pipe. Defaults let the SUB queue grow to 1000 - # messages (20 s of video at 50 Hz) with megabytes more hidden in the - # kernel buffer, which is the backlog _recv_latest would then have to - # throw away every frame. RCVBUF stays well above the ~2.5 MB/s the - # stream actually needs, so it costs no throughput. - self._sock.setsockopt(zmq.RCVHWM, 4) - self._sock.setsockopt(zmq.RCVBUF, 512 * 1024) - - self._emit_images = True - self.running = True - - self._measure_focus = False - self._focus_mask = None - self._beam_x = 0 - self._beam_y = 0 - self._last_beam_pos = None - self._focus_radius = 40 - - self._fps_window_start = time.perf_counter() - self._fps_frame_count = 0 - self._fps_emit_period_s = 0.5 - self._last_frame_time = None - self._no_frame_timeout_s = 5.0 - - self._camera_available = False - self._last_camera_error: str | None = None - - self._dropped = 0 # stale frames skipped since the last fps report - self._frames_in_flight = 0 - - if isinstance(topic, str): - self._sock.setsockopt_string(zmq.SUBSCRIBE, topic) - elif isinstance(topic, bytes): - self._sock.setsockopt(zmq.SUBSCRIBE, topic) - else: - self._sock.setsockopt(zmq.SUBSCRIBE, b"") - - self._sock.connect(pred_zmq_url) - - def set_emit_images(self, enabled: bool) -> None: - self._emit_images = enabled - - def _set_camera_available(self, available: bool, error: str | None = None) -> None: - if available != self._camera_available: - self._camera_available = available - self.camera_availability_changed.emit(available) - - if error is not None and error != self._last_camera_error: - self._last_camera_error = error - self.camera_error.emit(error) - - if available: - self._last_camera_error = None - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - self._beam_x = s.geom.beam_location_pxl.x - self._beam_y = s.geom.beam_location_pxl.y - if (self._beam_x, self._beam_y) != self._last_beam_pos: - self._focus_mask = None - self._last_beam_pos = (self._beam_x, self._beam_y) - - @Slot(bool) - def enable_focus_measurement(self, enabled: bool = True): - self._measure_focus = enabled - - def _try_parse_json(self, part: bytes) -> dict | None: - # Binary frames (JPEG starts with 0xff) are not JSON; decoding them as - # utf-8 raises UnicodeDecodeError on every frame. Cheap sniff instead. - if part.lstrip()[:1] != b"{": - return None - try: - decoded = json.loads(part.decode("utf-8")) - return decoded if isinstance(decoded, dict) else None - except Exception: - logger.debug("Could not parse the prediction payload as JSON", exc_info=True) - return None - - def _decode_rgb_image(self, header: dict, data: bytes) -> np.ndarray | None: - if not header: - return None - - arr = np.frombuffer(data, dtype=np.uint8) - - encoding = str(header.get("encoding", "")).lower() - if encoding == "jpeg": - encoded = np.frombuffer(data, dtype=np.uint8) - bgr = cv2.imdecode(encoded, cv2.IMREAD_COLOR) - if bgr is None: - return None - return cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) - - if header.get("type") == "uint8": - shape = header.get("shape") - if not shape or not isinstance(shape, (list, tuple)): - return None - - if len(shape) == 2: - h, w = int(shape[0]), int(shape[1]) - if arr.size != h * w: - return None - bayer = arr.reshape((h, w)) - return cv2.cvtColor(bayer, cv2.COLOR_BAYER_GB2RGB) - - if len(shape) == 3 and int(shape[2]) == 3: - h, w, c = int(shape[0]), int(shape[1]), int(shape[2]) - if arr.size != h * w * c: - return None - return arr.reshape((h, w, 3)) - - return None - - def _rgb_to_qimage(self, rgb: np.ndarray) -> QImage: - # .copy() because QImage does not own the numpy buffer it wraps. - return QImage(rgb.data, rgb.shape[1], rgb.shape[0], QImage.Format.Format_RGB888).copy() - - def _emit_image(self, image: QImage) -> None: - """Emit a frame only while the GUI is keeping up, dropping it otherwise. - - `image` is a queued cross-thread signal and Qt's event queue has no - high-water mark, so if the GUI paints slower than frames arrive the - queue grows without bound and the picture on screen falls further - behind for as long as the stream runs. Capping the frames in flight - paces the feed to whatever the GUI can actually sustain. - - The cap is 2 rather than 1 so that one frame can be queued while the - GUI paints the other: at 1 the GUI idles until the worker finishes - decoding the next frame. The second slot costs one frame of latency - (20 ms at 50 Hz) and buys back that idle time. - """ - if self._frames_in_flight >= self.MAX_FRAMES_IN_FLIGHT: - self._dropped += 1 - return - - self._frames_in_flight += 1 - self.image.emit(image) - - def notify_frame_displayed(self) -> None: - """Called from the GUI thread once a frame has been handed to the views.""" - self._frames_in_flight = max(0, self._frames_in_flight - 1) - - def _emit_focus_measure_if_enabled(self, rgb: np.ndarray) -> None: - if not self._measure_focus: - return - - gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY) - if self._focus_mask is None or self._focus_mask.shape != gray.shape: - height, width = gray.shape - y, x = np.ogrid[:height, :width] - self._focus_mask = (x - self._beam_x) ** 2 + ( - y - self._beam_y - ) ** 2 <= self._focus_radius**2 - - sharpness = focus_measure_edges(gray, self._focus_mask) - self.focus_measure.emit(sharpness) - - def _recv_latest(self) -> list[bytes]: - """Return the newest queued message, discarding the backlog behind it. - - zmq.CONFLATE is unusable here: it keeps only the last *part*, which - shreds multipart messages. recv_multipart is atomic though — a - non-blocking recv either yields a whole message or raises Again — so - draining in a loop is a multipart-safe conflate. The drain runs after - the (slow) decode of the previous frame, so it eats exactly the - backlog that piled up while we were busy, and the stream is always - consumed at line rate no matter how long a frame takes to decode. - """ - # Bind locally: run() nulls the attribute on cleanup, so it is Optional - # to the type checker even though it cannot be None while run() loops. - sock = self._sock - assert sock is not None, "_recv_latest called after the socket was closed" - parts = sock.recv_multipart() # honours RCVTIMEO, may raise zmq.Again - while True: - try: - parts = sock.recv_multipart(zmq.NOBLOCK) - except zmq.Again: - return parts - self._dropped += 1 - - def run(self): - try: - while self.running: - try: - parts = self._recv_latest() - except zmq.Again: - now = time.perf_counter() - elapsed = now - self._fps_window_start - if elapsed >= self._fps_emit_period_s: - no_frames_long = ( - self._last_frame_time is None - or (now - self._last_frame_time) >= self._no_frame_timeout_s - ) - self.fps_measure.emit(float("nan") if no_frames_long else 0.0) - self._fps_window_start = now - self._fps_frame_count = 0 - - if no_frames_long: - self._set_camera_available(False, "Sample camera feed unavailable") - continue - - if not parts: - continue - - now = time.perf_counter() - self._last_frame_time = now - self._fps_frame_count += 1 - - elapsed = now - self._fps_window_start - if elapsed >= self._fps_emit_period_s: - fps = self._fps_frame_count / elapsed if elapsed > 0 else 0.0 - self.fps_measure.emit(float(fps)) - if self._dropped: - logger.debug( - "Sample camera: skipped %d stale frame(s), showing %.1f fps", - self._dropped, - fps, - ) - self._dropped = 0 - self._fps_window_start = now - self._fps_frame_count = 0 - - json_dicts: list[dict] = [] - non_json_parts: list[bytes] = [] - - for p in parts: - d = self._try_parse_json(p) - if d is not None: - json_dicts.append(d) - else: - non_json_parts.append(p) - - header = next( - ( - d - for d in json_dicts - if d.get("encoding") == "jpeg" - or ("shape" in d and d.get("type") == "uint8") - ), - None, - ) - detections = next((d for d in json_dicts if "boxes" in d), None) - target = next((d for d in json_dicts if "target_point" in d), None) - image_bytes = max(non_json_parts, key=len) if non_json_parts else None - - if self._emit_images and header and image_bytes: - rgb = self._decode_rgb_image(header, image_bytes) - if rgb is None: - self._set_camera_available( - False, "Sample camera feed unavailable: failed to decode frame" - ) - else: - self._set_camera_available(True) - self._emit_focus_measure_if_enabled(rgb) - if self.running: - self._emit_image(self._rgb_to_qimage(rgb)) - elif self._emit_images: - self._set_camera_available( - False, "Sample camera feed unavailable: no frame header in zmq stream" - ) - - if detections and self.running: - self.prediction.emit(detections) - - if target and self.running: - self.target_point.emit(target) - - except Exception as e: - if self.running: - self._set_camera_available(False, f"Sample camera feed unavailable: {e}") - logger.exception("PredictionSubscriber error") - finally: - try: - if self._sock is not None: - self._sock.close(0) - except Exception: - logger.debug("Error closing the prediction ZMQ socket", exc_info=True) - finally: - self._sock = None - - try: - if self._ctx is not None: - self._ctx.term() - except Exception: - logger.debug("Error terminating the prediction ZMQ context", exc_info=True) - finally: - self._ctx = None - - def stop(self): - self.running = False - self.requestInterruption() - - # Do NOT close the socket here: zmq sockets are not thread-safe, and - # closing from the GUI thread while run() uses it aborts libzmq - # (Assertion failed: pfd.revents & POLLIN, signaler.cpp). RCVTIMEO=500ms - # guarantees run() notices running=False and closes it in its own thread. - if not self.wait(1500): - logger.warning("PredictionSubscriber did not stop within timeout") diff --git a/src/aare/gui/threads/sse_client.py b/src/aare/gui/threads/sse_client.py deleted file mode 100644 index 78f3ca8e..00000000 --- a/src/aare/gui/threads/sse_client.py +++ /dev/null @@ -1,211 +0,0 @@ -from typing import ClassVar - -from PySide6.QtCore import QByteArray, QObject, QTimer, QUrl, Signal, Slot -from PySide6.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest, QSslError - - -class SSEClient(QObject): - # Signals - connected = Signal() - disconnected = Signal() - message_received = Signal(str) # Raw SSE data - event_received = Signal(str, str) # event_type, data - error_occurred = Signal(str) - - def __init__(self, parent=None): - super().__init__(parent) - self._network_manager = QNetworkAccessManager(self) - self._network_manager.sslErrors.connect(self._handle_ssl_errors) - self._reply: QNetworkReply | None = None - self._reconnect_timer = QTimer(self) - self._reconnect_timer.setSingleShot(True) - self._reconnect_timer.timeout.connect(self._attempt_reconnect) - - self._url = QUrl() - self._headers: dict[str, str] = {} - self._buffer = QByteArray() - self._connected = False - self._reconnect_delay = 1000 # Start with 1 second - self._max_reconnect_delay = 30000 # Max 30 seconds - - # Current SSE event data - self._current_event = "" - self._current_data = "" - self._current_id = "" - - def connect_to_sse(self, url: str, headers: dict[str, str] | None = None): - """Connect to SSE endpoint""" - self._url = QUrl(url) - self._headers = headers or {} - - if self._reply: - self._reply.abort() - self._reply.deleteLater() - self._reply = None - - self._start_connection() - - def disconnect_from_sse(self): - """Disconnect from SSE""" - self._reconnect_timer.stop() - - if self._reply: - self._reply.abort() - self._reply.deleteLater() - self._reply = None - - if self._connected: - self._connected = False - self.disconnected.emit() - - def is_connected(self) -> bool: - """Check if connected to SSE""" - return self._connected and self._reply and self._reply.isOpen() - - _SELF_SIGNED_ERRORS: ClassVar[set[QSslError.SslError]] = { - QSslError.SslError.SelfSignedCertificate, - QSslError.SslError.SelfSignedCertificateInChain, - } - - @staticmethod - def _handle_ssl_errors(reply: QNetworkReply, errors: list): - self_signed = [e for e in errors if e.error() in SSEClient._SELF_SIGNED_ERRORS] - if self_signed: - reply.ignoreSslErrors(self_signed) - - def _start_connection(self): - """Start SSE connection""" - request = QNetworkRequest(self._url) - - # Set SSE-specific headers - request.setRawHeader(b"Accept", b"text/event-stream") - request.setRawHeader(b"Cache-Control", b"no-cache") - request.setRawHeader(b"Connection", b"keep-alive") - - # Add custom headers - for key, value in self._headers.items(): - request.setRawHeader(key.encode(), value.encode()) - - print(f"Connecting to SSE: {self._url.toString()}") - - self._reply = self._network_manager.get(request) - self._reply.readyRead.connect(self._on_ready_read) - self._reply.finished.connect(self._on_finished) - self._reply.errorOccurred.connect(self._on_error) - - @Slot() - def _on_ready_read(self): - """Handle incoming SSE data""" - if not self._reply: - return - - # First successful read means we're connected - if not self._connected: - self._connected = True - self._reconnect_delay = 1000 # Reset reconnect delay - self.connected.emit() - - data = self._reply.readAll() - self._buffer.append(data) - self._process_buffer() - - def _process_buffer(self): - """Process SSE data buffer""" - while b"\n" in self._buffer: - newline_index = self._buffer.indexOf(b"\n") - line_data = self._buffer.left(newline_index) - self._buffer.remove(0, newline_index + 1) - - # Remove carriage return if present - if line_data.endsWith(b"\r"): - line_data.chop(1) - - line = line_data.data().decode("utf-8", errors="ignore") - self._parse_sse_line(line) - - def _parse_sse_line(self, line: str): - """Parse individual SSE line""" - if not line: - # Empty line indicates end of event - if self._current_data: - if self._current_event: - self.event_received.emit(self._current_event, self._current_data) - else: - self.message_received.emit(self._current_data) - - # Clear current event data - self._current_event = "" - self._current_data = "" - self._current_id = "" - return - - # Skip comments - if line.startswith(":"): - return - - # Parse field and value - colon_index = line.find(":") - if colon_index == -1: - # Field with no value - field = line - if field == "data": - self._current_data += "\n" - return - - field = line[:colon_index] - value = line[colon_index + 1 :] - - # Remove leading space from value - value = value.removeprefix(" ") - - if field == "data": - if self._current_data: - self._current_data += "\n" - self._current_data += value - elif field == "event": - self._current_event = value - elif field == "id": - self._current_id = value - elif field == "retry": - try: - retry_time = int(value) - if retry_time > 0: - self._reconnect_delay = retry_time - except ValueError: - pass - - @Slot() - def _on_finished(self): - """Handle connection finished""" - if self._connected: - self._connected = False - self.disconnected.emit() - - if self._reply: - self._reply.deleteLater() - self._reply = None - - # Auto-reconnect after delay - print(f"SSE connection finished, reconnecting in {self._reconnect_delay}ms") - self._reconnect_timer.start(self._reconnect_delay) - - # Exponential backoff - self._reconnect_delay = min(self._reconnect_delay * 2, self._max_reconnect_delay) - - @Slot(QNetworkReply.NetworkError) - def _on_error(self, error: QNetworkReply.NetworkError): - """Handle network error""" - error_string = self._reply.errorString() if self._reply else "Unknown network error" - print(f"SSE Network error: {error} - {error_string}") - - self.error_occurred.emit(error_string) - - if self._connected: - self._connected = False - self.disconnected.emit() - - @Slot() - def _attempt_reconnect(self): - """Attempt to reconnect""" - print("Attempting to reconnect to SSE...") - self._start_connection() diff --git a/src/aare/gui/tutorials/__init__.py b/src/aare/gui/tutorials/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/aare/gui/tutorials/controls_help_dialog.py b/src/aare/gui/tutorials/controls_help_dialog.py deleted file mode 100644 index 0883e97a..00000000 --- a/src/aare/gui/tutorials/controls_help_dialog.py +++ /dev/null @@ -1,212 +0,0 @@ -from PySide6.QtCore import Qt -from PySide6.QtWidgets import QDialog, QDialogButtonBox, QTabWidget, QTextEdit, QVBoxLayout, QWidget - - -class ControlsHelpDialog(QDialog): - def __init__(self, parent=None): - super().__init__(parent) - - self.setWindowTitle("Mouse / Keyboard Controls") - self.setMinimumSize(760, 560) - - layout = QVBoxLayout(self) - - self._tabs = QTabWidget(self) - self._tabs.addTab( - self._create_tab( - """ -

Sample Camera

- -

Mouse Wheel

-
    -
  • 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
  • -
- -

Mouse Click / Drag

-
    -
  • Left click: move sample to clicked position
  • -
  • Shift + Left click: move using the special Z-alignment click behaviour
  • -
  • Ctrl + Left click on active raster grid: move to the clicked position under the grid
  • -
  • Left drag on active raster grid: move active raster grid
  • -
  • Right click: open sample camera context menu
  • -
  • Right drag on empty area: draw raster grid
  • -
  • Right drag on active raster grid: resize raster grid
  • -
- -

Mouse Move

-
    -
  • Shift + Mouse move: inspect/load raster image under cursor
  • -
  • Mouse move: show completed-grid tooltip or coordinates, depending on mode
  • -
- -

Beam Mark Mode

-
    -
  • Shift + Left click: set beam mark at clicked position
  • -
  • Mouse wheel: change exposure by a large step
  • -
  • Alt + Mouse wheel: change exposure by a small step
  • -
- """ - ), - "Sample Camera", - ) - self._tabs.addTab( - self._create_tab( - """ -

Sample Camera Context Menu

-
    -
  • Scale to fit
  • -
  • Show coordinates
  • -
  • Grab
  • -
  • Grab with overlay
  • -
  • Auto-focus
  • -
  • Mark beam center
  • -
  • Delete grid (when on active grid)
  • -
  • Evaluate grid (when on active grid)
  • -
  • Delete completed grids
  • -
- -

Notes

-
    -
  • Some actions appear only when the cursor is over the active raster grid.
  • -
  • Grid actions depend on the current sample camera state and current raster visibility.
  • -
- """ - ), - "Context Menu", - ) - self._tabs.addTab( - self._create_tab( - """ -

Video Views

-

Applies to gonio camera, beamline view, and combined beamline views.

- -

Mouse

-
    -
  • Ctrl + Mouse wheel: zoom in/out
  • -
  • Mouse wheel: normal scrolling when Ctrl is not pressed
  • -
  • Mouse drag: rubber-band drag/selection behaviour is enabled
  • -
- -

Keyboard

-
    -
  • F: fit to view
  • -
  • R: reset zoom
  • -
  • + or =: zoom in
  • -
  • -: zoom out
  • -
  • 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
  • -
- """ - ), - "Video Views", - ) - self._tabs.addTab( - self._create_tab( - """ -

Other Interactive Areas

- -

Sample Queue

-
    -
  • Delete: remove selected samples from the queue
  • -
  • Space: run / pause queue automation
  • -
  • Drag and drop: reorder queue items or add samples from the Sample List
  • -
- -

Workflow Panel

-
    -
  • Delete: remove selected queue items
  • -
  • Space: pause / resume workflow
  • -
  • Ctrl + R: refresh workflow queue
  • -
  • Ctrl + Delete: clear non-running workflow queue items
  • -
  • Right click on workflow queue item: start item, remove it, or move it in the queue
  • -
- -

Sample / Reference Tables

-
    -
  • Right click on sample row: open row actions such as mount
  • -
  • Right click on table header: open column filter options
  • -
- -

Fluorescence Plot

-
    -
  • Delete: remove selected samples from the queue
  • - -
  • Mouse move: show energy/count tooltip and vertical marker line
  • -
  • Right click: save spectrum as CSV
  • -
- -

Target Stability Panel

-
    -
  • Mouse wheel: zoom the selected wheel axis
  • -
  • Shift + Mouse wheel: zoom score axis
  • -
  • Left drag: pan selected axes
  • -
  • Right click: reset view / auto-scale
  • -
  • Click a visible trace point: target wheel/pan controls to that trace's axis group
  • -
- -

Status Bar / Labels

-
    -
  • Left click on session, p-group, shutter, and state labels: open quick action menus
  • -
- -

General Widgets

-
    -
  • Left click on clickable labels/value labels: trigger the widget's click action
  • -
- -

Notes

-
    -
  • Some wheel interactions are intentionally disabled in certain scroll areas to prevent accidental scrolling.
  • -
  • Available actions can depend on beamline state, current mode, and widget focus.
  • -
- """ - ), - "Other Panels", - ) - self._tabs.addTab( - self._create_tab( - """ -

Application Shortcuts

- -
    -
  • 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: go to Sample camera tab
  • -
  • 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
  • -
- """ - ), - "App Shortcuts", - ) - layout.addWidget(self._tabs) - - buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close, parent=self) - buttons.rejected.connect(self.reject) - buttons.accepted.connect(self.accept) - layout.addWidget(buttons) - - def _create_tab(self, html: str) -> QWidget: - text = QTextEdit(self) - text.setReadOnly(True) - text.setLineWrapMode(QTextEdit.LineWrapMode.WidgetWidth) - text.setTextInteractionFlags( - Qt.TextInteractionFlag.TextSelectableByMouse - | Qt.TextInteractionFlag.TextSelectableByKeyboard - ) - text.setHtml(html) - return text diff --git a/src/aare/gui/tutorials/tutorial_actions.py b/src/aare/gui/tutorials/tutorial_actions.py deleted file mode 100644 index bdfda44b..00000000 --- a/src/aare/gui/tutorials/tutorial_actions.py +++ /dev/null @@ -1,42 +0,0 @@ -from __future__ import annotations - -from typing import Any - -from aare.gui.tutorials.tutorial_models import TutorialAction, TutorialContext - - -def _set_nested_value(data: dict[str, Any], path: str, value: Any) -> None: - current = data - parts = path.split(".") - for part in parts[:-1]: - if part not in current or not isinstance(current[part], dict): - current[part] = {} - current = current[part] - current[parts[-1]] = value - - -class TutorialActionExecutor: - def __init__(self, window): - self.window = window - - def execute_action(self, action: TutorialAction, context: TutorialContext) -> None: - action_id = action.action_id - params = action.params - - if action_id == "enter_demo_mode": - context.demo_mode_enabled = True - _set_nested_value(context.state, "demo.enabled", True) - return - - if action_id == "exit_demo_mode": - context.demo_mode_enabled = False - _set_nested_value(context.state, "demo.enabled", False) - return - - if action_id == "set_context_state": - path = str(params["path"]) - value = params.get("value") - _set_nested_value(context.state, path, value) - return - - raise ValueError(f"Unknown tutorial action: {action_id}") diff --git a/src/aare/gui/tutorials/tutorial_manager.py b/src/aare/gui/tutorials/tutorial_manager.py deleted file mode 100644 index 8180a238..00000000 --- a/src/aare/gui/tutorials/tutorial_manager.py +++ /dev/null @@ -1,713 +0,0 @@ -from __future__ import annotations - -import time -from dataclasses import dataclass -from typing import Any - -from aarecommon.config.logger import setup_logger -from PySide6.QtCore import ( - Property, - QEasingCurve, - QObject, - QPropertyAnimation, - QRect, - Qt, - QTimer, - Signal, -) -from PySide6.QtGui import QPainter, QPen -from PySide6.QtWidgets import QLabel, QPushButton, QWidget - -from aare.gui.constants import LOGGER_NAME -from aare.gui.styles import ( - DEFAULT_TEXT, - FONT_BODY_LG, - FONT_TITLE, - NOTE_TEXT, - SHADOW, - TUTORIAL_BORDER, - TUTORIAL_HIGHLIGHT, - WHITE, - qcolor, -) -from aare.gui.tutorials.tutorial_models import ( - StepFlow, - StepStatus, - TutorialContext, - TutorialScenario, - TutorialStepDefinition, -) -from aare.gui.tutorials.tutorial_runtime import ( - CompletionEvaluator, - ResolvedTutorialTarget, - TutorialActionExecutor, - TutorialEvent, - TutorialEventBus, - TutorialTargetResolver, - TutorialTextResolver, - build_runtime_state_for_scenario, - ensure_step_runtime_state, -) - -logger = setup_logger(LOGGER_NAME) - - -def _now_ms() -> int: - return int(time.time() * 1000) - - -@dataclass(slots=True) -class OverlayStepViewModel: - title: str - body: str - hint: str | None = None - rect: QRect | None = None - can_go_next: bool = True - can_go_back: bool = False - can_skip: bool = False - next_label: str = "Next" - waiting_for_target_click: bool = False - - -class TutorialOverlay(QWidget): - """ - Presentation-only overlay. - - It knows how to: - - dim the app - - highlight a target rect - - show tutorial copy - - expose buttons/signals - - It does NOT know anything about tutorial scenarios or completion rules. - """ - - next_requested = Signal() - back_requested = Signal() - skip_requested = Signal() - cancelled = Signal() - highlight_clicked = Signal() - - def __init__(self, parent: QWidget | None = None): - super().__init__(parent) - self.setAttribute(Qt.WA_TransparentForMouseEvents, False) - self.setWindowFlags(Qt.FramelessWindowHint) - self.setAttribute(Qt.WA_TranslucentBackground, True) - self.setFocusPolicy(Qt.StrongFocus) - - self.current_rect = QRect() - self.target_rect = QRect() - self.opacity = 1.0 - self._waiting_for_click = False - self._highlight_padding_px = 6 - self._dummy = 0.0 - - self.anim = QPropertyAnimation(self, b"dummy") - self.anim.valueChanged.connect(self.update) - - self.callout = QLabel(self) - self.callout.setStyleSheet(f""" - background: {WHITE}; - color: {DEFAULT_TEXT}; - padding: 16px; - border: 2px solid {TUTORIAL_BORDER}; - border-radius: 10px; - font-size: {FONT_TITLE}; - """) - self.callout.setWordWrap(True) - self.callout.hide() - - button_style = f""" - QPushButton {{ - font-size: {FONT_BODY_LG}; - font-weight: 700; - padding: 10px 16px; - }} - """ - - self.back_button = QPushButton("Back", self) - self.back_button.setStyleSheet(button_style) - self.back_button.setMinimumHeight(44) - self.back_button.clicked.connect(self.back_requested.emit) - self.back_button.hide() - - self.skip_button = QPushButton("Skip", self) - self.skip_button.setStyleSheet(button_style) - self.skip_button.setMinimumHeight(44) - self.skip_button.clicked.connect(self.skip_requested.emit) - self.skip_button.hide() - - self.next_button = QPushButton("Next", self) - self.next_button.setStyleSheet(button_style) - self.next_button.setMinimumHeight(44) - self.next_button.clicked.connect(self.next_requested.emit) - self.next_button.hide() - - self.end_button = QPushButton("End tutorial", self) - self.end_button.setStyleSheet(button_style) - self.end_button.setMinimumHeight(44) - self.end_button.clicked.connect(self.cancelled.emit) - self.end_button.hide() - - self.hide() - - def get_dummy(self) -> float: - return float(self._dummy) - - def set_dummy(self, value: float) -> None: - self._dummy = float(value) - t = self._dummy - self.current_rect = self._interpolate_rect(self.current_rect, self.target_rect, t) - self.opacity = t - self.update() - - dummy = Property(float, get_dummy, set_dummy) - - def showEvent(self, event) -> None: - super().showEvent(event) - if self.parentWidget() is not None: - self.setGeometry(self.parentWidget().rect()) - self._position_end_button() - - def resizeEvent(self, event) -> None: - super().resizeEvent(event) - if self.parentWidget() is not None: - self.setGeometry(self.parentWidget().rect()) - self._position_end_button() - self._reposition_action_buttons() - - def keyPressEvent(self, event) -> None: - if event.key() == Qt.Key_Escape: - self.cancelled.emit() - event.accept() - return - super().keyPressEvent(event) - - def mousePressEvent(self, event) -> None: - if ( - self._waiting_for_click - and self.current_rect.isValid() - and self.current_rect.contains(event.pos()) - ): - self.highlight_clicked.emit() - event.accept() - return - super().mousePressEvent(event) - - def paintEvent(self, event) -> None: - painter = QPainter(self) - painter.fillRect(self.rect(), qcolor(SHADOW, int(150 * self.opacity))) - - if self.current_rect.isValid(): - pen = QPen(qcolor(TUTORIAL_HIGHLIGHT), 4) - painter.setPen(pen) - painter.setBrush(Qt.NoBrush) - painter.drawRoundedRect(self.current_rect, 8, 8) - - def animate_to(self, rect: QRect, duration: int = 300) -> None: - self.target_rect = rect.intersected(self.rect()) - self.anim.stop() - self.anim.setStartValue(0.0) - self.anim.setEndValue(1.0) - self.anim.setDuration(duration) - self.anim.setEasingCurve(QEasingCurve.InOutQuad) - self.anim.start() - - def set_step_view(self, view: OverlayStepViewModel) -> None: - rect = view.rect if view.rect is not None else QRect() - if rect.isValid(): - pad = int(self._highlight_padding_px) - rect = QRect(rect) - rect.adjust(-pad, -pad, pad, pad) - rect = rect.intersected(self.rect()) - - self.current_rect = rect - self.target_rect = rect - - text_parts = [] - if view.title.strip(): - text_parts.append(f"{view.title}") - if view.body.strip(): - text_parts.append(view.body) - if view.hint: - text_parts.append(f"{view.hint}") - - self.callout.setText("

".join(text_parts)) - self.callout.setMaximumWidth(460) - self.callout.adjustSize() - - self._waiting_for_click = bool(view.waiting_for_target_click) - - self.back_button.setVisible(True) - self.back_button.setEnabled(view.can_go_back) - - self.skip_button.setVisible(view.can_skip) - self.skip_button.setEnabled(view.can_skip) - - self.next_button.setVisible(True) - self.next_button.setEnabled(view.can_go_next) - self.next_button.setText(view.next_label) - - self.callout.show() - self._position_end_button() - self._position_callout(rect) - self._reposition_action_buttons() - self.update() - - def clear_view(self) -> None: - self.current_rect = QRect() - self.target_rect = QRect() - self.callout.hide() - self.back_button.hide() - self.skip_button.hide() - self.next_button.hide() - self.end_button.hide() - self._waiting_for_click = False - self.update() - - def _position_end_button(self) -> None: - self.end_button.adjustSize() - margin = 10 - x = max(margin, self.width() - self.end_button.width() - margin) - y = margin - self.end_button.move(x, y) - self.end_button.setVisible(True) - - def _position_callout(self, rect: QRect) -> None: - margin = 10 - - if rect.isValid(): - bubble_x = rect.x() - bubble_y_above = rect.y() - self.callout.height() - 12 - bubble_y_below = rect.y() + rect.height() + 12 - bubble_y = bubble_y_above if bubble_y_above >= margin else bubble_y_below - else: - bubble_x = margin - bubble_y = margin + 48 - - bubble_x = min( - max(margin, bubble_x), max(margin, self.width() - self.callout.width() - margin) - ) - bubble_y = min( - max(margin, bubble_y), max(margin, self.height() - self.callout.height() - margin - 60) - ) - - self.callout.move(bubble_x, bubble_y) - - def _reposition_action_buttons(self) -> None: - buttons = [ - btn for btn in (self.back_button, self.skip_button, self.next_button) if btn.isVisible() - ] - if not buttons: - return - - margin = 10 - spacing = 8 - y = self.callout.y() + self.callout.height() + 10 - - widths = [] - total_width = 0 - for btn in buttons: - btn.adjustSize() - widths.append(btn.width()) - total_width += btn.width() - - total_width += spacing * (len(buttons) - 1) - x = min( - max(margin, self.callout.x() + self.callout.width() - total_width), - max(margin, self.width() - total_width - margin), - ) - y = min( - max(margin, y), - max(margin, self.height() - max(btn.height() for btn in buttons) - margin), - ) - - for btn in buttons: - btn.move(x, y) - x += btn.width() + spacing - - @staticmethod - def _interpolate_rect(r1: QRect, r2: QRect, t: float) -> QRect: - x = r1.x() + (r2.x() - r1.x()) * t - y = r1.y() + (r2.y() - r1.y()) * t - w = r1.width() + (r2.width() - r1.width()) * t - h = r1.height() + (r2.height() - r1.height()) * t - return QRect(int(x), int(y), int(w), int(h)) - - -class TutorialManager(QObject): - """ - Scenario-driven tutorial controller. - - This replaces the old step model with: - - declarative scenarios - - runtime context/state - - target resolution - - text resolution - - action execution - - event-driven completion - """ - - tutorial_started = Signal(str) - tutorial_stopped = Signal(str) - tutorial_completed = Signal(str) - step_changed = Signal(str, str) # scenario_id, step_id - - def __init__( - self, - parent_window: QWidget, - target_resolver: TutorialTargetResolver, - text_resolver: TutorialTextResolver, - action_executor: TutorialActionExecutor, - event_bus: TutorialEventBus | None = None, - parent: QObject | None = None, - ): - super().__init__(parent) - self.window = parent_window - self.overlay = TutorialOverlay(parent_window) - - self.target_resolver = target_resolver - self.text_resolver = text_resolver - self.action_executor = action_executor - self.event_bus = event_bus or TutorialEventBus(self) - self.completion_evaluator = CompletionEvaluator(self.event_bus) - - self.scenarios: dict[str, TutorialScenario] = {} - - self.current_scenario: TutorialScenario | None = None - self.context: TutorialContext | None = None - self.runtime_state = None - self._current_resolved_target: ResolvedTutorialTarget | None = None - - self._step_timeout_timer = QTimer(self) - self._step_timeout_timer.setSingleShot(True) - self._step_timeout_timer.timeout.connect(self._on_step_timeout) - - self.overlay.next_requested.connect(self._on_next_requested) - self.overlay.back_requested.connect(self._on_back_requested) - self.overlay.skip_requested.connect(self._on_skip_requested) - self.overlay.cancelled.connect(self.stop) - self.overlay.highlight_clicked.connect(self._on_highlight_clicked) - - self.event_bus.event_emitted.connect(self._on_tutorial_event) - - def add_scenario(self, scenario: TutorialScenario) -> None: - self.scenarios[scenario.id] = scenario - - def start(self, scenario_id: str, language: str = "en") -> None: - scenario = self.scenarios.get(scenario_id) - if scenario is None: - raise ValueError(f"Tutorial scenario not found: {scenario_id}") - - if self.current_scenario is not None: - self.stop() - - self.current_scenario = scenario - self.context = TutorialContext(scenario_id=scenario.id, language=language) - self.runtime_state = build_runtime_state_for_scenario(scenario) - self.runtime_state.started_at_ms = _now_ms() - self.runtime_state.active_step_index = -1 - self._current_resolved_target = None - - self.overlay.setGeometry(self.window.rect()) - self.overlay.show() - self.overlay.raise_() - self.overlay.activateWindow() - self.overlay.setFocus() - - self.tutorial_started.emit(scenario.id) - self._advance_to_index(0) - - def stop(self) -> None: - scenario_id = self.current_scenario.id if self.current_scenario else None - - self._step_timeout_timer.stop() - - if self.current_scenario and self.context: - current_step = self.get_current_step() - if current_step is not None: - self._run_cleanup_actions(current_step) - - if self.runtime_state is not None: - self.runtime_state.stopped_at_ms = _now_ms() - - self.overlay.clear_view() - self.overlay.hide() - - self.current_scenario = None - self.context = None - self.runtime_state = None - self._current_resolved_target = None - - if scenario_id is not None: - self.tutorial_stopped.emit(scenario_id) - - def emit_event(self, name: str, payload: dict[str, Any] | None = None) -> TutorialEvent: - event = self.event_bus.emit_event(name, payload or {}) - if self.context is not None: - self.context.event_log.append(event) - return event - - def get_current_step(self) -> TutorialStepDefinition | None: - if self.current_scenario is None or self.runtime_state is None: - return None - - index = self.runtime_state.active_step_index - if not (0 <= index < len(self.current_scenario.steps)): - return None - return self.current_scenario.steps[index] - - def _advance_to_index(self, new_index: int) -> None: - if self.current_scenario is None or self.context is None or self.runtime_state is None: - return - - previous_step = self.get_current_step() - if previous_step is not None: - self._run_cleanup_actions(previous_step) - - if new_index >= len(self.current_scenario.steps): - scenario_id = self.current_scenario.id - self.runtime_state.completed_at_ms = _now_ms() - self.overlay.clear_view() - self.overlay.hide() - self.current_scenario = None - self.context = None - self.runtime_state = None - self._current_resolved_target = None - self.tutorial_completed.emit(scenario_id) - self.tutorial_stopped.emit(scenario_id) - return - - new_index = max(new_index, 0) - - self.runtime_state.active_step_index = new_index - step = self.current_scenario.steps[new_index] - - self.context.current_step_index = new_index - self.context.current_step_id = step.id - - step_state = ensure_step_runtime_state(self.runtime_state, step.id) - step_state.status = StepStatus.ACTIVE - if step_state.started_at_ms is None: - step_state.started_at_ms = _now_ms() - - self._run_setup_actions(step) - self._enter_current_step() - - def _enter_current_step(self) -> None: - if self.current_scenario is None or self.context is None or self.runtime_state is None: - return - - step = self.get_current_step() - if step is None: - return - - self._step_timeout_timer.stop() - self._current_resolved_target = self._resolve_step_target(step) - - title = self.text_resolver.resolve_text(step.title, self.context.language) - body = self.text_resolver.resolve_text(step.body, self.context.language) - hint = ( - self.text_resolver.resolve_text(step.hint, self.context.language) - if step.hint is not None - else None - ) - - rect = self._resolved_target_rect(self._current_resolved_target) - - if rect is not None and rect.isValid(): - self.overlay.animate_to(rect) - - is_first = self.runtime_state.active_step_index <= 0 - is_last = self.runtime_state.active_step_index == (len(self.current_scenario.steps) - 1) - - waiting_for_target_click = bool( - step.completion is not None and step.completion.kind.value == "target_clicked" - ) - can_go_next = step.flow == StepFlow.NEXT_ONLY - next_label = "Finish" if is_last and can_go_next else "Next" - - view = OverlayStepViewModel( - title=title, - body=body, - hint=hint, - rect=rect, - can_go_next=can_go_next, - can_go_back=self.current_scenario.allow_back and not is_first, - can_skip=self.current_scenario.allow_skip and step.skippable, - next_label=next_label, - waiting_for_target_click=waiting_for_target_click, - ) - self.overlay.set_step_view(view) - - if step.timeout_ms is not None and step.timeout_ms > 0: - self._step_timeout_timer.start(int(step.timeout_ms)) - - self.step_changed.emit(self.current_scenario.id, step.id) - self._try_auto_advance_current_step() - - def _resolve_step_target(self, step: TutorialStepDefinition) -> ResolvedTutorialTarget | None: - if step.target is None or self.context is None: - return None - try: - return self.target_resolver.resolve_target(step.target, self.context) - except Exception: - logger.debug("Could not resolve the tutorial step target", exc_info=True) - return None - - def _resolved_target_rect(self, resolved: ResolvedTutorialTarget | None) -> QRect | None: - if resolved is None: - return None - - if resolved.widget is not None: - widget = resolved.widget - top_left_global = widget.mapToGlobal(widget.rect().topLeft()) - bottom_right_global = widget.mapToGlobal(widget.rect().bottomRight()) - top_left = self.overlay.mapFromGlobal(top_left_global) - bottom_right = self.overlay.mapFromGlobal(bottom_right_global) - return QRect(top_left, bottom_right).normalized().intersected(self.overlay.rect()) - - if resolved.rect is not None: - return QRect(resolved.rect).intersected(self.overlay.rect()) - - return None - - def _run_setup_actions(self, step: TutorialStepDefinition) -> None: - if self.context is None: - return - for action in step.setup_actions: - self.action_executor.execute_action(action, self.context) - - def _run_cleanup_actions(self, step: TutorialStepDefinition) -> None: - if self.context is None: - return - for action in step.cleanup_actions: - self.action_executor.execute_action(action, self.context) - - def _mark_current_step_completed(self) -> None: - if self.current_scenario is None or self.context is None or self.runtime_state is None: - return - - step = self.get_current_step() - if step is None: - return - - step_state = ensure_step_runtime_state(self.runtime_state, step.id) - step_state.status = StepStatus.COMPLETED - step_state.completed_at_ms = _now_ms() - - if step.id not in self.context.completed_step_ids: - self.context.completed_step_ids.append(step.id) - - def _mark_current_step_skipped(self) -> None: - if self.current_scenario is None or self.context is None or self.runtime_state is None: - return - - step = self.get_current_step() - if step is None: - return - - step_state = ensure_step_runtime_state(self.runtime_state, step.id) - step_state.status = StepStatus.SKIPPED - step_state.skipped_at_ms = _now_ms() - - def _mark_current_step_failed(self, message: str | None = None) -> None: - if self.current_scenario is None or self.runtime_state is None: - return - - step = self.get_current_step() - if step is None: - return - - step_state = ensure_step_runtime_state(self.runtime_state, step.id) - step_state.status = StepStatus.FAILED - step_state.failed_at_ms = _now_ms() - step_state.last_error = message - - def _is_current_step_complete(self, *, target_clicked: bool = False) -> bool: - if self.context is None: - return False - - step = self.get_current_step() - if step is None: - return False - - if step.flow == StepFlow.NEXT_ONLY: - return False - - return self.completion_evaluator.is_step_complete( - step, self.context, target_clicked=target_clicked - ) - - def _try_auto_advance_current_step(self, *, target_clicked: bool = False) -> None: - step = self.get_current_step() - if step is None: - return - - if step.flow == StepFlow.NEXT_ONLY: - return - - if self._is_current_step_complete(target_clicked=target_clicked): - self._mark_current_step_completed() - assert self.runtime_state is not None - self._advance_to_index(self.runtime_state.active_step_index + 1) - - def _on_next_requested(self) -> None: - step = self.get_current_step() - if step is None or self.runtime_state is None: - return - - if step.flow == StepFlow.NEXT_ONLY: - self._mark_current_step_completed() - self._advance_to_index(self.runtime_state.active_step_index + 1) - return - - if self._is_current_step_complete(): - self._mark_current_step_completed() - self._advance_to_index(self.runtime_state.active_step_index + 1) - - def _on_back_requested(self) -> None: - if self.current_scenario is None or self.runtime_state is None: - return - if not self.current_scenario.allow_back: - return - - target_index = self.runtime_state.active_step_index - 1 - if target_index < 0: - return - - self._advance_to_index(target_index) - - def _on_skip_requested(self) -> None: - step = self.get_current_step() - if step is None or self.current_scenario is None or self.runtime_state is None: - return - if not self.current_scenario.allow_skip or not step.skippable: - return - self._mark_current_step_skipped() - self._advance_to_index(self.runtime_state.active_step_index + 1) - - def _on_highlight_clicked(self) -> None: - self._try_auto_advance_current_step(target_clicked=True) - - def _on_tutorial_event(self, event: TutorialEvent) -> None: - if self.current_scenario is None or self.context is None: - return - self._try_auto_advance_current_step() - - def _on_step_timeout(self) -> None: - step = self.get_current_step() - if step is None: - return - - self._mark_current_step_failed("Step timed out.") - - if ( - step.skippable - and self.current_scenario is not None - and self.current_scenario.allow_skip - ) and self.runtime_state is not None: - self._advance_to_index(self.runtime_state.active_step_index + 1) - return - - self.overlay.next_button.setEnabled(True) diff --git a/src/aare/gui/tutorials/tutorial_models.py b/src/aare/gui/tutorials/tutorial_models.py deleted file mode 100644 index fe2bae5c..00000000 --- a/src/aare/gui/tutorials/tutorial_models.py +++ /dev/null @@ -1,151 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass, field -from enum import Enum -from typing import Any - - -class TutorialMode(str, Enum): - LINEAR = "linear" - GUIDED = "guided" - SANDBOX = "sandbox" - - -class StepKind(str, Enum): - INFO = "info" - ACTION = "action" - CONFIRMATION = "confirmation" - - -class StepFlow(str, Enum): - NEXT_ONLY = "next_only" - AUTO_ADVANCE_ON_COMPLETE = "auto_advance_on_complete" - REQUIRE_COMPLETE_OR_SKIP = "require_complete_or_skip" - - -class StepStatus(str, Enum): - PENDING = "pending" - ACTIVE = "active" - COMPLETED = "completed" - SKIPPED = "skipped" - FAILED = "failed" - - -class TargetKind(str, Enum): - WIDGET = "widget" - REGION = "region" - DYNAMIC = "dynamic" - NONE = "none" - - -class CompletionKind(str, Enum): - MANUAL_NEXT = "manual_next" - TARGET_CLICKED = "target_clicked" - EVENT_OCCURRED = "event_occurred" - STATE_MATCH = "state_match" - ALL_OF = "all_of" - ANY_OF = "any_of" - - -@dataclass(slots=True) -class CompletionRule: - kind: CompletionKind - value: Any = None - children: list[CompletionRule] = field(default_factory=list) - description: TutorialTextRef | None = None - - -@dataclass(slots=True) -class TutorialTextRef: - key: str - args: dict[str, Any] = field(default_factory=dict) - - -@dataclass(slots=True) -class TutorialAction: - action_id: str - params: dict[str, Any] = field(default_factory=dict) - - -@dataclass(slots=True) -class TutorialEvent: - name: str - payload: dict[str, Any] = field(default_factory=dict) - - -@dataclass(slots=True) -class TutorialTarget: - kind: TargetKind - target_id: str - anchor: str | None = None - - -@dataclass(slots=True) -class TutorialStepState: - step_id: str - status: StepStatus = StepStatus.PENDING - started_at_ms: int | None = None - completed_at_ms: int | None = None - last_error: str | None = None - - -@dataclass(slots=True) -class TutorialStepDefinition: - id: str - kind: StepKind - title: TutorialTextRef - body: TutorialTextRef - - target: TutorialTarget | None = None - completion: CompletionRule | None = None - hint: TutorialTextRef | None = None - - flow: StepFlow = StepFlow.NEXT_ONLY - optional: bool = False - skippable: bool = True - timeout_ms: int | None = None - - success_message: TutorialTextRef | None = None - timeout_message: TutorialTextRef | None = None - error_message: TutorialTextRef | None = None - - setup_actions: list[TutorialAction] = field(default_factory=list) - cleanup_actions: list[TutorialAction] = field(default_factory=list) - - metadata: dict[str, Any] = field(default_factory=dict) - - -@dataclass(slots=True) -class TutorialScenario: - id: str - title: TutorialTextRef - description: TutorialTextRef - mode: TutorialMode - steps: list[TutorialStepDefinition] - - version: str = "1.0" - tags: set[str] = field(default_factory=set) - - requires_demo_context: bool = False - allow_skip: bool = True - allow_back: bool = True - estimated_minutes: int | None = None - - metadata: dict[str, Any] = field(default_factory=dict) - - -@dataclass(slots=True) -class TutorialContext: - scenario_id: str - language: str = "en" - - current_step_id: str | None = None - current_step_index: int = -1 - - demo_mode_enabled: bool = False - completed_step_ids: list[str] = field(default_factory=list) - - state: dict[str, Any] = field(default_factory=dict) - event_log: list[TutorialEvent] = field(default_factory=list) - - metadata: dict[str, Any] = field(default_factory=dict) diff --git a/src/aare/gui/tutorials/tutorial_registration.py b/src/aare/gui/tutorials/tutorial_registration.py deleted file mode 100644 index 76bd4771..00000000 --- a/src/aare/gui/tutorials/tutorial_registration.py +++ /dev/null @@ -1,154 +0,0 @@ -from __future__ import annotations - -from aare.gui.tutorials.tutorial_models import ( - StepFlow, - StepKind, - TargetKind, - TutorialAction, - TutorialMode, - TutorialScenario, - TutorialStepDefinition, - TutorialTarget, - TutorialTextRef, -) - - -def register_tutorials(window, tutorial_manager) -> None: - manual_workflow_demo = TutorialScenario( - id="manual_workflow_demo", - title=TutorialTextRef("tutorial.manual.title"), - description=TutorialTextRef("tutorial.manual.description"), - mode=TutorialMode.SANDBOX, - requires_demo_context=True, - allow_skip=True, - allow_back=True, - steps=[ - TutorialStepDefinition( - id="welcome", - kind=StepKind.INFO, - title=TutorialTextRef("tutorial.manual.welcome.title"), - body=TutorialTextRef( - "tutorial.manual.welcome.body", - {"sample_name": "test_sample", "sample_position": "X1-2"}, - ), - flow=StepFlow.NEXT_ONLY, - setup_actions=[ - TutorialAction("enter_demo_mode"), - TutorialAction( - "set_context_state", {"path": "demo.sample_name", "value": "test_sample"} - ), - TutorialAction( - "set_context_state", {"path": "demo.sample_position", "value": "X1-2"} - ), - ], - ), - TutorialStepDefinition( - id="sample_list", - kind=StepKind.INFO, - title=TutorialTextRef("tutorial.manual.sample_list.title"), - body=TutorialTextRef( - "tutorial.manual.sample_list.body", - {"sample_name": "test_sample", "sample_position": "X1-2"}, - ), - target=TutorialTarget(TargetKind.WIDGET, "tell_samples"), - flow=StepFlow.NEXT_ONLY, - ), - TutorialStepDefinition( - id="select_sample", - kind=StepKind.INFO, - title=TutorialTextRef("tutorial.manual.select_sample.title"), - body=TutorialTextRef( - "tutorial.manual.select_sample.body", {"sample_name": "test_sample"} - ), - hint=TutorialTextRef("tutorial.manual.select_sample.hint"), - target=TutorialTarget(TargetKind.WIDGET, "tell_samples"), - flow=StepFlow.NEXT_ONLY, - ), - TutorialStepDefinition( - id="mount_sample", - kind=StepKind.INFO, - title=TutorialTextRef("tutorial.manual.mount.title"), - body=TutorialTextRef("tutorial.manual.mount.body", {"sample_name": "test_sample"}), - hint=TutorialTextRef("tutorial.manual.mount.hint"), - target=TutorialTarget(TargetKind.WIDGET, "tell_samples"), - flow=StepFlow.NEXT_ONLY, - ), - TutorialStepDefinition( - id="sample_camera", - kind=StepKind.INFO, - title=TutorialTextRef("tutorial.manual.sample_camera.title"), - body=TutorialTextRef("tutorial.manual.sample_camera.body"), - hint=TutorialTextRef("tutorial.manual.sample_camera.hint"), - target=TutorialTarget(TargetKind.WIDGET, "sample_camera"), - flow=StepFlow.NEXT_ONLY, - ), - TutorialStepDefinition( - id="beamline_controls", - kind=StepKind.INFO, - title=TutorialTextRef("tutorial.manual.beamline_controls.title"), - body=TutorialTextRef("tutorial.manual.beamline_controls.body"), - target=TutorialTarget(TargetKind.WIDGET, "beamline_controls"), - flow=StepFlow.NEXT_ONLY, - ), - TutorialStepDefinition( - id="auto_loop_center", - kind=StepKind.INFO, - title=TutorialTextRef("tutorial.manual.auto_loop_center.title"), - body=TutorialTextRef("tutorial.manual.auto_loop_center.body"), - target=TutorialTarget(TargetKind.WIDGET, "beamline_loop_center_auto"), - flow=StepFlow.NEXT_ONLY, - ), - TutorialStepDefinition( - id="ml_box", - kind=StepKind.INFO, - title=TutorialTextRef("tutorial.manual.ml_box.title"), - body=TutorialTextRef("tutorial.manual.ml_box.body"), - target=TutorialTarget(TargetKind.WIDGET, "beamline_loop_center_box"), - flow=StepFlow.NEXT_ONLY, - ), - TutorialStepDefinition( - id="raster_parameters", - kind=StepKind.INFO, - title=TutorialTextRef("tutorial.manual.raster_parameters.title"), - body=TutorialTextRef("tutorial.manual.raster_parameters.body"), - target=TutorialTarget(TargetKind.WIDGET, "raster_parameters"), - flow=StepFlow.NEXT_ONLY, - ), - TutorialStepDefinition( - id="raster_canvas", - kind=StepKind.INFO, - title=TutorialTextRef("tutorial.manual.raster_canvas.title"), - body=TutorialTextRef("tutorial.manual.raster_canvas.body"), - hint=TutorialTextRef("tutorial.manual.raster_canvas.hint"), - target=TutorialTarget(TargetKind.WIDGET, "raster_canvas"), - flow=StepFlow.NEXT_ONLY, - ), - TutorialStepDefinition( - id="rotation_parameters", - kind=StepKind.INFO, - title=TutorialTextRef("tutorial.manual.rotation_parameters.title"), - body=TutorialTextRef("tutorial.manual.rotation_parameters.body"), - target=TutorialTarget(TargetKind.WIDGET, "rotation_parameters"), - flow=StepFlow.NEXT_ONLY, - ), - TutorialStepDefinition( - id="simple_collection", - kind=StepKind.INFO, - title=TutorialTextRef("tutorial.manual.simple_collection.title"), - body=TutorialTextRef("tutorial.manual.simple_collection.body"), - target=TutorialTarget(TargetKind.WIDGET, "simple_collection_parameters"), - flow=StepFlow.NEXT_ONLY, - ), - TutorialStepDefinition( - id="file_names", - kind=StepKind.INFO, - title=TutorialTextRef("tutorial.manual.file_names.title"), - body=TutorialTextRef("tutorial.manual.file_names.body"), - target=TutorialTarget(TargetKind.WIDGET, "file_path_panel"), - flow=StepFlow.NEXT_ONLY, - cleanup_actions=[TutorialAction("exit_demo_mode")], - ), - ], - ) - - tutorial_manager.add_scenario(manual_workflow_demo) diff --git a/src/aare/gui/tutorials/tutorial_runtime.py b/src/aare/gui/tutorials/tutorial_runtime.py deleted file mode 100644 index 1d8f1bf1..00000000 --- a/src/aare/gui/tutorials/tutorial_runtime.py +++ /dev/null @@ -1,290 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass, field -from typing import Any, Protocol, runtime_checkable - -from aarecommon.config.logger import setup_logger -from PySide6.QtCore import QObject, QRect, Signal -from PySide6.QtWidgets import QWidget - -from aare.gui.constants import LOGGER_NAME -from aare.gui.tutorials.tutorial_models import ( - CompletionKind, - CompletionRule, - StepStatus, - TutorialAction, - TutorialContext, - TutorialEvent, - TutorialScenario, - TutorialStepDefinition, - TutorialTarget, - TutorialTextRef, -) - -logger = setup_logger(LOGGER_NAME) - - -@dataclass(slots=True) -class ResolvedTutorialTarget: - """ - Runtime representation of a tutorial target. - - A target may resolve to: - - a live widget - - a concrete rectangle - - both - """ - - target_id: str - widget: QWidget | None = None - rect: QRect | None = None - metadata: dict[str, Any] = field(default_factory=dict) - - -@dataclass(slots=True) -class TutorialStepRuntimeState: - step_id: str - status: StepStatus = StepStatus.PENDING - started_at_ms: int | None = None - completed_at_ms: int | None = None - skipped_at_ms: int | None = None - failed_at_ms: int | None = None - last_error: str | None = None - metadata: dict[str, Any] = field(default_factory=dict) - - -@dataclass(slots=True) -class TutorialScenarioRuntimeState: - scenario_id: str - active_step_index: int = -1 - step_states: dict[str, TutorialStepRuntimeState] = field(default_factory=dict) - started_at_ms: int | None = None - completed_at_ms: int | None = None - stopped_at_ms: int | None = None - metadata: dict[str, Any] = field(default_factory=dict) - - -@runtime_checkable -class TutorialTargetResolver(Protocol): - def resolve_target( - self, target: TutorialTarget, context: TutorialContext - ) -> ResolvedTutorialTarget | None: - """ - Resolve a declarative TutorialTarget into a live runtime target. - """ - ... - - -@runtime_checkable -class TutorialTextResolver(Protocol): - def resolve_text(self, text: TutorialTextRef, language: str) -> str: - """ - Resolve a TutorialTextRef into display text for the given language. - """ - ... - - -@runtime_checkable -class TutorialActionExecutor(Protocol): - def execute_action(self, action: TutorialAction, context: TutorialContext) -> None: - """ - Execute a model-defined tutorial action. - """ - ... - - -class TutorialEventBus(QObject): - """ - Minimal event bus for tutorial-relevant GUI/application events. - """ - - event_emitted = Signal(object) - - def __init__(self, parent: QObject | None = None): - super().__init__(parent) - self._events: list[TutorialEvent] = [] - - def emit_event(self, name: str, payload: dict[str, Any] | None = None) -> TutorialEvent: - event = TutorialEvent(name=name, payload=payload or {}) - self._events.append(event) - self.event_emitted.emit(event) - return event - - def events(self) -> list[TutorialEvent]: - return list(self._events) - - def clear(self) -> None: - self._events.clear() - - def has_event(self, name: str, **expected_payload: Any) -> bool: - for event in self._events: - if event.name != name: - continue - if all(event.payload.get(k) == v for k, v in expected_payload.items()): - return True - return False - - def last_event(self, name: str) -> TutorialEvent | None: - for event in reversed(self._events): - if event.name == name: - return event - return None - - -class DictionaryTextResolver: - """ - Simple resolver backed by in-memory dictionaries. - - translations example: - { - "en": { - "tutorial.ui.next": "Next", - "tutorial.manual.mount.body": "Right-click on {sample_name}.", - } - } - """ - - def __init__(self, translations: dict[str, dict[str, str]] | None = None): - self._translations = translations or {} - - def resolve_text(self, text: TutorialTextRef, language: str) -> str: - template = self._translations.get(language, {}).get(text.key, text.key) - try: - return template.format(**text.args) - except Exception: - logger.debug("Could not resolve the tutorial text template", exc_info=True) - return template - - -class NoOpActionExecutor: - """ - Safe default action executor that intentionally does nothing. - Useful while wiring the system up incrementally. - """ - - def execute_action(self, action: TutorialAction, context: TutorialContext) -> None: - return - - -class DictTargetResolver: - """ - Simple target resolver for direct target-id -> widget mapping. - - This is a good first implementation for the GUI. - """ - - def __init__(self, widget_map: dict[str, QWidget]): - self._widget_map = dict(widget_map) - - def resolve_target( - self, target: TutorialTarget, context: TutorialContext - ) -> ResolvedTutorialTarget | None: - widget = self._widget_map.get(target.target_id) - if widget is None: - return None - return ResolvedTutorialTarget(target_id=target.target_id, widget=widget, rect=widget.rect()) - - -class CompletionEvaluator: - """ - Evaluates a CompletionRule using tutorial context and event history. - """ - - def __init__(self, event_bus: TutorialEventBus): - self._event_bus = event_bus - - def is_step_complete( - self, - step: TutorialStepDefinition, - context: TutorialContext, - *, - target_clicked: bool = False, - ) -> bool: - if step.completion is None: - return True - return self.evaluate(step.completion, context, target_clicked=target_clicked) - - def evaluate( - self, rule: CompletionRule, context: TutorialContext, *, target_clicked: bool = False - ) -> bool: - match rule.kind: - case CompletionKind.MANUAL_NEXT: - return False - - case CompletionKind.TARGET_CLICKED: - return bool(target_clicked) - - case CompletionKind.EVENT_OCCURRED: - return self._evaluate_event_rule(rule) - - case CompletionKind.STATE_MATCH: - return self._evaluate_state_rule(rule, context) - - case CompletionKind.ALL_OF: - return all( - self.evaluate(child, context, target_clicked=target_clicked) - for child in rule.children - ) - - case CompletionKind.ANY_OF: - return any( - self.evaluate(child, context, target_clicked=target_clicked) - for child in rule.children - ) - - return False - - def _evaluate_event_rule(self, rule: CompletionRule) -> bool: - if not isinstance(rule.value, dict): - return False - - event_name = rule.value.get("event_name") - if not event_name: - return False - - expected_payload = dict(rule.value.get("payload") or {}) - return self._event_bus.has_event(str(event_name), **expected_payload) - - def _evaluate_state_rule(self, rule: CompletionRule, context: TutorialContext) -> bool: - if not isinstance(rule.value, dict): - return False - - path = rule.value.get("path") - expected = rule.value.get("equals") - - if not path or not isinstance(path, str): - return False - - actual = get_nested_value(context.state, path) - return actual == expected - - -def get_nested_value(data: dict[str, Any], path: str, default: Any = None) -> Any: - """ - Resolve dotted paths like 'demo.raster.params_valid' inside nested dictionaries. - """ - current: Any = data - for part in path.split("."): - if not isinstance(current, dict): - return default - if part not in current: - return default - current = current[part] - return current - - -def ensure_step_runtime_state( - runtime_state: TutorialScenarioRuntimeState, step_id: str -) -> TutorialStepRuntimeState: - state = runtime_state.step_states.get(step_id) - if state is None: - state = TutorialStepRuntimeState(step_id=step_id) - runtime_state.step_states[step_id] = state - return state - - -def build_runtime_state_for_scenario(scenario: TutorialScenario) -> TutorialScenarioRuntimeState: - runtime_state = TutorialScenarioRuntimeState(scenario_id=scenario.id) - for step in scenario.steps: - runtime_state.step_states[step.id] = TutorialStepRuntimeState(step_id=step.id) - return runtime_state diff --git a/src/aare/gui/tutorials/tutorial_targets.py b/src/aare/gui/tutorials/tutorial_targets.py deleted file mode 100644 index e5e1ee30..00000000 --- a/src/aare/gui/tutorials/tutorial_targets.py +++ /dev/null @@ -1,39 +0,0 @@ -from __future__ import annotations - -from PySide6.QtWidgets import QWidget - -from aare.gui.tutorials.tutorial_models import TutorialContext, TutorialTarget -from aare.gui.tutorials.tutorial_runtime import ResolvedTutorialTarget - - -class MainWindowTutorialTargetResolver: - def __init__(self, window: QWidget): - self.window = window - - def resolve_target( - self, target: TutorialTarget, context: TutorialContext - ) -> ResolvedTutorialTarget | None: - beamline = getattr(self.window, "beamline", None) - data_collection = getattr(self.window, "data_collection", None) - loopctr = getattr(beamline, "loopctr", None) - - widget_map: dict[str, QWidget | None] = { - "tell_samples": getattr(self.window, "tell_samples", None), - "sample_camera": getattr(self.window, "sample_camera", None), - "beamline_controls": beamline, - "beamline_loop_center": loopctr, - "beamline_loop_center_auto": getattr(loopctr, "find_tip", None), - "beamline_loop_center_box": getattr(loopctr, "bounding_box", None), - "raster_panel": getattr(data_collection, "raster", None), - "raster_parameters": getattr(data_collection, "raster", None), - "raster_canvas": getattr(self.window, "sample_camera", None), - "rotation_parameters": getattr(data_collection, "screening", None), - "simple_collection_parameters": getattr(data_collection, "simple", None), - "file_path_panel": getattr(data_collection, "file_path_panel", None), - } - - widget = widget_map.get(target.target_id) - if widget is None: - return None - - return ResolvedTutorialTarget(target_id=target.target_id, widget=widget, rect=widget.rect()) diff --git a/src/aare/gui/tutorials/tutroial_texts.py b/src/aare/gui/tutorials/tutroial_texts.py deleted file mode 100644 index 92550bf9..00000000 --- a/src/aare/gui/tutorials/tutroial_texts.py +++ /dev/null @@ -1,77 +0,0 @@ -MANUAL_MOUNT_TUTORIAL = { - "en": { - "tutorial.manual.title": "Manual workflow tutorial", - "tutorial.manual.description": "A guided walkthrough of the manual sample-centering and collection workflow.", - "tutorial.manual.welcome.title": "Welcome", - "tutorial.manual.welcome.body": ( - "This tutorial walks through the manual workflow using the test sample " - "'{sample_name}' in position {sample_position}. " - "It is intended to teach the interface and the normal order of operations." - ), - "tutorial.manual.sample_list.title": "Sample list", - "tutorial.manual.sample_list.body": ( - "This is the sample list. For this tutorial, look for '{sample_name}' " - "in position {sample_position}." - ), - "tutorial.manual.select_sample.title": "Selecting a sample", - "tutorial.manual.select_sample.body": ( - "Start by selecting '{sample_name}' in the sample list." - ), - "tutorial.manual.select_sample.hint": ( - "Later we can validate this step from a real selection event." - ), - "tutorial.manual.mount.title": "Mounting the sample", - "tutorial.manual.mount.body": ( - "To mount the sample, right-click '{sample_name}' and choose the mount action." - ), - "tutorial.manual.mount.hint": ( - "This is the real workflow: select the sample, right-click it, and mount it from the context menu." - ), - "tutorial.manual.sample_camera.title": "Sample camera", - "tutorial.manual.sample_camera.body": ( - "This is the main sample camera view. The orange square is the beam marker. " - "Left-clicking on the sample moves the smargon so that the selected point moves to the beam position." - ), - "tutorial.manual.sample_camera.hint": ( - "You can also use the mouse wheel here to rotate omega by 90° steps." - ), - "tutorial.manual.beamline_controls.title": "Beamline controls", - "tutorial.manual.beamline_controls.body": ( - "Additional controls for sample motion, lighting, zoom, and alignment are available in this panel." - ), - "tutorial.manual.auto_loop_center.title": "Auto loop centering", - "tutorial.manual.auto_loop_center.body": ( - "This button runs automatic loop centering. It can help bring the sample into position automatically." - ), - "tutorial.manual.ml_box.title": "ML box raster generation", - "tutorial.manual.ml_box.body": ( - "This button uses the ML box tool to generate a raster region automatically from the camera image." - ), - "tutorial.manual.raster_parameters.title": "Raster parameters", - "tutorial.manual.raster_parameters.body": ( - "Here you can change raster collection parameters such as exposure, transmission, " - "grid size, and other raster settings before evaluating the scan." - ), - "tutorial.manual.raster_canvas.title": "Drawing a raster", - "tutorial.manual.raster_canvas.body": ( - "You can draw a raster grid in the sample camera view using the mouse." - ), - "tutorial.manual.raster_canvas.hint": ( - "Use the mouse right-click workflow you described to create the raster region on the sample." - ), - "tutorial.manual.rotation_parameters.title": "Rotation parameters", - "tutorial.manual.rotation_parameters.body": ( - "This panel contains rotation scan parameters. You can change the values, " - "reload parameters from the database, or override them with user-defined values." - ), - "tutorial.manual.simple_collection.title": "Simple data collection", - "tutorial.manual.simple_collection.body": ( - "This panel contains simplified data-collection parameters for quick collection setup." - ), - "tutorial.manual.file_names.title": "File names and paths", - "tutorial.manual.file_names.body": ( - "Here you can review filenames and output paths before collection. " - "This is where you should explain how filenames are constructed and where data will be written." - ), - } -} diff --git a/src/aare/gui/widgets/__init__.py b/src/aare/gui/widgets/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/aare/gui/widgets/alert_banner.py b/src/aare/gui/widgets/alert_banner.py deleted file mode 100644 index 2198f178..00000000 --- a/src/aare/gui/widgets/alert_banner.py +++ /dev/null @@ -1,195 +0,0 @@ -from aarecommon.config.logger import setup_logger -from PySide6.QtCore import QPoint, Qt, QTimer, Slot -from PySide6.QtWidgets import QFrame, QGraphicsDropShadowEffect, QHBoxLayout, QLabel, QSizePolicy - -from aare.gui.constants import LOGGER_NAME -from aare.gui.styles import SHADOW, qcolor - -logger = setup_logger(LOGGER_NAME) - - -class AlertBanner(QFrame): - def __init__(self, parent=None): - super().__init__(parent) - - self.setObjectName("alertBanner") - self.setProperty("alertKind", "error") - - self._current_message = None - self._current_is_error = None - self._clear_timer = QTimer(self) - self._clear_timer.setSingleShot(True) - self._clear_timer.timeout.connect(self.clear_message) - - # Countdown timer for "waiting" state - self._countdown_timer = QTimer(self) - self._countdown_timer.setInterval(1000) - self._countdown_timer.timeout.connect(self._tick_countdown) - self._countdown_remaining = 0 - self._countdown_base_message = "" - - self._label = QLabel("", self) - self._label.setWordWrap(True) - self._label.setAlignment(Qt.AlignmentFlag.AlignCenter) - - layout = QHBoxLayout(self) - layout.setContentsMargins(24, 12, 24, 12) - layout.addWidget(self._label) - - shadow = QGraphicsDropShadowEffect(self) - shadow.setBlurRadius(18) - shadow.setOffset(0, 3) - shadow.setColor(qcolor(SHADOW, 55)) - self.setGraphicsEffect(shadow) - - self.setVisible(False) - self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) - - self._float_host = None - self._float_anchor = None - - def float_over(self, host) -> None: - """Overlay this banner at the top of `host` instead of occupying layout - space — added because showing/hiding the baton banner was shifting the - whole content stack up and down. No event filters on purpose: filters - firing during widget teardown corrupted PySide (tests crashed with - "QPushButton returned NULL"); the host repositions us on resize instead - (see _AlertBannerHost in main_window).""" - self.setParent(host) - self._float_host = host - # Click-through: the banner covers live UI now, so it must not eat - # mouse events meant for the widgets underneath. - self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True) - - def anchor_to(self, widget) -> None: - """Render as a compact toast under `widget`'s bottom edge (must be a - descendant of the float host) instead of a full-width top bar — the - baton messages sit below the sample camera view this way. Falls back - to the top bar while the anchor is hidden. - ponytail: position goes stale if a splitter drag moves the anchor while - the toast is up; it self-corrects on the next show.""" - self._float_anchor = widget - - def showEvent(self, event): - super().showEvent(event) - self.reposition() - - def reposition(self) -> None: - host = self._float_host - if host is None or not self.isVisible(): - return - anchor = self._float_anchor - if anchor is not None and anchor.isVisible(): - top_left = anchor.mapTo(host, QPoint(0, 0)) - w = min(self.sizeHint().width(), anchor.width()) - h = self.heightForWidth(w) if self.hasHeightForWidth() else self.sizeHint().height() - x = top_left.x() + (anchor.width() - w) // 2 - y = min(top_left.y() + anchor.height() + 4, host.height() - h) - self.setGeometry(x, y, w, h) - else: - w = host.width() - h = self.heightForWidth(w) if self.hasHeightForWidth() else self.sizeHint().height() - self.setGeometry(0, 0, w, h) - self.raise_() - - def _set_alert_kind(self, kind: str) -> None: - self.setProperty("alertKind", kind) - self.style().unpolish(self) - self.style().polish(self) - self.style().unpolish(self._label) - self.style().polish(self._label) - self.update() - - @Slot(str, bool) - def show_message(self, msg: str, is_error: bool = True, auto_clear_ms: int | None = None): - """Show error (red) or success (green) message.""" - self._stop_countdown() - self._clear_timer.stop() - - if not msg: - self.clear_message() - return - - if is_error: - decorated = f"🛑 {msg} 🛑" - self._set_alert_kind("error") - else: - decorated = f"✅ {msg} ✅" - self._set_alert_kind("success") - if auto_clear_ms is None: - timeout = 5000 - else: - timeout = int(auto_clear_ms) - self._clear_timer.start(timeout) - - self._current_message = msg - self._current_is_error = is_error - self._label.setText(decorated) - self.setVisible(True) - # Resize to the new text even when already visible (no showEvent then). - self.reposition() - - @Slot(str, int) - def show_waiting(self, msg: str, countdown_seconds: int = 0): - """ - Show a waiting/pending message (yellow) with optional countdown. - - Args: - msg: Base message to display - countdown_seconds: If > 0, append countdown and auto-update - """ - self._clear_timer.stop() - self._stop_countdown() - - if not msg: - self.clear_message() - return - - self._countdown_base_message = msg - self._countdown_remaining = countdown_seconds - - self._apply_waiting_style() - self._update_waiting_text() - - if countdown_seconds > 0: - self._countdown_timer.start() - - self.setVisible(True) - self.reposition() - - def _apply_waiting_style(self): - """Apply yellow/waiting style.""" - self._set_alert_kind("waiting") - - def _update_waiting_text(self): - """Update the waiting message text, including countdown if active.""" - if self._countdown_remaining > 0: - decorated = f"⏳ {self._countdown_base_message} ({self._countdown_remaining}s) ⏳" - else: - decorated = f"⏳ {self._countdown_base_message} ⏳" - self._label.setText(decorated) - - def _tick_countdown(self): - """Called every second during countdown.""" - self._countdown_remaining -= 1 - if self._countdown_remaining <= 0: - self._stop_countdown() - self.clear_message() - return - - self._update_waiting_text() - - def _stop_countdown(self): - """Stop the countdown timer.""" - self._countdown_timer.stop() - self._countdown_remaining = 0 - self._countdown_base_message = "" - - @Slot() - def clear_message(self): - self._current_message = None - self._current_is_error = None - self._clear_timer.stop() - self._set_alert_kind("error") - self._label.clear() - self.setVisible(False) diff --git a/src/aare/gui/widgets/baton_request_dialog.py b/src/aare/gui/widgets/baton_request_dialog.py deleted file mode 100644 index 0bc9c919..00000000 --- a/src/aare/gui/widgets/baton_request_dialog.py +++ /dev/null @@ -1,376 +0,0 @@ -from PySide6.QtCore import Qt, QTimer, Signal -from PySide6.QtGui import QFont -from PySide6.QtWidgets import ( - QDialog, - QFrame, - QHBoxLayout, - QLabel, - QProgressBar, - QPushButton, - QVBoxLayout, -) - -from aare.gui.styles import ( - BATON_DANGER_BG, - BATON_DANGER_HOVER, - BATON_DANGER_PRESSED, - BATON_INFO, - BATON_OK_BG, - BATON_OK_HOVER, - BATON_OK_PRESSED, - BATON_WARN, - DIM_TEXT, - FONT_BODY, - FONT_LABEL, - HINT_TEXT, - LIGHT_BORDER, - PROGRESS_TRACK_BG, - WHITE, -) - -# Tall touch targets for the three baton hand-over buttons (Accept / Refuse / -# Cancel Request) — operators hit these under time pressure. -_BUTTON_HEIGHT = "88px" - - -class BatonRequestDialog(QDialog): - """ - Dialog shown to current baton holder when someone requests control. - - Based on the workflow diagram: - - User can Accept (transfer immediately or queue if busy) - - User can Refuse (deny the request) - - If user ignores/closes, timeout causes auto-transfer - """ - - accepted_signal = Signal() - refused_signal = Signal() - - def __init__(self, requester: str, timeout_seconds: int = 30, parent=None): - super().__init__(parent) - self.setWindowTitle("⚡ Baton Request") - self.setModal(False) # Non-modal so user can see beamline status - self.setMinimumWidth(400) - self.setWindowFlags(self.windowFlags() | Qt.WindowType.WindowStaysOnTopHint) - - self._timeout = timeout_seconds - self._remaining = timeout_seconds - self._requester = requester - - self._setup_ui() - self._start_timer() - - def _setup_ui(self): - layout = QVBoxLayout(self) - layout.setSpacing(15) - - # Header - header = QLabel("🔔 Control Request") - header_font = QFont() - header_font.setPointSize(14) - header_font.setBold(True) - header.setFont(header_font) - header.setAlignment(Qt.AlignmentFlag.AlignCenter) - layout.addWidget(header) - - # Separator - line = QFrame() - line.setFrameShape(QFrame.Shape.HLine) - line.setFrameShadow(QFrame.Shadow.Sunken) - layout.addWidget(line) - - # Message - self.message_label = QLabel( - f"{self._requester} is requesting control of the beamline." - ) - self.message_label.setWordWrap(True) - self.message_label.setAlignment(Qt.AlignmentFlag.AlignCenter) - layout.addWidget(self.message_label) - - # Timeout progress - progress_layout = QVBoxLayout() - - self.progress = QProgressBar() - self.progress.setRange(0, self._timeout) - self.progress.setValue(self._timeout) - self.progress.setTextVisible(False) - self.progress.setFixedHeight(8) - self.progress.setStyleSheet(f""" - QProgressBar {{ - border: 1px solid {LIGHT_BORDER}; - border-radius: 4px; - background-color: {PROGRESS_TRACK_BG}; - }} - QProgressBar::chunk {{ - background-color: {BATON_OK_BG}; - border-radius: 3px; - }} - """) - progress_layout.addWidget(self.progress) - - self.time_label = QLabel(f"{self._timeout} seconds remaining") - self.time_label.setAlignment(Qt.AlignmentFlag.AlignCenter) - self.time_label.setStyleSheet(f"color: {DIM_TEXT};") - progress_layout.addWidget(self.time_label) - - layout.addLayout(progress_layout) - - # Warning about auto-transfer - self.warning_label = QLabel("⚠️ If you don't respond, control will transfer automatically.") - self.warning_label.setWordWrap(True) - self.warning_label.setAlignment(Qt.AlignmentFlag.AlignCenter) - self.warning_label.setStyleSheet(f"color: {BATON_WARN}; font-style: italic;") - layout.addWidget(self.warning_label) - - # Buttons - button_layout = QHBoxLayout() - button_layout.setSpacing(20) - - # Height lives in QSS, not setMinimumHeight(): the app stylesheet caps - # every QPushButton at 16px (styles.py) and Qt re-applies that cap via - # setMin/MaxHeight at polish, overwriting any value set here in code. - self.accept_btn = QPushButton("✓ Accept") - self.accept_btn.setStyleSheet(f""" - QPushButton {{ - background-color: {BATON_OK_BG}; - color: {WHITE}; - border: none; - border-radius: 5px; - min-height: {_BUTTON_HEIGHT}; - max-height: {_BUTTON_HEIGHT}; - font-weight: bold; - font-size: {FONT_LABEL}; - }} - QPushButton:hover {{ - background-color: {BATON_OK_HOVER}; - }} - QPushButton:pressed {{ - background-color: {BATON_OK_PRESSED}; - }} - """) - self.accept_btn.clicked.connect(self._on_accept) - button_layout.addWidget(self.accept_btn) - - self.refuse_btn = QPushButton("✗ Refuse") - self.refuse_btn.setStyleSheet(f""" - QPushButton {{ - background-color: {BATON_DANGER_BG}; - color: {WHITE}; - border: none; - border-radius: 5px; - min-height: {_BUTTON_HEIGHT}; - max-height: {_BUTTON_HEIGHT}; - font-weight: bold; - font-size: {FONT_LABEL}; - }} - QPushButton:hover {{ - background-color: {BATON_DANGER_HOVER}; - }} - QPushButton:pressed {{ - background-color: {BATON_DANGER_PRESSED}; - }} - """) - self.refuse_btn.clicked.connect(self._on_refuse) - button_layout.addWidget(self.refuse_btn) - - layout.addLayout(button_layout) - - # Info text - info_label = QLabel( - "If the beamline is busy, transfer will occur after " - "the current operation completes." - ) - info_label.setWordWrap(True) - info_label.setAlignment(Qt.AlignmentFlag.AlignCenter) - info_label.setStyleSheet(f"color: {HINT_TEXT};") - layout.addWidget(info_label) - - def _start_timer(self): - self._timer = QTimer(self) - self._timer.setInterval(1000) - self._timer.timeout.connect(self._tick) - # finished fires on accept/reject/close alike — replaces the - # closeEvent override that existed only to stop this timer. - self.finished.connect(self._timer.stop) - self._timer.start() - - def _tick(self): - self._remaining -= 1 - self.progress.setValue(self._remaining) - self.time_label.setText(f"{self._remaining} seconds remaining") - - # Change progress bar color as time runs out - if self._remaining <= 10: - self.progress.setStyleSheet(f""" - QProgressBar {{ - border: 1px solid {LIGHT_BORDER}; - border-radius: 4px; - background-color: {PROGRESS_TRACK_BG}; - }} - QProgressBar::chunk {{ - background-color: {BATON_WARN}; - border-radius: 3px; - }} - """) - - if self._remaining <= 5: - self.progress.setStyleSheet(f""" - QProgressBar {{ - border: 1px solid {LIGHT_BORDER}; - border-radius: 4px; - background-color: {PROGRESS_TRACK_BG}; - }} - QProgressBar::chunk {{ - background-color: {BATON_DANGER_BG}; - border-radius: 3px; - }} - """) - self.time_label.setStyleSheet(f"color: {BATON_DANGER_BG}; font-weight: bold;") - - if self._remaining <= 0: - self._timer.stop() - # Timeout = auto-accept (as per your diagram: "Ignores request" → auto transfer) - self._on_accept() - - def _on_accept(self): - self.accepted_signal.emit() - self.accept() - - def _on_refuse(self): - self.refused_signal.emit() - self.reject() - - -class BatonPendingDialog(QDialog): - """ - Dialog shown to the user who requested the baton while they wait for a response - or for the beamline queue to clear. - """ - - cancelled_signal = Signal() - - def __init__(self, target_user: str, timeout_seconds: int = 30, parent=None): - super().__init__(parent) - self.setWindowTitle("⏳ Baton Request Pending") - self.setModal(False) - self.setMinimumWidth(400) - self.setWindowFlags(self.windowFlags() | Qt.WindowType.WindowStaysOnTopHint) - - self._timeout = timeout_seconds - self._remaining = timeout_seconds - self._target_user = target_user - - self._setup_ui() - self._start_timer() - - def _setup_ui(self): - layout = QVBoxLayout(self) - layout.setSpacing(15) - - self.header = QLabel("⏳ Requesting Control") - header_font = QFont() - header_font.setPointSize(14) - header_font.setBold(True) - self.header.setFont(header_font) - self.header.setAlignment(Qt.AlignmentFlag.AlignCenter) - layout.addWidget(self.header) - - line = QFrame() - line.setFrameShape(QFrame.Shape.HLine) - line.setFrameShadow(QFrame.Shadow.Sunken) - layout.addWidget(line) - - self.message_label = QLabel(f"Waiting for {self._target_user} to respond...") - self.message_label.setWordWrap(True) - self.message_label.setAlignment(Qt.AlignmentFlag.AlignCenter) - layout.addWidget(self.message_label) - - self.progress_layout = QVBoxLayout() - self.progress = QProgressBar() - self.progress.setRange(0, max(1, self._timeout)) - self.progress.setValue(self._timeout) - self.progress.setTextVisible(False) - self.progress.setFixedHeight(8) - self.progress.setStyleSheet(f""" - QProgressBar {{ - border: 1px solid {LIGHT_BORDER}; - border-radius: 4px; - background-color: {PROGRESS_TRACK_BG}; - }} - QProgressBar::chunk {{ - background-color: {BATON_INFO}; - border-radius: 3px; - }} - """) - self.progress_layout.addWidget(self.progress) - - self.time_label = QLabel(f"{self._timeout} seconds remaining") - self.time_label.setAlignment(Qt.AlignmentFlag.AlignCenter) - self.time_label.setStyleSheet(f"color: {DIM_TEXT};") - self.progress_layout.addWidget(self.time_label) - - layout.addLayout(self.progress_layout) - - button_layout = QHBoxLayout() - self.cancel_btn = QPushButton("✗ Cancel Request") - # See accept_btn in BatonRequestDialog for why height is QSS-only. - self.cancel_btn.setStyleSheet(f""" - QPushButton {{ - background-color: {BATON_DANGER_BG}; - color: {WHITE}; - border: none; - border-radius: 5px; - min-height: {_BUTTON_HEIGHT}; - max-height: {_BUTTON_HEIGHT}; - font-weight: bold; - font-size: {FONT_LABEL}; - }} - QPushButton:hover {{ background-color: {BATON_DANGER_HOVER}; }} - QPushButton:pressed {{ background-color: {BATON_DANGER_PRESSED}; }} - """) - self.cancel_btn.clicked.connect(self._on_cancel) - button_layout.addWidget(self.cancel_btn) - layout.addLayout(button_layout) - - def _start_timer(self): - self._timer = QTimer(self) - self._timer.setInterval(1000) - self._timer.timeout.connect(self._tick) - # finished fires on accept/reject/close alike — replaces the - # closeEvent override that existed only to stop this timer. - self.finished.connect(self._timer.stop) - self._timer.start() - - def _tick(self): - self._remaining -= 1 - self._remaining = max(self._remaining, 0) - - self.progress.setValue(self._remaining) - self.time_label.setText(f"{self._remaining} seconds remaining") - if self._remaining <= 0: - self._timer.stop() - - def update_remaining(self, remaining: int): - self._remaining = remaining - self.progress.setValue(self._remaining) - self.time_label.setText(f"{self._remaining} seconds remaining") - - def set_queued_state(self): - self._timer.stop() - self.header.setText("⏳ Transfer Queued") - self.header.setStyleSheet( - f"color: {BATON_WARN}; font-weight: bold; font-size: {FONT_BODY};" - ) - self.message_label.setText( - "The beamline is currently busy. Your request was accepted and " - "the baton will be transferred as soon as the current operation completes." - ) - self.progress.setRange(0, 0) # Indeterminate - self.progress.show() - self.time_label.setText("Waiting for beamline to be idle...") - self.time_label.show() - # Keep cancel button so they can abort the wait if they change their mind - - def _on_cancel(self): - self.cancelled_signal.emit() - self.reject() diff --git a/src/aare/gui/widgets/busy_overlay.py b/src/aare/gui/widgets/busy_overlay.py deleted file mode 100644 index 19b6fd6d..00000000 --- a/src/aare/gui/widgets/busy_overlay.py +++ /dev/null @@ -1,231 +0,0 @@ -import math -import time -from dataclasses import dataclass - -from aarecommon.models.models import SessionsStateEnum -from aarecommon.models.tell import TellStateModel -from PySide6.QtCore import QPoint, QRect, Qt -from PySide6.QtGui import QColor, QFont, QFontMetrics, QPainter, QPen - -from aare.gui.styles import ( - BUSY_BLUE, - BUSY_BLUE_BORDER, - BUSY_BLUE_DOT, - BUSY_PSI_RED, - BUSY_PSI_RED_BORDER, - BUSY_PSI_RED_DOT, - BUSY_YELLOW, - BUSY_YELLOW_BORDER, - BUSY_YELLOW_DOT, - SHADOW, - WHITE, - qcolor, -) - - -@dataclass(frozen=True) -class BusyOverlayStyle: - text: str - badge_bg: str - badge_fg: str - overlay_fill: QColor - overlay_border: QColor - overlay_text: QColor - accent_dot: str - # Hint line under the title. draw_busy_badge renders it whenever set; - # AxisVideoPanel strips it because only the sample-camera badge is a - # click target and the hint invites a click. - subtext: str = "" - # Wave-animate the title letters. Only the busy/robot warnings: a static - # "In viewing mode" badge must not look like an in-progress operation. - animate: bool = False - - -def draw_wave_text( - painter: QPainter, - x: int, - baseline: int, - text: str, - fm: QFontMetrics, - fg: QColor, - shadow: QColor | None = None, - amplitude: int = 5, -) -> None: - """Per-letter hop wave for the busy warnings, so the text reads as an - in-progress signal instead of a frozen label. The phase comes from the - wall clock and repaints ride the ~20 fps camera frames — no timer here; - if the stream stalls the wave freezes, which is acceptable (the text - stays legible and a stalled feed has its own error surface).""" - now = time.monotonic() - for index, char in enumerate(text): - # Clipped sine: letters rest on the baseline and hop up in sequence. - lift = -round(amplitude * max(0.0, math.sin(now * 5.5 - index * 0.55))) - if shadow is not None: - painter.setPen(QPen(shadow)) - painter.drawText(QPoint(x + 1, baseline + lift + 1), char) - painter.setPen(QPen(fg)) - painter.drawText(QPoint(x, baseline + lift), char) - x += fm.horizontalAdvance(char) - - -def draw_busy_badge( - painter: QPainter, - viewport_width: int, - viewport_height: int, - style: BusyOverlayStyle, - *, - fill: QColor | None = None, -) -> QRect: - """The one badge renderer for every camera view — sample camera and the - Axis video views draw the same box so the message reads identically - everywhere (each view used to have its own look). Returns the badge rect - so interactive views can use it as a click target. `fill` overrides the - style's fill (hover feedback).""" - font = QFont() - font.setPointSize(24) - font.setBold(True) - font_metrics = QFontMetrics(font) - - sub_font = QFont() - sub_font.setPointSize(12) - sub_metrics = QFontMetrics(sub_font) - - title_width = font_metrics.horizontalAdvance(style.text) - sub_width = sub_metrics.horizontalAdvance(style.subtext) if style.subtext else 0 - - padding_x = 20 - padding_y = 14 - sub_gap = 6 - bg_width = max(title_width, sub_width) + 2 * padding_x - bg_height = font_metrics.height() + 2 * padding_y - if style.subtext: - bg_height += sub_gap + sub_metrics.height() - - position_x = int((viewport_width - bg_width) / 2) - position_y = int(viewport_height * 0.68 - bg_height / 2) - bg_rect = QRect(position_x, position_y, bg_width, bg_height) - - painter.setPen(QPen(style.overlay_border, 2, Qt.PenStyle.SolidLine)) - painter.setBrush(fill if fill is not None else QColor(style.overlay_fill)) - painter.drawRoundedRect(bg_rect, 10, 10) - - painter.setPen(QPen(style.overlay_text, 2, Qt.PenStyle.SolidLine)) - painter.setFont(font) - title_x = position_x + (bg_width - title_width) // 2 - title_y = position_y + padding_y + font_metrics.ascent() - if style.animate: - draw_wave_text( - painter, title_x, title_y, style.text, font_metrics, QColor(style.overlay_text) - ) - else: - painter.drawText(QPoint(title_x, title_y), style.text) - - if style.subtext: - painter.setFont(sub_font) - sub_x = position_x + (bg_width - sub_width) // 2 - sub_y = position_y + padding_y + font_metrics.height() + sub_gap + sub_metrics.ascent() - painter.drawText(QPoint(sub_x, sub_y), style.subtext) - - return bg_rect - - -def draw_busy_status_text( - painter: QPainter, viewport_width: int, viewport_height: int, style: BusyOverlayStyle -) -> None: - """Non-clickable busy status for the passive Axis views: solid colored - text with a 1px shadow, no badge box — the pill read as a button (same - look as the sample camera's own warning text). Same position/typeface as - draw_busy_badge so the message reads identically everywhere.""" - font = QFont() - font.setPointSize(24) - font.setBold(True) - font_metrics = QFontMetrics(font) - painter.setFont(font) - - x = (viewport_width - font_metrics.horizontalAdvance(style.text)) // 2 - baseline = int(viewport_height * 0.68) + font_metrics.ascent() // 2 - if style.animate: - draw_wave_text( - painter, - x, - baseline, - style.text, - font_metrics, - qcolor(style.badge_bg), - shadow=qcolor(SHADOW, 200), - ) - return - painter.setPen(QPen(qcolor(SHADOW, 200))) - painter.drawText(QPoint(x + 1, baseline + 1), style.text) - painter.setPen(QPen(qcolor(style.badge_bg))) - painter.drawText(QPoint(x, baseline), style.text) - - -# The one "not yours" badge. Module-level so the sample camera can paint the -# same box while the session state is still unknown (no status yet), instead -# of a differently colored hand-rolled one. -VIEWING_MODE_STYLE = BusyOverlayStyle( - text="Viewing mode, Click here to grab the baton", - badge_bg=BUSY_YELLOW, - badge_fg=WHITE, - overlay_fill=qcolor(BUSY_YELLOW, 195), - overlay_border=qcolor(BUSY_YELLOW_BORDER, 235), - overlay_text=qcolor(WHITE), - accent_dot=BUSY_YELLOW_DOT, - subtext="Grab the baton if you need to interact with GUI", -) - - -def build_busy_overlay_style( - *, - is_busy: bool, - tell_state: TellStateModel | None, - session_state: SessionsStateEnum | None = None, - auto_centering: bool = False, -) -> BusyOverlayStyle | None: - if session_state in { - SessionsStateEnum.OwnedByElse, - SessionsStateEnum.PendingYouToElse, - SessionsStateEnum.Vacant, - }: - return VIEWING_MODE_STYLE - - # Auto loop centering is busy + SampleAlignment in /status — the exact - # combo the callers hide (manual omega moves look identical), so it - # gets its own flag: the GUI knows it POSTed /alc/center_loop, or the - # automation progress says the Center step is running. Checked before - # is_busy because the callers pass is_busy=False during alignment. - if auto_centering: - return _animated("AUTO CENTERING", BUSY_PSI_RED, BUSY_PSI_RED_BORDER, BUSY_PSI_RED_DOT) - - if not is_busy: - return None - - activity_value = str(getattr(getattr(tell_state, "activity", None), "value", "") or "").lower() - - # Cooling is the one robot phase that keeps its own (blue) color: it is - # long, harmless and the operator should read it as "wait" not "danger". - # Every other busy state shares the PSI red so the badge reads as one - # "hands off" signal instead of a per-activity rainbow. - if activity_value == "cooling": - return _animated("ROBOT COOLING", BUSY_BLUE, BUSY_BLUE_BORDER, BUSY_BLUE_DOT) - - text = { - "mounting": "ROBOT MOUNTING", - "unmounting": "ROBOT UNMOUNTING", - "drying": "ROBOT DRYING", - }.get(activity_value, "BEAMLINE BUSY") - return _animated(text, BUSY_PSI_RED, BUSY_PSI_RED_BORDER, BUSY_PSI_RED_DOT) - - -def _animated(text: str, base: str, border: str, dot: str) -> BusyOverlayStyle: - return BusyOverlayStyle( - text=text, - badge_bg=base, - badge_fg=WHITE, - overlay_fill=qcolor(base, 190), - overlay_border=qcolor(border, 235), - overlay_text=qcolor(WHITE), - accent_dot=dot, - animate=True, - ) diff --git a/src/aare/gui/widgets/button_with_payload.py b/src/aare/gui/widgets/button_with_payload.py deleted file mode 100644 index 5e53a137..00000000 --- a/src/aare/gui/widgets/button_with_payload.py +++ /dev/null @@ -1,16 +0,0 @@ -from PySide6.QtCore import Signal, Slot -from PySide6.QtWidgets import QPushButton - - -class ButtonWithPayload(QPushButton): - pressed = Signal(dict) - - def __init__(self, text: str, payload: dict, parent=None): - super().__init__(parent) - self.payload = payload - self.setText(text) - self.clicked.connect(self.button_pressed) - - @Slot() - def button_pressed(self): - self.pressed.emit(self.payload) diff --git a/src/aare/gui/widgets/camera_image.py b/src/aare/gui/widgets/camera_image.py deleted file mode 100644 index 74565ad5..00000000 --- a/src/aare/gui/widgets/camera_image.py +++ /dev/null @@ -1,1579 +0,0 @@ -import math -import time -from enum import Enum -from typing import ClassVar - -from aarecommon.config.logger import setup_logger -from aarecommon.math.coordinate import Coordinate, SmargonCoordinate -from aarecommon.math.sample_geometry import SampleGeometryModel -from aarecommon.models.models import ( - AutofocusSettings, - BeamlineStateEnum, - DAQStatusModel, - SampleCameraSettings, - SessionsStateEnum, -) -from PySide6.QtCore import QPoint, QPointF, QRect, QRectF, Qt, QTimer, Signal, Slot -from PySide6.QtGui import ( - QBrush, - QColor, - QCursor, - QFont, - QFontMetrics, - QLinearGradient, - QPainter, - QPen, - QPixmap, - QPolygonF, - QTransform, - QWheelEvent, -) -from PySide6.QtWidgets import ( - QFileDialog, - QFrame, - QGraphicsPixmapItem, - QGraphicsScene, - QGraphicsView, - QMenu, - QToolTip, -) - -from aare.gui.constants import LOGGER_NAME -from aare.gui.models.bookmark import SmargonBookmarkList -from aare.gui.scan_logic.raster_grid_manager import RasterGridManager -from aare.gui.styles import ( - BEAM_BUSY, - BEAM_IDLE, - BEAM_MARKING, - BEAM_OPEN, - CLASS_COLORS, - LEGEND_BG, - LEGEND_TEXT, - MARK_BADGE_BG, - MARKER_GREEN, - PATH_END, - PATH_START, - SCALE_BAR_GREY, - SHADOW, - TARGET_COLORS, - TEXT, - THEME_SUNSET, - TOOLTIP_TEXT, - WHITE, - font_scale, - qcolor, -) -from aare.gui.widgets.busy_overlay import ( - VIEWING_MODE_STYLE, - BusyOverlayStyle, - build_busy_overlay_style, - draw_busy_badge, - draw_wave_text, -) - -logger = setup_logger(LOGGER_NAME) - - -class SampleCameraImageState(Enum): - IDLE = 0 - DRAWING_RASTER_GRID = 1 - MOVING_RASTER_GRID = 2 - RESIZE_RASTER_GRID = 3 - BEAM_MARKING = 4 - - -class SampleCameraImageLabel(QGraphicsView): - smargon = Signal(SmargonCoordinate) - session_badge_clicked = Signal() - - evaluate_grid = Signal() - clear_grid = Signal() - clear_evaluated_grids = Signal() - load_image = Signal(QPointF) - - zoom_change = Signal(int) - set_omega = Signal(float) - set_helical_start = Signal(SmargonCoordinate) - set_helical_end = Signal(SmargonCoordinate) - update_beam_mark = Signal(float, float) - autofocus = Signal(AutofocusSettings) - samcam_updated = Signal(SampleCameraSettings) - - switch_raster_grid = Signal() - # "More…" link in the help overlay; main window opens the full F1 dialog. - open_full_help = Signal() - - def __init__( - self, - geom: SampleGeometryModel, - raster: RasterGridManager, - default_image: str | None, - parent=None, - ): - super().__init__(parent) - - self._shutter = None - self._raster_mgr = raster - self._state = SampleCameraImageState.IDLE - self._session_state: SessionsStateEnum | None = None - self._sam_cam = SampleCameraSettings(exposure=0.1, gain=100.0) - self._is_daq_busy = False - self._camera_available = True - self._camera_error_message: str | None = None - # Baton gate: watching allowed, operating not (main_window drives it). - self._operations_allowed = True - self._session_badge_rect: QRect | None = None # viewport coords - self._session_badge_hovered = False - # Hover polarity for the badge: light themes darken, Sunset brightens. - # Set via set_theme from MainWindow._apply_theme. - self._dark_theme = False - self._last_grid_update_ts = 0.0 - self._grid_update_min_interval_s = 1.0 / 25.0 - self._tell_state = None - self._auto_centering = False - self._busy_overlay_style: BusyOverlayStyle | None = None - self._mounted_sample_name: str | None = None - - self._geom = geom - self._bookmarks: SmargonBookmarkList = SmargonBookmarkList() - # Fit-to-view from the first frame; the right-click "Scale to fit" - # toggle can still switch back to 1:1. - self._autoscale = True - self._show_coords = False - # Full-frame crosshair through the beam center; off by default so the - # default view stays as before, toggled from the right-click menu. - self._show_beam_crosshair = False - self._helical_start = SmargonCoordinate() - self._helical_end = SmargonCoordinate() - self._raster_alpha = 127 - self._bounding_box = None - self._show_detections = False - self._show_detection_polygons = True - - self._show_target_point = True - self._show_target_coordinates = True - self._show_overlay_legend = False - self._compact_overlay_legend = False - # "?" badge is a mouse-controls cheatsheet, decoupled from the legend — - # legend visibility is already handled by the panel checkboxes. - self._help_expanded = False - self._help_hit_rect: QRectF | None = None # viewport coords, set on paint - self._help_more_rect: QRectF | None = None # "More…" link inside the overlay - self._target_point = None - self._target_shape = None - self._target_color_name = "Cyan" - self._last_target_update_ts = 0.0 - self._target_min_update_interval_s = 0.03 - self._target_smoothing_alpha = 0.45 - self._smoothed_target_point: tuple[float, float] | None = None - - self.start_point = None # Starting point of the rectangle - self.end_point = None # Ending point of the rectangle - - self.scene = QGraphicsScene(self) - self.setScene(self.scene) - - self.setMouseTracking(True) - # QGraphicsView delivers mouse moves through its viewport, so hover - # events (no button pressed) only fire if the viewport tracks the mouse. - # Without this the "Show coordinates" hover tooltip never appears. - self.viewport().setMouseTracking(True) - self._update_camera_interaction_feedback() - - if default_image is not None: - pixmap = QPixmap(default_image) - self.pixmap_item = QGraphicsPixmapItem(pixmap) - self.scene.addItem(self.pixmap_item) - else: - pixmap = QPixmap(2000, 2000) - pixmap.fill(Qt.GlobalColor.white) - self.pixmap_item = QGraphicsPixmapItem(pixmap) - self.scene.addItem(self.pixmap_item) - - self.setFrameShape(QFrame.Shape.NoFrame) - self.setRenderHints(QPainter.RenderHint.TextAntialiasing) - - # Create a timer for throttling wheel events - self.wheel_event_timer = QTimer() - self.wheel_event_timer.setSingleShot(True) - self.wheel_event_threshold = 500 # Minimum delay between wheel events in ms - self.last_wheel_event = 0 # Timestamp of the last processed wheel event - - self.click_timer = QTimer() # Timer to detect click vs hold - self.click_timer.setSingleShot(True) # The timer runs only once - self.left_click_hold_threshold = 200 - self.right_click_hold_threshold = 200 - - self.raster_timer = QTimer() - self.raster_timer.setSingleShot(True) - self.raster_timer_interval = 400 - self.raster_timer.timeout.connect(self._on_raster_timer_timeout) - self._pending_load_pos = None - - self._detections = [] # list of dicts from publisher - self._det_shape = None # shape from payload [h,w] so we can scale - - # Scene position under the cursor; drives the corner coords/scale HUD. - self._hover_pos: QPointF | None = None - - def _update_camera_interaction_feedback(self) -> None: - if self._camera_available: - self.viewport().setCursor(Qt.CursorShape.ArrowCursor) - self.setToolTip("") - else: - self.viewport().setCursor(Qt.CursorShape.ForbiddenCursor) - self.setToolTip("Sample camera feed unavailable") - - def _show_camera_unavailable_tooltip( - self, event, action: str = "Sample camera interaction" - ) -> None: - QToolTip.showText( - self.mapToGlobal(event.pos()), - f"{action} disabled: sample camera feed unavailable", - self, - ) - - def _camera_interaction_enabled(self) -> bool: - # Watching is free; clicking (targets, raster, smargon moves) needs - # the camera AND the session baton. - return self._camera_available and self._operations_allowed - - @Slot(bool) - def set_operations_enabled(self, enabled: bool): - self._operations_allowed = enabled - self.update() - - @Slot(bool) - def set_camera_available(self, available: bool): - self._camera_available = available - if available: - self._camera_error_message = None - self._update_camera_interaction_feedback() - self.update() - - @Slot(str) - def set_camera_error_message(self, message: str): - # Thread errors arrive as "...unavailable: X" — reword to the - # "...unavailable because X" phrasing the overlay shows. - self._camera_error_message = message.replace(": ", " because ", 1) - self.update() - - @Slot(dict) - def update_detections(self, payload: dict): - try: - self._det_shape = payload.get("shape", None) - self._detections = payload.get("boxes", []) or [] - except Exception as e: - logger.debug(f"Exception in update_detections: {e}", exc_info=True) - self._detections = [] - self.update() - - @Slot(dict) - def update_target_point(self, payload: dict): - now = time.monotonic() - if now - self._last_target_update_ts < self._target_min_update_interval_s: - return - - try: - self._target_shape = payload.get("shape", self._det_shape) - raw_target = payload.get("target_point") - - target_xy = self._coerce_target_point(raw_target) - if target_xy is None: - return - - self._target_point = raw_target - if self._smoothed_target_point is None: - self._smoothed_target_point = target_xy - else: - px, py = self._smoothed_target_point - nx, ny = target_xy - alpha = self._target_smoothing_alpha - self._smoothed_target_point = ( - (1.0 - alpha) * px + alpha * nx, - (1.0 - alpha) * py + alpha * ny, - ) - self._last_target_update_ts = now - except Exception as e: - logger.debug(f"Exception in update_target_point: {e}", exc_info=True) - self._target_point = None - self._smoothed_target_point = None - self.update() - - @Slot(bool) - def set_auto_centering(self, active: bool) -> None: - # ponytail: only stored — the overlay style is rebuilt on the next - # /status tick (500 ms), well within the seconds a centering takes. - self._auto_centering = active - - def _busy_overlay_text(self) -> str: - tell_state = self._tell_state - if tell_state is None: - return "BEAMLINE BUSY" - - activity_value = str(getattr(tell_state.activity, "value", "") or "").lower() - if activity_value not in {"mounting", "unmounting", "drying", "cooling"}: - return "BEAMLINE BUSY" - - activity_name = tell_state.activity.display_name() - - return f"TELL {activity_name}".upper() - - def _draw_status_text( - self, painter: QPainter, text: str, color, center_x: int, baseline_y: int, fm: QFontMetrics - ): - # Solid colored text with a 1px shadow — survives any camera image - # behind it without a badge box. - x = center_x - fm.horizontalAdvance(text) // 2 - painter.setPen(QPen(qcolor(SHADOW, 200))) - painter.drawText(QPoint(x + 1, baseline_y + 1), text) - painter.setPen(QPen(qcolor(color) if isinstance(color, str) else color)) - painter.drawText(QPoint(x, baseline_y), text) - - def _draw_busy_overlay(self, painter: QPainter): - if self._busy_overlay_style is None: - return - - style = self._busy_overlay_style - - painter.save() - painter.resetTransform() - - font = QFont() - font.setPointSize(24) - font.setBold(True) - font_metrics = QFontMetrics(font) - - # Robot/busy WARNINGS are not clickable: no badge box, just solid - # text in the state's color. Only the session badges (a real click - # target) keep the button-like pill below. - if self._session_state not in ( - SessionsStateEnum.Vacant, - SessionsStateEnum.OwnedByElse, - SessionsStateEnum.PendingYouToElse, - ): - self._session_badge_rect = None - painter.setFont(font) - baseline = int(self.viewport().height() * 0.68) + font_metrics.ascent() // 2 - if style.animate: - x = self.viewport().width() // 2 - font_metrics.horizontalAdvance(style.text) // 2 - draw_wave_text( - painter, - x, - baseline, - style.text, - font_metrics, - qcolor(style.badge_bg), - shadow=qcolor(SHADOW, 200), - ) - else: - self._draw_status_text( - painter, - style.text, - style.badge_bg, - self.viewport().width() // 2, - baseline, - font_metrics, - ) - painter.restore() - return - - # The session badge doubles as the click target for the grab/request - # menu, same as the _draw_session_overlay badge it hides. - self._session_badge_rect = draw_busy_badge( - painter, - self.viewport().width(), - self.viewport().height(), - style, - fill=self._badge_fill(style), - ) - - painter.restore() - - def _badge_fill(self, style: BusyOverlayStyle) -> QColor: - fill = QColor(style.overlay_fill) - if self._session_badge_hovered: - # Hover: darker in the light themes, brighter in Sunset. - fill = fill.lighter(125) if self._dark_theme else fill.darker(115) - return fill - - def _draw_session_overlay(self, painter: QPainter): - """Session badge for when the busy overlay has nothing to draw, i.e. - the session state is still unknown (no status yet, or one without a - session). Same yellow "viewing mode" badge as the known not-owned - states, so the click target looks identical whichever path paints it - (it used to be a gold/orange/red "Guest Mode" box of its own).""" - if self._busy_overlay_style is not None: - # Busy overlay drew (and owns) the session badge rect — don't clobber. - return - self._session_badge_rect = None - - if self._session_state in ( - SessionsStateEnum.OwnedByYou, - SessionsStateEnum.PendingElseToYou, - ): - return - - painter.save() - painter.resetTransform() - self._session_badge_rect = draw_busy_badge( - painter, - self.viewport().width(), - self.viewport().height(), - VIEWING_MODE_STYLE, - fill=self._badge_fill(VIEWING_MODE_STYLE), - ) - painter.restore() - - def _draw_camera_unavailable_overlay(self, painter: QPainter): - if self._camera_available: - return - - painter.save() - painter.resetTransform() - - font = QFont() - font.setPointSize(22) - font.setBold(True) - painter.setFont(font) - fm = QFontMetrics(font) - - # Bottom-center, no badge box — solid colored text (the pill read - # as a button). The camera thread's reason is appended upstream as - # "... because " when it is known. - margin = 18 - text = fm.elidedText( - self._camera_error_message or "Sample camera feed unavailable", - Qt.TextElideMode.ElideRight, - self.viewport().width() - 2 * margin, - ) - baseline = self.viewport().height() - margin - fm.descent() - self._draw_status_text( - painter, text, MARK_BADGE_BG, self.viewport().width() // 2, baseline, fm - ) - - painter.restore() - - def drawForeground(self, painter, rect): - self._draw_ml_bounding_box(painter) - self._draw_beam_center(painter) - self._raster_mgr.draw_grid(painter, self._raster_alpha) - self._draw_helical(painter) - self._draw_busy_overlay(painter) - self._draw_session_overlay(painter) - self._draw_camera_unavailable_overlay(painter) - self._draw_detections(painter, rect) - self._draw_target_point(painter) - self._draw_overlay_legend(painter) - self._draw_mounted_sample(painter) - self._draw_hover_hud(painter) - self._draw_help_overlay(painter) - - def resizeEvent(self, event): - super().resizeEvent(event) - self._scaling() - - def mousePressEvent(self, event): - # "More…" link before the box toggle: its rect lies inside the help box, - # so the toggle below would swallow the click otherwise. - if ( - event.button() == Qt.MouseButton.LeftButton - and self._help_more_rect is not None - and self._help_more_rect.contains(QPointF(self.viewport().mapFrom(self, event.pos()))) - ): - self._help_expanded = False - self.update() - self.open_full_help.emit() - event.accept() - return - - # Help badge first: pure UI affordance, must work even when camera - # interaction is disabled (session overlay etc.). - if ( - event.button() == Qt.MouseButton.LeftButton - and self._help_hit_rect is not None - and self._help_hit_rect.contains(QPointF(self.viewport().mapFrom(self, event.pos()))) - ): - self._help_expanded = not self._help_expanded - self.update() - event.accept() - return - - # Session badge: the way IN when everything else is gated — must fire - # before the interaction-enabled check below. - if ( - event.button() == Qt.MouseButton.LeftButton - and self._session_badge_rect is not None - and self._session_badge_rect.contains(self.viewport().mapFrom(self, event.pos())) - ): - self.session_badge_clicked.emit() - event.accept() - return - - if not self._camera_interaction_enabled(): - if event.button() in (Qt.MouseButton.LeftButton, Qt.MouseButton.RightButton): - self._show_camera_unavailable_tooltip(event) - event.accept() - return - - self.start_point = self.mapToScene(event.pos()) - ctrl_override_move = bool(event.modifiers() & Qt.KeyboardModifier.ControlModifier) - - match self._state: - case SampleCameraImageState.BEAM_MARKING: - self.click_timer.start(self.right_click_hold_threshold) - case SampleCameraImageState.IDLE: - self.click_timer.start(self.right_click_hold_threshold) - if event.button() == Qt.MouseButton.RightButton: - if self._raster_mgr.is_part_of_active_grid(self.start_point): - self._state = SampleCameraImageState.RESIZE_RASTER_GRID - else: - self._state = SampleCameraImageState.DRAWING_RASTER_GRID - elif event.button() == Qt.MouseButton.LeftButton and ( - self._raster_mgr.is_part_of_active_grid(self.start_point) - and not ctrl_override_move - ): - self._state = SampleCameraImageState.MOVING_RASTER_GRID - - def _update_grid(self): - now = time.monotonic() - if (now - self._last_grid_update_ts) < self._grid_update_min_interval_s: - return - self._last_grid_update_ts = now - - match self._state: - case SampleCameraImageState.DRAWING_RASTER_GRID: - self.switch_raster_grid.emit() - self._raster_mgr.update_active_grid(self.start_point, self.end_point) - case SampleCameraImageState.MOVING_RASTER_GRID: - self.switch_raster_grid.emit() - self._raster_mgr.move_active_grid(self.end_point - self.start_point) - self.start_point = self.end_point - case SampleCameraImageState.RESIZE_RASTER_GRID: - self.switch_raster_grid.emit() - self._raster_mgr.resize_active_grid(self.end_point) - - @Slot(str) - def set_theme(self, theme: str): - self._dark_theme = theme == THEME_SUNSET - self.update() - - def leaveEvent(self, event): - if self._session_badge_hovered: - self._session_badge_hovered = False - self.update() - if self._hover_pos is not None: - self._hover_pos = None - self.update() - if self._help_expanded: - # Pointer left the widget with the cheatsheet open — fold it, - # same as wandering off the box below. - self._help_expanded = False - self.update() - super().leaveEvent(event) - - def mouseMoveEvent(self, event): - # Hover HUD before the interaction gate: watching is free, so the - # coords/scale readout must work even without the session baton. - self._hover_pos = self.mapToScene(event.pos()) - self.update() - - # Expanded help folds when the pointer wanders off the box — click - # is not the only way back to the "?" badge. Before the gate: the - # badge is a pure UI affordance, live even in viewing mode. - if ( - self._help_expanded - and self._help_hit_rect is not None - and not self._help_hit_rect.contains( - QPointF(self.viewport().mapFrom(self, event.pos())) - ) - ): - self._help_expanded = False - self.update() - - # Badge hover feedback must run BEFORE the interaction gate: the - # badge is visible precisely when interaction is disabled. - hovered = self._session_badge_rect is not None and self._session_badge_rect.contains( - self.viewport().mapFrom(self, event.pos()) - ) - if hovered != self._session_badge_hovered: - self._session_badge_hovered = hovered - self.update() - - if not self._camera_interaction_enabled(): - return - - mouse_pos = self.mapToScene(event.pos()) - - # Hover tooltips (completed-grid info / pixel coordinates) should work in - # any state, not only IDLE -- e.g. while beam-marking in beam location. - grid_txt = self._raster_mgr.is_part_of_completed_grid(mouse_pos) - if grid_txt: - QToolTip.showText(self.mapToGlobal(event.pos()), grid_txt, self) - elif self._show_coords: - QToolTip.showText( - self.mapToGlobal(event.pos()), f"{mouse_pos.x():.0f}, {mouse_pos.y():.0f} pxl", self - ) - - if self._state == SampleCameraImageState.IDLE and ( - event.modifiers() & Qt.KeyboardModifier.ShiftModifier - ): - if not self.raster_timer.isActive(): - self.load_image.emit(mouse_pos) - self.raster_timer.start(self.raster_timer_interval) - else: - self._pending_load_pos = mouse_pos - - self.end_point = mouse_pos - - if not self.click_timer.isActive(): - self.end_point = self.mapToScene(event.pos()) - self._update_grid() - self.update() - - def _on_raster_timer_timeout(self): - if self._pending_load_pos is not None: - self.load_image.emit(self._pending_load_pos) - self._pending_load_pos = None - - def mouseReleaseEvent(self, event): - if not self._camera_interaction_enabled(): - self.click_timer.stop() - if self._state != SampleCameraImageState.BEAM_MARKING: - self._state = SampleCameraImageState.IDLE - event.accept() - return - - if event.button() == Qt.MouseButton.LeftButton: - if self.click_timer.isActive(): - self.click_timer.stop() - self._left_single_click(event) - else: - self._update_grid() - self.update() - if event.button() == Qt.MouseButton.RightButton: - if self.click_timer.isActive(): - self.click_timer.stop() - self._right_click_menu(event) - else: - self._update_grid() - self.update() - if self._state != SampleCameraImageState.BEAM_MARKING: - self._state = SampleCameraImageState.IDLE - - def _right_click_menu(self, event): - if not self._camera_interaction_enabled(): - self._show_camera_unavailable_tooltip(event) - return - - menu = QMenu(self) - - scale_action = menu.addAction("Scale to fit") - scale_action.setCheckable(True) - scale_action.setChecked(self._autoscale) - - show_coord_action = menu.addAction("Show coordinates") - show_coord_action.setCheckable(True) - show_coord_action.setChecked(self._show_coords) - - show_detections_action = menu.addAction("Show ML predictions") - show_detections_action.setCheckable(True) - show_detections_action.setChecked(self._show_detections) - - grab_action = menu.addAction("Grab") - grab_with_overlay_action = menu.addAction("Grab with overlay") - - autofocus_action = menu.addAction("Auto-focus") - - beam_mark_action = menu.addAction("Mark beam center") - crosshair_action = menu.addAction("Show beam crosshair") - crosshair_action.setCheckable(True) - crosshair_action.setChecked(self._show_beam_crosshair) - - delete_action = None - evaluate_action = None - - scene_pos = self.mapToScene(event.pos()) - - menu.addSection("Grid") - - if self._raster_mgr.is_part_of_active_grid(scene_pos): - delete_action = menu.addAction("Delete grid") - evaluate_action = menu.addAction("Evaluate grid") - delete_completed_action = menu.addAction("Delete completed grids") - - action = menu.exec_(self.mapToGlobal(event.pos())) - - if action is None: - return - elif action == show_coord_action: - self._show_coords = not self._show_coords - logger.info( - f"Show-coordinates hover tooltip {'enabled' if self._show_coords else 'disabled'}" - ) - self.update() - elif action == scale_action: - self._autoscale = not self._autoscale - self._scaling() - elif action == show_detections_action: - self._show_detections = not self._show_detections - self.update() - elif action == delete_action: - self.clear_grid.emit() - elif action == evaluate_action: - self.evaluate_grid.emit() - elif action == delete_completed_action: - self.clear_evaluated_grids.emit() - elif action == grab_action: - self._screenshot_with_dialog(overlay=False) - elif action == grab_with_overlay_action: - self._screenshot_with_dialog(overlay=True) - elif action == autofocus_action: - self.autofocus.emit( - AutofocusSettings( - center_x_pxl=None, center_y_pxl=None, radius_pxl=30, z_range_um=2000, z_steps=10 - ) - ) - elif action == beam_mark_action: - c = self.mapToScene(event.pos()) - self.update_beam_mark.emit(c.x(), c.y()) - elif action == crosshair_action: - self._show_beam_crosshair = not self._show_beam_crosshair - self.update() - - def _screenshot_with_dialog(self, overlay: bool): - file_path, _ = QFileDialog.getSaveFileName( - self, "Save View As", "", "JPEG Files (*.jpg; *.jpeg);;All Files (*)" - ) - - if file_path: - self._screenshot(file_path=file_path, overlay=overlay) - - def _screenshot(self, file_path: str, overlay: bool): - scene_rect = self.scene.sceneRect() - pixmap = QPixmap(scene_rect.size().toSize()) - painter = QPainter(pixmap) - self.scene.render(painter) - if overlay: - self.drawForeground(painter, scene_rect) - painter.end() - pixmap.save(file_path, "JPEG") - - def _scaling(self): - if not self._autoscale: - self.setTransform(QTransform()) - self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded) - self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded) - return - - if self.pixmap_item is None: - return - - self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) - - if ( - self.pixmap_item.boundingRect().width() == 0 - or self.pixmap_item.boundingRect().height() == 0 - ): - ratio = 1.0 - else: - ratio_w = self.viewport().size().width() / self.pixmap_item.boundingRect().width() - ratio_h = self.viewport().size().height() / self.pixmap_item.boundingRect().height() - ratio = min(ratio_w, ratio_h) - - ratio = max(ratio, 0.1) - - if ratio >= 1.0: - # Don't enable scaling when gain in ratio is < 5% (to avoid back-and-forth) - self.setTransform(QTransform()) - else: - matrix = QTransform() - matrix.scale(ratio, ratio) - self.setTransform(matrix) - - @Slot(QPixmap) - def update_pixmap(self, pixmap: QPixmap): - size_changed = self.pixmap_item is None or self.pixmap_item.pixmap().size() != pixmap.size() - if self.pixmap_item is not None: # Ensure pixmap_item exists - self.pixmap_item.setPixmap(pixmap) # Update the pixmap in the item - else: - # If no pixmap item exists (rare case), create one - self.pixmap_item = QGraphicsPixmapItem(pixmap) - self.scene.addItem(self.pixmap_item) - if size_changed and self._autoscale: - # Refit when the frame size differs from what was fitted (real - # stream resolution vs the 2000x2000 startup placeholder, or a - # camera source switch) — resizeEvent only refits on view resize. - self._scaling() - self.viewport().update() # Request an update to redraw the view - - @Slot(DAQStatusModel) - def update_daq_status(self, s: DAQStatusModel): - self._geom = s.geom - self._sam_cam = s.bl.sample_camera - self._bounding_box = s.box - self._tell_state = s.tell_state - - new_name = s.sample.sample_name if s.sample is not None else None - if new_name != self._mounted_sample_name: - self._mounted_sample_name = new_name - self.viewport().update() - - new_session_state = s.session.session if hasattr(s, "session") else None - if new_session_state != self._session_state: - self._session_state = new_session_state - self.update() - - # Same exception as the main window's motion watch: busy during - # Sample alignment IS the alignment, and the sample motion is watched - # right here — no BEAMLINE BUSY curtain over it. The "In viewing - # mode" badge is session-driven and unaffected by the gate. - new_busy_style = build_busy_overlay_style( - is_busy=bool(s.busy) and s.state != BeamlineStateEnum.SampleAlignment, - tell_state=s.tell_state, - session_state=self._session_state, - auto_centering=self._auto_centering, - ) - if new_busy_style != self._busy_overlay_style: - self._busy_overlay_style = new_busy_style - self.update() - - if s.bl.shutter_open != self._shutter: - self._shutter = s.bl.shutter_open - - if s.busy != self._is_daq_busy: - self._is_daq_busy = s.busy - self.update() - - if s.state == BeamlineStateEnum.BeamLocation: - self._state = SampleCameraImageState.BEAM_MARKING - elif self._state == SampleCameraImageState.BEAM_MARKING: - self._state = SampleCameraImageState.IDLE - - def _left_single_click(self, event): - if not self._camera_interaction_enabled(): - logger.info("Ignoring click because sample camera feed is unavailable") - self._show_camera_unavailable_tooltip(event, "Point-on-click") - return - - match self._state: - case SampleCameraImageState.BEAM_MARKING: - if ( - event.button() == Qt.MouseButton.LeftButton - and event.modifiers() & Qt.KeyboardModifier.ShiftModifier - ): - point = self.mapToScene(event.pos()) - self.update_beam_mark.emit(point.x(), point.y()) - case SampleCameraImageState.IDLE: - point = self.mapToScene(event.pos()) - if not self.scene.sceneRect().contains(point): - return - - if event.modifiers() & Qt.KeyboardModifier.ShiftModifier: - sc = SmargonCoordinate(sh_mm=self._geom.smargon_z(point.y())) - self.smargon.emit(sc) - else: - sample_coord = self._geom.picture_to_sample( - Coordinate(x=point.x(), y=point.y()) - ) - smargon_coord = SmargonCoordinate( - sh_mm=self._geom.beamline_to_smargon(sample_coord) - ) - self.smargon.emit(smargon_coord) - - def _draw_detections(self, painter: QPainter, rect): - if not self._show_detections: - return - if not getattr(self, "_detections", None): - return - if self.pixmap_item is None: - return - pix = self.pixmap_item.pixmap() - if pix.isNull(): - return - - det_shape = self._det_shape - if det_shape is None: - return - img_h, img_w = det_shape[0], det_shape[1] - disp_w = pix.width() - disp_h = pix.height() - sx = disp_w / float(img_w) - sy = disp_h / float(img_h) - - color_map = {label: qcolor(hex_str) for label, hex_str in CLASS_COLORS.items()} - - for det in self._detections: - try: - x1 = det["x1"] * sx - y1 = det["y1"] * sy - x2 = det["x2"] * sx - y2 = det["y2"] * sy - poly = det.get("poly", None) - label = str(det.get("label", "")).lower() - conf = det.get("conf", 0.0) - except Exception as e: - logger.debug(f"Error in draw detection {det}: {e}", exc_info=True) - continue - - color = color_map.get(label, qcolor(CLASS_COLORS["needle"])) - - pen = QPen(color, 3) - painter.setPen(pen) - painter.setBrush(Qt.BrushStyle.NoBrush) - detection_rect = QRect(int(x1), int(y1), int(max(1, x2 - x1)), int(max(1, y2 - y1))) - painter.drawRect(detection_rect) - - # Only draw polygon if the separate toggle is enabled - if self._show_detection_polygons and poly and len(poly) >= 3: - polygon = QPolygonF( - [QPointF(x1 + float(p[0]) * sx, y1 + float(p[1]) * sy) for p in poly] - ) - painter.drawPolygon(polygon) - - painter.setPen(QPen(qcolor(WHITE), 1)) - painter.setBrush(color) - text_bg_rect = QRect(int(x1), int(y1 - 16), int(8 + 7 * len(label)), 16) - painter.drawRect(text_bg_rect) - painter.setPen(QPen(qcolor(WHITE))) - painter.drawText(QPoint(int(x1) + 2, int(y1 - 4)), f"{label} {conf:.2f}") - - def _target_color(self) -> QColor: - color_map = {name: qcolor(hex_str) for name, hex_str in TARGET_COLORS.items()} - return color_map.get(self._target_color_name, qcolor(TARGET_COLORS["Cyan"])) - - def _coerce_target_point(self, raw) -> tuple[float, float] | None: - try: - if isinstance(raw, dict): - 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.debug(f"Error parsing target point {raw}: {e}", exc_info=True) - return None - - def _draw_target_point(self, painter: QPainter): - if not self._show_target_point: - return - if self._smoothed_target_point is None: - return - if self.pixmap_item is None: - return - - pix = self.pixmap_item.pixmap() - if pix.isNull(): - return - - shape = self._target_shape or self._det_shape - if shape is None or len(shape) < 2: - return - - try: - img_h, img_w = int(shape[0]), int(shape[1]) - tx, ty = self._smoothed_target_point - except Exception as e: - logger.debug( - f"Error using smoothed target point {self._smoothed_target_point}: {e}", - exc_info=True, - ) - return - - sx = pix.width() / float(img_w) - sy = pix.height() / float(img_h) - - px = tx * sx - py = ty * sy - - color = self._target_color() - glow = QColor(color) - glow.setAlpha(70) - - painter.save() - painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) - - painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QBrush(glow)) - painter.drawEllipse(QPointF(px, py), 20, 20) - - painter.setBrush(Qt.BrushStyle.NoBrush) - painter.setPen(QPen(color, 3, Qt.PenStyle.SolidLine)) - painter.drawEllipse(QPointF(px, py), 12, 12) - painter.setPen(QPen(qcolor(WHITE), 1, Qt.PenStyle.SolidLine)) - painter.drawEllipse(QPointF(px, py), 5, 5) - - painter.setPen(QPen(color, 2, Qt.PenStyle.SolidLine)) - painter.drawLine(QPointF(px - 20, py), QPointF(px - 7, py)) - painter.drawLine(QPointF(px + 7, py), QPointF(px + 20, py)) - painter.drawLine(QPointF(px, py - 20), QPointF(px, py - 7)) - painter.drawLine(QPointF(px, py + 7), QPointF(px, py + 20)) - - label_text = "Target" - if self._show_target_coordinates: - label_text = f"Target ({tx:.1f}, {ty:.1f})" - - font = QFont() - font.setPointSize(10) - font.setBold(True) - painter.setFont(font) - - fm = QFontMetrics(font) - text_rect = fm.boundingRect(label_text) - bubble_rect = QRectF(px + 16, py - 28, text_rect.width() + 16, text_rect.height() + 10) - - painter.setPen(QPen(color, 2)) - painter.setBrush(qcolor(LEGEND_BG, 190)) - painter.drawRoundedRect(bubble_rect, 8, 8) - - painter.setPen(QPen(qcolor(LEGEND_TEXT), 1)) - painter.drawText( - QPointF(bubble_rect.left() + 8, bubble_rect.top() + 7 + fm.ascent()), label_text - ) - - painter.restore() - - def _legend_should_show(self) -> bool: - return self._show_overlay_legend and ( - self._show_target_point - or self._show_detections - or self._show_coords - or self._state == SampleCameraImageState.BEAM_MARKING - ) - - def _legend_lines(self) -> list[tuple[str, QColor | None]]: - lines: list[tuple[str, QColor | None]] = [] - - if self._compact_overlay_legend: - if self._show_target_point: - target_label = "Target" - if self._show_target_coordinates: - target_label += " + coords" - lines.append((target_label, self._target_color())) - - if self._show_detections: - lines.extend( - [ - ("Pin", qcolor(CLASS_COLORS["pin"])), - ("Loop", qcolor(CLASS_COLORS["loop_all"])), - ("Face", qcolor(CLASS_COLORS["loop_face"])), - ("Crystal", qcolor(CLASS_COLORS["crystal"])), - ] - ) - - if self._show_coords: - lines.append(("Coords tooltip", qcolor(TOOLTIP_TEXT))) - - lines.append(("Beam marker: shutter open", qcolor(BEAM_OPEN))) - lines.append(("Beam marker: idle", qcolor(BEAM_IDLE))) - lines.append(("Beam marker: busy", qcolor(BEAM_BUSY))) - return lines - - if self._show_target_point: - target_label = f"Target marker ({self._target_color_name})" - if self._show_target_coordinates: - target_label += " + coords" - lines.append((target_label, self._target_color())) - - if self._show_detections: - lines.extend( - [ - ("Prediction: Pin", qcolor(CLASS_COLORS["pin"])), - ("Prediction: Loop_all", qcolor(CLASS_COLORS["loop_all"])), - ("Prediction: Loop_face", qcolor(CLASS_COLORS["loop_face"])), - ("Prediction: Crystal", qcolor(CLASS_COLORS["crystal"])), - ("Prediction: Needle", qcolor(CLASS_COLORS["needle"])), - ("Prediction: Ice", qcolor(CLASS_COLORS["ice"])), - ] - ) - - if self._show_coords: - lines.append(("Cursor tooltip: pixel coordinates", qcolor(TOOLTIP_TEXT))) - - lines.append(("Beam marker: shutter open", qcolor(BEAM_OPEN))) - lines.append(("Beam marker: idle", qcolor(BEAM_IDLE))) - lines.append(("Beam marker: busy", qcolor(BEAM_BUSY))) - lines.append(("Beam marker: marking mode", qcolor(BEAM_MARKING))) - - return lines - - # (header, [entries]) — kept concise on purpose; the full table lives in - # docs/cheatsheet.md. - _HELP_SECTIONS: ClassVar[list[tuple[str, list[str]]]] = [ - ( - "Sample camera", - [ - "Left click — move sample here", - "Shift + Left click — Z-alignment move", - "Right click — context menu", - "Wheel — rotate omega 90° (Shift: 10°)", - "Ctrl / Alt + Wheel — exposure coarse / fine", - ], - ), - ( - "Raster grid", - [ - "Right drag — draw grid (on grid: resize)", - "Left drag — move grid", - "Ctrl + Left click — move sample under grid", - "Shift + move — inspect raster image at cursor", - ], - ), - ] - - def _draw_help_badge(self, painter: QPainter): - # ponytail: painted circle, not a real QWidget button — the overlay it - # toggles is painter-drawn too, and a widget would need layout juggling. - diameter = 22 - # Center top, not a corner: corners drift oddly on scale-to-fit, - # the top middle stays put and stays out of the sample's way. - rect = QRectF((self.viewport().width() - diameter) / 2, 18, diameter, diameter) - - painter.save() - painter.resetTransform() - painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) - painter.setPen(QPen(qcolor(LEGEND_TEXT, 60), 1)) - painter.setBrush(qcolor(LEGEND_BG, 170)) - painter.drawEllipse(rect) - - font = QFont() - font.setPointSize(10) - font.setBold(True) - painter.setFont(font) - painter.setPen(QPen(qcolor(LEGEND_TEXT), 1)) - painter.drawText(rect, Qt.AlignmentFlag.AlignCenter, "?") - painter.restore() - - self._help_hit_rect = rect - - def _draw_help_overlay(self, painter: QPainter): - self._help_hit_rect = None - self._help_more_rect = None - if not self._help_expanded: - self._draw_help_badge(painter) - return - - painter.save() - painter.resetTransform() - painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) - - font = QFont() - font.setPointSize(9) - header_font = QFont(font) - header_font.setBold(True) - fm = QFontMetrics(font) - header_fm = QFontMetrics(header_font) - - line_height = fm.height() + 4 - header_height = header_fm.height() + 6 - padding = 10 - - max_width = 0 - n_lines = 0 - for header, entries in self._HELP_SECTIONS: - max_width = max(max_width, header_fm.horizontalAdvance(header)) - n_lines += len(entries) - for entry in entries: - max_width = max(max_width, fm.horizontalAdvance(entry)) - - more_text = "More… (F1)" - max_width = max(max_width, fm.horizontalAdvance(more_text)) - - width = max_width + padding * 2 - height = ( - len(self._HELP_SECTIONS) * header_height - + (n_lines + 1) * line_height # +1: trailing "More…" link line - + padding * 2 - ) - - # Top center, where the collapsed "?" badge sits — expanding must not - # send the mouse to the other end of the view to close it again. - bg_rect = QRectF((self.viewport().width() - width) / 2, 18, width, height) - self._help_hit_rect = bg_rect # click anywhere on the box to close - painter.setPen(QPen(qcolor(LEGEND_TEXT, 60), 1)) - painter.setBrush(qcolor(LEGEND_BG, 190)) - painter.drawRoundedRect(bg_rect, 8, 8) - - y = bg_rect.top() + padding - for header, entries in self._HELP_SECTIONS: - painter.setFont(header_font) - painter.setPen(QPen(qcolor(LEGEND_TEXT), 1)) - painter.drawText(QPointF(bg_rect.left() + padding, y + header_fm.ascent()), header) - y += header_height - painter.setFont(font) - painter.setPen(QPen(qcolor(LEGEND_TEXT), 1)) - for entry in entries: - painter.drawText(QPointF(bg_rect.left() + padding, y + fm.ascent()), entry) - y += line_height - - # Trailing link to the full F1 dialog; underlined so it reads as - # clickable, right-aligned like a dialog's action button. - link_font = QFont(font) - link_font.setUnderline(True) - painter.setFont(link_font) - painter.setPen(QPen(qcolor(LEGEND_TEXT), 1)) - more_x = bg_rect.right() - padding - fm.horizontalAdvance(more_text) - painter.drawText(QPointF(more_x, y + fm.ascent()), more_text) - self._help_more_rect = QRectF(more_x, y, fm.horizontalAdvance(more_text), line_height) - - painter.restore() - - def _draw_overlay_legend(self, painter: QPainter): - if not self._legend_should_show() or self._help_expanded: - return - - painter.save() - painter.resetTransform() - painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) - - font = QFont() - font.setPointSize(8 if self._compact_overlay_legend else 9) - painter.setFont(font) - fm = QFontMetrics(font) - - lines = self._legend_lines() - line_height = max(14 if self._compact_overlay_legend else 16, fm.height() + 2) - swatch_size = 8 if self._compact_overlay_legend else 10 - text_padding = 6 if self._compact_overlay_legend else 8 - section_padding = 8 if self._compact_overlay_legend else 10 - left = 18 - # Bottom-anchored above the "?" help badge (18px margin + 22px badge + gap). - top = self.viewport().height() - (len(lines) * line_height + 16) - 48 - - max_text_width = 0 - for text, _color in lines: - max_text_width = max(max_text_width, fm.horizontalAdvance(text)) - - width = swatch_size + text_padding + max_text_width + section_padding * 2 - height = len(lines) * line_height + 16 - - bg_rect = QRectF(left, max(18, top), width, height) - painter.setPen(QPen(qcolor(LEGEND_TEXT, 60), 1)) - painter.setBrush(qcolor(LEGEND_BG, 170)) - painter.drawRoundedRect(bg_rect, 8, 8) - - y = bg_rect.top() + 12 - for text, color in lines: - if color is not None: - painter.setPen(QPen(color, 2)) - painter.setBrush(color) - painter.drawRect( - QRectF(bg_rect.left() + section_padding, y + 2, swatch_size, swatch_size) - ) - else: - painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(Qt.BrushStyle.NoBrush) - - painter.setPen(QPen(qcolor(LEGEND_TEXT), 1)) - painter.drawText( - QPointF( - bg_rect.left() + section_padding + swatch_size + text_padding, - y + fm.ascent() + 1, - ), - text, - ) - y += line_height - - painter.restore() - - @staticmethod - def _scale_bar(um_per_view_px: float) -> tuple[float, str]: - """Nice 1-2-5 scale-bar length (µm) for the current zoom, with label.""" - target_um = um_per_view_px * 120.0 # aim for a ~120 px wide bar - exponent = math.floor(math.log10(target_um)) - base = target_um / 10.0**exponent - nice = 5.0 if base >= 5.0 else 2.0 if base >= 2.0 else 1.0 - bar_um = nice * 10.0**exponent - label = f"{bar_um / 1000.0:g} mm" if bar_um >= 1000.0 else f"{bar_um:g} µm" - return bar_um, label - - def _mounted_hud_ink(self) -> tuple[str, str]: - """(text, shadow) for the mounted-sample HUD: theme text ink on a white - halo in the light themes (pure black read too harsh over the camera), - white on black in Sunset. The camera image behind is arbitrary, so - the pair follows the theme rather than the pixels.""" - return (WHITE, SHADOW) if self._dark_theme else (TEXT, WHITE) - - def _draw_mounted_sample(self, painter: QPainter): - # Top-left HUD line (legend sits bottom-left, scale bar bottom-right): - # which sample is on the gonio, readable without leaving the camera. - if not self._mounted_sample_name: - return - - painter.save() - painter.resetTransform() - painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) - - font = QFont() - # Follows the Ctrl+plus/minus text zoom — painted HUDs bypass QSS. - font.setPointSize(round(10 * font_scale())) - font.setBold(True) - painter.setFont(font) - fm = QFontMetrics(font) - - margin = 18 - text = f"Currently mounted: {self._mounted_sample_name}" - baseline = margin + fm.ascent() - ink, halo = self._mounted_hud_ink() - painter.setPen(QPen(qcolor(halo, 200))) - painter.drawText(QPointF(margin + 1, baseline + 1), text) - painter.setPen(QPen(qcolor(ink))) - painter.drawText(QPointF(margin, baseline), text) - painter.restore() - - def _draw_hover_hud(self, painter: QPainter): - # Bottom-right HUD: grey scale bar over the hovered pixel coordinates. - if self._hover_pos is None or self.pixmap_item is None: - return - if not self.pixmap_item.sceneBoundingRect().contains(self._hover_pos): - return - - painter.save() - painter.resetTransform() - painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) - - font = QFont() - font.setPointSize(10) - font.setBold(True) - painter.setFont(font) - fm = QFontMetrics(font) - - margin = 18 - right = self.viewport().width() - margin - coords_text = f"{self._hover_pos.x():.0f}, {self._hover_pos.y():.0f} pxl" - coords_baseline = self.viewport().height() - margin - fm.descent() - grey = qcolor(SCALE_BAR_GREY) - - def shadowed_text(x: float, baseline: float, text: str, color: QColor): - painter.setPen(QPen(qcolor(SHADOW, 200))) - painter.drawText(QPointF(x + 1, baseline + 1), text) - painter.setPen(QPen(color)) - painter.drawText(QPointF(x, baseline), text) - - shadowed_text( - right - fm.horizontalAdvance(coords_text), coords_baseline, coords_text, qcolor(WHITE) - ) - - # view-pixel scale: scene px -> viewport px via the current zoom. - zoom = self.transform().m11() - if zoom > 0: - um_per_view_px = self._geom.pixel_in_mm * 1000.0 / zoom - bar_um, label = self._scale_bar(um_per_view_px) - bar_px = bar_um / um_per_view_px - bar_y = coords_baseline - fm.ascent() - 12 - painter.setPen(QPen(grey, 3)) - painter.drawLine(QPointF(right - bar_px, bar_y), QPointF(right, bar_y)) - painter.drawLine(QPointF(right - bar_px, bar_y - 4), QPointF(right - bar_px, bar_y + 4)) - painter.drawLine(QPointF(right, bar_y - 4), QPointF(right, bar_y + 4)) - shadowed_text( - right - (bar_px + fm.horizontalAdvance(label)) / 2, bar_y - 8, label, grey - ) - - painter.restore() - - @Slot(bool) - def set_show_detections(self, show: bool): - self._show_detections = show - self.update() - - @Slot(bool) - def set_show_detection_polygons(self, show: bool): - self._show_detection_polygons = show - self.update() - - @Slot(bool) - def set_show_target_point(self, show: bool): - self._show_target_point = show - self.update() - - @Slot(bool) - def set_show_target_coordinates(self, show: bool): - self._show_target_coordinates = show - self.update() - - @Slot(bool) - def set_show_overlay_legend(self, show: bool): - self._show_overlay_legend = show - self.update() - - @Slot(bool) - def set_compact_overlay_legend(self, compact: bool): - self._compact_overlay_legend = compact - self.update() - - @Slot(str) - def set_target_color(self, color_name: str): - self._target_color_name = color_name - self.update() - - def target_overlay_settings(self) -> dict: - return { - "show_target_point": self._show_target_point, - "show_target_coordinates": self._show_target_coordinates, - "show_detections": self._show_detections, - "show_detection_polygons": self._show_detection_polygons, - "show_overlay_legend": self._show_overlay_legend, - "compact_overlay_legend": self._compact_overlay_legend, - "target_color": self._target_color_name, - } - - def _draw_ml_bounding_box(self, painter: QPainter): - if self._bounding_box is None: - return - - painter.setPen(QPen(qcolor(MARKER_GREEN), 3, Qt.PenStyle.SolidLine)) - - painter.setBrush(Qt.BrushStyle.NoBrush) - painter.drawRect( - QRect( - int(self._bounding_box.bottom_x), - int(self._bounding_box.bottom_y), - int(self._bounding_box.top_x - self._bounding_box.bottom_x), - int(self._bounding_box.top_y - self._bounding_box.bottom_y), - ) - ) - - def _draw_beam_center(self, painter: QPainter): - beam_size_pxl = self._geom.beam_size_pxl - - if self._state == SampleCameraImageState.BEAM_MARKING: - painter.setPen(QPen(qcolor(BEAM_MARKING), 3, Qt.PenStyle.SolidLine)) - - elif self._shutter: - painter.setPen(QPen(qcolor(BEAM_OPEN), 3, Qt.PenStyle.SolidLine)) - - elif self._is_daq_busy is True: - # Use red color to indicate busy state - painter.setPen(QPen(qcolor(BEAM_BUSY), 3, Qt.PenStyle.SolidLine)) - else: - painter.setPen(QPen(qcolor(BEAM_IDLE), 3, Qt.PenStyle.SolidLine)) - - painter.setBrush(Qt.BrushStyle.NoBrush) - painter.drawRect( - QRect( - int(self._geom.beam_location_pxl.x - beam_size_pxl.x / 2), - int(self._geom.beam_location_pxl.y - beam_size_pxl.y / 2), - int(beam_size_pxl.x), - int(beam_size_pxl.y), - ) - ) - if self._show_beam_crosshair: - # Anuschka and Katherine really want a crosshair at 10s - arm = 33 - cx = int(self._geom.beam_location_pxl.x) - cy = int(self._geom.beam_location_pxl.y) - painter.drawLine(cx - arm, cy, cx + arm, cy) - painter.drawLine(cx, cy - arm, cx, cy + arm) - - @staticmethod - def _draw_circle(painter, coord: Coordinate, color: QColor, radius=10): - painter.setPen(QPen(Qt.PenStyle.NoPen)) - painter.setBrush(color) - painter.drawEllipse(coord.x - radius, coord.y - radius, 2 * radius, 2 * radius) - - @staticmethod - def _draw_arrow(painter: QPainter, start: Coordinate, end: Coordinate): - gradient = QLinearGradient() - gradient.setStart(QPointF(start.x, start.y)) # Start of the gradient (green) - gradient.setFinalStop(QPointF(end.x, end.y)) # End of the gradient (red) - - gradient.setColorAt(0.0, qcolor(PATH_START)) # Start color - gradient.setColorAt(1.0, qcolor(PATH_END)) # End color - - pen = QPen() - pen.setBrush(gradient) # Use gradient as the brush for the pen - pen.setWidth(4) # Set pen width - - painter.setPen(pen) - - painter.drawLine(QPointF(start.x, start.y), QPointF(end.x, end.y)) - - def _draw_helical(self, painter: QPainter): - if self._helical_start.sh_mm is not None: - start_pxl = self._geom.smargon_to_picture(self._helical_start.sh_mm) - self._draw_circle(painter, start_pxl, qcolor(PATH_START)) - else: - start_pxl = None - - if self._helical_end.sh_mm is not None: - end_pxl = self._geom.smargon_to_picture(self._helical_end.sh_mm) - self._draw_circle(painter, end_pxl, qcolor(PATH_END)) - else: - end_pxl = None - - if start_pxl is not None and end_pxl is not None: - self._draw_arrow(painter, start_pxl, end_pxl) - - @Slot(SmargonCoordinate) - def show_helical_start(self, pos: SmargonCoordinate): - self._helical_start = pos - self.update() - - @Slot(SmargonCoordinate) - def show_helical_end(self, pos: SmargonCoordinate): - self._helical_end = pos - self.update() - - @Slot(int) - def raster_alpha(self, value: int): - if 0 <= value <= 255: - self._raster_alpha = value - - def keyPressEvent(self, event): - mouse_global_pos = QCursor.pos() - mouse_view_pos = self.mapFromGlobal(mouse_global_pos) - mouse_scene_pos = self.mapToScene(mouse_view_pos) - - if ( - event.key() == Qt.Key.Key_Shift - and self._state == SampleCameraImageState.IDLE - and self._camera_interaction_enabled() - and not self.raster_timer.isActive() - ): - self.load_image.emit(mouse_scene_pos) - self.raster_timer.start(self.raster_timer_interval) - - super().keyPressEvent(event) - - def wheelEvent(self, event: QWheelEvent): - if not self.wheel_event_timer.isActive(): - # Qt's xcb/windows platform plugins swap wheel axes while Alt is held, - # so a vertical scroll lands in angleDelta().x() and y() is 0. Without - # this fallback, copysign(_, 0) is always positive and Alt+wheel - # exposure can only ever increase. - delta_y = event.angleDelta().y() or event.angleDelta().x() - if delta_y == 0: - return - match self._state: - case SampleCameraImageState.BEAM_MARKING: - if event.modifiers() & Qt.KeyboardModifier.AltModifier: - new_exp_time = self._sam_cam.exposure * (1.0 + math.copysign(0.1, delta_y)) - new_settings = SampleCameraSettings( - exposure=new_exp_time, gain=self._sam_cam.gain - ) - self.samcam_updated.emit(new_settings) - else: - new_exp_time = self._sam_cam.exposure * (1.0 + math.copysign(0.5, delta_y)) - new_settings = SampleCameraSettings( - exposure=new_exp_time, gain=self._sam_cam.gain - ) - self.samcam_updated.emit(new_settings) - case SampleCameraImageState.IDLE: - if event.modifiers() & Qt.KeyboardModifier.AltModifier: - new_exp_time = self._sam_cam.exposure * (1.0 + math.copysign(0.1, delta_y)) - new_settings = SampleCameraSettings( - exposure=new_exp_time, gain=self._sam_cam.gain - ) - self.samcam_updated.emit(new_settings) - elif event.modifiers() & Qt.KeyboardModifier.ControlModifier: - new_exp_time = self._sam_cam.exposure * (1.0 + math.copysign(0.5, delta_y)) - new_settings = SampleCameraSettings( - exposure=new_exp_time, gain=self._sam_cam.gain - ) - self.samcam_updated.emit(new_settings) - elif event.modifiers() & Qt.KeyboardModifier.ShiftModifier: - self.set_omega.emit(self._geom.omega_deg + math.copysign(10.0, delta_y)) - else: - self.set_omega.emit(self._geom.omega_deg + math.copysign(90.0, delta_y)) - - # Start the timer to throttle further events - self.wheel_event_timer.start(self.wheel_event_threshold) diff --git a/src/aare/gui/widgets/clickable_label.py b/src/aare/gui/widgets/clickable_label.py deleted file mode 100644 index a12aad26..00000000 --- a/src/aare/gui/widgets/clickable_label.py +++ /dev/null @@ -1,40 +0,0 @@ -from PySide6.QtCore import Qt, Signal -from PySide6.QtWidgets import QLabel - - -class ClickableLabel(QLabel): - clicked = Signal() - - # Hover affordance (hand cursor + underline) marks a label as operable — - # the one shared look for every clickable status-bar entry. ValueLabel - # flips it off for the passive readouts it renders. - _hover_affordance = True - - def __init__(self, parent=None): - super().__init__(parent) - if self._hover_affordance: - self.setCursor(Qt.CursorShape.PointingHandCursor) - - def _set_underline(self, on: bool) -> None: - # Font toggle, not QSS :hover — these labels carry rich text (colored - # spans), and the widget font reliably underlines it; stylesheet - # text-decoration does not reach rich-text content. - font = self.font() - font.setUnderline(on) - self.setFont(font) - - def enterEvent(self, event): - if self._hover_affordance: - self._set_underline(True) - super().enterEvent(event) - - def leaveEvent(self, event): - if self._hover_affordance: - self._set_underline(False) - super().leaveEvent(event) - - def mousePressEvent(self, event): - if event.button() == Qt.MouseButton.LeftButton: - self.clicked.emit() - else: - super().mousePressEvent(event) diff --git a/src/aare/gui/widgets/flow_layout.py b/src/aare/gui/widgets/flow_layout.py deleted file mode 100644 index 20378222..00000000 --- a/src/aare/gui/widgets/flow_layout.py +++ /dev/null @@ -1,95 +0,0 @@ -from PySide6.QtCore import QPoint, QRect, QSize, Qt -from PySide6.QtWidgets import QLayout, QWidget - - -class FlowLayout(QLayout): - """Left-to-right layout that wraps to new rows when the width runs out — - Qt ships no built-in for this, so this is the canonical Qt example - trimmed down. Added for the status-bar readouts: on narrow windows they - were simply clipped; now they wrap and stay readable. - """ - - def __init__(self, parent=None, hspacing: int = 10, vspacing: int = 2): - super().__init__(parent) - self._items = [] - self._hspace = hspacing - self._vspace = vspacing - - def addItem(self, item): - self._items.append(item) - - def count(self): - return len(self._items) - - def itemAt(self, index): - return self._items[index] if 0 <= index < len(self._items) else None - - # Newer PySide stubs declare a non-Optional return, but Qt's own takeAt - # contract is "nullptr if out of range" — suppress, don't lie. - def takeAt(self, index): # pyright: ignore[reportIncompatibleMethodOverride] - return self._items.pop(index) if 0 <= index < len(self._items) else None - - def expandingDirections(self): - return Qt.Orientation(0) - - def hasHeightForWidth(self): - return True - - def heightForWidth(self, width): - return self._do_layout(QRect(0, 0, width, 0), test_only=True) - - def setGeometry(self, rect): - super().setGeometry(rect) - self._do_layout(rect, test_only=False) - - def sizeHint(self): - return self.minimumSize() - - def minimumSize(self): - size = QSize() - for item in self._items: - size = size.expandedTo(item.minimumSize()) - margins = self.contentsMargins() - return size + QSize(margins.left() + margins.right(), margins.top() + margins.bottom()) - - def _do_layout(self, rect, test_only: bool) -> int: - margins = self.contentsMargins() - x = rect.x() + margins.left() - y = rect.y() + margins.top() - right = rect.right() - margins.right() - line_height = 0 - for item in self._items: - # Hidden widgets must not leave gaps in the row. - if item.isEmpty(): - continue - hint = item.sizeHint() - next_x = x + hint.width() - if next_x - 1 > right and line_height > 0: - x = rect.x() + margins.left() - y += line_height + self._vspace - next_x = x + hint.width() - line_height = 0 - if not test_only: - item.setGeometry(QRect(QPoint(x, y), hint)) - x = next_x + self._hspace - line_height = max(line_height, hint.height()) - return y + line_height + margins.bottom() - rect.y() - - -class FlowHost(QWidget): - """Widget owning a FlowLayout. Parents like QStatusBar ignore - heightForWidth, so the host pins its own minimum height to the wrapped - height on every resize — the bar then grows to fit the rows. - """ - - def __init__(self, parent=None, hspacing: int = 10, vspacing: int = 2): - super().__init__(parent) - self._flow = FlowLayout(self, hspacing=hspacing, vspacing=vspacing) - self._flow.setContentsMargins(0, 0, 0, 0) - - def add_widget(self, widget: QWidget) -> None: - self._flow.addWidget(widget) - - def resizeEvent(self, event): - super().resizeEvent(event) - self.setMinimumHeight(self._flow.heightForWidth(self.width())) diff --git a/src/aare/gui/widgets/local_contact_status_widget.py b/src/aare/gui/widgets/local_contact_status_widget.py deleted file mode 100644 index 00b1f879..00000000 --- a/src/aare/gui/widgets/local_contact_status_widget.py +++ /dev/null @@ -1,395 +0,0 @@ -from __future__ import annotations - -from collections.abc import Iterable -from typing import ClassVar - -from aarecommon.config.logger import setup_logger -from aarecommon.models.models import DAQStatusModel -from PySide6.QtCore import Qt, Slot -from PySide6.QtWidgets import QFrame, QGridLayout, QLabel, QSizePolicy, QVBoxLayout - -from aare.gui.constants import LOGGER_NAME -from aare.gui.styles import ( - CARD_BORDER, - CHIP_BAD_BG, - CHIP_BAD_TEXT, - CHIP_INFO_BG, - CHIP_INFO_TEXT, - CHIP_NEUTRAL_BG, - CHIP_WARN_BG, - CHIP_WARN_TEXT, - HEADING_TEXT, - MUTED_TEXT, - SUBTLE_TEXT, - SUCCESS_BG, - SUCCESS_TEXT, - SURFACE, -) -from aare.gui.widgets.title_label import TitleLabel - -logger = setup_logger(LOGGER_NAME) - - -class LocalContactStatusWidget(QFrame): - FIELD_TITLES: ClassVar[dict[str, str]] = { - "beamline_state": "Beamline state", - "busy": "Busy", - "sample": "Sample", - "tell_connected": "TELL connected", - "tell_state": "TELL state", - "tell_error": "TELL error", - "bec": "BEC", - "detector": "Detector", - "tell": "TELL backend", - "aerotech": "Aerotech", - "smargon": "Smargon", - "smargon_connected": "Smargon connected", - "smargon_error": "Smargon error", - "aerotech_connected": "Aerotech connected", - "aerotech_error": "Aerotech error", - "session": "Session", - "open_guis": "Open GUIs", - "box": "ML box", - "last_best_res": "Last best res", - "last_best_b_factor": "Last best B factor", - "crystal_size": "Crystal size", - "beamline_name": "Beamline", - "ring_current": "Ring current", - "front_light": "Front light", - "back_light": "Back light", - "cryojet": "Cryojet", - "shutter": "Shutter", - "exposure_shutter": "Exposure shutter", - "flux": "Flux", - "transmission": "Transmission", - "zoom": "Zoom", - "commissioning_mode": "Commissioning mode", - "omega": "Omega", - "beam_size": "Beam size", - "smargon_position": "Smargon position", - "aerotech_position": "Aerotech position", - "detector_description": "Detector description", - "detector_serial": "Detector serial", - "dtz": "Detector distance", - "energy": "Energy", - "wavelength": "Wavelength", - "beam_center": "Beam centre", - } - - def __init__( - self, - *, - title: str = "Status", - visible_fields: Iterable[str] | None = None, - summary: str = "DAQ and backend status overview.", - parent=None, - ): - super().__init__(parent) - self._last_status: DAQStatusModel | None = None - self._device_state_payload: dict = {} - self._row_widgets: dict[str, tuple[QLabel, QLabel]] = {} - self._title = title - self._visible_fields = tuple(visible_fields or ()) - - self.setFrameShape(QFrame.Shape.StyledPanel) - self.setFrameShadow(QFrame.Shadow.Raised) - self.setObjectName("localContactStatusCard") - self.setStyleSheet( - f""" - QFrame#localContactStatusCard {{ - background: {SURFACE}; - border: 1px solid {CARD_BORDER}; - }} - """ - ) - self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Maximum) - - layout = QVBoxLayout(self) - layout.setContentsMargins(12, 12, 12, 12) - layout.setSpacing(6) - - layout.addWidget(TitleLabel(self._title, self)) - - self._summary = QLabel(summary, self) - self._summary.setWordWrap(True) - self._summary.setStyleSheet(f"border: none; background: transparent; color: {SUBTLE_TEXT};") - layout.addWidget(self._summary) - - self._grid = QGridLayout() - self._grid.setContentsMargins(0, 0, 0, 0) - self._grid.setHorizontalSpacing(14) - # Tight rows; the badge keeps 2px vertical padding so text never clips. - self._grid.setVerticalSpacing(2) - layout.addLayout(self._grid) - - self._rebuild_rows() - - def set_summary_text(self, text: str) -> None: - self._summary.setText(text) - - def set_visible_fields(self, fields: Iterable[str]) -> None: - self._visible_fields = tuple(fields) - self._rebuild_rows() - self._refresh() - - def _clear_grid(self) -> None: - while self._grid.count(): - item = self._grid.takeAt(0) - widget = item.widget() - if widget is not None: - widget.deleteLater() - - def _rebuild_rows(self) -> None: - self._clear_grid() - self._row_widgets.clear() - - for row, key in enumerate(self._visible_fields): - title = QLabel(self.FIELD_TITLES.get(key, key.replace("_", " ").title()), self) - title.setStyleSheet( - f"font-weight: 700; border: none; background: transparent; color: {HEADING_TEXT};" - ) - value = QLabel(self._badge("WAITING", tone="neutral"), self) - value.setWordWrap(True) - value.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) - value.setStyleSheet(f"border: none; background: transparent; color: {SUBTLE_TEXT};") - self._row_widgets[key] = (title, value) - self._grid.addWidget(title, row, 0, alignment=Qt.AlignmentFlag.AlignTop) - self._grid.addWidget(value, row, 1) - # Word-wrapped value labels report a near-zero minimum height, so - # cramped tabs (e.g. Hardware) could compress rows until the text - # clipped; guarantee one full text line + badge padding per row. - self._grid.setRowMinimumHeight(row, self.fontMetrics().height() + 6) - - def _badge(self, text: str, *, tone: str = "neutral") -> str: - palette = { - "good": (SUCCESS_BG, SUCCESS_TEXT), - "warn": (CHIP_WARN_BG, CHIP_WARN_TEXT), - "bad": (CHIP_BAD_BG, CHIP_BAD_TEXT), - "neutral": (CHIP_NEUTRAL_BG, MUTED_TEXT), - "info": (CHIP_INFO_BG, CHIP_INFO_TEXT), - } - background, foreground = palette.get(tone, palette["neutral"]) - return ( - f"{text}" - ) - - def _format_bool( - self, value: bool | None, *, true_text: str = "CONNECTED", false_text: str = "DISCONNECTED" - ) -> str: - if value is True: - return self._badge(true_text, tone="good") - if value is False: - return self._badge(false_text, tone="bad") - return self._badge("UNKNOWN", tone="neutral") - - def _format_device_status(self, device: str) -> str: - payload = ( - self._device_state_payload.get(device, {}) - if isinstance(self._device_state_payload, dict) - else {} - ) - mode = str(payload.get("mode", "unknown")) - error = payload.get("error") - - if error: - return ( - f"{self._badge('ERROR', tone='bad')} " - f"{self._badge(mode.upper(), tone='warn')} " - f"{error}" - ) - if mode == "simulated": - return self._badge("SIMULATED", tone="warn") - if mode == "live": - return self._badge("LIVE", tone="good") - return self._badge("UNKNOWN", tone="neutral") - - def _format_tell_state(self, status: DAQStatusModel) -> str: - tell_state = getattr(status, "tell_state", None) - if tell_state is None: - return self._badge("UNAVAILABLE", tone="neutral") - - activity = getattr(tell_state.activity, "value", str(tell_state.activity)) - message = str(getattr(tell_state, "message", "") or "").strip() - - text = self._badge(str(activity).upper(), tone="info") - if message: - text = f"{text} {message}" - return text - - def _format_sample(self, status: DAQStatusModel) -> str: - if status.sample is None: - return self._badge("NONE", tone="neutral") - - sample_name = str(getattr(status.sample, "sample_name", "") or "").strip() - sample_loc = "" - if getattr(status.sample, "location", None) is not None: - try: - sample_loc = f" ({status.sample.loc_str()})" - except Exception: - logger.debug("Could not format the sample location", exc_info=True) - sample_loc = "" - if sample_name: - return f"{self._badge('MOUNTED', tone='info')} {sample_name}{sample_loc}" - return self._badge("MOUNTED", tone="info") - - def _format_state(self, status: DAQStatusModel) -> str: - state = getattr(status, "state", None) - if state is None: - return self._badge("UNKNOWN", tone="neutral") - - display_name = getattr(state, "display_name", None) - if callable(display_name): - return self._badge(str(display_name()).upper(), tone="info") - return self._badge(str(getattr(state, "name", state)).upper(), tone="info") - - def _format_field_value(self, key: str, status: DAQStatusModel) -> str: - if key == "beamline_state": - return self._format_state(status) - if key == "busy": - return ( - self._badge("BUSY", tone="warn") - if bool(status.busy) - else self._badge("IDLE", tone="good") - ) - if key == "sample": - return self._format_sample(status) - if key == "tell_connected": - return self._format_bool(getattr(status, "tell_connected", None)) - if key == "tell_state": - return self._format_tell_state(status) - if key == "tell_error": - err = getattr(status, "tell_error", None) - return str(err) if err else self._badge("NONE", tone="good") - if key in {"bec", "detector", "tell", "aerotech", "smargon"}: - return self._format_device_status(key) - if key == "smargon_connected": - return self._format_bool(getattr(status, "smargon_connected", None)) - if key == "smargon_error": - err = getattr(status, "smargon_error", None) - return str(err) if err else self._badge("NONE", tone="good") - if key == "aerotech_connected": - return self._format_bool(getattr(status, "aerotech_connected", None)) - if key == "aerotech_error": - err = getattr(status, "aerotech_error", None) - return str(err) if err else self._badge("NONE", tone="good") - if key == "session": - session = getattr(status, "session", None) - if session is None: - return self._badge("UNKNOWN", tone="neutral") - return f"{getattr(session, 'session', '-')}, pgroup={getattr(session, 'current_pgroup', '-')}, staff={getattr(session, 'staff', False)}" - if key == "open_guis": - open_guis = getattr(status, "open_guis", []) or [] - if not open_guis: - return self._badge("NONE", tone="neutral") - return str(len(open_guis)) - if key == "box": - box = getattr(status, "box", None) - if box is None: - return self._badge("NONE", tone="neutral") - return f"({box.top_x:.1f}, {box.top_y:.1f}) → ({box.bottom_x:.1f}, {box.bottom_y:.1f})" - if key == "last_best_res": - value = getattr(status, "last_best_res", None) - return f"{value:.3f} Å" if value is not None else self._badge("NONE", tone="neutral") - if key == "last_best_b_factor": - value = getattr(status, "last_best_b_factor", None) - return f"{value:.3f}" if value is not None else self._badge("NONE", tone="neutral") - if key == "crystal_size": - crystal = getattr(status, "crystal_size", None) - if crystal is None: - return self._badge("NONE", tone="neutral") - return f"x={crystal.x:.3f}, y={crystal.y:.3f}, z={crystal.z:.3f}" - if key == "beamline_name": - return str(getattr(status.bl, "name", "-")) - if key == "ring_current": - return f"{getattr(status.bl, 'ring_current_mA', 0.0):.2f} mA" - if key == "front_light": - return f"{getattr(status.bl, 'front_light', 0.0):.1f} %" - if key == "back_light": - return f"{getattr(status.bl, 'back_light', 0.0):.1f} %" - if key == "cryojet": - return f"{getattr(status.bl, 'cryojet_K', 0.0):.2f} K" - if key == "shutter": - return self._format_bool( - getattr(status.bl, "shutter_open", None), true_text="OPEN", false_text="CLOSED" - ) - if key == "exposure_shutter": - return self._format_bool( - getattr(status.bl, "exp_shutter_open", None), true_text="OPEN", false_text="CLOSED" - ) - if key == "flux": - return f"{getattr(status.bl, 'flux_ph_s', 0.0):.3g} ph/s" - if key == "transmission": - transmission = getattr(status.bl, "transmission", None) - return ( - f"{100.0 * transmission:.2f} %" - if transmission is not None - else self._badge("NONE", tone="neutral") - ) - if key == "zoom": - return f"{getattr(status.bl, 'zoom', 0.0):.3f}" - if key == "commissioning_mode": - return self._format_bool( - getattr(status.bl, "commissioning_mode", None), true_text="ON", false_text="OFF" - ) - if key == "omega": - return f"{getattr(status.geom, 'omega_deg', 0.0):.3f}°" - if key == "beam_size": - beam_size = getattr(status.geom, "beam_size_mm", None) - if beam_size is None: - return self._badge("UNKNOWN", tone="neutral") - return f"{beam_size.x * 1000.0:.1f} × {beam_size.y * 1000.0:.1f} µm" - if key == "smargon_position": - smargon = getattr(status.geom, "smargon", None) - if smargon is None or getattr(smargon, "sh_mm", None) is None: - return self._badge("UNKNOWN", tone="neutral") - return ( - f"sh=({smargon.sh_mm.x:.4f}, {smargon.sh_mm.y:.4f}, {smargon.sh_mm.z:.4f}) mm, " - f"phi={smargon.phi_deg:.3f}°, chi={smargon.chi_deg:.3f}°" - ) - if key == "aerotech_position": - pos = getattr(status.geom, "aerotech_meas", None) - if pos is None: - return self._badge("UNKNOWN", tone="neutral") - return f"({pos.x:.4f}, {pos.y:.4f}, {pos.z:.4f}) mm" - if key == "detector_description": - return str(getattr(status.diffraction, "detector_description", "-")) - if key == "detector_serial": - return str(getattr(status.diffraction, "detector_serial_number", "-")) - if key == "dtz": - return f"{getattr(status.diffraction, 'dtz_mm', 0.0):.3f} mm" - if key == "energy": - return f"{getattr(status.diffraction, 'energy_keV', 0.0):.4f} keV" - if key == "wavelength": - wavelength = getattr(status.diffraction, "wavelength_angstrom", None) - return ( - f"{wavelength:.5f} Å" - if wavelength is not None - else self._badge("NONE", tone="neutral") - ) - if key == "beam_center": - beam_center = getattr(status.diffraction, "beam_center_pxl", None) - if beam_center is None: - return self._badge("UNKNOWN", tone="neutral") - return f"({beam_center[0]:.2f}, {beam_center[1]:.2f}) px" - - return self._badge("N/A", tone="neutral") - - def _refresh(self) -> None: - if self._last_status is None: - for _title, value in self._row_widgets.values(): - value.setText(self._badge("WAITING", tone="neutral")) - return - - for key, (_title, value) in self._row_widgets.items(): - value.setText(self._format_field_value(key, self._last_status)) - - @Slot(dict) - def set_device_state_payload(self, payload: dict) -> None: - self._device_state_payload = payload or {} - self._refresh() - - @Slot(DAQStatusModel) - def set_daq_status(self, status: DAQStatusModel) -> None: - self._last_status = status - self._refresh() diff --git a/src/aare/gui/widgets/login.py b/src/aare/gui/widgets/login.py deleted file mode 100644 index 758e7510..00000000 --- a/src/aare/gui/widgets/login.py +++ /dev/null @@ -1,76 +0,0 @@ -import json - -import jwt -from aarecommon.models.auth import get_user -from aarecommon.models.models import TokenData -from PySide6.QtCore import QByteArray, QUrl, QUrlQuery, Slot -from PySide6.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest -from PySide6.QtWidgets import QDialog, QHBoxLayout, QLabel, QLineEdit, QPushButton, QVBoxLayout - -from aare.gui.styles import APP_BACKGROUND - - -class LoginDialog(QDialog): - def __init__(self, base_url: str | None): - super().__init__() - self.token = "" - self.setWindowTitle("User Authentication") - self.setMinimumWidth(400) - self.setStyleSheet(f"background-color: {APP_BACKGROUND};") - self._base_url = base_url - self._reply = None - self._network_manager = None - - # Layout - layout = QVBoxLayout(self) - - # Username - self.name_label = QLabel("Username:") - self.name_entry = QLineEdit() - user = get_user() - self.name_entry.setText(user) - self.name_entry.setPlaceholderText("Enter username") - layout.addWidget(self.name_label) - layout.addWidget(self.name_entry) - - # Buttons - button_layout = QHBoxLayout() - self.ok_button = QPushButton("OK") - self.ok_button.clicked.connect(self.authenticate) # Close dialog with accept status - self.cancel_button = QPushButton("Cancel") - self.cancel_button.clicked.connect(self.reject) # Close dialog with reject status - button_layout.addWidget(self.ok_button) - button_layout.addWidget(self.cancel_button) - - layout.addLayout(button_layout) - - @Slot() - def authenticate(self): - if self._base_url is None: - token_data = TokenData( - sub=self.name_entry.text(), staff=True, session=15, pgroups=["p16371", "p22233"] - ) - self.token = jwt.encode(token_data.model_dump(), "ABC123") - self.accept() - self._network_manager = QNetworkAccessManager(self) - request = QNetworkRequest(QUrl(f"{self._base_url}/token")) - request.setHeader( - QNetworkRequest.KnownHeaders.ContentTypeHeader, "application/x-www-form-urlencoded" - ) - - payload = QUrlQuery() - payload.addQueryItem("username", f"{self.name_entry.text()}") - payload.addQueryItem("password", "") - payload_string = payload.toString() - self._reply = self._network_manager.post(request, QByteArray.fromStdString(payload_string)) - self._reply.finished.connect(self.handle_token_response) - - @Slot() - def handle_token_response(self): - if self._reply is not None and self._reply.error() == QNetworkReply.NetworkError.NoError: - response_data = self._reply.readAll().data() - response_json = json.loads(response_data.decode("utf-8")) - if "access_token" in response_json: - self.token = response_json["access_token"] - self._reply.deleteLater() - self.accept() diff --git a/src/aare/gui/widgets/message_box.py b/src/aare/gui/widgets/message_box.py deleted file mode 100644 index 8919f06a..00000000 --- a/src/aare/gui/widgets/message_box.py +++ /dev/null @@ -1,162 +0,0 @@ -import time - -from aarecommon.config.logger import setup_logger -from PySide6.QtCore import QEventLoop -from PySide6.QtWidgets import QCheckBox, QMessageBox - -from aare.gui.constants import LOGGER_NAME - -logger = setup_logger(LOGGER_NAME) - -LOW_CURRENT_THRESHOLD = 360.0 -SNOOZE_SECONDS = 3600.0 # "Don't ask again for 1 hour" - - -class _PreconditionSnooze: - """Session-global 'don't ask me again for 1 hour' for precondition prompts. - - In-memory only, so it auto-clears when the GUI restarts. - """ - - def __init__(self): - self._until = 0.0 - - def active(self) -> bool: - return time.monotonic() < self._until - - def snooze(self) -> None: - self._until = time.monotonic() + SNOOZE_SECONDS - logger.info("Precondition prompts snoozed for 1 hour") - - def clear(self) -> None: - self._until = 0.0 - - -# Shared across all panels for the session. -precondition_snooze = _PreconditionSnooze() - - -def precondition_problems(ring_current, shutter_open, door_prohibited) -> list[str]: - """List the beamline conditions that are currently not satisfied.""" - problems: list[str] = [] - if ring_current is None: - problems.append("Ring current is unknown.") - elif ring_current < LOW_CURRENT_THRESHOLD: - problems.append(f"Ring current is low: {round(ring_current, 2)} mA.") - if not shutter_open: - problems.append("Experiment safety shutter is closed.") - if door_prohibited is False: - problems.append("Hutch is not in the prohibited state (doors open / not searched).") - return problems - - -def precondition_check(parent, *, ring_current, shutter_open, door_prohibited) -> bool: - """Combined ring current / safety shutter / hutch door pre-action check. - - Shows ONE 'Do you wish to continue?' dialog listing every failing - condition, with a 'Don't ask me again for 1 hour' checkbox. Returns True to - proceed. Honours the session-global snooze and never blocks outright. - """ - if precondition_snooze.active(): - return True - - problems = precondition_problems(ring_current, shutter_open, door_prohibited) - if not problems: - return True - - box = QMessageBox(parent) - box.setIcon(QMessageBox.Icon.Warning) - box.setWindowTitle("Beamline not ready") - box.setText("\n".join(problems) + "\n\nDo you wish to continue?") - box.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No) - box.setDefaultButton(QMessageBox.StandardButton.No) - snooze_cb = QCheckBox("Don't ask me again for 1 hour") - box.setCheckBox(snooze_cb) - - proceed = box.exec() == QMessageBox.StandardButton.Yes - if proceed and snooze_cb.isChecked(): - precondition_snooze.snooze() - return proceed - - -def reply_box(parent, title: str = "Warning", msg: str = "Warning."): - return QMessageBox.question( - parent, - title, - f"{msg} Do you wish to continue?", - QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, - QMessageBox.StandardButton.No, - ) - - -def continue_msg_box(parent, title: str = "Warning", msg: str = "Warning.") -> QMessageBox: - box = QMessageBox(parent) - box.setWindowTitle(title) - box.setText(f"{msg} Do you wish to continue?") - box.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No) - box.show() - return box - - -def ring_current_low_check(parent, ring_current) -> bool: - if ring_current is None: - logger.debug("Ring current: unknown") - msg = "Ring current: unknown." - too_low = True - else: - too_low = ring_current < LOW_CURRENT_THRESHOLD - if too_low: - rc = round(ring_current, 2) - logger.debug(f"Ring current low {rc} mA") - msg = f"Ring current is low: {rc} mA." - else: - logger.debug(f"Ring current: {round(ring_current, 2)} mA") - return True - - # Ask user only when unknown or too low - reply = reply_box(parent, title="Ring current too low", msg=msg) - return reply == QMessageBox.StandardButton.Yes - - -def experiment_hutch_shutter_check(parent, shutter_state) -> bool: - if shutter_state: - logger.debug("Experiment shutter open") - return True - else: - reply = reply_box( - parent, title="Experiment shutter open", msg="Experiment shutter is Closed." - ) - return reply == QMessageBox.StandardButton.Yes - - -def ring_current_auto_check(parent, ring_current, check_func) -> bool: - msg = ( - "Ring current: unknown." - if ring_current is None - else f"Ring current is low {round(ring_current, 2)} mA." - ) - return conditions_auto_check(parent, msg, title="Ring current too low") - - -def conditions_auto_check(parent, msg: str, title: str = "Beamline not ready") -> bool: - """Pause-and-wait dialog that auto-resumes when ``check_func()`` becomes True. - - Used to hold automation between samples until the beamline recovers. The - box auto-accepts (resume) as soon as the condition is satisfied; the user - can also click 'Yes' to continue now (override) or 'No' to stop automation. - Returns True to resume, False to stop. - """ - box = continue_msg_box(parent, title=title, msg=msg) - loop = QEventLoop() - - def finish(_=None): - if loop.isRunning(): - loop.quit() - - box.finished.connect(finish) - - box.show() - loop.exec() # returns as soon as box finishes without blocking UI processing of its signals - - result = box.result() - return result == QMessageBox.StandardButton.Yes diff --git a/src/aare/gui/widgets/motor_move_group.py b/src/aare/gui/widgets/motor_move_group.py deleted file mode 100644 index 3315d4b0..00000000 --- a/src/aare/gui/widgets/motor_move_group.py +++ /dev/null @@ -1,192 +0,0 @@ -"""Batch entry -> apply for motor value boxes. - -Why: typing into a motor box used to fire the move on Enter, one axis at a -time. Operators want to stage several targets, review them, then start all -motors with one click. The group tracks a per-box state machine: - - neutral (theme default) --user edit--> pending (orange) - pending --Move clicked--> moving (green) - moving --actual reaches target--> neutral - -Colors are QSS dynamic properties ("movestate" on the box), styled per theme -in styles.py — same pattern as NumberLineEdit's "invalid" property, so the -existing out-of-range red still wins while typing. - -Modular on purpose: any panel opts a NumberLineEdit in with add_box(); boxes -not registered keep their old behavior. -""" - -from PySide6.QtCore import QEvent, QObject, QPoint, Qt, Signal, Slot -from PySide6.QtWidgets import QDoubleSpinBox, QPushButton, QToolTip - -from aare.gui.widgets.number_line_edit import NumberLineEdit - - -class SpinMoveState(QObject): - """MotorMoveGroup's state machine for a single QDoubleSpinBox whose apply - gate is a button (the Set Energy rows): neutral tracks the readback, a - user edit stages pending (orange) and enables the button, the click turns - moving (green), and arrival within tol returns to neutral. The movestate - property sits on the spinbox itself — its inner QLineEdit is transparent - by theme design, so coloring it shows nothing. The caller keeps its own - clicked connection for the actual send; this object only tracks state.""" - - def __init__(self, spin: QDoubleSpinBox, button: QPushButton, tol: float, parent=None): - super().__init__(parent) - self._spin = spin - self._button = button - # "at target" window: the mono never lands exactly on the setpoint - self._tol = tol - self._state = "" # "" (neutral) | "pending" | "moving" - self._target = 0.0 - self._actual: float | None = None - # valueChanged fires for our own readback sync too; the flag is how a - # user edit is told apart (a spinbox has no textEdited-only signal for - # arrows/wheel). - self._syncing = False - spin.valueChanged.connect(self._on_value_changed) - button.clicked.connect(self._on_applied) - button.setEnabled(False) - - @Slot(float) - def _on_value_changed(self, value: float): - if self._syncing: - return - # editing back to the current readback cancels the pending change - if self._actual is not None and abs(value - self._actual) <= self._tol: - self._set_state("") - else: - self._set_state("pending") - - @Slot() - def _on_applied(self): - self._target = self._spin.value() - self._set_state("moving") - - @Slot(float) - def update_actual(self, value: float): - """Feed the readback. Neutral spins track it; pending/moving keep - showing the user's target until the move completes.""" - self._actual = value - if self._state == "moving" and abs(value - self._target) <= self._tol: - self._set_state("") - if self._state == "": - self._syncing = True - self._spin.setValue(value) - self._syncing = False - - def _set_state(self, state: str): - if self._spin.property("movestate") != state: - self._spin.setProperty("movestate", state) - self._spin.style().unpolish(self._spin) - self._spin.style().polish(self._spin) - self._state = state - self._button.setEnabled(state == "pending") - - -class MotorMoveGroup(QObject): - # {name: target} for every box that was pending when Move was clicked - applied = Signal(dict) - - def __init__(self, button_text: str = "Move", parent=None): - super().__init__(parent) - self.button = QPushButton(button_text) - self.button.setEnabled(False) - self.button.clicked.connect(self._apply) - self._boxes: dict[str, NumberLineEdit] = {} - self._tols: dict[str, float] = {} - self._state: dict[str, str] = {} # "" (neutral) | "pending" | "moving" - self._targets: dict[str, float] = {} - - def add_box(self, name: str, box: NumberLineEdit, tol: float = 0.1): - # tol is the "at target" window — hardware never lands exactly on the - # setpoint, so this stays a per-box knob (encoder resolution differs - # per motor). - self._boxes[name] = box - self._tols[name] = tol - self._state[name] = "" - box.textEdited.connect(lambda _text, n=name: self._on_edited(n)) - # Below-min can only be judged on Enter (typing "3" may become "30"), - # and the validator swallows editingFinished for out-of-range text — - # so catch the key directly. - box.installEventFilter(self) - - # -- panel-facing API ---------------------------------------------------- - @Slot(str, float) - def update_actual(self, name: str, value: float): - """Feed the motor's actual position. Neutral boxes track it (same as - the old direct update_value call); pending/moving boxes keep showing - the user's target until the move completes.""" - box = self._boxes[name] - state = self._state[name] - if state == "moving" and abs(value - self._targets[name]) <= self._tols[name]: - self._set_state(name, "") - state = "" - if state == "": - box.update_value(value) - - # -- internals ----------------------------------------------------------- - def _on_edited(self, name: str): - box = self._boxes[name] - try: - value = float(box.text()) - except ValueError: - # incomplete entry ("", "-", "1e"): stay/become pending, no tips - self._set_state(name, "pending") - return - top = box.range_validator.top() - if value > top: - QToolTip.showText( - box.mapToGlobal(QPoint(0, box.height())), - f"Maximum value: {box.to_string(top)}", - box, - ) - # editing back to the current position cancels the pending move - if abs(value - box.saved_value) <= self._tols[name]: - self._set_state(name, "") - else: - self._set_state(name, "pending") - - def eventFilter(self, obj, event): - if ( - event.type() == QEvent.Type.KeyPress - and event.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter) - and obj in self._boxes.values() - ): - try: - value = float(obj.text()) - except ValueError: - return super().eventFilter(obj, event) - bottom = obj.range_validator.bottom() - if value < bottom: - QToolTip.showText( - obj.mapToGlobal(QPoint(0, obj.height())), - f"Too small — minimum value: {obj.to_string(bottom)}", - obj, - ) - return super().eventFilter(obj, event) - - @Slot() - def _apply(self): - targets = {} - for name, box in self._boxes.items(): - # out-of-range text stays pending (red via the invalid property); - # only valid targets are sent - if self._state[name] == "pending" and box.validate(box.text()): - targets[name] = box.value - self._targets[name] = box.value - self._set_state(name, "moving") - if targets: - self.applied.emit(targets) - # ponytail: no timeout — a move that never reaches target leaves the - # box green until the user re-edits it; add a watchdog if that bites. - - def _set_state(self, name: str, state: str): - box = self._boxes[name] - if box.property("movestate") != state: - box.setProperty("movestate", state) - # property selectors only re-evaluate on repolish - box.style().unpolish(box) - box.style().polish(box) - self._state[name] = state - self.button.setEnabled(any(s == "pending" for s in self._state.values())) diff --git a/src/aare/gui/widgets/no_wheel_scroll_area.py b/src/aare/gui/widgets/no_wheel_scroll_area.py deleted file mode 100644 index 1dce19d9..00000000 --- a/src/aare/gui/widgets/no_wheel_scroll_area.py +++ /dev/null @@ -1,11 +0,0 @@ -from PySide6.QtWidgets import QScrollArea - - -class NoWheelScrollArea(QScrollArea): - """Historic name: it used to swallow the wheel entirely so scrolling the - column could not nudge a value widget. WheelValueGuard now protects the - value widgets themselves (right button + wheel to adjust), so the wheel - scrolls the column content normally again — and only ever scrolls.""" - - def __init__(self, parent=None): - super().__init__(parent) diff --git a/src/aare/gui/widgets/number_line_edit.py b/src/aare/gui/widgets/number_line_edit.py deleted file mode 100644 index e9ea2bed..00000000 --- a/src/aare/gui/widgets/number_line_edit.py +++ /dev/null @@ -1,283 +0,0 @@ -from PySide6.QtCore import Qt, Signal, Slot -from PySide6.QtGui import QDoubleValidator -from PySide6.QtWidgets import QCheckBox, QHBoxLayout, QLineEdit, QWidget - - -class NumberLineEdit(QLineEdit): - """Colors are centralized: the per-theme INPUT rules in styles.py key on - the :read-only pseudo-class and the "invalid" dynamic property set here — - no inline stylesheets, so both themes restyle these fields. - - track_pending=True additionally shows the "movestate" pending color (same - QSS as the motor move boxes) while the typed text differs from the last - committed value; Enter/focus-out commits and clears it. Opt-in because - MotorMoveGroup owns the movestate property on the boxes it registers.""" - - newValue = Signal(float) - - def __init__( - self, - min_val: float, - max_val: float, - default: float = 0.0, - decimals: int = 2, - parent=None, - track_pending: bool = False, - ): - super().__init__(parent) - self._read_only: bool = False - self._is_valid: bool = True - self._track_pending: bool = track_pending - self._applied_value: float = default - if track_pending: - # textEdited is user-only: programmatic setText never marks pending. - self.textEdited.connect(self._on_pending_edit) - - # Use a QDoubleValidator to only allow valid floating point numbers. - # Named range_validator: plain "validator" would shadow - # QLineEdit.validator() and break type checking at call sites. - self.range_validator = QDoubleValidator() - self.range_validator.setNotation(QDoubleValidator.Notation.StandardNotation) - self.decimal_count = decimals - self.range_validator.setRange(min_val, max_val, self.decimal_count) - self.setValidator(self.range_validator) - self.setAlignment(Qt.AlignmentFlag.AlignRight) - self.setToolTip( - f"Minimum: {self.to_string(min_val):s}\nMaximum: {self.to_string(max_val):s}" - ) - - # Connect the textChanged signal to a custom slot to check validity - self.textChanged.connect(self.on_text_changed) - self.editingFinished.connect(self.on_editing_finished) - self.setText(self.to_string(default)) - self.saved_value = default - self.initial_value = default - - def to_string(self, i: float) -> str: - format_string = f"{{:.{self.decimal_count}f}}" - return format_string.format(i) - - def _set_invalid(self, invalid: bool) -> None: - if self.property("invalid") == invalid: - return - self.setProperty("invalid", invalid) - # Property selectors are only re-evaluated on repolish. - self.style().unpolish(self) - self.style().polish(self) - - def _set_pending(self, pending: bool) -> None: - if not self._track_pending: - return - state = "pending" if pending else "" - if self.property("movestate") == state: - return - self.setProperty("movestate", state) - self.style().unpolish(self) - self.style().polish(self) - - @Slot(str) - def _on_pending_edit(self, text: str): - try: - value = float(text) - except ValueError: - # incomplete entry ("", "-", "1e"): pending until it parses - self._set_pending(True) - return - # string compare so "200" matches an applied "200.00"; typing back the - # committed value cancels the pending state (same rule as MotorMoveGroup) - self._set_pending(self.to_string(value) != self.to_string(self._applied_value)) - - @Slot(str) - def on_text_changed(self, text: str): - # when text changes check validation and change the colour of the line edit - self._is_valid = self.validate(text) - self._set_invalid(not self._is_valid) - - @Slot() - def on_editing_finished(self): - val = float(self.text()) - self._applied_value = val - self._set_pending(False) - self.newValue.emit(val) - self.saved_value = self.saved_value - - @property - def value(self) -> float: - return float(self.text()) - - @property - def committed_value(self) -> float: - """The value that was applied last, by Enter/focus-out or by a - programmatic write. Unlike ``value`` it ignores text that is still - being typed, and it never raises on a half-written number.""" - return self._applied_value - - def set_committed_value(self, val: float): - """Show ``val`` as the committed value, unless the field already shows - it. Skipping the rewrite keeps a refresh that changes nothing from - stealing text the user is in the middle of typing.""" - if self.to_string(val) != self.to_string(self._applied_value): - self.force_update_value(val) - - @Slot(float) - def update_value(self, val: float): - if abs(val - self.saved_value) > 0.001: - self.force_update_value(val) - - def force_update_value(self, val: float): - # Always update text and saved_value - self.blockSignals(True) - self.saved_value = val - self.setText(self.to_string(val)) - self.blockSignals(False) - # programmatic rewrite is a commit: the shown value IS the applied one - self._applied_value = val - self._set_pending(False) - - @Slot(float, float) - def update_limits(self, min_val: float, max_val: float): - self.range_validator.setRange(min_val, max_val, self.decimal_count) - self.setToolTip( - f"Minimum: {self.to_string(min_val):s}\nMaximum: {self.to_string(max_val):s}" - ) - self.on_text_changed(self.text()) - - def validate(self, text) -> bool: - return self.range_validator.validate(str(text), 0)[0] == QDoubleValidator.State.Acceptable - - def setReadOnly(self, ro: bool): - # Colors follow via the QSS :read-only pseudo-class (updates without - # a repolish); validity is already tracked by the invalid property. - super().setReadOnly(ro) - self._read_only = ro - - def get_default(self) -> float: - return float(self.initial_value) - - def reset_to_default(self): - # Force set to initial default - self.force_update_value(self.initial_value) - - -class CheckedLineEdit(QWidget): - newValue = Signal(float) - readOnlyChanged = Signal(bool) - - def __init__( - self, - min_val: float, - max_val: float, - /, - default: float = 0.0, - decimals: int = 2, - check_box_text: str = "", - start_checked: bool = False, - parent=None, - ): - super().__init__(parent) - self._busy = False - self._checked = start_checked - self._internal_value = default - self._external_value = default - - self.check_box = QCheckBox(check_box_text, self) - self.check_box.stateChanged.connect(self._on_checked_toggled) - self.check_box.setChecked(self._checked) - - self.editor = NumberLineEdit(min_val, max_val, default, decimals, self) - self.editor.newValue.connect(self._on_editor_value_changed) - self.editor.newValue.connect(self.newValue.emit) - self.editor.setReadOnly(not self._checked) - - self.layout = QHBoxLayout(self) - self.layout.setContentsMargins(0, 0, 0, 0) - self.layout.addWidget(self.check_box) - self.layout.addWidget(self.editor) - - def _on_editor_value_changed(self, value_float: float): - if self._checked: - self._internal_value = value_float - else: - self._external_value = value_float - - def _on_checked_toggled(self, checked: bool): - # when check box is clicked, change read only state of editor - self._checked = checked - if checked: - self.editor.force_update_value(self._internal_value) - else: - self.editor.force_update_value(self._external_value) - self.setReadOnly() - - def set_busy(self, busy: bool): - # if an external wants to change the busy state. - # update self._busy and change editor read only state. After enable/disable check_box and set colour - self.blockSignals(True) - self._busy = busy - self.setReadOnly() - self.check_box.blockSignals(True) - - # No inline checkbox fills: the theme's :disabled rules grey it. - if self._busy: - self.check_box.setEnabled(False) - if self._checked: - self.editor.force_update_value(self._internal_value) - - else: - self.check_box.setEnabled(True) - self.check_box.blockSignals(False) - self.blockSignals(False) - - def update_value(self, value): - # wrapper for NumberLineEdit.update_value - self._external_value = value - if not self._checked: - self.editor.update_value(value) - self._on_editor_value_changed(value) - - def force_update_value(self, value): - # wrapper for NumberLineEdit.force_update_value - self._external_value = value - if not self._checked: - self.editor.force_update_value(value) - self._on_editor_value_changed(value) - - @property - def value(self) -> float: - # wrapper for NumberLineEdit.value - return self.editor.value - - def update_limits(self, min_val: float, max_val: float): - # wrapper for NumberLineEdit.update_limits - self.editor.update_limits(min_val, max_val) - - def isChecked(self) -> bool: - # wrapper for check_box.isChecked() - return self.check_box.isChecked() - - def isReadOnly(self) -> bool: - return self.editor.isReadOnly() - - def external_read_only(self, ro: bool): - self.check_box.setChecked(not ro) - self.editor.setReadOnly(ro) - - def setReadOnly(self): - # Change editor read only state based on self._busy and self._checked - should_be_ro = True - if ( - not self._busy and self._checked - ): # Only set editor to writeable if busy is False and the checkbox is checked, - should_be_ro = False - self.editor.setReadOnly(False) - - # state_changed = self.editor.isReadOnly() != should_be_ro - self.editor.setReadOnly(should_be_ro) - self.readOnlyChanged.emit(should_be_ro) - - def get_default(self) -> float: - return float(self._internal_value) - - def reset_to_default(self): - # Force set to initial default - self.force_update_value(self._internal_value) diff --git a/src/aare/gui/widgets/pgroup_dialog.py b/src/aare/gui/widgets/pgroup_dialog.py deleted file mode 100644 index 296dbc9a..00000000 --- a/src/aare/gui/widgets/pgroup_dialog.py +++ /dev/null @@ -1,130 +0,0 @@ -from PySide6.QtCore import Qt -from PySide6.QtWidgets import ( - QComboBox, - QCompleter, - QDialog, - QLabel, - QMessageBox, - QPushButton, - QVBoxLayout, -) - -from aare.gui.styles import DANGER_ACCENT - - -class PGroupDialog(QDialog): - def __init__( - self, curr_pgroup: str | None = None, pgroups: list[str] | None = None, parent=None - ): - super().__init__(parent) - self.setWindowTitle("Change current p-group") - self.setMinimumWidth(300) - - self._pgroups = [ - str(p).strip() for p in (pgroups or []) if p is not None and str(p).strip() - ] - - layout = QVBoxLayout(self) - - self.label = QLabel("Set p-group:", self) - layout.addWidget(self.label) - - self.combo = QComboBox(self) - self.combo.setEditable(True) - self.combo.setInsertPolicy(QComboBox.InsertPolicy.NoInsert) - self.combo.addItems(self._pgroups) - - completer = QCompleter(self._pgroups, self) - completer.setCaseSensitivity(Qt.CaseInsensitive) - completer.setFilterMode(Qt.MatchFlag.MatchContains) - completer.setCompletionMode(QCompleter.CompletionMode.PopupCompletion) - self.combo.setCompleter(completer) - - default_pgroup = self._latest_pgroup(self._pgroups) - if curr_pgroup and curr_pgroup in self._pgroups: - self.combo.setCurrentText(curr_pgroup) - elif default_pgroup is not None: - self.combo.setCurrentText(default_pgroup) - - layout.addWidget(self.combo) - - self.ok_button = QPushButton("OK", self) - self.cancel_button = QPushButton("Cancel", self) - - layout.addWidget(self.ok_button) - layout.addWidget(self.cancel_button) - - self.ok_button.clicked.connect(self._validate_and_accept) - self.cancel_button.clicked.connect(self.reject) - - if self.combo.lineEdit() is not None: - self.combo.lineEdit().textEdited.connect(self._live_validate) - self._live_validate(self.combo.currentText()) - - @staticmethod - def _latest_pgroup(pgroups: list[str]) -> str | None: - """ - Return the numerically largest p-group, e.g. p16371 over p01234. - Falls back to lexicographic max if parsing fails. - """ - if not pgroups: - return None - - def _key(pg: str): - s = str(pg).strip() - if s.startswith("p") and s[1:].isdigit(): - return (1, int(s[1:]), s) - return (0, -1, s) - - return max(pgroups, key=_key) - - def _set_error_state(self, is_error: bool, message: str | None = None) -> None: - if is_error: - self.combo.setStyleSheet(f"border: 2px solid {DANGER_ACCENT};") - if message: - self.label.setText( - f"Set p-group: {message}" - ) - else: - self.label.setText("Set p-group:") - else: - self.combo.setStyleSheet("") - self.label.setText("Set p-group:") - - def _live_validate(self, text: str) -> None: - text = (text or "").strip() - if not text: - self._set_error_state(True, "Select a p-group") - return - if self._pgroups and text not in self._pgroups: - self._set_error_state(True, "Not in allowed list") - return - self._set_error_state(False) - - def _validate_and_accept(self) -> None: - entered_text = (self.combo.currentText() or "").strip() - - if not entered_text: - QMessageBox.warning(self, "Invalid P-Group", "You must select a p-group.") - self.combo.setFocus() - return - - if self._pgroups and entered_text not in self._pgroups: - QMessageBox.warning( - self, - "Invalid P-Group", - f"P-group '{entered_text}' is not in your allowed list.\n" - f"Please select from: {', '.join(self._pgroups)}", - ) - self.combo.setFocus() - if self.combo.lineEdit() is not None: - self.combo.lineEdit().selectAll() - self._set_error_state(True, "Not in allowed list") - return - - self._set_error_state(False) - self.accept() - - def get_input(self): - """Return the input text when the dialog is accepted.""" - return (self.combo.currentText() or "").strip() diff --git a/src/aare/gui/widgets/popout_window.py b/src/aare/gui/widgets/popout_window.py deleted file mode 100644 index 980c228e..00000000 --- a/src/aare/gui/widgets/popout_window.py +++ /dev/null @@ -1,260 +0,0 @@ -from PySide6.QtCore import QEvent, QPoint, QRect, QSize, Qt -from PySide6.QtGui import QColor, QCursor, QGuiApplication, QIcon, QPainter, QPalette, QPen, QPixmap -from PySide6.QtWidgets import QDockWidget, QHBoxLayout, QLabel, QToolButton, QVBoxLayout, QWidget - -from aare.gui.styles import FRAME_L1_COLOR, FRAME_L1_WIDTH, qcolor - -# Title-bar buttons: icon fills the button, both the same size. These are -# minimums — the real size follows the font metrics (see _titlebar_button), -# so the glyphs keep up with the DPI/font settings of the machine (fixed px -# rendered tiny on the RHEL9 consoles). -TITLEBAR_BUTTON_PX = 22 -TITLEBAR_ICON_PX = 18 - - -def _titlebar_icon(kind: str, color: QColor, size: int = TITLEBAR_ICON_PX) -> QIcon: - """Hand-painted borderless glyphs — the style's standard title-bar - pixmaps draw boxed icons, and text glyphs are missing from the - container's fonts. Color comes from the caller's palette so the glyphs - follow the theme (they are pixmaps, QSS color cannot reach them).""" - # Paint at the physical resolution so the glyph stays crisp on HiDPI. - screen = QGuiApplication.primaryScreen() - dpr = screen.devicePixelRatio() if screen is not None else 1.0 - pixmap = QPixmap(round(size * dpr), round(size * dpr)) - pixmap.setDevicePixelRatio(dpr) - pixmap.fill(Qt.GlobalColor.transparent) - painter = QPainter(pixmap) - painter.setRenderHint(QPainter.RenderHint.Antialiasing) - pen = QPen(color, 2) - pen.setCapStyle(Qt.PenCapStyle.RoundCap) - pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin) - painter.setPen(pen) - if kind == "close": - painter.drawLine(4, 4, size - 4, size - 4) - painter.drawLine(size - 4, 4, 4, size - 4) - else: # "popout": window in the lower left, arrow escaping top-right - painter.drawRect(3, size // 2 - 1, size // 2 - 1, size // 2 - 1) - painter.drawLine(size // 2 + 1, size // 2 - 1, size - 3, 3) - painter.drawLine(size - 8, 3, size - 3, 3) - painter.drawLine(size - 3, 3, size - 3, 8) - painter.end() - return QIcon(pixmap) - - -def _titlebar_button(parent: QWidget, tooltip: str) -> QToolButton: - # Icon is set by DockTitleBar._tint_icons (initially and on theme change). - button = QToolButton(parent) - # Size from the font, not fixed px: a setup with larger fonts/DPI gets - # proportionally larger glyphs. The constants act as the floor. - icon_px = max(TITLEBAR_ICON_PX, parent.fontMetrics().height()) - button_px = icon_px + (TITLEBAR_BUTTON_PX - TITLEBAR_ICON_PX) - button.setIconSize(QSize(icon_px, icon_px)) - button.setFixedSize(button_px, button_px) - button.setAutoRaise(True) - # No button chrome — the glyph IS the button. The padding/height zeroing - # is the opt-out from the app sheets' global QToolButton cap (16px + - # padding): without it the light theme's horizontal padding shrinks the - # content box and Qt scales the glyph down to a speck. - button.setStyleSheet( - "QToolButton { border: none; background: transparent;" - f" padding: 0px; min-height: 0px; max-height: {button_px}px; }}" - ) - button.setToolTip(tooltip) - button.setCursor(Qt.CursorShape.PointingHandCursor) - return button - - -class DockTitleBar(QWidget): - """Dock title bar with a ⤢ pop-out button right next to ✕. - - Qt's native dock title bar cannot host extra buttons, so this replaces - it: [title … ⤢ ✕]. Trade-off: the dock can no longer be dragged by its - title — acceptable here, these docks are pinned to the bottom row. - """ - - def __init__(self, dock: QDockWidget, on_popout): - super().__init__(dock) - layout = QHBoxLayout(self) - layout.setContentsMargins(8, 2, 4, 2) - layout.setSpacing(2) - - title = QLabel(dock.windowTitle(), self) - title.setStyleSheet("background: transparent;") - layout.addWidget(title) - layout.addStretch(1) - - self.popout_button = _titlebar_button( - self, "Open in a separate window (the panel stays here too)" - ) - self.popout_button.clicked.connect(on_popout) - layout.addWidget(self.popout_button) - - close_button = _titlebar_button(self, "Close panel (reopen via the View menu)") - close_button.clicked.connect(dock.close) - layout.addWidget(close_button) - - self._icon_buttons = {"popout": self.popout_button, "close": close_button} - self._tint_icons() - - def _tint_icons(self) -> None: - color = self.palette().color(QPalette.ColorRole.WindowText) - for kind, button in self._icon_buttons.items(): - button.setIcon(_titlebar_icon(kind, color, button.iconSize().width())) - - def changeEvent(self, event): - # A theme switch lands here as a palette/style change; the glyphs are - # pixmaps, so they must be repainted in the new text color. - if event.type() in (QEvent.Type.PaletteChange, QEvent.Type.StyleChange): - self._tint_icons() - super().changeEvent(event) - - -class PopoutWindow(QWidget): - """Additional top-level window for a panel mirror. - - Unlike a floated QDockWidget it never removes anything from the main - window — closing it just hides it (geometry kept for reopening) and the - main window is untouched. The layout leaves RESIZE_MARGIN px of the - window exposed around the content as a fat, easy-to-hit resize band; - frameless floats only give a few px. Resize uses startSystemResize with - a manual fallback for window managers that lack it. - """ - - # 6px: enough to grab without pixel-hunting, small enough that the area - # right around the content doesn't hijack table interactions. - RESIZE_MARGIN = 6 - # Clicks can never land outside a window, so a from-the-outside grab zone - # has to be window area that only LOOKS external: the visible border is - # drawn OUTER_GRIP px inside the real edge, and the halo beyond it - # resizes too. - OUTER_GRIP = 4 - - def __init__(self, title: str, content: QWidget, parent=None): - super().__init__(parent, Qt.WindowType.Window) - # QWidget SUBCLASSES skip QSS background painting unless this is set; - # an unpainted top-level renders black on the container's - # non-composited X11 (the PopoutWindow QSS rule supplies the fill). - self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) - self.setWindowTitle(title) - self.setMinimumSize(300, 160) - layout = QVBoxLayout(self) - m = self.RESIZE_MARGIN + self.OUTER_GRIP - layout.setContentsMargins(m, m, m, m) - layout.addWidget(content) - self.setMouseTracking(True) - self._manual_edges = Qt.Edge(0) - self._press_global: QPoint | None = None - self._press_geom: QRect | None = None - self._placed = False - - def showEvent(self, event): - # First show opens near the click (the ⤢ button = the cursor), not at - # the WM's default top-left; reopening keeps the last geometry. - if not self._placed: - self._placed = True - cursor = QCursor.pos() - pos = cursor - QPoint(60, 20) - screen = QGuiApplication.screenAt(cursor) or QGuiApplication.primaryScreen() - if screen is not None: - geo = screen.availableGeometry() - pos.setX(max(geo.left(), min(pos.x(), geo.right() - self.width()))) - pos.setY(max(geo.top(), min(pos.y(), geo.bottom() - self.height()))) - self.move(pos) - super().showEvent(event) - - def paintEvent(self, event): - super().paintEvent(event) - # Optional perceived window border, inset by OUTER_GRIP (see class - # note). Level-1 frame — weight/color are knobs in styles.py; the - # default width 0 paints nothing (resize still works via the cursor - # hint over the grab band). - width = int(FRAME_L1_WIDTH.rstrip("px")) - if width <= 0: - return - painter = QPainter(self) - painter.setPen(QPen(qcolor(FRAME_L1_COLOR), width)) - g = self.OUTER_GRIP - painter.drawRect(self.rect().adjusted(g, g, -g - 1, -g - 1)) - - def _edges_at(self, pos: QPoint) -> Qt.Edge: - m = self.RESIZE_MARGIN + self.OUTER_GRIP - edges = Qt.Edge(0) - if pos.x() <= m: - edges |= Qt.Edge.LeftEdge - if pos.x() >= self.width() - m: - edges |= Qt.Edge.RightEdge - if pos.y() <= m: - edges |= Qt.Edge.TopEdge - if pos.y() >= self.height() - m: - edges |= Qt.Edge.BottomEdge - return edges - - def _cursor_for(self, edges: Qt.Edge): - horizontal = edges & (Qt.Edge.LeftEdge | Qt.Edge.RightEdge) - vertical = edges & (Qt.Edge.TopEdge | Qt.Edge.BottomEdge) - if horizontal and vertical: - same_diag = bool(edges & Qt.Edge.LeftEdge) == bool(edges & Qt.Edge.TopEdge) - return Qt.CursorShape.SizeFDiagCursor if same_diag else Qt.CursorShape.SizeBDiagCursor - if horizontal: - return Qt.CursorShape.SizeHorCursor - if vertical: - return Qt.CursorShape.SizeVerCursor - return None - - def mousePressEvent(self, event): - edges = self._edges_at(event.position().toPoint()) - if event.button() == Qt.MouseButton.LeftButton and edges: - handle = self.windowHandle() - if handle is None or not handle.startSystemResize(edges): - self._manual_edges = edges - self._press_global = event.globalPosition().toPoint() - self._press_geom = QRect(self.geometry()) - return - super().mousePressEvent(event) - - def mouseMoveEvent(self, event): - # Both press fields are set together in mousePressEvent; the second - # check exists for the pyright gate, which can't see that pairing. - if self._manual_edges and self._press_global is not None and self._press_geom is not None: - delta = event.globalPosition().toPoint() - self._press_global - geom = QRect(self._press_geom) - if self._manual_edges & Qt.Edge.LeftEdge: - geom.setLeft(min(geom.left() + delta.x(), geom.right() - self.minimumWidth())) - if self._manual_edges & Qt.Edge.RightEdge: - geom.setRight(max(geom.right() + delta.x(), geom.left() + self.minimumWidth())) - if self._manual_edges & Qt.Edge.TopEdge: - geom.setTop(min(geom.top() + delta.y(), geom.bottom() - self.minimumHeight())) - if self._manual_edges & Qt.Edge.BottomEdge: - geom.setBottom(max(geom.bottom() + delta.y(), geom.top() + self.minimumHeight())) - self.setGeometry(geom) - return - cursor = self._cursor_for(self._edges_at(event.position().toPoint())) - if cursor is None: - self.unsetCursor() - else: - self.setCursor(cursor) - super().mouseMoveEvent(event) - - def mouseReleaseEvent(self, event): - self._manual_edges = Qt.Edge(0) - self._press_global = None - self._press_geom = None - super().mouseReleaseEvent(event) - - -if __name__ == "__main__": - # ponytail: smallest check that fails if the edge maths breaks - import os - - os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") - from PySide6.QtWidgets import QApplication, QLabel - - app = QApplication([]) - w = PopoutWindow("t", QLabel("x")) - w.resize(400, 300) - assert w._edges_at(QPoint(5, 150)) == Qt.Edge.LeftEdge - assert w._edges_at(QPoint(398, 298)) == (Qt.Edge.RightEdge | Qt.Edge.BottomEdge) - assert w._edges_at(QPoint(200, 150)) == Qt.Edge(0) - assert w._cursor_for(Qt.Edge.LeftEdge | Qt.Edge.TopEdge) == Qt.CursorShape.SizeFDiagCursor - assert w._cursor_for(Qt.Edge.RightEdge | Qt.Edge.TopEdge) == Qt.CursorShape.SizeBDiagCursor - print("gude") diff --git a/src/aare/gui/widgets/raster_grid_table.py b/src/aare/gui/widgets/raster_grid_table.py deleted file mode 100644 index 7f76791d..00000000 --- a/src/aare/gui/widgets/raster_grid_table.py +++ /dev/null @@ -1,131 +0,0 @@ -from PySide6.QtCore import Signal, Slot -from PySide6.QtWidgets import ( - QHBoxLayout, - QHeaderView, - QPushButton, - QTableWidget, - QTableWidgetItem, - QWidget, -) - -from aare.gui.scan_logic.raster_grid_manager import RasterGridManager -from aare.gui.styles import FONT_BODY, TABLE_SHADE_BG - - -class RasterGridTable(QTableWidget): - copy_clicked = Signal(int) - delete_clicked = Signal(int) - visible_clicked = Signal(int, bool) - goto_clicked = Signal(int) - - def __init__(self, raster_mgr: RasterGridManager, parent=None): - super().__init__(parent) - self._raster_mgr = raster_mgr - - self.setColumnCount(5) - self.setHorizontalHeaderLabels(["Omega", "Chi", "Phi", "Size (WxH)", "Actions"]) - - self.verticalHeader().setVisible(False) - - # Configure header - header = self.horizontalHeader() - for i in range(4): - header.setSectionResizeMode(i, QHeaderView.ResizeMode.ResizeToContents) - header.setSectionResizeMode(4, QHeaderView.ResizeMode.Stretch) - - # Exactly 5 rows of space; more grids scroll inside the table. - header_height = self.horizontalHeader().sizeHint().height() - row_height = self.verticalHeader().defaultSectionSize() - self.setFixedHeight(header_height + 3 * row_height + 1 * self.frameWidth()) - - # Connect to raster manager signals - self._raster_mgr.completed_grid_updated.connect(self.refresh_table) - self.copy_clicked.connect(self._raster_mgr.completed_grid_redo) - self.delete_clicked.connect(self._raster_mgr.completed_grid_scan_delete) - self.visible_clicked.connect(self._raster_mgr.completed_grid_scan_toggle_visible) - self.goto_clicked.connect(self._raster_mgr.completed_grid_scan_goto) - - def add_rows(self): - for r in self._raster_mgr.get_completed_grids(): - req = r.request - - row_position = self.rowCount() - self.insertRow(row_position) - - # Add data cells - self.setItem(row_position, 0, QTableWidgetItem(f"{req.omega_deg:.1f}")) - self.setItem(row_position, 1, QTableWidgetItem(f"{req.smargon_top_left.chi_deg:.1f}")) - self.setItem(row_position, 2, QTableWidgetItem(f"{req.smargon_top_left.phi_deg:.1f}")) - self.setItem(row_position, 3, QTableWidgetItem(f"{req.n_x} x {req.n_y}")) - - # Add action buttons - self.add_action_buttons(row_position, req.visible) - - def add_action_buttons(self, row: int, visible: bool): - """Create and add action buttons for the specified row.""" - actions_widget = QWidget() - actions_layout = QHBoxLayout(actions_widget) - actions_layout.setContentsMargins(4, 4, 4, 4) - actions_layout.setSpacing(4) - - button_style = f""" - QPushButton {{ - border: none; - background: transparent; - font-size: {FONT_BODY}; - }} - QPushButton:hover {{ - background-color: {TABLE_SHADE_BG}; - border-radius: 3px; - }} - """ - - # Copy button - copy_btn = QPushButton("⧉") - copy_btn.setFixedSize(24, 24) - copy_btn.setToolTip("Copy") - copy_btn.setStyleSheet(button_style) - copy_btn.clicked.connect(lambda checked, r=row: self.copy_clicked.emit(r)) - actions_layout.addWidget(copy_btn) - - # Redo button - goto_btn = QPushButton("🏃‍♂️") # Circular arrow for goto - goto_btn.setFixedSize(24, 24) - goto_btn.setToolTip("Goto scan") - goto_btn.setStyleSheet(button_style) - goto_btn.clicked.connect(lambda checked, r=row: self.goto_clicked.emit(r)) - actions_layout.addWidget(goto_btn) - - # Visible button - if visible: - visible_btn = QPushButton("👁") - else: - visible_btn = QPushButton("‍🗨") - visible_btn.setChecked(visible) # Initially visible - - visible_btn.setFixedSize(24, 24) - visible_btn.setToolTip("Toggle visibility") - visible_btn.setStyleSheet(button_style) - visible_btn.setCheckable(True) - visible_btn.clicked.connect( - lambda checked, r=row: self.visible_clicked.emit(r, not visible) - ) - actions_layout.addWidget(visible_btn) - - # Delete button - delete_btn = QPushButton("🗑") - delete_btn.setFixedSize(24, 24) - delete_btn.setToolTip("Delete") - delete_btn.setStyleSheet(button_style) - delete_btn.clicked.connect(lambda checked, r=row: self.delete_clicked.emit(r)) - actions_layout.addWidget(delete_btn) - - self.setCellWidget(row, 4, actions_widget) - - @Slot() - def refresh_table(self): - """Refresh the entire table content.""" - # Clear existing rows - self.setRowCount(0) - # Repopulate with current data - self.add_rows() diff --git a/src/aare/gui/widgets/splash_screen.py b/src/aare/gui/widgets/splash_screen.py deleted file mode 100644 index 6b776aab..00000000 --- a/src/aare/gui/widgets/splash_screen.py +++ /dev/null @@ -1,35 +0,0 @@ -from PySide6.QtCore import Qt -from PySide6.QtWidgets import QApplication, QProgressBar, QSplashScreen - -from aare.gui.styles import SPLASH_ACCENT, SPLASH_BG, SPLASH_BORDER, SPLASH_TEXT, qcolor - - -class LoadingSplashScreen(QSplashScreen): - def __init__(self, pixmap): - super().__init__(pixmap) - self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint) - self.progress = QProgressBar(self) - # Position the progress bar at the bottom of the splash screen - self.progress.setGeometry(10, self.size().height() - 30, self.size().width() - 20, 20) - self.progress.setStyleSheet(f""" - QProgressBar {{ - border: 1px solid {SPLASH_BORDER}; - border-radius: 5px; - text-align: center; - background-color: {SPLASH_BG}; - color: {SPLASH_TEXT}; - }} - QProgressBar::chunk {{ - background-color: {SPLASH_ACCENT}; - }} - """) - - def set_progress(self, value, message=None): - self.progress.setValue(value) - if message: - self.showMessage( - message, - Qt.AlignmentFlag.AlignBottom | Qt.AlignmentFlag.AlignCenter, - qcolor(SPLASH_TEXT), - ) - QApplication.processEvents() diff --git a/src/aare/gui/widgets/status_bar.py b/src/aare/gui/widgets/status_bar.py deleted file mode 100644 index a89583d9..00000000 --- a/src/aare/gui/widgets/status_bar.py +++ /dev/null @@ -1,696 +0,0 @@ -import math - -from aarecommon.config.logger import setup_logger -from aarecommon.models.auth import BatonStatus -from aarecommon.models.models import BeamlineStateEnum, DAQStatusModel, SessionsStateEnum, TokenData -from PySide6.QtCore import QPoint, QTimer, Signal, Slot -from PySide6.QtGui import QFont -from PySide6.QtWidgets import QDialog, QLabel, QMenu, QMessageBox, QSizePolicy, QStatusBar - -from aare.gui.constants import LOGGER_NAME -from aare.gui.styles import THEME_SUNRISE, status_colors -from aare.gui.widgets.baton_request_dialog import BatonRequestDialog -from aare.gui.widgets.clickable_label import ClickableLabel -from aare.gui.widgets.flow_layout import FlowHost -from aare.gui.widgets.pgroup_dialog import PGroupDialog -from aare.gui.widgets.value_label import ValueLabel - -logger = setup_logger(LOGGER_NAME) - - -class StatusBar(QStatusBar): - set_pgroup = Signal(str) - dewar_exchange = Signal() - sample_alignment = Signal() - sample_exchange = Signal() - beam_location = Signal() - - force_session = Signal() - end_session = Signal() - request_baton = Signal() - cancel_baton_request = Signal() - release_baton = Signal() - baton_request_accepted = Signal() - baton_request_refused = Signal() - - get_all_pgroups = Signal() - staff_pgroups_loaded = Signal(list) - baton_request_received = Signal(dict) - - close_shutter = Signal() - open_shutter = Signal() - - def __init__(self, token: TokenData, parent=None): - super().__init__(parent) - self._decoded_token = token - self._status = None - self._is_staff = self._decoded_token.staff - self._allowed_pgroups = self._decoded_token.pgroups - - # Per-theme flag colors (MainWindow._apply_theme calls set_theme) — - # painted in code per DAQ tick, QSS cannot reach the rich-text spans. - self._colors = status_colors(THEME_SUNRISE) - self._message_is_error = False - - self._message_clear_timer = QTimer(self) - self._message_clear_timer.setSingleShot(True) - self._message_clear_timer.timeout.connect(self.clear_connection_message) - - self._baton_status: BatonStatus | None = None - self._has_pending_request: bool = False - self._pgroup_dialog_for_baton: PGroupDialog | None = None - self._baton_request_dialog: BatonRequestDialog | None = None - self._pgroup_dialog_shown_for_current_baton: bool = False - - self.message_label = QLabel("", self) - self.message_label.setVisible(False) - self.message_label.setSizePolicy(QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Preferred) - - self.sharpness = ValueLabel("Samcam image sharpness", "", self) - self.samcam_fps = ValueLabel("Samcam FPS", "fps", self) - self.flux = ValueLabel("Flux", "ph/s", self) - self.transmission = ValueLabel("Transmission", "", self) - self.ring_current = ValueLabel("Ring current", "mA", self) - self.wvl = ValueLabel("Wavelength", "Å", self) - self.cryo_label = ValueLabel("Cryo", "K", self) - - self.pgroup_label = ClickableLabel(self) - self.pgroup_label.clicked.connect(self.show_pgroup_menu) - - self.state_label = ClickableLabel(parent=self) - self.state_label.clicked.connect(self.show_state_menu) - - self.tell_state_label = QLabel("Tell: —", self) - - # Plain QLabel: "Beamline: Busy/Idle" is a passive readout, no click. - self.busy_label = QLabel(parent=self) - - self.session_label = ClickableLabel(parent=self) - self.session_label.clicked.connect(self.show_session_menu) - - self.shutter_label = ClickableLabel(parent=self) - self.shutter_label.clicked.connect(self.show_shutter_menu) - - self.exp_shutter_label = ValueLabel("ExpHutch Shutter", "", self) - - # Split layout: the passive readouts wrap in a flow host (narrow - # windows used to clip them outright), while the four operables — - # Fast Shutter | State | p-group | Session — are addPermanentWidget - # so QStatusBar itself pins them to the right corner at a fixed spot - # regardless of wrapping; no showMessage is ever used here, so - # nothing hides either side. - # TODO(cryo): a cryo operation (fill/anneal menu) is planned; when it - # gets a click handler, swap to ClickableLabel and move it over to - # the permanent (right-pinned) group with the other operables. - self.info_host = FlowHost(self) - for widget in ( - self.message_label, - self.sharpness, - self.samcam_fps, - self.flux, - self.transmission, - self.ring_current, - self.wvl, - self.exp_shutter_label, - self.tell_state_label, - self.busy_label, - self.cryo_label, - ): - self.info_host.add_widget(widget) - self.addWidget(self.info_host, 1) - - for widget in (self.shutter_label, self.state_label, self.pgroup_label, self.session_label): - self.addPermanentWidget(widget) - - def _ratchet_widths(self, *labels: QLabel) -> None: - # ponytail: grow-only min-width ratchet — per-tick number width - # changes used to re-flow the row and jitter every neighbour; pin - # each label to the widest text it has shown. Never shrinks until - # restart, which is fine for a status bar; per-label fixed widths - # from font metrics if a pathological long value ever sticks. - for label in labels: - label.setMinimumWidth(max(label.minimumWidth(), label.sizeHint().width())) - - def set_theme(self, theme: str) -> None: - """Adopt the theme's flag colors: recolor the connection message and - re-render the DAQ-driven labels from the last status right away.""" - self._colors = status_colors(theme) - self._apply_message_style() - if self._status is not None: - self.update_daq_status(self._status) - - def _apply_message_style(self) -> None: - color = self._colors["alert"] if self._message_is_error else self._colors["ok"] - self.message_label.setStyleSheet(f"color: {color}; font-weight: bold;") - - @Slot(str, bool) - def show_connection_message(self, msg: str, is_error: bool = True): - self._message_is_error = is_error - self._message_clear_timer.stop() - self.message_label.setText(msg) - self._apply_message_style() - self.message_label.setVisible(bool(msg)) - - if not is_error: - self._message_clear_timer.start(5000) - - @Slot() - def clear_connection_message(self): - self._message_clear_timer.stop() - self.message_label.clear() - self.message_label.setVisible(False) - - @Slot(float) - def update_sharpness(self, val: float): - self.sharpness.set_value(f"{val:.3f}") - self._ratchet_widths(self.sharpness) - - @Slot(float) - def update_samcam_fps(self, fps: float): - if fps is None or (isinstance(fps, float) and math.isnan(fps)): - self.samcam_fps.set_value("off") - return - if not math.isfinite(fps) or fps < 0: - self.samcam_fps.set_value("error") - return - self.samcam_fps.set_value(f"{fps:.1f}") - self._ratchet_widths(self.samcam_fps) - - @Slot(DAQStatusModel) - def update_daq_status(self, status: DAQStatusModel): - try: - self._status = status - if status.bl.flux_ph_s is None or status.bl.transmission is None: - self.flux.set_value("0") - else: - try: - num = f"{(status.bl.flux_ph_s * status.bl.transmission):.2E}" - mod, exp = num.split("E") - self.flux.set_value(f"{mod} x 10{int(exp)}") - except Exception as e: # noqa - logger.error(f"Error parsing flux result: {e}") - self.flux.set_value(f"{status.bl.flux_ph_s:.2E}") - - if status.bl.transmission is None: - self.transmission.set_value("(moving)") - else: - self.transmission.set_value(f"{status.bl.transmission:.5f}") - - if status.bl.ring_current_mA < 5.0: - self.ring_current.set_value( - f"{status.bl.ring_current_mA:.2f}", self._colors["alert"] - ) - elif status.bl.ring_current_mA < 390.0: - self.ring_current.set_value( - f"{status.bl.ring_current_mA:.2f}", self._colors["warn"] - ) - else: - self.ring_current.set_value(f"{status.bl.ring_current_mA:.2f}") - - if status.diffraction.wavelength_angstrom: - self.wvl.set_value(f"{status.diffraction.wavelength_angstrom:.2f}") - - if status.bl.cryojet_K < 110.0: - self.cryo_label.set_value(f"{status.bl.cryojet_K:.1f}", self._colors["info"]) - elif status.bl.cryojet_K < 250.0: - self.cryo_label.set_value(f"{status.bl.cryojet_K:.1f}", self._colors["warn"]) - else: - self.cryo_label.set_value(f"{status.bl.cryojet_K:.1f}", self._colors["alert"]) - - if status.bl.shutter_open: - self.shutter_label.setText( - f"""Fast Shutter: Open ☢️ """ - ) - else: - self.shutter_label.setText( - f"""Fast Shutter: Closed 🚪 """ - ) - - if status.bl.exp_shutter_open: - self.exp_shutter_label.setText( - f"""ExpHutch Shutter: Open """ - ) - else: - self.exp_shutter_label.setText( - f"""ExpHutch Shutter: Closed 🚪 """ - ) - - if status.session.current_pgroup is not None: - self.pgroup_label.setText(f"""p-group: {status.session.current_pgroup} """) - else: - self.pgroup_label.setText("Inactive p-group ") - - self.state_label.setText(f"""State: {status.state.display_name()} """) - - tell_text = "—" - tell_color = self._colors["tell"] - if status.tell_state is not None: - tell_text = status.tell_state.activity.display_name() - - if status.tell_state.activity.value == "error": - tell_color = self._colors["alert"] - elif status.tell_state.activity.value in { - "mounting", - "unmounting", - "drying", - "cooling", - }: - tell_color = self._colors["warn"] - else: - tell_color = self._colors["ok"] - - self.tell_state_label.setText(f"Tell: {tell_text} ") - self.tell_state_label.setStyleSheet(f"color: {tell_color};") - - if status.busy: - busy_flag = f""" Busy 🔒 """ - else: - busy_flag = f""" Idle 🔓 """ - - html_content = f"""Beamline: {busy_flag} """ - - self.busy_label.setText(html_content) - - session_flag = "" - if status.session.session == SessionsStateEnum.Vacant: - session_flag = ( - f""" Vacant 🔓 """ - ) - elif status.session.session == SessionsStateEnum.OwnedByYou: - session_flag = f""" Owned ⬤ """ - elif status.session.session == SessionsStateEnum.OwnedByElse: - session_flag = ( - f""" Other 🔒 """ - ) - elif status.session.session == SessionsStateEnum.PendingYouToElse: - session_flag = ( - f""" Waiting... ⏳ """ - ) - elif status.session.session == SessionsStateEnum.PendingElseToYou: - session_flag = ( - f""" Request! ⚡ """ - ) - - html_content_session = f"""Session: {session_flag}""" - self.session_label.setText(html_content_session) - - self._ratchet_widths( - self.flux, - self.transmission, - self.ring_current, - self.wvl, - self.cryo_label, - self.shutter_label, - self.exp_shutter_label, - self.tell_state_label, - self.busy_label, - self.state_label, - self.pgroup_label, - self.session_label, - ) - except Exception: - logger.exception("Error updating DAQ status in status bar") - - @Slot(BatonStatus) - def update_baton_status(self, status: BatonStatus): - """Update baton status from SSE stream.""" - prev_incoming = bool(self._baton_status and self._baton_status.incoming_request) - - # Detect if we just became the holder (e.g., from a queue resolving) - was_holder = bool(self._baton_status and self._baton_status.you_are_holder) - now_holder = bool(status and status.you_are_holder) - - self._baton_status = status - self._has_pending_request = status.you_have_pending_request if status else False - self._update_session_display() - - # Reset one-shot flag when we lose the baton - if not now_holder: - self._pgroup_dialog_shown_for_current_baton = False - - # If we just acquired the baton, prompt for p-group (and only once) - if now_holder and not was_holder: - self._show_pgroup_after_baton_grant() - - # Handle incoming request dialogs (when someone requests from us) - incoming = bool(status and status.incoming_request) - if incoming and not prev_incoming: - logger.info(f"Incoming baton request detected: {status.pending_request}") - self._emit_incoming_baton_request(status) - elif not incoming and self._baton_request_dialog is not None: - logger.info("Baton request no longer incoming, closing local dialog reference") - try: - self._baton_request_dialog.close() - except Exception: - logger.exception("Error closing baton request dialog") - self._baton_request_dialog = None - - def _show_pgroup_after_baton_grant(self) -> None: - """ - Single-source for p-group selection after baton is granted. - Uses a one-shot flag to prevent duplicates from multiple status updates. - """ - if self._pgroup_dialog_shown_for_current_baton: - logger.debug("P-group dialog already shown for this baton grant, skipping") - return - - self._pgroup_dialog_shown_for_current_baton = True - self.show_change_dialog() - - def _emit_incoming_baton_request(self, status: BatonStatus) -> None: - requester = "Another user" - timeout = 30 - if status.pending_request is not None: - requester = status.pending_request.requester_username or requester - timeout = int(status.pending_request.timeout_seconds or timeout) - - self.baton_request_received.emit({"requester": requester, "timeout": timeout}) - - @Slot() - def _on_baton_dialog_accepted(self): - self.baton_request_accepted.emit() - self._baton_request_dialog = None - - @Slot() - def _on_baton_dialog_refused(self): - self.baton_request_refused.emit() - self._baton_request_dialog = None - - def _update_session_display(self): - """Update session label based on current status.""" - if self._status is None: - return - - session_state = self._status.session.session - - # Base text - if session_state == SessionsStateEnum.OwnedByYou: - text = "Session: You" - elif session_state == SessionsStateEnum.PendingElseToYou: - text = "Session: You (⚡ Request)" - elif session_state == SessionsStateEnum.OwnedByElse: - holder_name = "" - if self._baton_status and self._baton_status.holder: - holder_name = self._baton_status.holder.username - text = f"Session: {holder_name or 'Other'}" - elif session_state == SessionsStateEnum.PendingYouToElse: - holder_name = "" - if self._baton_status and self._baton_status.holder: - holder_name = self._baton_status.holder.username - text = f"Session: {holder_name or 'Other'} (⏳ Waiting)" - else: - text = "Session: Vacant" - - self.session_label.setText(text) - self._ratchet_widths(self.session_label) - - def show_session_menu(self, global_pos: QPoint | None = None): - menu = QMenu(self) - is_busy = self._status and self._status.busy - session_state = self._status.session.session if self._status else SessionsStateEnum.Vacant - # Determine if we are the holder or waiting for baton - is_yours = session_state in ( - SessionsStateEnum.OwnedByYou, - SessionsStateEnum.PendingElseToYou, - ) - # Check baton status for fallback if status.session is not yet updated - if not is_yours and self._baton_status: - is_yours = self._baton_status.you_are_holder or self._baton_status.incoming_request - - is_vacant = session_state == SessionsStateEnum.Vacant - is_other = session_state in ( - SessionsStateEnum.OwnedByElse, - SessionsStateEnum.PendingYouToElse, - ) - has_pending = session_state == SessionsStateEnum.PendingYouToElse - - # Determine holder info from baton status - holder_is_staff = ( - self._baton_status and self._baton_status.holder and self._baton_status.holder.is_staff - ) - - # --- GRAB / REQUEST --- - if is_vacant: - # Vacant - simple grab - action_grab = menu.addAction("Grab") - action_grab.setEnabled(True) - action_grab.triggered.connect(self._on_grab_clicked) - elif is_other: - # Someone else has it - if has_pending: - # Already have a pending request - show cancel option - action_cancel = menu.addAction("Cancel Request") - action_cancel.triggered.connect(self._on_cancel_request_clicked) - elif self._is_staff: - # Staff can always grab (override) - action_grab = menu.addAction("Grab (Override)") - action_grab.setEnabled(not is_busy) # Still respect busy for safety - action_grab.triggered.connect(self._on_grab_clicked) - elif holder_is_staff: - # Non-staff cannot request from staff - allowed = self._baton_status and getattr( - self._baton_status, "allow_non_staff_request", False - ) - action_grab = menu.addAction("Request from Staff") - action_grab.setEnabled(allowed) - if allowed: - action_grab.triggered.connect(self._on_grab_clicked) - else: - # Same level - request with timeout - action_request = menu.addAction("Request Control") - action_request.setEnabled(True) - action_request.triggered.connect(self._on_grab_clicked) - elif is_yours: - # You have it - show release option - action_release = menu.addAction("Release") - action_release.setEnabled(True) # Always allow release - action_release.triggered.connect(self._on_release_clicked) - - if session_state == SessionsStateEnum.PendingElseToYou: - action_accept = menu.addAction("Accept Request") - action_accept.triggered.connect(self._on_baton_dialog_accepted) - - menu.addSeparator() - - # --- END SESSION (cleanup) --- - action_end = menu.addAction("End Session") - action_end.setEnabled(bool(is_yours or self._is_staff)) - action_end.triggered.connect(self.end_session_clicked) - - # --- STAFF: FORCE GRAB (emergency) --- - if self._is_staff and is_other: - menu.addSeparator() - action_force = menu.addAction("⚠️ Force Take Over") - action_force.triggered.connect(self._on_force_session_clicked) - - if global_pos is not None: - # Invoked from the camera's session badge — open at the click. - menu.move(global_pos) - else: - label_geometry = self.session_label.geometry() - menu_width = max(label_geometry.width(), menu.sizeHint().width()) - menu.move( - self.mapToGlobal(label_geometry.topLeft()) - QPoint(0, menu.sizeHint().height()) - ) - menu.setFixedWidth(menu_width) - menu.exec() - - def show_pgroup_menu(self): - in_curr = self._status - - logger.info(f"in_curr is {in_curr}") - - if not in_curr: - print(f"is status None?: {self._status}") - - allow_pgroup_menu = self._is_staff or in_curr - - owned_by_you = self._status and self._status.session.session == SessionsStateEnum.OwnedByYou - - if allow_pgroup_menu: - logger.info("showing pgroup menu") - menu = QMenu(self) - - action_1 = menu.addAction("Change") - action_1.setEnabled(bool(owned_by_you)) - action_1.triggered.connect(self.show_change_dialog) - - label_geometry = self.pgroup_label.geometry() - menu.move( - self.mapToGlobal(label_geometry.topLeft()) - QPoint(0, menu.sizeHint().height()) - ) - menu.setFixedWidth(label_geometry.width()) - - menu.exec() - - def show_shutter_menu(self): - menu = QMenu(self) - action_1 = menu.addAction("Close shutter") - action_1.triggered.connect(self.close_shutter_clicked) - - action_2 = menu.addAction("Open shutter") - action_2.triggered.connect(self.open_shutter_clicked) - - label_geometry = self.shutter_label.geometry() - menu.move(self.mapToGlobal(label_geometry.topLeft()) - QPoint(0, menu.sizeHint().height())) - menu.setFixedWidth(label_geometry.width()) - - menu.exec() - - def show_state_menu(self): - if self._status is None: - return - - logger.info(self._status.state) - menu = QMenu(self) - - if self._status.busy or self._status.state in [BeamlineStateEnum.Moving]: - return - - action_0 = menu.addAction("Available transitions") - font = QFont() - font.setBold(True) - action_0.setFont(font) - # Optionally make it non-clickable since it's a header - action_0.setEnabled(False) - menu.addSeparator() - - if self._status.state in [ - BeamlineStateEnum.RobotSampleExchange, - BeamlineStateEnum.SampleExchange, - BeamlineStateEnum.DewarTransfer, - BeamlineStateEnum.BeamLocation, - BeamlineStateEnum.DataCollection, - BeamlineStateEnum.XrayFluorescence, - BeamlineStateEnum.XtalSnapshot, - ]: - action_1 = menu.addAction("Sample alignment") - action_1.triggered.connect(self.sa) - elif self._status.state in [BeamlineStateEnum.SampleAlignment]: - action_2 = menu.addAction("Manual sample exchange") - action_2.triggered.connect(self.se) - action_3 = menu.addAction("Dewar transfer") - action_3.triggered.connect(self.dl) - action_4 = menu.addAction("Beam location") - if self._is_staff: - action_4.triggered.connect(self.beam_location) - else: - # Same gate as the state strip: greyed, not hidden, so - # non-staff learn the state exists but needs admin mode. - action_4.setText("Beam location (admin mode only)") - action_4.setEnabled(False) - elif self._status.state in [BeamlineStateEnum.Maintenance]: - action_2 = menu.addAction("Manual sample exchange") - action_2.triggered.connect(self.se) - - label_geometry = self.state_label.geometry() - menu.move(self.mapToGlobal(label_geometry.topLeft()) - QPoint(0, menu.sizeHint().height())) - menu.setFixedWidth(label_geometry.width()) - - menu.exec() - - def _latest_pgroup(self, pgroups: list[str]) -> str | None: - if not pgroups: - return None - - def _key(pg: str): - s = str(pg).strip() - if s.startswith("p") and s[1:].isdigit(): - return (1, int(s[1:]), s) - return (0, -1, s) - - return max(pgroups, key=_key) - - def _after_baton_granted_select_pgroup(self) -> None: - """ - Deprecated: kept for backward compatibility. - Use _show_pgroup_after_baton_grant() instead. - """ - self._show_pgroup_after_baton_grant() - - def show_change_dialog(self): - logger.debug(self._decoded_token.pgroups) - curr = self._status.session.current_pgroup - pgroups = [ - str(p) for p in (self._allowed_pgroups or []) if p is not None and str(p).strip() - ] - if self._is_staff: - - def _on_loaded(lst: list): - try: - merged = { - str(p).strip() for p in (lst or []) if p is not None and str(p).strip() - } - if not merged: - merged = set(pgroups) - self._generate_pgroup_dialogue(curr=curr, pgroups=sorted(merged)) - finally: - try: - self.staff_pgroups_loaded.disconnect(_on_loaded) - except Exception as e: - logger.debug(f"Error disconnecting: {e}", exc_info=True) - - self.staff_pgroups_loaded.connect(_on_loaded) - self._list_staff_pgroups() - return - - self._generate_pgroup_dialogue(curr=curr, pgroups=pgroups) - - def _on_grab_clicked(self): - """Handle grab/request click - baton first, p-group after grant.""" - self.request_baton.emit() - - def _on_release_clicked(self): - """Handle release click.""" - self.release_baton.emit() - - def _on_cancel_request_clicked(self): - """Handle cancel request click.""" - self.cancel_baton_request.emit() - - def _on_force_session_clicked(self): - """Staff emergency force take over (bypasses baton protocol).""" - self.force_session.emit() - - def grab_session_clicked(self): - """Legacy method - now routes to baton request.""" - self.request_baton.emit() - - def end_session_clicked(self): - self.end_session.emit() - - def sa(self): - self.sample_alignment.emit() - - def se(self): - self.sample_exchange.emit() - - def dl(self): - self.dewar_exchange.emit() - - def close_shutter_clicked(self): - self.close_shutter.emit() - - def open_shutter_clicked(self): - self.open_shutter.emit() - - def _list_staff_pgroups(self): - self.get_all_pgroups.emit() - - def _generate_pgroup_dialogue(self, curr: str | None = None, pgroups: list | None = None): - # logger.info(pgroups) # too much information for normal operation - dialog = PGroupDialog(curr_pgroup=curr, pgroups=pgroups, parent=self.window()) - - if dialog.exec() == QDialog.DialogCode.Accepted: - entered_text = dialog.get_input() - if pgroups and entered_text not in pgroups: - logger.warning(f"Attempted to set invalid pgroup: {entered_text}") - QMessageBox.warning( - self, - "Invalid P-Group", - f"P-group '{entered_text}' is not in your allowed list.\n" - f"Please select from: {', '.join(pgroups)}", - ) - self._generate_pgroup_dialogue(curr=curr, pgroups=pgroups) - return - self.set_pgroup.emit(entered_text) diff --git a/src/aare/gui/widgets/status_label.py b/src/aare/gui/widgets/status_label.py deleted file mode 100644 index 613e2fa8..00000000 --- a/src/aare/gui/widgets/status_label.py +++ /dev/null @@ -1,15 +0,0 @@ -from PySide6.QtCore import Qt, Slot -from PySide6.QtWidgets import QLabel - - -class StatusLabel(QLabel): - def __init__(self, val: float, decimals: int = 0, parent=None): - super().__init__(parent) - - self.format_string = f"{{:.{decimals}f}}" - self.setText(self.format_string.format(val)) - self.setAlignment(Qt.AlignmentFlag.AlignRight) - - @Slot() - def new_value(self, val: float): - self.setText(self.format_string.format(val)) diff --git a/src/aare/gui/widgets/text_list_dialog.py b/src/aare/gui/widgets/text_list_dialog.py deleted file mode 100644 index 0d548234..00000000 --- a/src/aare/gui/widgets/text_list_dialog.py +++ /dev/null @@ -1,45 +0,0 @@ -from __future__ import annotations - -from collections.abc import Iterable - -from PySide6.QtGui import QGuiApplication -from PySide6.QtWidgets import QDialog, QDialogButtonBox, QPushButton, QTextEdit, QVBoxLayout - - -class TextListDialog(QDialog): - def __init__(self, *, title: str, parent=None): - super().__init__(parent) - self.setWindowTitle(title) - self.setMinimumSize(680, 460) - - layout = QVBoxLayout(self) - layout.setContentsMargins(12, 12, 12, 12) - layout.setSpacing(8) - - self._text = QTextEdit(self) - self._text.setReadOnly(True) - layout.addWidget(self._text, 1) - - buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close, parent=self) - self._copy_button = QPushButton("Copy to clipboard", self) - self._copy_button.clicked.connect(self._copy_to_clipboard) - buttons.addButton(self._copy_button, QDialogButtonBox.ButtonRole.ActionRole) - - buttons.rejected.connect(self.reject) - buttons.accepted.connect(self.accept) - layout.addWidget(buttons) - - def set_items(self, items: Iterable[str], *, empty_message: str = "No items found.") -> None: - values = [str(item) for item in items if str(item).strip()] - if not values: - self._text.setPlainText(empty_message) - return - self._text.setPlainText("\n".join(values)) - - def set_text(self, text: str) -> None: - self._text.setPlainText(str(text or "")) - - def _copy_to_clipboard(self) -> None: - clipboard = QGuiApplication.clipboard() - if clipboard is not None: - clipboard.setText(self._text.toPlainText()) diff --git a/src/aare/gui/widgets/title_label.py b/src/aare/gui/widgets/title_label.py deleted file mode 100644 index 0abc91fa..00000000 --- a/src/aare/gui/widgets/title_label.py +++ /dev/null @@ -1,183 +0,0 @@ -from PySide6.QtCore import QSettings, Qt, QTimer -from PySide6.QtGui import QPainter, QPalette -from PySide6.QtWidgets import QHBoxLayout, QLabel, QLayout, QPushButton, QStyle, QStyleOption - -from aare.gui.styles import BANNER_TEXT, BANNER_TEXT_SHADOW, FONT_VALUE, qcolor - -# Universal vertical rhythm between stacked panels: each panel contributes -# PANEL_VMARGIN top and bottom, the column adds PANEL_VSPACING between them, -# so every banner-to-banner gap is 4 + 3 + 4 = 11px in every column. -PANEL_VSPACING = 3 -PANEL_VMARGIN = 4 - - -def tighten_column(layout: QLayout) -> None: - """Apply the universal panel gap to a column layout and its child panels. - - Qt's defaults (9px margins + 6px spacing) and ad-hoc per-panel margins - made the gaps uneven between the left and right columns. - """ - layout.setSpacing(PANEL_VSPACING) - for i in range(layout.count()): - item = layout.itemAt(i) - widget = item.widget() if item is not None else None - child_layout = widget.layout() if widget is not None else None - if child_layout is not None: - m = child_layout.contentsMargins() - child_layout.setContentsMargins(m.left(), PANEL_VMARGIN, m.right(), PANEL_VMARGIN) - - -def section_title(text: str, parent=None) -> QLabel: - """Small in-panel section heading — for controls grouped under one - shared TitleLabel banner (e.g. the Beam Config. panel). Look lives in - the per-theme QLabel#sectionTitle rules in styles.py.""" - label = QLabel(text, parent) - label.setObjectName("sectionTitle") - label.setAlignment(Qt.AlignmentFlag.AlignCenter) - return label - - -class TitleLabel(QLabel): - def __init__( - self, text: str, parent=None, collapsible: bool = False, default_collapsed: bool = True - ): - super().__init__(parent) - # Plain text + QSS font instead of

: rich-text heading margins - # would clip vertically in the halved banner height. - self.setText(text) - # No widget stylesheet: the banner look lives in the per-theme - # TitleLabel rules in styles.py — a stylesheet set here would win - # over the theme and pin the light banner into the dark theme. - self.setAlignment(Qt.AlignmentFlag.AlignCenter) - - # Half the original 50px: the full-height banner wasted vertical space. - self.setFixedHeight(25) - - self._collapsible = collapsible - if not collapsible: - return - - self._collapsed = False - # ponytail: settings key is the title text — unique across panels; - # renaming a title just resets that panel to expanded once. - self._settings_key = f"panel_collapsed/{text}" - - self.toggle_button = QPushButton("−", self) - # Bare glyph, no pill: the shared beamlineStateToggleButton QSS paints - # a translucent white background, which is unwanted on these banners. - # FONT_VALUE (18px), not FONT_BODY: a bare +/- glyph reads smaller than - # the 16px banner title beside it; the big-glyph size evens them out. - self.toggle_button.setStyleSheet( - f"QPushButton {{ background: transparent; border: none;" - f" color: {BANNER_TEXT}; font-size: {FONT_VALUE}; font-weight: 700; }}" - ) - self.toggle_button.setToolTip("Minimise panel") - self.toggle_button.setFixedSize(21, 21) - self.toggle_button.setCursor(Qt.CursorShape.PointingHandCursor) - self.toggle_button.clicked.connect(self.toggle_collapsed) - - button_layout = QHBoxLayout(self) - button_layout.setContentsMargins(0, 0, 8, 0) - button_layout.addStretch() - button_layout.addWidget(self.toggle_button) - - self.setCursor(Qt.CursorShape.PointingHandCursor) - - settings = QSettings("PSI", "AareGUI") - # Per-panel default (collapsed unless the caller opts out); once the - # user toggles a banner, their choice is persisted per title and wins. - if settings.value(self._settings_key, default_collapsed, type=bool): - self._collapsed = True - # Deferred: the panel adds its other widgets after constructing - # the TitleLabel, so siblings don't exist yet. `self` as the - # receiver context, or the pending timer outlives a deleted - # banner and fires into the dead C++ object — the source of the - # long-standing "QPushButton returned NULL" SystemError flake - # poisoning whatever test runs next. - QTimer.singleShot(0, self, self._apply_collapsed) - - def paintEvent(self, event): - # QSS has no text-shadow, so paint by hand: the QSS background box - # first, then the title twice — an offset dark pass under the normal - # one — for the subtle emboss the OS titlebar text has. - painter = QPainter(self) - opt = QStyleOption() - opt.initFrom(self) - self.style().drawPrimitive(QStyle.PrimitiveElement.PE_Widget, opt, painter, self) - - flags = int(self.alignment()) - # Reserve the toggle-button zone (21px + 8px margin) on BOTH sides in - # the text rect only — widget margins would move the button itself. - reserve = 29 if self._collapsible else 0 - rect = self.rect().adjusted(reserve, 0, -reserve, 0) - painter.setFont(self.font()) - # Elide instead of overflowing when the panel column is narrow. - text = painter.fontMetrics().elidedText( - self.text(), Qt.TextElideMode.ElideRight, rect.width() - ) - painter.setPen(qcolor(BANNER_TEXT_SHADOW, 110)) - painter.drawText(rect.translated(0, 1), flags, text) - # QSS-resolved 'color' (per-theme TitleLabel rule), not a constant — - # light paints banner white, dark paints dusk gold. - painter.setPen(self.palette().color(QPalette.ColorRole.WindowText)) - painter.drawText(rect, flags, text) - - def mousePressEvent(self, event): - if self._collapsible: - self.toggle_collapsed() - super().mousePressEvent(event) - - def expand(self) -> None: - if self._collapsible and self._collapsed: - self.toggle_collapsed() - - def is_collapsed(self) -> bool: - return bool(self._collapsible and self._collapsed) - - def set_collapsed(self, collapsed: bool, persist: bool = True) -> None: - # persist=False: transient programmatic fold (e.g. the session-vacant - # gate) that must not overwrite the user's saved per-panel choice. - if not self._collapsible or collapsed == self._collapsed: - return - self._collapsed = collapsed - self._apply_collapsed() - if persist: - QSettings("PSI", "AareGUI").setValue(self._settings_key, self._collapsed) - - def toggle_collapsed(self) -> None: - self._collapsed = not self._collapsed - self._apply_collapsed() - QSettings("PSI", "AareGUI").setValue(self._settings_key, self._collapsed) - if not self._collapsed: - # Expanding a group banner (Beamline / Experiment) opens every - # nested panel banner too — a group opening onto a wall of still- - # collapsed banners reads as broken. No-op for leaf panels, which - # have no nested TitleLabels. - parent = self.parentWidget() - if parent is not None: - for child in parent.findChildren(TitleLabel): - if child is not self: - child.expand() - - def _apply_collapsed(self) -> None: - parent = self.parentWidget() - parent_layout = parent.layout() if parent is not None else None - if parent_layout is None: - return - self._set_visible(parent_layout, not self._collapsed) - self.toggle_button.setText("+" if self._collapsed else "−") - self.toggle_button.setToolTip("Restore panel" if self._collapsed else "Minimise panel") - - def _set_visible(self, layout: QLayout, visible: bool) -> None: - # Recursive: panels like SamcamPanel nest sub-layouts via addLayout. - for i in range(layout.count()): - item = layout.itemAt(i) - if item is None: - continue - widget = item.widget() - child_layout = item.layout() - if widget is not None: - if widget is not self: - widget.setVisible(visible) - elif child_layout is not None: - self._set_visible(child_layout, visible) diff --git a/src/aare/gui/widgets/value_label.py b/src/aare/gui/widgets/value_label.py deleted file mode 100644 index f286d7dc..00000000 --- a/src/aare/gui/widgets/value_label.py +++ /dev/null @@ -1,21 +0,0 @@ -from aare.gui.widgets.clickable_label import ClickableLabel - - -class ValueLabel(ClickableLabel): - # clicked signal + left-click mousePressEvent inherited from - # ClickableLabel — this class only adds the "descr: value unit" text. - # Passive readout: no hand cursor / hover underline. - _hover_affordance = False - - def __init__(self, text: str, unit: str = "", parent=None): - super().__init__(parent) - self._descr = text - self._unit = unit - - def set_value(self, s: str, color: str | None = None): - if color is not None: - self.setText( - f"""{self._descr}: {s} {self._unit} """ - ) - else: - self.setText(f"{self._descr}: {s} {self._unit}") diff --git a/src/aare/gui/widgets/video_image.py b/src/aare/gui/widgets/video_image.py deleted file mode 100644 index a03cee45..00000000 --- a/src/aare/gui/widgets/video_image.py +++ /dev/null @@ -1,123 +0,0 @@ -from PySide6.QtCore import QRectF, Qt, Slot -from PySide6.QtGui import QImage, QKeySequence, QPainter, QPixmap, QShortcut -from PySide6.QtWidgets import QGraphicsPixmapItem, QGraphicsScene, QGraphicsView - -from aare.gui.widgets.busy_overlay import BusyOverlayStyle, draw_busy_status_text - - -class VideoGraphicsView(QGraphicsView): - def __init__(self): - super().__init__() - - # Create scene - self.scene = QGraphicsScene() - self.setScene(self.scene) - - # Create pixmap item for video frames - self.pixmap_item = QGraphicsPixmapItem() - self.scene.addItem(self.pixmap_item) - - # Configure view - self.setRenderHint(self.renderHints() | QPainter.RenderHint.Antialiasing) - self.setDragMode(QGraphicsView.DragMode.RubberBandDrag) - self.setResizeAnchor(QGraphicsView.ViewportAnchor.AnchorViewCenter) - self.setTransformationAnchor(QGraphicsView.ViewportAnchor.AnchorUnderMouse) - - # Enable zooming and panning - self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded) - self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded) - - # Initial settings - self.zoom_factor = 1.0 - self.min_zoom = 0.1 - self.max_zoom = 5.0 - - self._busy_overlay_style: BusyOverlayStyle | None = None - - # QShortcut instead of a keyPressEvent override: one fewer Qt→Python - # callback on the render path, same focus behavior (WidgetShortcut = - # active only while the view has focus). - for key, slot in ( - (Qt.Key.Key_F, self.fit_to_view), - (Qt.Key.Key_R, self.reset_zoom), - (Qt.Key.Key_Plus, self.zoom_in), - (Qt.Key.Key_Equal, self.zoom_in), - (Qt.Key.Key_Minus, self.zoom_out), - ): - shortcut = QShortcut(QKeySequence(key), self) - shortcut.setContext(Qt.ShortcutContext.WidgetShortcut) - shortcut.activated.connect(slot) - - @Slot(QImage) - def update_frame(self, qt_image: QImage): - """Update the video frame""" - pixmap = QPixmap.fromImage(qt_image) - self.pixmap_item.setPixmap(pixmap) - - # Fit to view on first frame - if self.zoom_factor == 1.0: - self.fit_to_view() - - self.viewport().update() - - def set_busy_overlay_style(self, style: BusyOverlayStyle | None) -> None: - if self._busy_overlay_style == style: - return - self._busy_overlay_style = style - self.viewport().update() - - def fit_to_view(self): - """Fit the video to the view""" - if self.pixmap_item.pixmap().isNull(): - return - - self.fitInView(self.pixmap_item, Qt.AspectRatioMode.KeepAspectRatio) - self.zoom_factor = 1.0 - - def reset_zoom(self): - """Reset zoom to 100%""" - self.resetTransform() - self.zoom_factor = 1.0 - - def zoom_in(self): - """Zoom in""" - if self.zoom_factor < self.max_zoom: - factor = 1.25 - self.scale(factor, factor) - self.zoom_factor *= factor - - def zoom_out(self): - """Zoom out""" - if self.zoom_factor > self.min_zoom: - factor = 0.8 - self.scale(factor, factor) - self.zoom_factor *= factor - - def wheelEvent(self, event): - """Handle mouse wheel for zooming""" - if event.modifiers() & Qt.KeyboardModifier.ControlModifier: - # Zoom with Ctrl + wheel - if event.angleDelta().y() > 0: - self.zoom_in() - else: - self.zoom_out() - event.accept() - else: - # Normal scrolling - super().wheelEvent(event) - - def drawForeground(self, painter: QPainter, rect: QRectF): - super().drawForeground(painter, rect) - - if self._busy_overlay_style is None: - return - - painter.save() - painter.resetTransform() - painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) - # Plain shadowed text like the sample camera's warnings, not the - # badge pill: these views are passive and the pill read as a button. - draw_busy_status_text( - painter, self.viewport().width(), self.viewport().height(), self._busy_overlay_style - ) - painter.restore() diff --git a/src/aare/gui/widgets/wheel_value_guard.py b/src/aare/gui/widgets/wheel_value_guard.py deleted file mode 100644 index f06eb504..00000000 --- a/src/aare/gui/widgets/wheel_value_guard.py +++ /dev/null @@ -1,87 +0,0 @@ -from PySide6.QtCore import QObject, Qt -from PySide6.QtGui import QWheelEvent -from PySide6.QtWidgets import ( - QAbstractScrollArea, - QAbstractSpinBox, - QApplication, - QComboBox, - QDial, - QSlider, - QTabBar, -) - - -class WheelValueGuard(QObject): - """App-level wheel safety for value widgets. - - The wheel only ADJUSTS a slider / spin box / dial / combo while the - RIGHT mouse button is held down — a deliberate two-hand gesture. A bare - wheel over any of them is re-aimed at the enclosing scroll area, so - scrolling a page can never nudge a value and therefore never moves a - motor. Install once with QApplication.installEventFilter. - """ - - # QTabBar: wheel switches tabs on Linux by default — same accidental-input - # hazard as a value nudge, so guard it too. - GUARDED = (QAbstractSpinBox, QSlider, QDial, QComboBox, QTabBar) - - def eventFilter(self, obj, event): - # isinstance, not event.type(): PySide 6.9 sometimes hands an app-level - # filter a QWidgetItem instead of a QEvent while layouts are torn down, - # and .type() then raises (pytest-qt CALL ERROR on a random test). - if isinstance(event, QWheelEvent) and isinstance(obj, self.GUARDED): - if event.buttons() & Qt.MouseButton.RightButton: - return False # right button held: deliberate value adjustment - area = obj.parentWidget() - while area is not None and not isinstance(area, QAbstractScrollArea): - area = area.parentWidget() - if area is not None: - relayed = QWheelEvent( - area.viewport().mapFromGlobal(event.globalPosition()), - event.globalPosition(), - event.pixelDelta(), - event.angleDelta(), - event.buttons(), - event.modifiers(), - event.phase(), - event.inverted(), - ) - QApplication.sendEvent(area.viewport(), relayed) - return True - # Not super().eventFilter(): QObject's does nothing but type-checks its - # arguments, so the stray QWidgetItem would raise there instead. - return False - - -if __name__ == "__main__": - # ponytail: smallest check that fails if the guard logic breaks - import os - - os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") - from PySide6.QtCore import QPoint, QPointF - - app = QApplication([]) - guard = WheelValueGuard() - app.installEventFilter(guard) - slider = QSlider(Qt.Orientation.Horizontal) - slider.setRange(0, 100) - slider.setValue(50) - slider.show() - - def wheel(buttons): - return QWheelEvent( - QPointF(5, 5), - QPointF(5, 5), - QPoint(0, 0), - QPoint(0, 120), - buttons, - Qt.KeyboardModifier.NoModifier, - Qt.ScrollPhase.NoScrollPhase, - False, - ) - - QApplication.sendEvent(slider, wheel(Qt.MouseButton.NoButton)) - assert slider.value() == 50, "bare wheel must not adjust the slider" - QApplication.sendEvent(slider, wheel(Qt.MouseButton.RightButton)) - assert slider.value() != 50, "right-button + wheel must adjust the slider" - print("gude") diff --git a/tests/integration/daq/test_daq_server.py b/tests/integration/daq/test_daq_server.py deleted file mode 100644 index 0fc50dca..00000000 --- a/tests/integration/daq/test_daq_server.py +++ /dev/null @@ -1,50 +0,0 @@ -import os - -import pytest -from fastapi.testclient import TestClient - -# We need to set the environment variable before importing the app -os.environ["JWT_AAREDAQ_KEY"] = "test_key_for_integration_testing" - -from aare.daq.server import app - - -@pytest.fixture -def client(): - # We use a TestClient to interact with the FastAPI app - # Note: Many endpoints require authentication and a running backend (daq, bl, etc.) - # For a simple integration test, we can check public endpoints. - return TestClient(app) - - -@pytest.mark.integration -def test_read_error_codes(client): - response = client.get("/meta/error-codes") - assert response.status_code == 200 - data = response.json() - assert "AuthErrorCode" in data - assert "AareErrorCode" in data - - -@pytest.mark.integration -def test_login_unauthorized(client): - # Testing login with invalid credentials. - # The current implementation raises KeyError if user not found, - # which FastAPI might convert to 500 or just propagate if using TestClient in some modes. - # However, let's just check for a non-200 status code. - response = client.post("/token", data={"username": "non_existent_user_123", "password": "bad"}) - assert response.status_code != 200 - - -@pytest.mark.integration -def test_status_unauthorized(client): - # Should fail because no Bearer token is provided - response = client.get("/status") - assert response.status_code == 401 - - -@pytest.mark.integration -def test_pgroup_unauthorized(client): - # Should fail because no Bearer token is provided - response = client.get("/access/pgroup") - assert response.status_code == 401 diff --git a/tests/integration/daq/test_database_connection.py b/tests/integration/daq/test_database_connection.py deleted file mode 100644 index 839b8b4d..00000000 --- a/tests/integration/daq/test_database_connection.py +++ /dev/null @@ -1,6 +0,0 @@ -import pytest - - -@pytest.mark.integration -def test_real_db_connection(): - pass diff --git a/tests/unit/daq/conftest.py b/tests/unit/daq/conftest.py deleted file mode 100644 index bcfe8aa7..00000000 --- a/tests/unit/daq/conftest.py +++ /dev/null @@ -1,15 +0,0 @@ -from unittest.mock import MagicMock - -import pytest - -from aare.daq.daq import AareDAQ - - -@pytest.fixture() -def mock_daq(): - daq = object.__new__(AareDAQ) - daq._set_state = MagicMock() - daq._devs = MagicMock() - daq._aare = MagicMock() - daq._handle_operation_error = MagicMock() - return daq diff --git a/tests/unit/daq/operations/face_detection/test_face_detection_logic.py b/tests/unit/daq/operations/face_detection/test_face_detection_logic.py deleted file mode 100644 index ca58fd43..00000000 --- a/tests/unit/daq/operations/face_detection/test_face_detection_logic.py +++ /dev/null @@ -1,128 +0,0 @@ -import numpy as np -import pytest - -from aare.daq.operations.face_detection.utils import ( - box_area_from_tuple, - box_height_from_tuple, - choose_best_fit, - chose_best_angle, - cos_model, - fit_cosine, - fit_metrics, - get_flat_face, - get_samples_out, - mad_filter, - prepare_samples, -) - - -def test_box_height_from_tuple(): - assert box_height_from_tuple((0, 0, 10, 20)) == 20 - assert box_height_from_tuple((0, 20, 10, 0)) == 20 - - -def test_box_area_from_tuple(): - assert box_area_from_tuple((0, 0, 10, 20)) == 200 - assert box_area_from_tuple((0, 20, 10, 0)) == 200 - - -def test_prepare_samples(): - boxes = {0: (0, 0, 10, 10), 90: (0, 0, 10, 20)} - samples = prepare_samples(boxes, area=False) - assert (0.0, 10.0) in samples - assert (90.0, 20.0) in samples - - samples_area = prepare_samples(boxes, area=True) - assert (0.0, 100.0) in samples_area - assert (90.0, 200.0) in samples_area - - -def test_cos_model(): - # A + B * cos(C * deg2rad(theta) - phi) - # theta=0, A=10, B=5, phi=0, C=1 -> 10 + 5 * cos(0) = 15 - assert pytest.approx(cos_model(0, 10, 5, 0, 1)) == 15.0 - # theta=180, A=10, B=5, phi=0, C=1 -> 10 + 5 * cos(pi) = 5 - assert pytest.approx(cos_model(180, 10, 5, 0, 1)) == 5.0 - - -def test_mad_filter(): - samples = [(0, 10), (10, 11), (20, 12), (30, 100), (40, 11)] - # med = 11, devs = [1, 0, 1, 89, 0], mad = median([0, 0, 1, 1, 89]) = 1 - # k*mad = 3.5. 100-11 = 89 > 3.5. Outlier. - filtered = mad_filter(samples) - assert (30, 100) not in filtered - assert len(filtered) == 4 - - assert mad_filter([]) == [] - - -def test_fit_metrics(): - y_true = np.array([10, 20, 30]) - y_pred = np.array([11, 19, 31]) - rmse, mae, r2 = fit_metrics(y_true, y_pred) - assert rmse == pytest.approx(1.0) - assert mae == pytest.approx(1.0) - # ss_tot = (10-20)^2 + (20-20)^2 + (30-20)^2 = 100 + 0 + 100 = 200 - # ss_res = 1^2 + (-1)^2 + 1^2 = 3 - # r2 = 1 - 3/200 = 0.985 - assert r2 == pytest.approx(0.985) - - -def test_fit_cosine_minimal_samples(): - samples = [(0, 10), (90, 20)] - result = fit_cosine(samples) - assert result["A"] == 15.0 - assert result["rmse"] is None - - -def test_fit_cosine_normal(): - # Generate perfect cosine data - degs = np.linspace(0, 360, 10) - ys = 10 + 5 * np.cos(np.deg2rad(degs) - 0.5) - samples = list(zip(degs, ys)) - result = fit_cosine(samples) - assert result["A"] == pytest.approx(10.0, abs=1e-2) - assert result["B"] == pytest.approx(5.0, abs=1e-2) - assert result["phi_rad"] == pytest.approx(0.5, abs=1e-2) - assert result["r2"] > 0.99 - - -def test_get_samples_out(): - boxes = {0: (0, 0, 10, 10), 90: (0, 0, 10, 20)} - out = get_samples_out(boxes) - assert len(out) == 2 - assert out[0]["angle_deg"] == 0.0 - assert out[0]["height"] == 10.0 - assert out[1]["angle_deg"] == 90.0 - assert out[1]["height"] == 20.0 - - -def test_choose_best_fit(): - fits = { - "Height": {"angle": 45, "params": {"rmse": 0.1, "mae": 0.1, "r2": 0.95}}, - "Area": {"angle": 50, "params": {"rmse": 0.05, "mae": 0.05, "r2": 0.98}}, - } - angle, _fit, name = choose_best_fit(fits) - assert name == "Area" - assert angle == 50.0 - - assert choose_best_fit({}) == (None, None, None) - - -def test_get_flat_face(): - boxes = {0: (0, 0, 10, 10), 90: (0, 0, 10, 20), 180: (0, 0, 10, 10), 270: (0, 0, 10, 5)} - angle, params = get_flat_face(boxes, 0, 360) - assert isinstance(angle, int) - assert "A" in params - - -def test_chose_best_angle(): - boxes = {0: (0, 0, 10, 10), 90: (0, 0, 10, 20)} - fit_results = {"Area": {"angle": 88}, "Height": {"angle": 92}} - # Candidates are 88 and 92. Measured are 0 and 90. - # 88 is closer to 90 than 92 is to 90? No, both are 2 deg away. - # min(abs(88-0), abs(88-90)) = 2 - # min(abs(92-0), abs(92-90)) = 2 - # It should pick one. - chosen = chose_best_angle(boxes, fit_results) - assert chosen in [88, 92] diff --git a/tests/unit/daq/operations/face_detection/test_face_detection_service.py b/tests/unit/daq/operations/face_detection/test_face_detection_service.py deleted file mode 100644 index 3c64fcc6..00000000 --- a/tests/unit/daq/operations/face_detection/test_face_detection_service.py +++ /dev/null @@ -1,234 +0,0 @@ -import types - -import pytest -from aarecommon.math.coordinate import Coordinate, SmargonCoordinate -from aarecommon.models.models import BoundingBoxModel, MLBoxModel, MLBoxType, ZoomModeEnum - -from aare.daq.operations.common.runtime import DAQRuntimeState -from aare.daq.operations.common.services import FaceDetectionProgressEmitter, OperationServices -from aare.daq.operations.face_detection.models import ( - FaceDetectionContext, - FaceDetectionDependencies, - FaceDetectionResult, - FaceDetectionSettings, -) -from aare.daq.operations.face_detection.service import FaceDetectionService - - -class DummyGeometry: - def __init__(self): - self.beam_location_pxl = Coordinate(x=100.0, y=100.0, z=0.0) - - def picture_to_smargon(self, coord: Coordinate) -> Coordinate: - return Coordinate(x=coord.x / 100.0, y=coord.y / 100.0, z=0.0) - - -def _box(cls: MLBoxType, x1: float, y1: float, x2: float, y2: float) -> MLBoxModel: - return MLBoxModel( - cls=cls, box=BoundingBoxModel(top_x=x1, top_y=y1, bottom_x=x2, bottom_y=y2), conf=0.95 - ) - - -@pytest.fixture -def context(): - progress_events = [] - - devs = types.SimpleNamespace( - lamp_light=0.0, - zoom=200.0, - aerotech_omega=0.0, - smargon_pos=None, - set_zoom=lambda zoom_value, wait=True: None, - smargon_wait=lambda timeout=60: None, - ) - - cfg = types.SimpleNamespace(zoom_mode=ZoomModeEnum.User) - - def emit_progress(payload): - progress_events.append(payload) - - runtime_state = DAQRuntimeState( - sample_provider=types.SimpleNamespace(sample=None), - sample_geometry_provider=types.SimpleNamespace(sample_geometry=DummyGeometry()), - status_provider=types.SimpleNamespace(status=None), - ) - - services = OperationServices( - screenshots=types.SimpleNamespace(save_to_db=lambda *args, **kwargs: None), - face_detection_progress=FaceDetectionProgressEmitter( - reporter=types.SimpleNamespace(emit_progress=emit_progress) - ), - ) - - ctx = FaceDetectionContext( - deps=FaceDetectionDependencies( - cfg=cfg, - devs=devs, - mlbox=types.SimpleNamespace( - predict=lambda **kwargs: types.SimpleNamespace( - box=None, target_point=None, focus=None - ) - ), - ), - runtime=runtime_state, - services=services, - settings=FaceDetectionSettings(), - ) - ctx._progress_events = progress_events - return ctx - - -def test_service_returns_empty_payload_when_no_boxes(monkeypatch, context, mock_logger): - service = FaceDetectionService(context=context, logger=mock_logger) - - monkeypatch.setattr( - context.deps.mlbox, - "predict", - lambda **kwargs: types.SimpleNamespace(box=None, target_point=None, focus=None), - ) - - result = service.run(steps=2, step_size=30) - - assert isinstance(result, FaceDetectionResult) - assert result.success is True - assert result.payload["running"] is False - assert result.payload["samples"] == [] - assert result.payload["height_fit"] == {} - assert result.payload["area_fit"] == {} - assert context.deps.cfg.zoom_mode == ZoomModeEnum.User - assert len(context._progress_events) >= 1 - assert context._progress_events[-1]["running"] is False - - -def test_service_prefers_face_boxes_when_ratio_is_high(monkeypatch, context, mock_logger): - service = FaceDetectionService(context=context, logger=mock_logger) - - predictions = iter( - [ - types.SimpleNamespace( - box=_box(MLBoxType.LOOP_FACE, 10, 20, 30, 40), target_point=None, focus=None - ), - types.SimpleNamespace( - box=_box(MLBoxType.LOOP_FACE, 12, 20, 32, 40), target_point=None, focus=None - ), - types.SimpleNamespace( - box=_box(MLBoxType.LOOP_ALL, 14, 20, 34, 40), target_point=None, focus=None - ), - types.SimpleNamespace( - box=_box(MLBoxType.LOOP_FACE, 16, 20, 36, 40), target_point=None, focus=None - ), - ] - ) - - monkeypatch.setattr(context.deps.mlbox, "predict", lambda **kwargs: next(predictions)) - - monkeypatch.setattr( - "aare.daq.operations.face_detection.service.fd.get_flat_face", - lambda boxes, start_angle, end_angle, use_area: ( - 45 if use_area else 50, - {"A": 1.0, "B": 2.0, "phi_rad": 0.1, "C": 3.0}, - ), - ) - monkeypatch.setattr( - "aare.daq.operations.face_detection.service.fd.choose_best_fit", - lambda fit_results: (47, {"A": 1.0}, "Area"), - ) - monkeypatch.setattr( - "aare.daq.operations.face_detection.service.fd.get_samples_out", - lambda boxes: [{"angle": angle, "box": box} for angle, box in sorted(boxes.items())], - ) - - result = service.run(steps=3, step_size=30, face_min_ratio=0.5) - - assert result.success is True - assert result.payload["running"] is False - assert result.payload["height_fit"]["best_angle_deg"] == 50 - assert result.payload["area_fit"]["best_angle_deg"] == 45 - assert context.deps.devs.aerotech_omega == 47 - assert [sample["angle"] for sample in result.payload["samples"]] == [0, 30, 90] - assert context._progress_events[-1]["running"] is False - - -def test_service_falls_back_to_loop_all_when_face_ratio_is_low(monkeypatch, context, mock_logger): - service = FaceDetectionService(context=context, logger=mock_logger) - - predictions = iter( - [ - types.SimpleNamespace( - box=_box(MLBoxType.LOOP_FACE, 10, 20, 30, 40), target_point=None, focus=None - ), - types.SimpleNamespace( - box=_box(MLBoxType.LOOP_ALL, 11, 20, 31, 40), target_point=None, focus=None - ), - types.SimpleNamespace( - box=_box(MLBoxType.LOOP_ALL, 12, 20, 32, 40), target_point=None, focus=None - ), - types.SimpleNamespace( - box=_box(MLBoxType.LOOP_ALL, 13, 20, 33, 40), target_point=None, focus=None - ), - types.SimpleNamespace( - box=_box(MLBoxType.LOOP_ALL, 14, 20, 34, 40), target_point=None, focus=None - ), - ] - ) - - monkeypatch.setattr(context.deps.mlbox, "predict", lambda **kwargs: next(predictions)) - - captured = {} - - def fake_get_flat_face(boxes, start_angle, end_angle, use_area): - captured["boxes_used"] = dict(boxes) - return 60, {"A": 1.0, "B": 2.0, "phi_rad": 0.2, "C": 4.0} - - monkeypatch.setattr( - "aare.daq.operations.face_detection.service.fd.get_flat_face", fake_get_flat_face - ) - monkeypatch.setattr( - "aare.daq.operations.face_detection.service.fd.choose_best_fit", - lambda fit_results: (60, {"A": 1.0}, "Height"), - ) - monkeypatch.setattr( - "aare.daq.operations.face_detection.service.fd.get_samples_out", - lambda boxes: [{"angle": angle} for angle in sorted(boxes.keys())], - ) - - result = service.run(steps=4, step_size=30, face_min_ratio=0.5) - - assert result.success is True - assert len(captured["boxes_used"]) == 4 - assert sorted(captured["boxes_used"].keys()) == [30, 60, 90, 120] - assert context.deps.devs.aerotech_omega == 60 - assert context._progress_events[-1]["running"] is False - - -def test_service_applies_centre_correction_when_target_is_far_from_beam( - monkeypatch, context, mock_logger -): - service = FaceDetectionService(context=context, logger=mock_logger) - - model = _box(MLBoxType.LOOP_FACE, 40, 160, 80, 200) - - service._centre_correction(model, tolerance=0.2) - - assert isinstance(context.deps.devs.smargon_pos, SmargonCoordinate) - assert context.deps.devs.smargon_pos.sh_mm.x == pytest.approx(1.0) - assert context.deps.devs.smargon_pos.sh_mm.y == pytest.approx(1.8) - - -def test_service_returns_failed_result_when_prediction_raises(monkeypatch, context, mock_logger): - service = FaceDetectionService(context=context, logger=mock_logger) - - monkeypatch.setattr( - context.deps.mlbox, - "predict", - lambda **kwargs: (_ for _ in ()).throw(RuntimeError("prediction failed")), - ) - - result = service.run(steps=1, step_size=30) - - assert result.success is False - assert isinstance(result.error, RuntimeError) - assert result.comment == "Face detection sequence failed" - assert result.payload["running"] is False - assert context.deps.cfg.zoom_mode == ZoomModeEnum.User - assert context._progress_events[-1]["running"] is False diff --git a/tests/unit/daq/operations/loop_centering/test_loop_centering_analyzer.py b/tests/unit/daq/operations/loop_centering/test_loop_centering_analyzer.py deleted file mode 100644 index 715472c3..00000000 --- a/tests/unit/daq/operations/loop_centering/test_loop_centering_analyzer.py +++ /dev/null @@ -1,139 +0,0 @@ -import types - -import pytest -from aarecommon.math.coordinate import Coordinate, SmargonCoordinate -from aarecommon.models.models import MLBoxType, MLOutputModel - -from aare.daq.mlbox import MLBoxPredictionsResult -from aare.daq.operations.common.runtime import DAQRuntimeState -from aare.daq.operations.common.services import OperationServices, PredictionProvider, TraceWriter -from aare.daq.operations.loop_centering.analyzer import LoopCenteringAnalyzer -from aare.daq.operations.loop_centering.models import ( - LoopCenteringContext, - LoopCenteringDependencies, - LoopCenteringSettings, -) - - -class DummyGeometry: - def picture_to_smargon(self, coord: Coordinate) -> Coordinate: - return Coordinate(x=coord.x / 100.0, y=coord.y / 100.0, z=0.0) - - -class DummyMlBox: - def get_preferred_class_box(self, boxes, preferred_class=None): - for cls in preferred_class: - box = boxes.get_best_for_class(cls) - if box: - return box - return None - - def check_box_relation(self, box0, box1): - return {"left": True, "top": False, "overlap_x": False, "overlap_y": False} - - -def _coord_target(x: float, y: float, z: float = 0.0) -> SmargonCoordinate: - return SmargonCoordinate(sh_mm=Coordinate(x=x, y=y, z=z)) - - -@pytest.fixture -def analyzer(mock_logger): - runtime_state = DAQRuntimeState( - sample_provider=types.SimpleNamespace(sample=None), - sample_geometry_provider=types.SimpleNamespace(sample_geometry=DummyGeometry()), - status_provider=types.SimpleNamespace(status=None), - ) - - ctx = LoopCenteringContext( - deps=LoopCenteringDependencies( - cfg=types.SimpleNamespace(), devs=types.SimpleNamespace(), mlbox=DummyMlBox() - ), - runtime=runtime_state, - services=OperationServices( - screenshots=types.SimpleNamespace(save_to_db=lambda *args, **kwargs: None), - traces=TraceWriter( - appender=types.SimpleNamespace(append_smargon_trace=lambda *args, **kwargs: None) - ), - predictions=PredictionProvider( - getter=types.SimpleNamespace( - get_predictions=lambda: MLBoxPredictionsResult( - predictions=None, image=None, target_point=None, focus=None - ) - ) - ), - ), - settings=LoopCenteringSettings(), - ) - return LoopCenteringAnalyzer(context=ctx, logger=mock_logger) - - -def test_is_ignore_only_classes_true(analyzer): - assert analyzer.is_ignore_only_classes( - [MLBoxType.PIN.value, MLBoxType.ICE.value, MLBoxType.NEEDLE.value] - ) - - -def test_is_ignore_only_classes_false_when_loop_present(analyzer): - assert not analyzer.is_ignore_only_classes([MLBoxType.PIN.value, MLBoxType.LOOP_FACE.value]) - - -def test_has_valid_target_classes_true(analyzer): - assert analyzer.has_valid_target_classes([MLBoxType.PIN.value, MLBoxType.CRYSTAL.value]) - - -def test_has_valid_target_classes_false(analyzer): - assert not analyzer.has_valid_target_classes([MLBoxType.PIN.value, MLBoxType.ICE.value]) - - -def test_select_smargon_target_prefers_prediction_when_within_tolerance(analyzer): - calculated = _coord_target(1.0, 2.0, 3.0) - predicted = _coord_target(1.0001, 2.0001, 3.0001) - - result = analyzer.select_smargon_target( - calculated_target=calculated, predicted_target=predicted, tolerance_um=500.0 - ) - - assert result is predicted - - -def test_select_smargon_target_keeps_calculated_when_outside_tolerance(analyzer): - calculated = _coord_target(1.0, 2.0, 3.0) - predicted = _coord_target(2.0, 3.0, 4.0) - - result = analyzer.select_smargon_target( - calculated_target=calculated, predicted_target=predicted, tolerance_um=500.0 - ) - - assert result is calculated - - -def test_analyze_angle_with_no_predictions_returns_empty_analysis(analyzer): - analysis = analyzer.analyze_angle(angle_deg=0, zoom_value=200.0, sample_id=1) - - assert analysis.angle_deg == 0 - assert analysis.classes == [] - assert analysis.selected_class is None - assert analysis.has_valid_target is False - assert analysis.ignore_only is False - assert analysis.calculated_target is None - assert analysis.predicted_target is None - assert analysis.final_target is None - - -def test_analyze_angle_with_crystal_prediction_returns_valid_target(analyzer): - boxes = MLOutputModel() - boxes.add_box(MLBoxType.CRYSTAL, (10, 20, 30, 40), conf=0.9) - - analyzer.ctx.services.predictions.getter.get_predictions = lambda: MLBoxPredictionsResult( - predictions=boxes, image=None, target_point=(25.0, 30.0), focus=1.0 - ) - - analysis = analyzer.analyze_angle(angle_deg=90, zoom_value=200.0, sample_id=1) - - assert analysis.selected_class == MLBoxType.CRYSTAL.value - assert MLBoxType.CRYSTAL.value in analysis.classes - assert analysis.has_valid_target is True - assert analysis.ignore_only is False - assert analysis.calculated_target is not None - assert analysis.predicted_target is not None - assert analysis.final_target is not None diff --git a/tests/unit/daq/operations/loop_centering/test_loop_centering_service.py b/tests/unit/daq/operations/loop_centering/test_loop_centering_service.py deleted file mode 100644 index 8059a644..00000000 --- a/tests/unit/daq/operations/loop_centering/test_loop_centering_service.py +++ /dev/null @@ -1,129 +0,0 @@ -import types - -import pytest -from aarecommon.models.models import LoopCenteringResult - -from aare.daq.operations.common.runtime import DAQRuntimeState -from aare.daq.operations.common.services import OperationServices, PredictionProvider, TraceWriter -from aare.daq.operations.loop_centering.models import ( - AngleAnalysis, - LoopCenteringContext, - LoopCenteringDependencies, - LoopCenteringSettings, -) -from aare.daq.operations.loop_centering.service import LoopCenteringService - - -@pytest.fixture -def context(): - devs = types.SimpleNamespace( - zoom=100.0, - aerotech_omega=0.0, - smargon_pos=None, - samcam_auto=lambda *args, **kwargs: None, - smargon_wait=lambda *args, **kwargs: None, - ) - screenshots = [] - traces = [] - - runtime_state = DAQRuntimeState( - sample_provider=types.SimpleNamespace(sample=None), - sample_geometry_provider=types.SimpleNamespace(sample_geometry=types.SimpleNamespace()), - status_provider=types.SimpleNamespace(status=None), - ) - - ctx = LoopCenteringContext( - deps=LoopCenteringDependencies( - cfg=types.SimpleNamespace(), devs=devs, mlbox=types.SimpleNamespace() - ), - runtime=runtime_state, - services=OperationServices( - screenshots=types.SimpleNamespace( - save_to_db=lambda sample_id, filename, wait=0.0: screenshots.append( - (sample_id, filename, wait) - ) - ), - traces=TraceWriter( - appender=types.SimpleNamespace( - append_smargon_trace=lambda **kwargs: traces.append(kwargs) - ) - ), - predictions=PredictionProvider( - getter=types.SimpleNamespace(get_predictions=lambda: None) - ), - ), - settings=LoopCenteringSettings(), - ) - ctx._screenshots = screenshots - ctx._traces = traces - return ctx - - -def test_service_fails_when_attempt_one_has_no_valid_targets(monkeypatch, context, mock_logger): - service = LoopCenteringService(context=context, logger=mock_logger) - - monkeypatch.setattr( - service, - "_run_angle_pass", - lambda **kwargs: AngleAnalysis( - angle_deg=kwargs["angle"], classes=[], has_valid_target=False, ignore_only=False - ), - ) - - result = service.run(sample_id=1) - - assert isinstance(result, LoopCenteringResult) - assert result.success is False - assert "attempt 1" in result.comment.lower() - - -def test_service_succeeds_when_correction_pass_has_valid_target(monkeypatch, context, mock_logger): - service = LoopCenteringService(context=context, logger=mock_logger) - - call_count = {"count": 0} - - def fake_run_angle_pass(**kwargs): - call_count["count"] += 1 - if call_count["count"] <= 2: - return AngleAnalysis( - angle_deg=kwargs["angle"], - classes=[MLBoxType.CRYSTAL.value] if kwargs["angle"] == 0 else [], - has_valid_target=kwargs["angle"] == 0, - ignore_only=False, - ) - return AngleAnalysis( - angle_deg=kwargs["angle"], - classes=[MLBoxType.CRYSTAL.value], - has_valid_target=True, - ignore_only=False, - moved=True, - ) - - from aarecommon.models.models import MLBoxType - - monkeypatch.setattr(service, "_run_angle_pass", fake_run_angle_pass) - - result = service.run(sample_id=2) - - assert result.success is True - - -def test_service_uses_settings_values(monkeypatch, context, mock_logger): - context.settings.zoom_value = 250.0 - context.settings.max_attempts = 3 - context.settings.angles = (0, 90) - - service = LoopCenteringService(context=context, logger=mock_logger) - - monkeypatch.setattr( - service, - "_run_angle_pass", - lambda **kwargs: AngleAnalysis( - angle_deg=kwargs["angle"], classes=[], has_valid_target=False, ignore_only=False - ), - ) - - result = service.run(sample_id=3) - - assert context.deps.devs.zoom == 250.0 - assert result.success is False diff --git a/tests/unit/daq/operations/mounting/test_mounting_service.py b/tests/unit/daq/operations/mounting/test_mounting_service.py deleted file mode 100644 index bf5a47ea..00000000 --- a/tests/unit/daq/operations/mounting/test_mounting_service.py +++ /dev/null @@ -1,283 +0,0 @@ -import sys -import types - -from aarecommon.errors.exception_handler import ( - CriticalTellException, - DoorSafetyError, - MountingFailed, -) -from aarecommon.math.coordinate import AerotechCoordinate, Coordinate -from aarecommon.models.models import DewarAddress, SampleShortInfo - -from aare.daq.operations.mounting.models import ( - MountingContext, - MountingDependencies, - MountingResult, - MountingSettings, -) -from aare.daq.operations.mounting.service import MountingService -from aare.devices.tell_client import TellEventValueEnum - -if "jfjoch_client.models.scan_result" not in sys.modules: - jfjoch_client_mod = types.ModuleType("jfjoch_client") - jfjoch_client_models_mod = types.ModuleType("jfjoch_client.models") - jfjoch_client_scan_result_mod = types.ModuleType("jfjoch_client.models.scan_result") - - jfjoch_client_scan_result_mod.ScanResult = dict - jfjoch_client_models_mod.scan_result = jfjoch_client_scan_result_mod - jfjoch_client_mod.models = jfjoch_client_models_mod - sys.modules["jfjoch_client"] = jfjoch_client_mod - sys.modules["jfjoch_client.models"] = jfjoch_client_models_mod - sys.modules["jfjoch_client.models.scan_result"] = jfjoch_client_scan_result_mod - - -def _make_sample(sample_id: int, name: str) -> SampleShortInfo: - return SampleShortInfo( - db_id=sample_id, - puck_name="puck1", - dewar_name="dew1", - sample_name=name, - run_number=1, - user="group1", - pin=sample_id, - location=DewarAddress(segment="A", pos=1), - ) - - -def _make_context(previous_sample=None, *, prohibited=True, alarm=False): - tell = types.SimpleNamespace( - mount=lambda **kwargs: TellEventValueEnum.SUCCESS, - unmount=lambda **kwargs: None, - dry=lambda **kwargs: None, - check_enable_motion=lambda: None, - wait_not_busy=lambda timeout=360.0: None, - validate_door_closed=lambda: None, - set_in_mount_position=lambda value: None, - ) - - devs = types.SimpleNamespace( - smargon_move_home=lambda: None, - aerotech_pos=None, - tell=tell, - magnet_position_sensor=types.SimpleNamespace(value=0), - pss=types.SimpleNamespace(is_prohibited=lambda: prohibited, alarm_active=lambda: alarm), - ) - - streak = {"count": 0} - - cfg = types.SimpleNamespace( - current_sample=previous_sample, - get_mount_failure_streak=lambda: streak["count"], - increment_mount_failure_streak=lambda: ( - streak.__setitem__("count", streak["count"] + 1) or streak["count"] - ), - reset_mount_failure_streak=lambda: streak.__setitem__("count", 0), - record_mount_failure=lambda: ( - streak.__setitem__("count", streak["count"] + 1) or streak["count"] - ), - record_mount_success=lambda: streak.__setitem__("count", 0), - ) - - return MountingContext( - deps=MountingDependencies(cfg=cfg, devs=devs), - settings=MountingSettings( - mount_position=AerotechCoordinate(at_mm=Coordinate(x=0, y=0, z=0), omega_deg=0) - ), - ) - - -def test_execute_mount_success(mock_logger): - previous_sample = _make_sample(1, "old") - target_sample = _make_sample(2, "new") - ctx = _make_context(previous_sample=previous_sample) - - service = MountingService(context=ctx, logger=mock_logger) - - result = service.execute(target=target_sample) - - assert isinstance(result, MountingResult) - assert result.success is True - assert result.mounted_sample == target_sample - assert result.previous_sample == previous_sample - assert result.did_unmount_previous is True - assert ctx.deps.cfg.current_sample == target_sample - - -def test_execute_unmount_success(mock_logger): - previous_sample = _make_sample(1, "old") - ctx = _make_context(previous_sample=previous_sample) - - service = MountingService(context=ctx, logger=mock_logger) - - result = service.execute(target=None) - - assert result.success is True - assert result.mounted_sample is None - assert result.previous_sample == previous_sample - assert result.did_unmount_previous is True - assert ctx.deps.cfg.current_sample is None - - -def test_execute_mount_returns_failed_result_for_no_pin_in_gripper(mock_logger): - target_sample = _make_sample(2, "new") - ctx = _make_context() - ctx.deps.devs.tell.mount = lambda **kwargs: TellEventValueEnum.NO_PIN_IN_GRIPPER - - service = MountingService(context=ctx, logger=mock_logger) - - result = service.execute(target=target_sample) - - assert result.success is False - assert isinstance(result.error, MountingFailed) - assert result.is_error is True - - -def test_execute_mount_returns_failed_result_for_unhandled_tell_response(mock_logger): - target_sample = _make_sample(2, "new") - ctx = _make_context() - ctx.deps.devs.tell.mount = lambda **kwargs: TellEventValueEnum.UNKNOWN - - service = MountingService(context=ctx, logger=mock_logger) - - result = service.execute(target=target_sample) - - assert result.success is False - assert isinstance(result.error, CriticalTellException) - assert result.is_error is True - - -def test_dry_unmounts_current_sample_before_drying(mock_logger): - previous_sample = _make_sample(1, "old") - ctx = _make_context(previous_sample=previous_sample) - unmount_calls = [] - dry_calls = [] - - ctx.deps.devs.tell.unmount = lambda **kwargs: unmount_calls.append(kwargs) - ctx.deps.devs.tell.dry = lambda **kwargs: dry_calls.append(kwargs) - - service = MountingService(context=ctx, logger=mock_logger) - service.dry(park=True, unmount=True) - - assert len(unmount_calls) == 1 - assert ctx.deps.cfg.current_sample is None - assert dry_calls == [{"wait_cold": -1, "wait": True}] - - -def test_execute_mount_triggers_dry_on_third_consecutive_failure(mock_logger): - target_sample = _make_sample(2, "new") - dry_calls = [] - - ctx = _make_context() - ctx.deps.devs.tell.mount = lambda **kwargs: TellEventValueEnum.NO_PIN_IN_GRIPPER - ctx.deps.devs.tell.dry = lambda **kwargs: dry_calls.append(kwargs) - ctx.deps.cfg.increment_mount_failure_streak() - ctx.deps.cfg.increment_mount_failure_streak() - - service = MountingService(context=ctx, logger=mock_logger) - - result = service.execute(target=target_sample) - - assert result.success is False - assert isinstance(result.error, MountingFailed) - assert result.error.critical is False - assert dry_calls == [{"wait": True}] - - -def test_execute_mount_stops_automation_on_fifth_consecutive_failure(mock_logger): - target_sample = _make_sample(2, "new") - dry_calls = [] - - ctx = _make_context() - ctx.deps.devs.tell.mount = lambda **kwargs: TellEventValueEnum.NO_PIN_IN_GRIPPER - ctx.deps.devs.tell.dry = lambda **kwargs: dry_calls.append(kwargs) - ctx.deps.cfg.increment_mount_failure_streak() - ctx.deps.cfg.increment_mount_failure_streak() - ctx.deps.cfg.increment_mount_failure_streak() - ctx.deps.cfg.increment_mount_failure_streak() - - service = MountingService(context=ctx, logger=mock_logger) - - result = service.execute(target=target_sample) - - assert result.success is False - assert isinstance(result.error, MountingFailed) - assert result.error.critical is True - assert "Mount failed 5 times in a row" in str(result.error) - assert {"wait_cold": -1, "wait": True} in dry_calls - - -def test_execute_mount_success_resets_failure_streak(mock_logger): - previous_sample = _make_sample(1, "old") - target_sample = _make_sample(2, "new") - ctx = _make_context(previous_sample=previous_sample) - ctx.deps.cfg.increment_mount_failure_streak() - ctx.deps.cfg.increment_mount_failure_streak() - - service = MountingService(context=ctx, logger=mock_logger) - - result = service.execute(target=target_sample) - - assert result.success is True - assert ctx.deps.cfg.get_mount_failure_streak() == 0 - - -def test_execute_mount_critical_tell_error_does_not_increment_failure_streak(mock_logger): - target_sample = _make_sample(2, "new") - ctx = _make_context() - - def mount(**kwargs): - raise CriticalTellException("critical tell problem") - - ctx.deps.devs.tell.mount = mount - - service = MountingService(context=ctx, logger=mock_logger) - - result = service.execute(target=target_sample) - - assert result.success is False - assert isinstance(result.error, CriticalTellException) - assert ctx.deps.cfg.get_mount_failure_streak() == 0 - - -def test_mount_blocked_when_not_prohibited(mock_logger): - """Doors open / hutch not in prohibited state -> critical DoorSafetyError, - and it is not counted as a mount-failure streak.""" - target_sample = _make_sample(2, "new") - ctx = _make_context(prohibited=False) - - service = MountingService(context=ctx, logger=mock_logger) - - result = service.execute(target=target_sample) - - assert result.success is False - assert isinstance(result.error, DoorSafetyError) - assert result.error.critical is True - # Door safety is a pre-flight gate, not a mount attempt: streak stays clear. - assert ctx.deps.cfg.get_mount_failure_streak() == 0 - - -def test_mount_blocked_when_alarm_active(mock_logger): - target_sample = _make_sample(3, "new") - ctx = _make_context(alarm=True) - - service = MountingService(context=ctx, logger=mock_logger) - - result = service.execute(target=target_sample) - - assert result.success is False - assert isinstance(result.error, DoorSafetyError) - assert result.error.critical is True - - -def test_unmount_blocked_when_not_prohibited_keeps_door_error(mock_logger): - """Unmount path must not swallow DoorSafetyError into UnmountingFailed.""" - previous_sample = _make_sample(1, "old") - ctx = _make_context(previous_sample=previous_sample, prohibited=False) - - service = MountingService(context=ctx, logger=mock_logger) - - result = service.execute(target=None) - - assert result.success is False - assert isinstance(result.error, DoorSafetyError) - assert result.error.critical is True diff --git a/tests/unit/daq/operations/screenshot/test_screenshot_service.py b/tests/unit/daq/operations/screenshot/test_screenshot_service.py deleted file mode 100644 index 6936fa55..00000000 --- a/tests/unit/daq/operations/screenshot/test_screenshot_service.py +++ /dev/null @@ -1,103 +0,0 @@ -import types - -import numpy as np -import pytest -from aarecommon.models.models import DewarAddress, SampleShortInfo - -from aare.daq.operations.screenshot.service import ScreenshotService - - -def _make_sample(sample_id: int = 7) -> SampleShortInfo: - return SampleShortInfo( - db_id=sample_id, - puck_name="puck1", - dewar_name="dew1", - sample_name="sample1", - run_number=1, - user="p12345", - pin=1, - location=DewarAddress(segment="A", pos=1), - ) - - -def test_save_to_db_uploads_image_via_shared_aare(mock_logger): - image = np.zeros((10, 10, 3), dtype=np.uint8) - upload_calls = [] - noncritical_calls = [] - - mlbox = types.SimpleNamespace(get_latest_image=lambda: image) - aare = types.SimpleNamespace( - upload_image=lambda sample_id, filename, bgr_image, **kwargs: upload_calls.append( - (sample_id, filename, bgr_image, kwargs) - ) - ) - - sample = _make_sample(11) - - def _run_noncritical(action, *, description, sample=None): - noncritical_calls.append((description, sample)) - return action() - - service = ScreenshotService( - mlbox=mlbox, - aare=aare, - logger=mock_logger, - run_noncritical=_run_noncritical, - sample_provider=lambda: sample, - pgroup_provider=lambda: "p12345", - ) - - service.save_to_db(11, "mounted", 0.0) - - assert len(upload_calls) == 1 - assert upload_calls[0][0] == 11 - assert upload_calls[0][1] == "mounted" - assert noncritical_calls == [("screenshot upload 'mounted'", sample)] - - -def test_send_to_db_writes_photo_and_uploads_with_default_message(mock_logger, tmp_path): - image = np.zeros((10, 10, 3), dtype=np.uint8) - upload_calls = [] - - mlbox = types.SimpleNamespace(get_latest_image=lambda: image) - aare = types.SimpleNamespace( - upload_image=lambda sample_id, filename, bgr_image, **kwargs: upload_calls.append( - (sample_id, filename, kwargs) - ) - ) - sample = _make_sample(15) - - service = ScreenshotService( - mlbox=mlbox, - aare=aare, - logger=mock_logger, - run_noncritical=lambda action, **kwargs: action(), - sample_provider=lambda: sample, - pgroup_provider=lambda: "p12345", - photos_root=str(tmp_path), - ) - - service.send_to_db( - filename="test image", message=None, default_message="default screenshot message" - ) - - expected_photo = tmp_path / "p12345" / "raw" / "photos" / "15" / "test_image.jpeg" - assert expected_photo.exists() - assert len(upload_calls) == 1 - assert upload_calls[0][0] == 15 - assert upload_calls[0][1] == "test_image" - assert upload_calls[0][2]["message"] == "default screenshot message" - - -def test_send_to_db_requires_mounted_sample(mock_logger): - service = ScreenshotService( - mlbox=types.SimpleNamespace(get_latest_image=lambda: np.zeros((4, 4, 3), dtype=np.uint8)), - aare=types.SimpleNamespace(upload_image=lambda *args, **kwargs: None), - logger=mock_logger, - run_noncritical=lambda action, **kwargs: action(), - sample_provider=lambda: None, - pgroup_provider=lambda: "p12345", - ) - - with pytest.raises(ValueError, match="valid sample_id"): - service.send_to_db(default_message="x") diff --git a/tests/unit/daq/operations/test_ml_raster_plan.py b/tests/unit/daq/operations/test_ml_raster_plan.py deleted file mode 100644 index 8b534d20..00000000 --- a/tests/unit/daq/operations/test_ml_raster_plan.py +++ /dev/null @@ -1,168 +0,0 @@ -import logging -import types - -import numpy as np -from aarecommon.math.coordinate import Coordinate, SmargonCoordinate -from aarecommon.math.sample_geometry import SampleGeometryModel -from aarecommon.models.models import MLBoxType, MLOutputModel - -from aare.daq.mlbox import MLBoxPredictionsResult -from aare.daq.operations.common import ml_bounding_box as mlb -from aare.daq.operations.common.ml_bounding_box import ( - _box_extends_beyond, - _box_to_raster_request, - _box_union, - build_ml_raster_plan, -) - -logger = logging.getLogger("test_ml_raster_plan") - - -def _geom() -> SampleGeometryModel: - return SampleGeometryModel( - beam_location_pxl=Coordinate(x=500, y=500), - 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=0, - beam_size_mm=Coordinate(x=0.01, y=0.01), - ) - - -def _fake_mlbox(loop_all=None, loop_face=None, crystals=()): - preds = MLOutputModel() - if loop_all is not None: - preds.add_box(MLBoxType.LOOP_ALL, loop_all, 0.9) - if loop_face is not None: - preds.add_box(MLBoxType.LOOP_FACE, loop_face, 0.8) - for c in crystals: - preds.add_box(MLBoxType.CRYSTAL, c, 0.7) - result = MLBoxPredictionsResult( - predictions=preds if preds.boxes else None, - image=np.zeros((1000, 1000, 3), dtype=np.uint8), - target_point=None, - focus=None, - ) - return types.SimpleNamespace(predict_all_best=lambda **kwargs: result) - - -def _plan(mlbox): - return build_ml_raster_plan( - mlbox=mlbox, - sample=None, - sample_geometry=_geom(), - upload_image=lambda *a, **k: None, - logger=logger, - filename=None, - max_images=100000, - min_cell_size_mm=0.0001, - skip_if_exceed_max_image_threshold=False, - ) - - -def test_box_helpers(): - assert _box_union((1, 1, 3, 3), (2, 0, 5, 4)) == (1, 0, 5, 4) - assert _box_extends_beyond((350, 150, 500, 300), (100, 100, 400, 400)) is True - assert _box_extends_beyond((150, 150, 300, 300), (100, 100, 400, 400)) is False - - -def test_plan_returns_loop_boxes_and_prefers_loop_face(): - plan = _plan(_fake_mlbox(loop_all=(100, 100, 400, 400), loop_face=(150, 150, 300, 300))) - assert plan is not None - assert plan.loop_all_box == (100, 100, 400, 400) - assert plan.loop_face_box == (150, 150, 300, 300) - assert plan.image_width == 1000 and plan.image_height == 1000 - assert plan.grid_request.n_x >= 1 and plan.grid_request.n_y >= 1 - - -def test_plan_none_when_no_loop(): - # crystal only, no loop -> no grid - assert _plan(_fake_mlbox(crystals=[(300, 300, 350, 350)])) is None - - -def _grid(box, *, grid_padding): - x1, y1, x2, y2 = box - return _box_to_raster_request( - x1=x1, - y1=y1, - x2=x2, - y2=y2, - sample=None, - sample_geometry=_geom(), - logger=logger, - filename=None, - sample_id=None, - max_images=100000, - min_cell_size_mm=0.0001, - skip_if_exceed_max_image_threshold=False, - grid_padding=grid_padding, - ) - - -def test_grid_padding_grows_and_shifts_top_left(monkeypatch): - # fraction 0 -> minimum one cell of padding per side - monkeypatch.setattr( - mlb, "cfg_get", lambda k, d=None: 0.0 if "grid_padding_fraction" in k else d - ) - box = (150, 150, 400, 300) - nopad = _grid(box, grid_padding=False) - pad = _grid(box, grid_padding=True) - assert pad.n_x == nopad.n_x + 2 # 1 cell each side in x - assert pad.n_y == nopad.n_y + 2 # 1 cell each side in y - # top-left shifted outward (cells added before cell 0) - assert pad.smargon_top_left.sh_mm.x != nopad.smargon_top_left.sh_mm.x - assert pad.smargon_top_left.sh_mm.z != nopad.smargon_top_left.sh_mm.z - - -def test_grid_padding_y_bottom_asymmetric(monkeypatch): - box = (150, 150, 400, 450) # tall box - - def cfg(y_bottom): - return lambda k, d=None: ( - y_bottom - if "grid_padding_fraction_y_bottom" in k - else (0.0 if "grid_padding_fraction" in k else d) - ) - - monkeypatch.setattr(mlb, "cfg_get", cfg(0.0)) # bottom == top (min 1 cell each) - sym = _grid(box, grid_padding=True) - monkeypatch.setattr(mlb, "cfg_get", cfg(0.6)) # much more padding at the bottom - bottom = _grid(box, grid_padding=True) - - assert bottom.n_y > sym.n_y # extra cells added at the bottom - assert bottom.n_x == sym.n_x # x unaffected - # top padding identical -> smargon_top_left (cell 0) unchanged - assert bottom.smargon_top_left == sym.smargon_top_left - - -def test_grid_padding_fraction_scales(monkeypatch): - box = (150, 150, 520, 420) - monkeypatch.setattr( - mlb, "cfg_get", lambda k, d=None: 0.0 if "grid_padding_fraction" in k else d - ) - small = _grid(box, grid_padding=True) - monkeypatch.setattr( - mlb, "cfg_get", lambda k, d=None: 0.5 if "grid_padding_fraction" in k else d - ) - big = _grid(box, grid_padding=True) - assert big.n_x > small.n_x and big.n_y > small.n_y - - -def test_crystal_union_extends_grid_only_when_enabled(monkeypatch): - # crystal extends well beyond the loop_face box on +x - def mlbox(): - return _fake_mlbox(loop_face=(150, 150, 300, 300), crystals=[(350, 150, 520, 300)]) - - def cfg(enabled): - return lambda k, d=None: ( - enabled if "include_crystal" in k else (0.0 if "grid_padding_fraction" in k else d) - ) - - monkeypatch.setattr(mlb, "cfg_get", cfg(False)) - off = _plan(mlbox()).grid_request - monkeypatch.setattr(mlb, "cfg_get", cfg(True)) - on = _plan(mlbox()).grid_request - - assert on.n_x > off.n_x # grid widened to reach the crystal - assert on.n_y == off.n_y # crystal is within the loop's y-range (same padding both) diff --git a/tests/unit/daq/test_aare_daq_loop_centering.py b/tests/unit/daq/test_aare_daq_loop_centering.py deleted file mode 100644 index 65971675..00000000 --- a/tests/unit/daq/test_aare_daq_loop_centering.py +++ /dev/null @@ -1,120 +0,0 @@ -import types -from unittest.mock import MagicMock, patch - -from aarecommon.errors.exception_handler import LoopCenteringFailed -from aarecommon.models.automation import ( - AutomationProgress, - StepState, - StepStatus, - WorkflowStateKind, -) -from aarecommon.models.models import SampleShortInfo - -from aare.daq.daq import AareDAQ - - -def test_execute_loop_centering_rejects_invalid_sample(mock_daq): - mock_daq._create_loop_centering_service = MagicMock() - - result = mock_daq._execute_loop_centering(None) - - assert result is False - mock_daq._create_loop_centering_service.assert_not_called() - - -def test_execute_loop_centering_handles_service_failure(mock_daq): - mock_daq._devs = types.SimpleNamespace(lamp_light=None) - mock_daq.save_screenshot_db = MagicMock() - - sample = SampleShortInfo( - db_id=1, - sample_name="S1", - puck_name="P1", - dewar_name="D1", - run_number=1, - user="p1", - pin=1, - location=None, - ) - - service = MagicMock() - service.run.return_value = types.SimpleNamespace( - success=False, comment="failed", error=LoopCenteringFailed("failed") - ) - mock_daq._create_loop_centering_service = MagicMock(return_value=service) - - result = mock_daq._execute_loop_centering(sample) - - assert result is False - mock_daq._handle_operation_error.assert_called_once() - - -def test_execute_loop_centering_handles_service_success(mock_daq): - mock_daq.save_screenshot_db = MagicMock() - - sample = SampleShortInfo( - db_id=1, - sample_name="S1", - puck_name="P1", - dewar_name="D1", - run_number=1, - user="p1", - pin=1, - location=None, - ) - - service = MagicMock() - service.run.return_value = types.SimpleNamespace(success=True, comment=None, error=None) - mock_daq._create_loop_centering_service = MagicMock(return_value=service) - - result = mock_daq._execute_loop_centering(sample) - - assert result is True - mock_daq.save_screenshot_db.assert_called_once() - - -def test_record_best_effort_step_failure_marks_progress_and_logs_warning(mock_logger): - daq = object.__new__(AareDAQ) - daq._automation_progress_cb = None - daq._set_progress_step = AareDAQ._set_progress_step.__get__(daq, AareDAQ) - - progress = AutomationProgress( - current_step="Center", - steps=[ - StepState( - step=WorkflowStateKind.LOOP_CENTRE, status=StepStatus.RUNNING, message="Centering" - ) - ], - finished=False, - success=None, - ) - sample = SampleShortInfo( - db_id=1, - sample_name="S1", - puck_name="P1", - dewar_name="D1", - run_number=1, - user="p1", - pin=1, - location=None, - ) - - with patch("aare.daq.daq.logger", mock_logger): - daq._record_best_effort_step_failure( - progress=progress, - step=WorkflowStateKind.LOOP_CENTRE, - error=LoopCenteringFailed("Loop centering failed"), - sample=sample, - code="LOOP_CENTERING_FAILED", - ) - - step = progress.steps[0] - assert step.status == StepStatus.FAILED - assert step.message == "Loop centering failed" - assert len(progress.events) == 1 - assert progress.events[0].level == "WARNING" - assert progress.events[0].code == "LOOP_CENTERING_FAILED" - assert progress.events[0].exception_class == "LoopCenteringFailed" - assert progress.events[0].message == "Loop centering failed" - assert progress.events[0].sample_id == 1 - mock_logger.warning.assert_called_once() diff --git a/tests/unit/daq/test_autofocus.py b/tests/unit/daq/test_autofocus.py deleted file mode 100644 index ce108fbd..00000000 --- a/tests/unit/daq/test_autofocus.py +++ /dev/null @@ -1,37 +0,0 @@ -import cv2 -import numpy as np - -from aare.daq.autofocus import calculate_focus_measure - - -def test_calculate_focus_measure_grayscale(): - # Create a focused spot (a sharp square) - image = np.zeros((100, 100), dtype=np.uint8) - image[40:60, 40:60] = 255 - - # Calculate focus measure at the center - fm = calculate_focus_measure(image, 50, 50, 20) - assert fm > 0 - - # Create a blurred spot - blurred = cv2.GaussianBlur(image, (21, 21), 0) - fm_blurred = calculate_focus_measure(blurred, 50, 50, 20) - - # Focused image should have higher variance of Laplacian - assert fm > fm_blurred - - -def test_calculate_focus_measure_color(): - # Create a color image - image = np.zeros((100, 100, 3), dtype=np.uint8) - image[40:60, 40:60, 0] = 255 # Blue square - - fm = calculate_focus_measure(image, 50, 50, 20) - assert fm > 0 - - -def test_calculate_focus_measure_out_of_bounds(): - image = np.zeros((100, 100), dtype=np.uint8) - # Even if radius goes out of bounds, np.ogrid and mask should handle it - fm = calculate_focus_measure(image, 0, 0, 200) - assert fm == 0 # All zeros, so variance is 0 diff --git a/tests/unit/daq/test_automation_progress_state_manager.py b/tests/unit/daq/test_automation_progress_state_manager.py deleted file mode 100644 index c03c3df2..00000000 --- a/tests/unit/daq/test_automation_progress_state_manager.py +++ /dev/null @@ -1,108 +0,0 @@ -from dataclasses import asdict - -from aarecommon.models.automation import ( - AutomationProgress, - StepState, - StepStatus, - WorkflowStateKind, -) - -from aare.daq.config import BeamlineConfig - - -class _FakeRedis: - def __init__(self): - self._store: dict[str, str | int] = {} - - def get(self, key: str): - return self._store.get(key) - - def set(self, key: str, value): - self._store[key] = value - - def delete(self, key: str): - self._store.pop(key, None) - - def incr(self, key: str) -> int: - value = int(self._store.get(key, 0)) + 1 - self._store[key] = value - return value - - -def _make_config_with_fake_redis() -> BeamlineConfig: - cfg = BeamlineConfig.__new__(BeamlineConfig) - cfg._bl = "testbeamline" - cfg.redis = _FakeRedis() - return cfg - - -def test_automation_progress_state_round_trip_dataclass(): - cfg = _make_config_with_fake_redis() - - progress = AutomationProgress( - current_step="Center", - steps=[ - StepState( - step=WorkflowStateKind.MOUNT, status=StepStatus.SUCCESS, message="Mount complete" - ), - StepState( - step=WorkflowStateKind.LOOP_CENTRE, - status=StepStatus.RUNNING, - message="Centering sample", - ), - StepState(step=WorkflowStateKind.RASTER, status=StepStatus.PENDING, message=""), - StepState( - step=WorkflowStateKind.DATA_COLLECTION, status=StepStatus.PENDING, message="" - ), - StepState(step=WorkflowStateKind.FINAL, status=StepStatus.PENDING, message=""), - ], - finished=False, - success=None, - ) - - written_state = cfg.set_automation_progress_state(progress) - - assert written_state["seq"] == 1 - assert written_state["progress"] == asdict(progress) - - read_state = cfg.get_automation_progress_state() - - assert read_state["seq"] == 1 - assert read_state["progress"] == asdict(progress) - - -def test_automation_progress_state_seq_increments(): - cfg = _make_config_with_fake_redis() - - first = AutomationProgress( - current_step="Mount", - steps=[ - StepState( - step=WorkflowStateKind.MOUNT, status=StepStatus.RUNNING, message="Mounting sample" - ) - ], - finished=False, - success=None, - ) - second = AutomationProgress( - current_step="Paused/Finished", - steps=[ - StepState( - step=WorkflowStateKind.FINAL, - status=StepStatus.SUCCESS, - message="Automation complete", - ) - ], - finished=True, - success=True, - ) - - first_state = cfg.set_automation_progress_state(first) - second_state = cfg.set_automation_progress_state(second) - - assert first_state["seq"] == 1 - assert second_state["seq"] == 2 - - final_state = cfg.get_automation_progress_state() - assert final_state["seq"] == 2 - assert final_state["progress"] == asdict(second) diff --git a/tests/unit/daq/test_beamcenterfit.py b/tests/unit/daq/test_beamcenterfit.py deleted file mode 100644 index 8155dcb9..00000000 --- a/tests/unit/daq/test_beamcenterfit.py +++ /dev/null @@ -1,73 +0,0 @@ -import numpy as np -import pytest - -from aare.daq.beamcenterfit import Gaussian2Dfit, beamcenter_fit - - -def create_synthetic_beam_image( - shape=(200, 200), center=(100, 100), sigma=(10, 10), theta=0, A=200, offset=20 -): - x = np.arange(shape[1]) - y = np.arange(shape[0]) - X, Y = np.meshgrid(x, y) - - x0, y0 = center - sig_x, sig_y = sigma - - 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 * sig_x**2) + y_rot**2 / (2 * sig_y**2))) + offset - # Add some noise - noise = np.random.normal(0, 2, shape) - image = (gaussian + noise).astype(np.uint8) - return image - - -def test_beamcenter_fit_success(): - # Create a synthetic image with a known beam center - true_center = (120, 80) - image = create_synthetic_beam_image(center=true_center, sigma=(8, 12), theta=np.radians(30)) - - result = beamcenter_fit(image) - - assert isinstance(result, Gaussian2Dfit) - # Check if the fitted center is close to the true center - assert pytest.approx(result.center_x, abs=2) == true_center[0] - assert pytest.approx(result.center_y, abs=2) == true_center[1] - assert result.peak_intensity > 150 - assert 0 <= result.rotation_angle < 360 - - -def test_beamcenter_fit_no_converge(): - # Create an image that is just noise, should probably fail or at least not find a good fit - image = np.random.randint(0, 50, (200, 200), dtype=np.uint8) - - # beamcenter_fit might still find some contour if there's enough noise, - # but curve_fit might fail to converge - # If it doesn't converge, it returns None now. - beamcenter_fit(image) - # It might actually return a result if it finds a random blob, - # but we want to test the failure path. - # To truly force non-convergence we might need a more extreme case, - # but return None is better than exit() anyway. - - -def test_beamcenter_fit_no_contours(): - # Completely black image, max(contours) will fail - image = np.zeros((100, 100), dtype=np.uint8) - with pytest.raises( - ValueError, match=r"max\(\) (arg is an empty sequence|iterable argument is empty)" - ): - beamcenter_fit(image) - - -def test_beamcenter_fit_small_blob(): - # Test with a very small blob - image = np.zeros((100, 100), dtype=np.uint8) - image[45:55, 45:55] = 255 - - result = beamcenter_fit(image) - assert isinstance(result, Gaussian2Dfit) - assert pytest.approx(result.center_x, abs=2) == 50 - assert pytest.approx(result.center_y, abs=2) == 50 diff --git a/tests/unit/daq/test_face_detection.py b/tests/unit/daq/test_face_detection.py deleted file mode 100644 index 8ccdc090..00000000 --- a/tests/unit/daq/test_face_detection.py +++ /dev/null @@ -1,88 +0,0 @@ -import types - -from aarecommon.models.models import DAQOperation - -from aare.daq.operations.face_detection.models import FaceDetectionResult - - -def test_execute_face_detection_reports_failure(monkeypatch): - from aare.daq.daq import AareDAQ - - daq = object.__new__(AareDAQ) - - calls = {"set_state": [], "handle_error": []} - - monkeypatch.setattr(daq, "_set_state", lambda state: calls["set_state"].append(state)) - monkeypatch.setattr( - daq, - "_create_face_detection_service", - lambda: types.SimpleNamespace( - run=lambda **kwargs: FaceDetectionResult( - success=False, - payload={"running": False, "samples": [], "height_fit": {}, "area_fit": {}}, - error=RuntimeError("fd failed"), - comment="face detection sequence failed", - ) - ), - ) - monkeypatch.setattr( - daq, "_handle_operation_error", lambda **kwargs: calls["handle_error"].append(kwargs) - ) - monkeypatch.setattr( - type(daq), - "sample", - property(lambda self: types.SimpleNamespace(sample_name="sample-1", db_id=1)), - ) - - result = daq._execute_face_detection(steps=7, step_size=30, report_error=True) - - assert result.success is False - assert len(calls["set_state"]) == 1 - assert len(calls["handle_error"]) == 1 - assert calls["handle_error"][0]["operation"] == DAQOperation.FACE_CENTERING - - -def test_execute_face_detection_can_skip_error_reporting(monkeypatch): - from aare.daq.daq import AareDAQ - - daq = object.__new__(AareDAQ) - - handle_error_calls = [] - - monkeypatch.setattr(daq, "_set_state", lambda state: None) - monkeypatch.setattr( - daq, - "_create_face_detection_service", - lambda: types.SimpleNamespace( - run=lambda **kwargs: FaceDetectionResult( - success=False, - payload={"running": False, "samples": [], "height_fit": {}, "area_fit": {}}, - error=RuntimeError("fd failed"), - comment="face detection sequence failed", - ) - ), - ) - monkeypatch.setattr( - daq, "_handle_operation_error", lambda **kwargs: handle_error_calls.append(kwargs) - ) - - result = daq._execute_face_detection(report_error=False) - - assert result.success is False - assert handle_error_calls == [] - - -def test_public_face_detection_uses_execute_face_detection(monkeypatch): - from aare.daq.daq import AareDAQ - - daq = object.__new__(AareDAQ) - - daq._execute_face_detection = lambda **kwargs: FaceDetectionResult( - success=True, - payload={"running": False, "samples": [{"angle": 45}], "height_fit": {}, "area_fit": {}}, - ) - - result = daq.face_detection(steps=7, step_size=30) - - assert result["running"] is False - assert result["samples"] == [{"angle": 45}] diff --git a/tests/unit/daq/test_gui_timeout.py b/tests/unit/daq/test_gui_timeout.py deleted file mode 100644 index a8381dc6..00000000 --- a/tests/unit/daq/test_gui_timeout.py +++ /dev/null @@ -1,83 +0,0 @@ -from types import SimpleNamespace -from unittest.mock import patch - - -def test_status_renews_gui_session_with_gui_timeout(client, mock_backend, daq_status_factory): - mock_cfg = mock_backend["cfg"] - mock_daq = mock_backend["daq"] - - from aarecommon.models.models import SessionsStateEnum - - mock_daq.status = daq_status_factory(current_pgroup="p12345", staff=True) - mock_daq.status.sample = None - mock_daq.status.box = None - mock_daq.status.last_best_res = None - mock_daq.status.last_best_b_factor = None - mock_daq.status.crystal_size = SimpleNamespace(x=0, y=0, z=0) - mock_daq.status.open_guis = [] - - mock_cfg.pgroup = "p12345" - mock_cfg.session_state.return_value = SessionsStateEnum.OwnedByYou - mock_cfg.get_open_gui_sessions.return_value = [] - mock_cfg.GUI_SESSION_EXPIRE_SECONDS = 10 - - response = client.get("/status", headers={"Authorization": "Bearer fake-token"}) - - assert response.status_code == 200 - mock_cfg.touch_gui_session.assert_called_once_with( - session=123, username="testuser", staff=True, expiry_sec=10 - ) - - -def test_status_hides_open_guis_for_non_staff(client, mock_backend, daq_status_factory): - with patch("aare.daq.auth.parse_token") as mock_parse: - from aarecommon.models.models import OpenGuiSessionInfo, SessionsStateEnum - - from aare.daq.auth import TokenData - - mock_parse.return_value = TokenData( - sub="user1", staff=False, pgroups=["p12345"], session=123 - ) - - mock_backend["daq"].status = daq_status_factory(current_pgroup="p12345", staff=False) - mock_backend["daq"].status.sample = None - mock_backend["daq"].status.box = None - mock_backend["daq"].status.last_best_res = None - mock_backend["daq"].status.last_best_b_factor = None - mock_backend["daq"].status.crystal_size = SimpleNamespace(x=0, y=0, z=0) - mock_backend["cfg"].pgroup = "p12345" - mock_backend["cfg"].session_state.return_value = SessionsStateEnum.OwnedByElse - mock_backend["cfg"].get_open_gui_sessions.return_value = [ - OpenGuiSessionInfo(session=1, username="staff1", last_seen_ts=1.0, staff=True) - ] - mock_backend["cfg"].get_gui_session.return_value = OpenGuiSessionInfo( - session=123, username="user1", last_seen_ts=2.0, staff=False - ) - - response = client.get("/status", headers={"Authorization": "Bearer fake-token"}) - - assert response.status_code == 200 - payload = response.json()["open_guis"] - assert len(payload) == 1 - assert payload[0]["session"] == 123 - assert payload[0]["username"] == "user1" - - -def test_admin_gui_sessions_includes_baton_holder_flag(client, mock_backend): - from types import SimpleNamespace - - from aarecommon.models.models import OpenGuiSessionInfo - - mock_cfg = mock_backend["cfg"] - mock_cfg.get_open_gui_sessions.return_value = [ - OpenGuiSessionInfo(session=11, username="user1", last_seen_ts=1.0, staff=False), - OpenGuiSessionInfo(session=22, username="holder", last_seen_ts=2.0, staff=True), - ] - mock_cfg.baton_holder = SimpleNamespace(session=22) - - response = client.get("/admin/gui_sessions", headers={"Authorization": "Bearer fake-token"}) - - assert response.status_code == 200 - payload = response.json() - assert payload[0]["session"] == 11 - assert payload[1]["session"] == 22 diff --git a/tests/unit/daq/test_mlbox.py b/tests/unit/daq/test_mlbox.py deleted file mode 100644 index 650e8c09..00000000 --- a/tests/unit/daq/test_mlbox.py +++ /dev/null @@ -1,130 +0,0 @@ -from unittest.mock import MagicMock, patch - -import numpy as np -import pytest -from aarecommon.models.beamline import MXBeamline -from aarecommon.models.models import MLBoxModel, MLBoxType, MLOutputModel - -from aare.daq.mlbox import MlBox - - -@pytest.fixture(autouse=True) -def no_mlbox_sleep(monkeypatch): - monkeypatch.setattr(MlBox, "RETRY_SLEEP_S", 0.0) - - -@pytest.fixture -def mock_wrapper(): - return MagicMock() - - -@pytest.fixture -def mlbox(mock_wrapper): - return MlBox(MXBeamline.X10SA, wrapper=mock_wrapper) - - -def test_init_x10sa(mock_wrapper): - ml = MlBox(MXBeamline.X10SA, wrapper=mock_wrapper) - assert ml._beamline == MXBeamline.X10SA - - -def test_predict_uses_injected_wrapper(): - fake = MagicMock() - fake.get_latest_prediction_bundle.return_value = MagicMock() - - ml = MlBox(MXBeamline.X10SA, wrapper=fake) - - ml._fetch_prediction_bundle() - - fake.get_latest_prediction_bundle.assert_called_once() - - -def test_init_unsupported(): - with pytest.raises(NotImplementedError): - MlBox(MXBeamline.SIMULATED) - - -def test_prediction_score(): - assert MlBox._prediction_score(None) == (0, 0.0) - - out = MLOutputModel() - assert MlBox._prediction_score(out) == (0, 0.0) - - out.add_box(MLBoxType.CRYSTAL, (0, 0, 10, 10), conf=0.9) - assert MlBox._prediction_score(out) == (1, 0.9) - - -def test_check_overlap(): - box_a = MLBoxModel.from_tuple(MLBoxType.CRYSTAL, (0, 0, 10, 10), conf=1.0) - box_b = MLBoxModel.from_tuple(MLBoxType.CRYSTAL, (5, 5, 15, 15), conf=1.0) - assert MlBox._check_overlap(box_a, box_b) > 0 - - box_c = MLBoxModel.from_tuple(MLBoxType.CRYSTAL, (20, 20, 30, 30), conf=1.0) - assert MlBox._check_overlap(box_a, box_c) == 0 - - -def test_filter_predictions(mlbox): - out = MLOutputModel() - out.add_box(MLBoxType.CRYSTAL, (0, 0, 10, 10), conf=0.4) - out.add_box(MLBoxType.CRYSTAL, (20, 20, 30, 30), conf=0.8) - - mlbox._filter_predictions(out, confidence_min=0.5) - assert len(out.boxes) == 1 - assert next(iter(out.boxes.values())).conf == 0.8 - - -@patch("cv2.imdecode") -def test_decode_bundle_image(mock_imdecode): - mock_imdecode.return_value = np.zeros((100, 100, 3)) - img = MlBox._decode_bundle_image(b"fake_jpeg") - assert img is not None - assert img.shape == (100, 100, 3) - - -def test_extract_bundle_meta(): - pred = MagicMock() - pred.target_point = [100.0, 200.0] - pred.focus_score = 0.5 - - meta = MlBox._extract_bundle_meta(pred) - assert meta.target_point == (100.0, 200.0) - assert meta.focus == 0.5 - - -def test_preferred_class_prefers_loop_over_pin_when_margin_not_exceeded(): - boxes = MLOutputModel() - boxes.add_box(MLBoxType.PIN, (0, 0, 10, 10), 0.8) - boxes.add_box(MLBoxType.LOOP_FACE, (1, 1, 9, 9), 0.75) - - best = MlBox.get_preferred_class_box_with_confidence_threshold( - boxes, loop_preference_margin=0.1 - ) - - assert best is not None - assert best.cls == MLBoxType.LOOP_FACE - - -def test_prediction_score_empty(): - assert MlBox._prediction_score(None) == (0, 0.0) - - -def test_prediction_score_uses_count_and_max_confidence(): - model = MLOutputModel() - model.add_box(MLBoxType.PIN, (0, 0, 10, 10), 0.4) - model.add_box(MLBoxType.CRYSTAL, (1, 1, 9, 9), 0.8) - - assert MlBox._prediction_score(model) == (2, 0.8) - - -def test_best_by_class_keeps_highest_confidence_per_class(): - results = [ - {"class": 1, "confidence": 0.4, "box": {"x1": 0, "y1": 0, "x2": 10, "y2": 10}}, - {"class": 1, "confidence": 0.8, "box": {"x1": 1, "y1": 1, "x2": 11, "y2": 11}}, - {"class": 2, "confidence": 0.6, "box": {"x1": 2, "y1": 2, "x2": 12, "y2": 12}}, - ] - - out = MlBox._best_by_class(results) - - assert out is not None - assert out.get_best_for_class(MLBoxType.PIN).conf == 0.8 - assert out.get_best_for_class(MLBoxType.CRYSTAL).conf == 0.6 diff --git a/tests/unit/daq/test_mount.py b/tests/unit/daq/test_mount.py deleted file mode 100644 index 2abdc2f1..00000000 --- a/tests/unit/daq/test_mount.py +++ /dev/null @@ -1,309 +0,0 @@ -from datetime import UTC, datetime, timedelta -from types import SimpleNamespace -from unittest.mock import MagicMock - -import pytest -from aarecommon.errors.exception_handler import BECCommunicationError, JFJochCommunicationError -from aarecommon.models.models import DAQOperation, DewarAddress, SampleShortInfo -from aarecommon.models.tell import TellActivityEnum, TellPhaseEnum, TellStateModel -from aareDB import SampleEventType - -from aare.daq.config import ABR_POS_MOUNT, BeamlineStateEnum -from aare.daq.daq import AareDAQ -from aare.daq.operations.mounting.models import MountingContext, MountingResult -from aare.daq.operations.screenshot.service import ScreenshotService - - -def _make_sample(sample_id: int, name: str) -> SampleShortInfo: - return SampleShortInfo( - db_id=sample_id, - puck_name="puck1", - dewar_name="dew1", - sample_name=name, - run_number=1, - user="group1", - pin=sample_id, - location=DewarAddress(segment="A", pos=1), - ) - - -def _make_daq(previous_sample: SampleShortInfo | None) -> AareDAQ: - daq = object.__new__(AareDAQ) - daq._cfg = SimpleNamespace(current_sample=previous_sample) - daq._aare = MagicMock() - daq._devs = MagicMock() - daq._set_state = MagicMock() - daq._handle_operation_error = MagicMock() - daq.save_screenshot_db = MagicMock() - daq.sync_current_sample_from_tell = MagicMock(return_value=previous_sample) - daq._create_mounting_service = MagicMock() - return daq - - -@pytest.fixture -def bare_daq(): - daq = object.__new__(AareDAQ) - daq._cfg = SimpleNamespace() - daq._devs = SimpleNamespace() - return daq - - -def test_create_mounting_service_builds_expected_context(mock_logger, bare_daq): - service = bare_daq._create_mounting_service() - - assert isinstance(service.ctx, MountingContext) - assert service.ctx.deps.cfg is bare_daq._cfg - assert service.ctx.deps.devs is bare_daq._devs - assert service.ctx.settings.mount_position == ABR_POS_MOUNT - - -def test_was_previous_sample_unmounted_since_prefers_tell_phase_confirmation(): - previous_sample = _make_sample(1, "old") - daq = _make_daq(previous_sample) - - started_at = datetime.now(UTC) - timedelta(seconds=5) - daq._safe_tell_state = MagicMock( - return_value=TellStateModel( - activity=TellActivityEnum.MOUNTING, - operation="mount", - phase=TellPhaseEnum.PICKING_NEW_SAMPLE, - last_update_ts=datetime.now(UTC).isoformat(), - last_event_class="Motion Sync", - last_event_value="Sample get on Puck", - ) - ) - daq._get_tell_events_from_redis = MagicMock(return_value=[]) - - assert daq._was_previous_sample_unmounted_since(started_at) is True - - -def test_execute_mount_and_prepare_success_uses_mounting_result_fields(): - previous_sample = _make_sample(1, "old") - target_sample = _make_sample(2, "new") - daq = _make_daq(previous_sample) - - service = MagicMock() - service.execute.return_value = MountingResult( - success=True, - mounted_sample=target_sample, - previous_sample=previous_sample, - did_unmount_previous=True, - ) - daq._create_mounting_service.return_value = service - - result = daq._execute_mount_and_prepare(target_sample) - - assert result is True - - send_calls = daq._aare.send_sample_event.call_args_list - assert send_calls[0].args[0] == previous_sample.db_id - assert send_calls[0].args[1] == SampleEventType.UNMOUNTING - assert send_calls[1].args[0] == target_sample.db_id - assert send_calls[1].args[1] == SampleEventType.MOUNTING - assert send_calls[2].args[0] == previous_sample.db_id - assert send_calls[2].args[1] == SampleEventType.UNMOUNTED - assert send_calls[3].args[0] == target_sample.db_id - assert send_calls[3].args[1] == SampleEventType.MOUNTED - - daq.save_screenshot_db.assert_called_once_with( - target_sample.db_id, f"{target_sample.db_id}_mounted" - ) - assert daq._set_state.call_args_list[0].args[0] == BeamlineStateEnum.RobotSampleExchange - assert daq._set_state.call_args_list[-1].args[0] == BeamlineStateEnum.SampleAlignment - - -def test_execute_mount_and_prepare_marks_previous_sample_unmounted_when_mount_fails_after_auto_unmount(): - previous_sample = _make_sample(1, "old") - target_sample = _make_sample(2, "new") - daq = _make_daq(previous_sample) - - service = MagicMock() - service.execute.return_value = MountingResult( - success=False, - error=RuntimeError("mount failed after unmount"), - comment="mount failed after unmount", - previous_sample=previous_sample, - ) - daq._create_mounting_service.return_value = service - daq._was_previous_sample_unmounted_since = MagicMock(return_value=True) - - result = daq._execute_mount_and_prepare(target_sample) - - assert result is False - assert daq._cfg.current_sample is None - - send_calls = daq._aare.send_sample_event.call_args_list - assert send_calls[0].args[0] == previous_sample.db_id - assert send_calls[0].args[1] == SampleEventType.UNMOUNTING - - assert send_calls[1].args[0] == target_sample.db_id - assert send_calls[1].args[1] == SampleEventType.MOUNTING - - assert send_calls[2].args[0] == previous_sample.db_id - assert send_calls[2].args[1] == SampleEventType.UNMOUNTED - assert send_calls[2].kwargs["comment"] == "Auto-unmount succeeded before mount failed" - - daq._handle_operation_error.assert_called_once() - assert daq._handle_operation_error.call_args.kwargs["operation"] == DAQOperation.MOUNT - assert daq._handle_operation_error.call_args.kwargs["sample"] == target_sample - assert daq._handle_operation_error.call_args.kwargs["event_type"] == SampleEventType.MOUNTFAILED - - assert daq._set_state.call_args_list[-1].args[0] == BeamlineStateEnum.SampleAlignment - - -def test_execute_mount_and_prepare_does_not_mark_previous_sample_unmounted_when_not_confirmed(): - previous_sample = _make_sample(1, "old") - target_sample = _make_sample(2, "new") - daq = _make_daq(previous_sample) - - service = MagicMock() - service.execute.return_value = MountingResult( - success=False, - error=RuntimeError("mount failed before unmount confirmation"), - comment="mount failed before unmount confirmation", - previous_sample=previous_sample, - ) - daq._create_mounting_service.return_value = service - daq._was_previous_sample_unmounted_since = MagicMock(return_value=False) - - result = daq._execute_mount_and_prepare(target_sample) - - assert result is False - assert daq._cfg.current_sample == previous_sample - - send_calls = daq._aare.send_sample_event.call_args_list - assert len(send_calls) == 2 - assert send_calls[0].args[0] == previous_sample.db_id - assert send_calls[0].args[1] == SampleEventType.UNMOUNTING - assert send_calls[1].args[0] == target_sample.db_id - assert send_calls[1].args[1] == SampleEventType.MOUNTING - - daq._handle_operation_error.assert_called_once() - assert daq._handle_operation_error.call_args.kwargs["event_type"] == SampleEventType.MOUNTFAILED - - -def test_execute_mount_and_prepare_unmount_success_uses_unmount_operation(): - previous_sample = _make_sample(1, "old") - daq = _make_daq(previous_sample) - - service = MagicMock() - service.execute.return_value = MountingResult( - success=True, - mounted_sample=None, - previous_sample=previous_sample, - did_unmount_previous=True, - ) - daq._create_mounting_service.return_value = service - - result = daq._execute_mount_and_prepare(None) - - assert result is True - - send_calls = daq._aare.send_sample_event.call_args_list - assert len(send_calls) == 2 - assert send_calls[0].args[0] == previous_sample.db_id - assert send_calls[0].args[1] == SampleEventType.UNMOUNTING - assert send_calls[1].args[0] == previous_sample.db_id - assert send_calls[1].args[1] == SampleEventType.UNMOUNTED - - daq.save_screenshot_db.assert_not_called() - assert daq._set_state.call_args_list[0].args[0] == BeamlineStateEnum.RobotSampleExchange - assert daq._set_state.call_args_list[-1].args[0] == BeamlineStateEnum.SampleAlignment - - -def test_raise_if_critical_jfjoch_detector_error_preserves_jfjoch_exception_family(): - daq = object.__new__(AareDAQ) - - original = JFJochCommunicationError( - "DAQ state error: detector must be idle", - operation="measure", - endpoint="/measurement/start", - base_url="http://detector", - status_code=500, - ) - - with pytest.raises(JFJochCommunicationError) as exc_info: - daq._raise_if_critical_jfjoch_detector_error(original, command="wait_till_done") - - exc = exc_info.value - assert "Critical detector error while running JFJoch command 'wait_till_done'" in str(exc) - assert exc.operation == "measure" - assert exc.endpoint == "/measurement/start" - assert exc.base_url == "http://detector" - assert exc.status_code == 500 - assert exc.critical is True - assert exc.__cause__ is original - - -def test_raise_if_critical_bec_error_preserves_bec_exception_family(): - daq = object.__new__(AareDAQ) - - original_exc = RuntimeError("planner disconnected") - original = BECCommunicationError( - "BEC operation failed", - operation="planner.move_to:data_collection", - endpoint="/bec", - base_url="redis://bec", - exception=original_exc, - ) - - with pytest.raises(BECCommunicationError) as exc_info: - daq._raise_if_critical_bec_error(original, command="planner.move_to:data_collection") - - exc = exc_info.value - assert "Critical BEC error while running 'planner.move_to:data_collection'" in str(exc) - assert exc.operation == "planner.move_to:data_collection" - assert exc.endpoint == "/bec" - assert exc.base_url == "redis://bec" - assert exc.exception is original_exc - assert exc.critical is True - assert exc.__cause__ is original - - -def test_raise_if_critical_jfjoch_detector_error_ignores_non_critical_jfjoch_errors(): - daq = object.__new__(AareDAQ) - - original = JFJochCommunicationError( - "temporary detector hiccup", - operation="measure", - endpoint="/measurement/start", - status_code=503, - ) - - assert daq._raise_if_critical_jfjoch_detector_error(original, command="wait_till_done") is None - - -def test_create_loop_centering_service_uses_shared_screenshot_service(): - daq = object.__new__(AareDAQ) - daq._cfg = SimpleNamespace() - daq._devs = SimpleNamespace() - daq._mlbox = SimpleNamespace(predict_all_best=MagicMock()) - daq._screenshot_service = MagicMock(spec=ScreenshotService) - daq._append_smargon_trace = MagicMock() - - type(daq).sample = property(lambda self: None) - type(daq).sample_geometry = property(lambda self: SimpleNamespace()) - type(daq).status = property(lambda self: SimpleNamespace()) - - service = daq._create_loop_centering_service() - - assert service.ctx.services.screenshots is daq._screenshot_service - - -def test_create_raster_service_uses_shared_screenshot_service(): - daq = object.__new__(AareDAQ) - daq._cfg = SimpleNamespace() - daq._devs = SimpleNamespace() - daq._mlbox = SimpleNamespace() - daq._jfjoch = SimpleNamespace() - daq._aare = SimpleNamespace() - daq._set_state = MagicMock() - daq._screenshot_service = MagicMock(spec=ScreenshotService) - - type(daq).sample = property(lambda self: None) - type(daq).sample_geometry = property(lambda self: SimpleNamespace()) - type(daq).status = property(lambda self: SimpleNamespace()) - - service = daq._create_raster_service() - - assert service.ctx.services.screenshots is daq._screenshot_service diff --git a/tests/unit/daq/test_raster_logic.py b/tests/unit/daq/test_raster_logic.py deleted file mode 100644 index 98b9fc2d..00000000 --- a/tests/unit/daq/test_raster_logic.py +++ /dev/null @@ -1,184 +0,0 @@ -import types -from unittest.mock import MagicMock - -import pytest -from aarecommon.math.coordinate import Coordinate, SmargonCoordinate -from aarecommon.models.raster_grid import RasterGridRequest -from jfjoch_client.exceptions import NotFoundException - -from aare.daq.operations.common.runtime import DAQRuntimeState -from aare.daq.operations.common.services import OperationServices -from aare.daq.operations.raster.models import RasterContext, RasterDependencies, RasterSettings -from aare.daq.operations.raster.service import RasterService - - -def make_request( - n_x: int, n_y: int, cell_x: float = 0.01, cell_y: float = 0.02 -) -> RasterGridRequest: - return RasterGridRequest( - exp_time_s=0.02, - transmission=1.0, - file_prefix="test", - n_x=n_x, - n_y=n_y, - grid_size_mm=Coordinate(x=cell_x, y=cell_y), - smargon_top_left=SmargonCoordinate(), - omega_deg=0.0, - ) - - -def _make_raster_context(*, jfjoch, aare, sample=None): - deps = RasterDependencies( - cfg=types.SimpleNamespace( - simulated_detector=False, - abr_meas_pos=types.SimpleNamespace(at_mm=Coordinate(x=0.0, y=0.0, z=0.0)), - get_beam_mark=lambda zoom: (0.0, 0.0), - ), - devs=types.SimpleNamespace(aerotech_omega=0.0, zoom=100.0), - mlbox=types.SimpleNamespace(), - jfjoch=jfjoch, - aare=aare, - ) - - runtime = DAQRuntimeState( - sample_provider=types.SimpleNamespace(sample=sample), - sample_geometry_provider=types.SimpleNamespace(sample_geometry=types.SimpleNamespace()), - status_provider=types.SimpleNamespace(status=None), - ) - - services = OperationServices( - screenshots=types.SimpleNamespace(save_to_db=lambda *args, **kwargs: None) - ) - - settings = RasterSettings( - auto_raster_max_images=4500, - auto_raster_min_cell_size_mm=0.005, - auto_raster_skip_if_exceed_max_image_threshold=True, - ) - - return RasterContext(deps=deps, runtime=runtime, services=services, settings=settings) - - -def make_service() -> RasterService: - jfjoch = MagicMock() - aare = MagicMock() - context = _make_raster_context(jfjoch=jfjoch, aare=aare) - return RasterService(context=context, logger=MagicMock()) - - -def test_grid_image_id_from_centre_offset_single_cell(): - request = make_request(1, 1) - image_id = RasterService._grid_image_id_from_centre_offset( - x_mm=request.grid_size_mm.x / 2.0, y_mm=request.grid_size_mm.y / 2.0, request=request - ) - assert image_id == 0 - - -def test_grid_image_id_from_centre_offset_odd_grid(): - request = make_request(5, 3, cell_x=0.01, cell_y=0.02) - - x_mm = ((request.n_x - 1) * request.grid_size_mm.x) / 2.0 - y_mm = ((request.n_y - 1) * request.grid_size_mm.y) / 2.0 - - image_id = RasterService._grid_image_id_from_centre_offset( - x_mm=x_mm, y_mm=y_mm, request=request - ) - - assert image_id == 7 - - -def test_grid_image_id_from_centre_offset_even_grid(): - request = make_request(4, 4, cell_x=0.01, cell_y=0.01) - - x_mm = ((request.n_x - 1) * request.grid_size_mm.x) / 2.0 - y_mm = ((request.n_y - 1) * request.grid_size_mm.y) / 2.0 - - image_id = RasterService._grid_image_id_from_centre_offset( - x_mm=x_mm, y_mm=y_mm, request=request - ) - - assert image_id == 6 - - -def test_grid_image_id_from_centre_offset_vertical_scan(): - request = make_request(1, 50, cell_x=0.01, cell_y=0.005) - - x_mm = request.grid_size_mm.x / 2.0 - y_mm = ((request.n_y - 1) * request.grid_size_mm.y) / 2.0 - - image_id = RasterService._grid_image_id_from_centre_offset( - x_mm=x_mm, y_mm=y_mm, request=request - ) - - assert image_id == 24 - - -def test_grid_image_id_from_centre_offset_rejects_non_positive_cell_size(): - request = make_request(3, 3) - request.grid_size_mm = Coordinate(x=0.0, y=0.01) - - with pytest.raises(ValueError, match="grid_size_mm must be positive"): - RasterService._grid_image_id_from_centre_offset(x_mm=0.0, y_mm=0.0, request=request) - - -def test_grid_image_id_from_centre_offset_rejects_zero_dimensions(): - request = make_request(1, 1) - request.n_x = 0 - - with pytest.raises(ValueError, match="Raster grid dimensions must be >= 1"): - RasterService._grid_image_id_from_centre_offset(x_mm=0.0, y_mm=0.0, request=request) - - -def test_upload_raster_diffraction_preview_skips_out_of_range_image_id(): - service = make_service() - - request = make_request(2, 2) - scan_result = MagicMock() - scan_result.images = [MagicMock(), MagicMock(), MagicMock(), MagicMock()] - - service._upload_raster_diffraction_preview( - sample_id=123, filename="preview", image_id=10, scan_result=scan_result, request=request - ) - - service.ctx.deps.jfjoch.get_diffraction_image.assert_not_called() - service.ctx.deps.aare.upload_jpg.assert_not_called() - - -def test_upload_raster_diffraction_preview_ignores_not_found(): - service = make_service() - - request = make_request(2, 2) - scan_result = MagicMock() - scan_result.images = [MagicMock(), MagicMock(), MagicMock(), MagicMock()] - service.ctx.deps.jfjoch.get_diffraction_image.side_effect = NotFoundException() - - service._upload_raster_diffraction_preview( - sample_id=123, filename="preview", image_id=2, scan_result=scan_result, request=request - ) - - service.ctx.deps.jfjoch.get_diffraction_image.assert_called_once_with( - 2, show_spots=True, show_res_est=True, show_beam_center=True - ) - service.ctx.deps.aare.upload_jpg.assert_not_called() - - -def test_upload_raster_diffraction_preview_uploads_when_present(): - service = make_service() - - request = make_request(2, 2) - scan_result = MagicMock() - scan_result.images = [MagicMock(), MagicMock(), MagicMock(), MagicMock()] - scan_result.images[2].spots = 479 - scan_result.images[2].res = 2.23 - service.ctx.deps.jfjoch.get_diffraction_image.return_value = b"jpeg-bytes" - - service._upload_raster_diffraction_preview( - sample_id=123, filename="preview", image_id=2, scan_result=scan_result, request=request - ) - - service.ctx.deps.jfjoch.get_diffraction_image.assert_called_once_with( - 2, show_spots=True, show_res_est=True, show_beam_center=True - ) - service.ctx.deps.aare.upload_jpg.assert_called_once_with( - 123, "preview", b"jpeg-bytes", message="Raster diffraction (479 spots, 2.23 Å)" - ) diff --git a/tests/unit/daq/test_rotation_params.py b/tests/unit/daq/test_rotation_params.py deleted file mode 100644 index 6f317333..00000000 --- a/tests/unit/daq/test_rotation_params.py +++ /dev/null @@ -1,45 +0,0 @@ -import importlib.util -from unittest.mock import MagicMock, patch - -import pytest -from aarecommon.models.models import SampleShortInfo - -from aare.beamline_dispatch.beamline_dispatch import get_beamline_dispatch -from aare.daq.daq import AareDAQ - - -@pytest.fixture() -def daq(mock_daq): - mock_daq.sync_current_sample_from_tell = MagicMock( - return_value=SampleShortInfo( - db_id=12345, - puck_name="T1", - pin=1, - dewar_name="TEST", - sample_name="test_sample", - run_number=42, - ) - ) - mock_daq.spreadsheet_params = MagicMock(return_value=(None, "/data/abcd/")) - mock_daq._cfg = MagicMock(auto_params=None) - return mock_daq - - -@pytest.mark.skipif( - importlib.util.find_spec("pxii_bec") is None, reason="run only for pxii flavour" -) -def test_pxii_default_params(daq: AareDAQ): - with patch.dict("os.environ", {"BEAMLINE": "X10SA"}): - daq._dispatch = get_beamline_dispatch() - params = daq.get_collection_params(prefer_smart=False)[0] - assert params.transmission == 0.1 - - -@pytest.mark.skipif( - importlib.util.find_spec("pxiii_bec") is None, reason="run only for pxiii flavour" -) -def test_pxiii_default_params(daq: AareDAQ): - with patch.dict("os.environ", {"BEAMLINE": "X06DA"}): - daq._dispatch = get_beamline_dispatch() - params = daq.get_collection_params(prefer_smart=False)[0] - assert params.transmission == 1 diff --git a/tests/unit/daq/test_rotation_screening_diffraction.py b/tests/unit/daq/test_rotation_screening_diffraction.py deleted file mode 100644 index 414f0839..00000000 --- a/tests/unit/daq/test_rotation_screening_diffraction.py +++ /dev/null @@ -1,68 +0,0 @@ -from types import SimpleNamespace -from unittest.mock import MagicMock - -from aare.daq.operations.rotation.service import RotationService - - -def _img(number, angle=0.0, spots=0, res=0.0): - return SimpleNamespace(number=number, angle=angle, spots=spots, res=res) - - -def _make_service(jfjoch, aare): - ctx = SimpleNamespace(deps=SimpleNamespace(jfjoch=jfjoch, aare=aare)) - return RotationService(context=ctx, logger=MagicMock()) - - -def test_screening_diffraction_uploads_one_image_per_wedge(): - jfjoch = MagicMock() - jfjoch.get_diffraction_image.side_effect = lambda image_id, **kw: f"jpeg-{image_id}".encode() - aare = MagicMock() - svc = _make_service(jfjoch, aare) - - scan_result = SimpleNamespace(images=[_img(0, 0.0, 245, 2.1), _img(1, 90.0, 12, 8.5)]) - svc._ingest_screening_diffraction(SimpleNamespace(db_id=123), scan_result) - - # one fetch + one upload per wedge, with spots + resolution-estimate ring - # + beam center overlays on - assert jfjoch.get_diffraction_image.call_count == 2 - for call in jfjoch.get_diffraction_image.call_args_list: - assert call.kwargs["show_spots"] is True - assert call.kwargs["show_res_est"] is True - assert call.kwargs["show_beam_center"] is True - - assert aare.upload_jpg.call_count == 2 - first = aare.upload_jpg.call_args_list[0] - assert first.args[:3] == (123, "123_screening_diffraction_0", b"jpeg-0") - assert "Screening diffraction (wedge 1" in first.kwargs["message"] - assert "245 spots" in first.kwargs["message"] - - -def test_screening_diffraction_skips_images_without_id(): - jfjoch = MagicMock() - jfjoch.get_diffraction_image.return_value = b"jpeg" - aare = MagicMock() - svc = _make_service(jfjoch, aare) - - svc._ingest_screening_diffraction( - SimpleNamespace(db_id=7), SimpleNamespace(images=[SimpleNamespace(number=None), _img(3)]) - ) - - jfjoch.get_diffraction_image.assert_called_once_with( - 3, show_spots=True, show_res_est=True, show_beam_center=True - ) - assert aare.upload_jpg.call_count == 1 - - -def test_screening_diffraction_tolerates_fetch_failure(): - jfjoch = MagicMock() - jfjoch.get_diffraction_image.side_effect = [Exception("buffer miss"), b"jpeg-6"] - aare = MagicMock() - svc = _make_service(jfjoch, aare) - - svc._ingest_screening_diffraction( - SimpleNamespace(db_id=9), SimpleNamespace(images=[_img(5), _img(6)]) - ) - - # first wedge failed and was skipped; second still uploaded - assert aare.upload_jpg.call_count == 1 - assert aare.upload_jpg.call_args.args[1] == "9_screening_diffraction_6" diff --git a/tests/unit/daq/test_server_hw_lock.py b/tests/unit/daq/test_server_hw_lock.py deleted file mode 100644 index 9113f162..00000000 --- a/tests/unit/daq/test_server_hw_lock.py +++ /dev/null @@ -1,73 +0,0 @@ -from unittest.mock import patch - -import fakeredis -import pytest -from redis.lock import Lock as RedisLock - -LOCK_NAME = "SIMULATED:hardware_busy_lock" -AUTH = {"Authorization": "Bearer fake-token"} - -THREAD_LOCAL = False - - -@pytest.fixture -def fake_redis(): - return fakeredis.FakeRedis(decode_responses=True) - - -@pytest.fixture -def hw_lock(server_module, client, fake_redis, monkeypatch): - """This worker's lock. - - Depends on ``client`` so that TestClient's lifespan (which overwrites - ``hardware_busy_lock``) has already run by the time we patch. - """ - lock = RedisLock(fake_redis, name=LOCK_NAME, thread_local=THREAD_LOCAL) - monkeypatch.setattr(server_module, "hardware_busy_lock", lock) - return lock - - -@pytest.fixture -def other_worker(fake_redis): - """A second uvicorn worker's view of the same lock in Redis.""" - return RedisLock(fake_redis, name=LOCK_NAME, thread_local=THREAD_LOCAL) - - -def test_endpoint_acquires_and_releases_the_lock(client, hw_lock, other_worker): - with patch("aare.daq.auth.check_jwt_rw"), patch("aare.daq.server.daq"): - response = client.put("/beamline/omega?val=10.5", headers=AUTH) - - assert response.status_code == 200 - # Released on the way out, so a second worker can take it. - assert not hw_lock.owned() - assert other_worker.acquire(blocking=False) - - -def test_endpoint_is_503_while_another_worker_holds_the_lock(client, hw_lock, other_worker): - assert other_worker.acquire(blocking=False) - - with patch("aare.daq.auth.check_jwt_rw"), patch("aare.daq.server.daq"): - response = client.put("/beamline/omega?val=10.5", headers=AUTH) - - assert response.status_code == 503 - assert response.json()["exception_class"] == "BeamlineBusyException" - # The rejected request must not have stolen or released the other worker's lock. - assert other_worker.owned() - assert not hw_lock.owned() - - -async def test_lock_hw_is_reentrant_for_the_owning_worker(server_module, hw_lock): - assert hw_lock.acquire(blocking=False) - - async with server_module._lock_hw(): - assert hw_lock.owned() - - assert hw_lock.owned(), "re-entrant exit released a lock it did not acquire" - - -async def test_lock_is_released_when_the_handler_raises(server_module, hw_lock): - with pytest.raises(RuntimeError): - async with server_module._lock_hw(): - raise RuntimeError("handler blew up") - - assert not hw_lock.owned(), "hardware lock leaked after an exception" diff --git a/tests/unit/daq/test_spreadsheetupdater.py b/tests/unit/daq/test_spreadsheetupdater.py deleted file mode 100644 index 078d3f36..00000000 --- a/tests/unit/daq/test_spreadsheetupdater.py +++ /dev/null @@ -1,122 +0,0 @@ -import json -from types import SimpleNamespace -from unittest.mock import MagicMock, patch - -import pytest - -from aare.daq.spreadsheetupdater import get_ws_headers, on_message, set_spreadsheet_in_redis - - -@pytest.fixture -def mock_config(): - with patch("aare.daq.spreadsheetupdater.config") as mock: - mock._bl = "X10SA" - mock.redis = MagicMock() - yield mock - - -def test_get_ws_headers_success(): - with patch("os.getenv", return_value="secret"): - headers = get_ws_headers() - assert headers == ["X-Shared-Password: secret"] - - -def test_get_ws_headers_fail(): - with patch("os.getenv", return_value=None), pytest.raises(ValueError): - get_ws_headers() - - -def test_set_spreadsheet_in_redis(mock_config): - data = {"test": "data"} - with patch("aare.daq.spreadsheetupdater.config") as mock_cfg_internal: - mock_client = MagicMock() - mock_cfg_internal.redis = mock_client - - set_spreadsheet_in_redis(data) - - found = False - for attr in dir(mock_cfg_internal): - val = getattr(mock_cfg_internal, attr) - if isinstance(val, MagicMock) and val.set.called: - found = True - break - assert found or mock_client.set.called - - -def test_on_message_success(mock_config): - normal_sample = SimpleNamespace( - id=1, - sample_name="S1", - run_number=100, - pgroup="p12345", - position=1, - priority=1, - mount_count=0, - rotation_count=0, - raster_count=0, - screening_count=0, - data_collection_parameters={}, - ) - ref_sample = SimpleNamespace( - id=2, - sample_name="R1", - run_number=1, - pgroup="p12345", - position=1, - priority=1, - mount_count=0, - rotation_count=0, - raster_count=0, - screening_count=0, - data_collection_parameters={}, - ) - - mock_pucks = [ - SimpleNamespace( - puck_name="P1", dewar_name="D1", tell_position="A1", samples=[normal_sample] - ), - SimpleNamespace(puck_name="Ref", dewar_name="D1", tell_position="X1", samples=[ref_sample]), - ] - - message = json.dumps({"samples": [{}, {}]}) - - with patch("aare.daq.spreadsheetupdater.PuckWithTellPosition", side_effect=mock_pucks): - on_message(None, message) - - calls = mock_config.redis.set.call_args_list - written_keys = [call.args[0] for call in calls] - - assert "X10SA:sample_spreadsheet" in written_keys - assert "X10SA:reference-tools" in written_keys - - -def test_on_message_empty_ref(mock_config): - message = json.dumps( - { - "samples": [ - { - "id": 1, - "barcode": "B1", - "position": "P1", - "puck_name": "P1", - "puck_type": "UniPuck", - "puck_location_in_dewar": 1, - "dewar_id": 1, - "pgroup": "p12345", - "dewar_name": "D1", - "tell_position": "A1", - "samples": [], - } - ] - } - ) - - on_message(None, message) - - ref_key = "X10SA:reference-tools" - mock_config.redis.delete.assert_called_with(ref_key) - - -def test_on_message_invalid_json(mock_config): - on_message(None, "invalid json") - mock_config.redis.set.assert_not_called() diff --git a/tests/unit/daq/test_tell_state_updater.py b/tests/unit/daq/test_tell_state_updater.py deleted file mode 100644 index e20ee32e..00000000 --- a/tests/unit/daq/test_tell_state_updater.py +++ /dev/null @@ -1,153 +0,0 @@ -from aarecommon.models.tell import TellActivityEnum, TellPhaseEnum - -from aare.daq.tell_state_machine import advance_tell_state, initial_tell_state - - -def test_mount_with_auto_unmount_uses_internal_phases(): - state = initial_tell_state() - - state = advance_tell_state( - state, "shell", 'mount("F", 2, 1, force=1, read_dm=0, auto_unmount=1)' - ) - assert state.activity == TellActivityEnum.MOUNTING - assert state.operation == "mount" - assert state.phase == TellPhaseEnum.PREPARING - assert state.sample_position == "F2-1" - assert state.mount_success is None - - state = advance_tell_state(state, "shell", "got result True") - assert state.activity == TellActivityEnum.MOUNTING - assert state.operation == "mount" - assert state.phase == TellPhaseEnum.PREPARING - assert state.mount_success is None - - state = advance_tell_state(state, "shell", "unmount: None None None True") - assert state.activity == TellActivityEnum.UNMOUNTING - assert state.operation == "mount" - assert state.phase == TellPhaseEnum.AUTO_UNMOUNT - - state = advance_tell_state(state, "Motion Sync", "Sample get from Gonio") - assert state.activity == TellActivityEnum.UNMOUNTING - assert state.operation == "mount" - assert state.phase == TellPhaseEnum.RETURNING_OLD_SAMPLE - - state = advance_tell_state(state, "Motion Sync", "Sample put on Puck") - assert state.activity == TellActivityEnum.UNMOUNTING - assert state.operation == "mount" - assert state.phase == TellPhaseEnum.OLD_SAMPLE_RETURNED - - state = advance_tell_state(state, "Motion Sync", "Sample get on Puck") - assert state.activity == TellActivityEnum.MOUNTING - assert state.operation == "mount" - assert state.phase == TellPhaseEnum.PICKING_NEW_SAMPLE - - state = advance_tell_state(state, "Motion Sync", "Sample put on Gonio") - assert state.activity == TellActivityEnum.MOUNTING - assert state.operation == "mount" - assert state.phase == TellPhaseEnum.PLACING_NEW_SAMPLE - - state = advance_tell_state(state, "Motion Sync", "Robot Clear after mount") - assert state.activity == TellActivityEnum.MOUNTING - assert state.operation == "mount" - assert state.phase == TellPhaseEnum.FINALIZING - - state = advance_tell_state(state, "shell", "setting mounted sample to F2-1") - assert state.activity == TellActivityEnum.MOUNTING - assert state.operation == "mount" - assert state.phase == TellPhaseEnum.COMPLETE - assert state.sample_position == "F2-1" - assert state.mount_success is True - - state = advance_tell_state(state, "state", "Ready") - assert state.activity == TellActivityEnum.IDLE - assert state.operation == "idle" - assert state.phase == TellPhaseEnum.IDLE - assert state.message == "Ready" - - -def test_plain_unmount_reaches_complete_before_ready(): - state = initial_tell_state() - - state = advance_tell_state(state, "shell", "unmount()") - assert state.activity == TellActivityEnum.UNMOUNTING - assert state.operation == "unmount" - assert state.phase == TellPhaseEnum.PREPARING - - state = advance_tell_state(state, "Motion Sync", "Sample get from Gonio") - assert state.phase == TellPhaseEnum.RETURNING_OLD_SAMPLE - - state = advance_tell_state(state, "Motion Sync", "Sample put on Puck") - assert state.phase == TellPhaseEnum.COMPLETE - assert state.mount_success is True - - state = advance_tell_state(state, "state", "Ready") - assert state.activity == TellActivityEnum.IDLE - assert state.operation == "idle" - assert state.phase == TellPhaseEnum.IDLE - - -def test_gripper_detection_moves_to_failed_phase(): - state = initial_tell_state() - state = advance_tell_state(state, "shell", 'mount("F", 2, 1)') - state = advance_tell_state(state, "Gripper detection", "Pin is lost") - - assert state.activity == TellActivityEnum.ERROR - assert state.phase == TellPhaseEnum.FAILED - assert state.mount_success is False - assert state.mount_error == "Pin is lost" - - -def test_got_result_false_during_auto_unmount_is_not_error(): - state = initial_tell_state() - - state = advance_tell_state( - state, "shell", 'mount("D", 5, 14, force=1, read_dm=0, auto_unmount=1)' - ) - assert state.activity == TellActivityEnum.MOUNTING - assert state.operation == "mount" - assert state.phase == TellPhaseEnum.PREPARING - - state = advance_tell_state(state, "shell", "unmount: None None None True") - assert state.activity == TellActivityEnum.UNMOUNTING - assert state.operation == "mount" - assert state.phase == TellPhaseEnum.AUTO_UNMOUNT - - state = advance_tell_state(state, "Motion Sync", "Sample get from Gonio") - assert state.activity == TellActivityEnum.UNMOUNTING - assert state.phase == TellPhaseEnum.RETURNING_OLD_SAMPLE - - state = advance_tell_state(state, "shell", "got result False") - assert state.activity == TellActivityEnum.UNMOUNTING - assert state.operation == "mount" - assert state.phase == TellPhaseEnum.RETURNING_OLD_SAMPLE - assert state.mount_success is None - assert state.mount_error in (None, "") - - state = advance_tell_state(state, "Motion Sync", "Sample put on Puck") - assert state.activity == TellActivityEnum.UNMOUNTING - assert state.phase == TellPhaseEnum.OLD_SAMPLE_RETURNED - - state = advance_tell_state(state, "Motion Sync", "Sample get on Puck") - assert state.activity == TellActivityEnum.MOUNTING - assert state.phase == TellPhaseEnum.PICKING_NEW_SAMPLE - - -def test_mount_phase_after_old_sample_returned_confirms_auto_unmount_completed(): - state = initial_tell_state() - - state = advance_tell_state( - state, "shell", 'mount("F", 2, 1, force=1, read_dm=0, auto_unmount=1)' - ) - state = advance_tell_state(state, "shell", "unmount: None None None True") - state = advance_tell_state(state, "Motion Sync", "Sample get from Gonio") - state = advance_tell_state(state, "Motion Sync", "Sample put on Puck") - assert state.phase == TellPhaseEnum.OLD_SAMPLE_RETURNED - - state = advance_tell_state(state, "Motion Sync", "Sample get on Puck") - assert state.phase == TellPhaseEnum.PICKING_NEW_SAMPLE - - state = advance_tell_state(state, "Motion Sync", "Sample put on Gonio") - assert state.phase == TellPhaseEnum.PLACING_NEW_SAMPLE - - state = advance_tell_state(state, "Motion Sync", "Robot Clear after mount") - assert state.phase == TellPhaseEnum.FINALIZING diff --git a/tests/unit/daq/test_tellupdater.py b/tests/unit/daq/test_tellupdater.py deleted file mode 100644 index e6af1767..00000000 --- a/tests/unit/daq/test_tellupdater.py +++ /dev/null @@ -1,191 +0,0 @@ -import json -from unittest.mock import MagicMock, patch - -from aare.daq import tellupdater -from aare.daq.config import BeamlineConfig - - -def test_compare_and_report_change(): - class MockPuck: - def __init__(self, puck_name, dewar_id, pos): - self.puck_name = puck_name - self.dewar_id = dewar_id - self.tell_position = pos - - old = [MockPuck("p1", 1, "A1"), MockPuck("p2", 1, "A2")] - new = [MockPuck("p2", 1, "A2"), MockPuck("p3", 1, "A3")] - - joined, left = tellupdater.compare_and_report_change(old, new) - assert joined == {("p3", 1, "A3")} - assert left == {("p1", 1, "A1")} - - -def test_compare_and_report_change_ignore_x1(): - class MockPuck: - def __init__(self, puck_name, dewar_id, pos): - self.puck_name = puck_name - self.dewar_id = dewar_id - self.tell_position = pos - - old = [MockPuck("p1", 1, "X1")] - new = [MockPuck("p2", 1, "X1")] - - joined, left = tellupdater.compare_and_report_change(old, new) - assert joined == set() - assert left == set() - - -@patch("aare.daq.tellupdater.tell_client") -@patch("aare.daq.tellupdater.aare_db") -def test_handle_tell_change_event(mock_db, mock_tell): - mock_tell.get_detected_pucks.return_value = ["puck1", "puck2"] - tellupdater.handle_tell_change_event() - mock_tell.get_detected_pucks.assert_called_once() - mock_db.set_pucks_beamline.assert_called_with(["puck1", "puck2"]) - - -@patch("aare.daq.tellupdater.tell_client") -def test_ws_update_samples_info(mock_tell): - pucks = [{"id": "1"}] - tellupdater.ws_update_samples_info(pucks) - mock_tell.set_samples_info.assert_called_with(pucks) - - -def test_on_sse_event(): - class MockEvent: - def __init__(self, event, data): - self.event = event - self.data = data - - event = MockEvent("DewarContentUpdate", "some data") - with patch("aare.daq.tellupdater.handle_tell_change_event") as mock_handle: - tellupdater.on_sse_event(event) - mock_handle.assert_called_once() - - -def test_extract_tracked_tell_event_with_json_payload(): - tracked = tellupdater.extract_tracked_tell_event( - "Gripper detection", json.dumps({"value": "Pin still in Gripper"}) - ) - assert tracked == ("Gripper detection", "Pin still in Gripper") - - -def test_extract_tracked_tell_event_for_standalone_message(): - tracked = tellupdater.extract_tracked_tell_event( - "Motion Sync", json.dumps({"message": "Sample put on Gonio"}) - ) - assert tracked == ("Motion Sync", "Sample put on Gonio") - - -def test_on_sse_event_tracks_interesting_event(): - class MockEvent: - def __init__(self, event, data): - self.event = event - self.data = data - - tellupdater.latest_tell_events.clear() - event = MockEvent("Motion Task", json.dumps({"value": "dry"})) - - with patch("aare.daq.tellupdater.handle_tell_change_event") as mock_handle: - tellupdater.on_sse_event(event) - mock_handle.assert_not_called() - - assert tellupdater.latest_tell_events["Motion Task"] == "dry" - - -def test_record_tell_event_logs_to_journal(): - tellupdater.latest_tell_events.clear() - tellupdater.tell_event_history.clear() - - with patch("aare.daq.tellupdater.logger.info") as mock_info: - tellupdater.record_tell_event("Motion Sync", "Sample put on Gonio") - - assert tellupdater.latest_tell_events["Motion Sync"] == "Sample put on Gonio" - mock_info.assert_called_once_with("[TELL][JOURNAL] event=Motion Sync value=Sample put on Gonio") - - -def test_record_tell_event_writes_history_to_redis(): - tellupdater.latest_tell_events.clear() - tellupdater.tell_event_history.clear() - - mock_config = MagicMock(spec=BeamlineConfig) - mock_config.redis = MagicMock() - mock_config._bl = "x10sa" - - with patch("aare.daq.tellupdater.config", mock_config): - tellupdater.record_tell_event("Motion Task", "dry") - - mock_config.redis.set.assert_called_once() - redis_key, redis_value = mock_config.redis.set.call_args.args - assert redis_key == "x10sa:tell_events" - - payload = json.loads(redis_value) - assert len(payload) == 1 - assert payload[0]["class"] == "Motion Task" - assert payload[0]["event"] == "dry" - assert "timestamp" in payload[0] - - -def test_record_tell_event_keeps_last_25_events(): - tellupdater.latest_tell_events.clear() - tellupdater.tell_event_history.clear() - - mock_config = MagicMock() - mock_config._bl = "x10sa" - - with patch("aare.daq.tellupdater.config", mock_config): - for idx in range(30): - tellupdater.record_tell_event("Motion Sync", f"event-{idx}") - - redis_key, redis_value = mock_config.redis.set.call_args.args - assert redis_key == "x10sa:tell_events" - - payload = json.loads(redis_value) - assert len(payload) == 25 - assert payload[0]["event"] == "event-5" - assert payload[-1]["event"] == "event-29" - - -def test_on_message_logs_json_decode_error(): - with patch("aare.daq.tellupdater.logger.exception") as mock_exception: - tellupdater.on_message(None, "{invalid") - - mock_exception.assert_called_once_with("[WS] Failed to process message") - - -@patch("aare.daq.tellupdater.tell_client") -@patch("aare.daq.tellupdater.aare_db") -def test_handle_tell_change_event_logs_failure(mock_db, mock_tell): - mock_tell.get_detected_pucks.side_effect = ValueError("boom") - - with patch("aare.daq.tellupdater.logger.exception") as mock_exception: - tellupdater.handle_tell_change_event() - - mock_exception.assert_called_once_with("[SSE] Failed to update puck state after TELL change") - - -@patch("aare.daq.tellupdater.websocket.WebSocketApp") -def test_on_message(mock_ws_app): - message = json.dumps( - [ - { - "id": 1, - "barcode": "B1", - "position": "P1", - "puck_name": "Puck1", - "puck_type": "Type1", - "puck_location_in_dewar": 1, - "dewar_id": 1, - "dewar_name": "Dewar1", - "pgroup": "p12345", - "tell_position": "A1", - } - ] - ) - with ( - patch("aare.daq.tellupdater.ws_update_samples_info") as mock_update, - patch("aare.daq.tellupdater.handle_tell_change_event"), - ): - tellupdater.current_pucks = [] - tellupdater.on_message(None, message) - mock_update.assert_called_once() diff --git a/tests/unit/daq/test_workflows.py b/tests/unit/daq/test_workflows.py deleted file mode 100644 index 4612b4e3..00000000 --- a/tests/unit/daq/test_workflows.py +++ /dev/null @@ -1,242 +0,0 @@ -from unittest.mock import MagicMock - -import pytest - -from aare.daq.config import ABR_OMEGA_MOUNT, ABR_POS_MOUNT -from aare.daq.workflows import ( - common2dh, - common_2rse, - dc2rse, - dc2sa, - dc2xtal_snapshot, - dh2sa, - sa2dc, - sa2dh, - sa2rse, - sa2se, - sa2xrf, - sa2xtal_snapshot, - se2sa, - xtal_snapshot2dc, - xtal_snapshot2sa, -) -from aare.devices.area_detector import AutoEnum -from aare.devices.bec_worker import BeamlineState - - -@pytest.fixture -def mock_devs(): - devs = MagicMock() - devs.bec_worker = MagicMock() - devs.bec_worker.planner = MagicMock() - devs.bec_worker.move_to = MagicMock() - devs.dtz = None - return devs - - -@pytest.fixture -def mock_cfg(): - cfg = MagicMock() - cfg.abr_meas_pos = "MEAS_POS" - cfg.dtz = None - cfg.dtz_safe_position = None - return cfg - - -def _assert_bec_moved(devs, state): - planner_calls = ( - devs.bec_worker.planner.move_to.call_args_list if devs.bec_worker is not None else [] - ) - direct_calls = devs.bec_worker.move_to.call_args_list if devs.bec_worker is not None else [] - - assert any(call.args == (state,) for call in planner_calls) or any( - call.args == (state,) for call in direct_calls - ), f"BEC was not asked to move to {state}" - - -def test_common_2rse(mock_devs, mock_cfg): - mock_devs.bec_worker = MagicMock() - mock_devs.bec_worker.planner = MagicMock() - mock_devs.bec_worker.move_to = MagicMock() - - common_2rse(mock_devs, mock_cfg) - - _assert_bec_moved(mock_devs, BeamlineState.ROBOT_SAMPLE_EXCHANGE) - mock_devs.smargon_move_home.assert_called_once() - assert mock_devs.aerotech_pos == ABR_POS_MOUNT - - -def test_common_2rse_moves_detector_to_safe_position_when_configured(mock_devs, mock_cfg): - mock_devs.dtz = 200 - mock_cfg.dtz_safe_position = 600 - - common_2rse(mock_devs, mock_cfg) - - mock_devs.bec_worker.det_z.assert_called_once_with(value=600) - _assert_bec_moved(mock_devs, BeamlineState.ROBOT_SAMPLE_EXCHANGE) - - -def test_common_2rse_ignores_missing_detector_safe_position(mock_devs, mock_cfg): - mock_devs.dtz = 200 - mock_cfg.dtz_safe_position = None - - common_2rse(mock_devs, mock_cfg) - - mock_devs.bec_worker.det_z.assert_not_called() - _assert_bec_moved(mock_devs, BeamlineState.ROBOT_SAMPLE_EXCHANGE) - - -def test_dc2sa_moves_detector_to_safe_position_when_configured(mock_devs, mock_cfg): - mock_devs.dtz = 200 - mock_cfg.dtz_safe_position = 600 - - dc2sa(mock_devs, mock_cfg) - - mock_devs.bec_worker.det_z.assert_called_once_with(value=600) - _assert_bec_moved(mock_devs, BeamlineState.SAMPLE_ALIGNMENT) - assert mock_devs.aerotech_pos == mock_cfg.abr_meas_pos - - -def test_dc2sa_ignores_missing_detector_safe_position(mock_devs, mock_cfg): - mock_devs.dtz = 200 - mock_cfg.dtz_safe_position = None - - dc2sa(mock_devs, mock_cfg) - - mock_devs.bec_worker.det_z.assert_not_called() - _assert_bec_moved(mock_devs, BeamlineState.SAMPLE_ALIGNMENT) - assert mock_devs.aerotech_pos == mock_cfg.abr_meas_pos - - -def test_sa2se(mock_devs, mock_cfg): - mock_devs.bec_worker = MagicMock() - mock_devs.bec_worker.planner = MagicMock() - mock_devs.bec_worker.move_to = MagicMock() - - sa2se(mock_devs, mock_cfg) - - mock_devs.samcam_auto.assert_any_call(AutoEnum.AUTO) - _assert_bec_moved(mock_devs, BeamlineState.MANUAL_SAMPLE_EXCHANGE) - assert mock_devs.aerotech_pos == ABR_POS_MOUNT - assert mock_devs.aerotech_omega == ABR_OMEGA_MOUNT - mock_devs.smargon_move_home.assert_called_once() - mock_devs.samcam_auto.assert_any_call(AutoEnum.ONCE) - - -def test_sa2rse(mock_devs, mock_cfg): - sa2rse(mock_devs, mock_cfg) - mock_devs.smargon_move_home.assert_called_once() - - -def test_sa2xtal_snapshot(mock_devs, mock_cfg): - mock_devs.bec_worker = MagicMock() - mock_devs.bec_worker.planner = MagicMock() - mock_devs.bec_worker.move_to = MagicMock() - - sa2xtal_snapshot(mock_devs, mock_cfg) - assert mock_devs.samcam_settings.exposure == 0.001 - _assert_bec_moved(mock_devs, BeamlineState.XTAL_SNAPSHOT) - - -def test_dc2xtal_snapshot(mock_devs, mock_cfg): - mock_devs.bec_worker = MagicMock() - mock_devs.bec_worker.planner = MagicMock() - mock_devs.bec_worker.move_to = MagicMock() - - dc2xtal_snapshot(mock_devs, mock_cfg) - assert mock_devs.samcam_settings.exposure == 0.001 - _assert_bec_moved(mock_devs, BeamlineState.XTAL_SNAPSHOT) - - -def test_xtal_snapshot2dc(mock_devs, mock_cfg): - mock_devs.bec_worker = MagicMock() - mock_devs.bec_worker.planner = MagicMock() - mock_devs.bec_worker.move_to = MagicMock() - - xtal_snapshot2dc(mock_devs, mock_cfg) - _assert_bec_moved(mock_devs, BeamlineState.DATA_COLLECTION) - - -def test_xtal_snapshot2sa(mock_devs, mock_cfg): - mock_devs.bec_worker = MagicMock() - mock_devs.bec_worker.planner = MagicMock() - mock_devs.bec_worker.move_to = MagicMock() - - xtal_snapshot2sa(mock_devs, mock_cfg) - _assert_bec_moved(mock_devs, BeamlineState.SAMPLE_ALIGNMENT) - - -def test_dc2rse(mock_devs, mock_cfg): - dc2rse(mock_devs, mock_cfg) - mock_devs.smargon_move_home.assert_called_once() - - -def test_se2sa(mock_devs, mock_cfg): - mock_devs.bec_worker = MagicMock() - mock_devs.bec_worker.planner = MagicMock() - mock_devs.bec_worker.move_to = MagicMock() - - se2sa(mock_devs, mock_cfg) - _assert_bec_moved(mock_devs, BeamlineState.SAMPLE_ALIGNMENT) - assert mock_devs.aerotech_pos == mock_cfg.abr_meas_pos - - -def test_sa2dc(mock_devs, mock_cfg): - mock_devs.bec_worker = MagicMock() - mock_devs.bec_worker.planner = MagicMock() - mock_devs.bec_worker.move_to = MagicMock() - - sa2dc(mock_devs, mock_cfg) - _assert_bec_moved(mock_devs, BeamlineState.DATA_COLLECTION) - - -def test_dc2sa(mock_devs, mock_cfg): - mock_devs.bec_worker = MagicMock() - mock_devs.bec_worker.planner = MagicMock() - mock_devs.bec_worker.move_to = MagicMock() - mock_cfg.dtz = None - - dc2sa(mock_devs, mock_cfg) - _assert_bec_moved(mock_devs, BeamlineState.SAMPLE_ALIGNMENT) - assert mock_devs.aerotech_pos == mock_cfg.abr_meas_pos - - -def test_sa2xrf(mock_devs, mock_cfg): - mock_devs.bec_worker = MagicMock() - mock_devs.bec_worker.planner = MagicMock() - mock_devs.bec_worker.move_to = MagicMock() - - sa2xrf(mock_devs, mock_cfg) - _assert_bec_moved(mock_devs, BeamlineState.FLUX_MEASUREMENT) - - -def test_sa2dh(mock_devs, mock_cfg): - mock_devs.tell.get_mounted_sample.return_value = "Sample" - sa2dh(mock_devs, mock_cfg) - mock_devs.tell.unmount.assert_called_with(wait=True) - mock_devs.tell.dry.assert_called_with(wait_cold=-1, wait=False) - - -def test_dh2sa(mock_devs, mock_cfg): - mock_devs.bec_worker = MagicMock() - mock_devs.bec_worker.planner = MagicMock() - mock_devs.bec_worker.move_to = MagicMock() - - dh2sa(mock_devs, mock_cfg) - _assert_bec_moved(mock_devs, BeamlineState.SAMPLE_ALIGNMENT) - - -def test_common2dh_skips_dry_when_tell_already_in_ppark(mock_devs, mock_cfg): - mock_devs.bec_worker = MagicMock() - mock_devs.bec_worker.planner = MagicMock() - mock_devs.bec_worker.move_to = MagicMock() - mock_devs.tell = MagicMock() - mock_devs.tell.is_position.return_value = True - mock_devs.tell.get_mounted_sample.return_value = None - - common2dh(mock_devs, mock_cfg) - - mock_devs.tell.is_position.assert_called_once_with("pPark") - mock_devs.tell.get_mounted_sample.assert_called_once_with() - mock_devs.tell.unmount.assert_not_called() - mock_devs.tell.dry.assert_not_called() diff --git a/tests/unit/devices/test_aerotech.py b/tests/unit/devices/test_aerotech.py deleted file mode 100644 index da84cd14..00000000 --- a/tests/unit/devices/test_aerotech.py +++ /dev/null @@ -1,111 +0,0 @@ -from unittest.mock import MagicMock, patch - -import pytest -from aarecommon.errors.exception_handler import AerotechCommunicationError -from aarecommon.math.coordinate import AerotechCoordinate, Coordinate -from aarecommon.models.beamline import MXBeamline - -from aare.devices.aerotech import AerotechController - - -@pytest.fixture -def mock_aerotech_api(): - with ( - patch("aarescan_client.ApiClient"), - patch("aarescan_client.DefaultApi") as mock_api_class, - patch("aarescan_client.Configuration"), - ): - mock_api = mock_api_class.return_value - yield mock_api - - -@pytest.fixture -def aerotech_controller(mock_aerotech_api): - with patch( - "aare.devices.aerotech.cfg_get", return_value="http://mx-x10sa-queue-01.psi.ch:5234" - ): - controller = AerotechController(MXBeamline.X10SA) - - controller._api = mock_aerotech_api - controller._simulated = False - return controller - - -def test_init_x10sa(mock_aerotech_api): - with patch( - "aare.devices.aerotech.cfg_get", return_value="http://mx-x10sa-queue-01.psi.ch:5234" - ): - controller = AerotechController(MXBeamline.X10SA) - assert controller._base == "http://mx-x10sa-queue-01.psi.ch:5234" - assert controller._simulated is False - - -def test_init_simulated(): - controller = AerotechController(MXBeamline.SIMULATED) - assert controller._simulated is True - - -def test_cancel(aerotech_controller: AerotechController, mock_aerotech_api): - aerotech_controller.cancel() - mock_aerotech_api.cancel_post.assert_called_once() - - -def test_is_idle(aerotech_controller: AerotechController, mock_aerotech_api): - mock_aerotech_api.status_get.return_value.state = "Idle" - assert aerotech_controller.is_idle() is True - - mock_aerotech_api.status_get.return_value.state = "Busy" - assert aerotech_controller.is_idle() is False - - -def test_get_position(aerotech_controller: AerotechController, mock_aerotech_api): - status = MagicMock() - status.x.pos = 1.0 - status.y.pos = 2.0 - status.z.pos = 3.0 - status.u.pos = 90.0 - mock_aerotech_api.status_get.return_value = status - - pos = aerotech_controller.get_position() - assert pos.at_mm.x == 1.0 - assert pos.at_mm.y == 2.0 - assert pos.at_mm.z == 3.0 - assert pos.omega_deg == 90.0 - - -def test_move_home(aerotech_controller: AerotechController, mock_aerotech_api): - aerotech_controller.move_home() - mock_aerotech_api.position_post.assert_called_once() - - -def test_position(aerotech_controller: AerotechController, mock_aerotech_api): - target = AerotechCoordinate(at_mm=Coordinate(x=1, y=2, z=3), omega_deg=45) - aerotech_controller.position(target) - mock_aerotech_api.position_post.assert_called_once() - - -def test_rotation_scan(aerotech_controller: AerotechController, mock_aerotech_api): - aerotech_controller.rotation_scan(rotation_deg=360, time_sec=10, start_pos_deg=0) - mock_aerotech_api.rotation_scan_post.assert_called_once() - - -def test_grid_scan(aerotech_controller: AerotechController, mock_aerotech_api): - aerotech_controller.grid_scan( - grid_elem_count_y=10, - grid_elem_size_y_um=10, - grid_elem_count_x=10, - grid_elem_size_x_um=10, - time_per_element_s=5, - ) - mock_aerotech_api.grid_scan_post.assert_called_once() - - -def test_screening_scan(aerotech_controller: AerotechController, mock_aerotech_api): - aerotech_controller.screening_scan(rotation_deg=10, wedge_deg=2, time_per_element_s=1, steps=5) - mock_aerotech_api.screening_post.assert_called_once() - - -def test_api_error(aerotech_controller: AerotechController, mock_aerotech_api): - mock_aerotech_api.status_get.side_effect = Exception("API Error") - with pytest.raises(AerotechCommunicationError): - aerotech_controller.is_idle() diff --git a/tests/unit/devices/test_enum_pv.py b/tests/unit/devices/test_enum_pv.py deleted file mode 100644 index 89658a5e..00000000 --- a/tests/unit/devices/test_enum_pv.py +++ /dev/null @@ -1,96 +0,0 @@ -from enum import Enum -from unittest.mock import patch - -import pytest - -from aare.devices.enum_pv import EnumPV - - -class MockPV: - def __init__(self, name): - self.pvname = name - self.enum_strs = None - self.value = None - - def get(self, as_string=False): - if as_string: - return str(self.value) - return self.value - - def put(self, value): - self.value = value - - -@pytest.fixture -def mock_pvs(): - with patch("aare.devices.set_get_pv.PV") as mock_pv: - set_pv = MockPV("SET") - get_pv = MockPV("GET") - mock_pv.side_effect = lambda name: set_pv if name == "SET" else get_pv - yield set_pv, get_pv - - -def test_enum_pv_init_fail(mock_pvs): - set_pv, _get_pv = mock_pvs - set_pv.enum_strs = None - with pytest.raises(RuntimeError): - EnumPV("test", "SET", "GET") - - -def test_enum_pv_init_success(mock_pvs): - set_pv, _get_pv = mock_pvs - set_pv.enum_strs = ("State1", "State2") - epv = EnumPV("test", "SET", "GET") - assert epv.name == "test" - - -def test_enum_pv_position(mock_pvs): - set_pv, get_pv = mock_pvs - set_pv.enum_strs = ("State1", "State2") - get_pv.value = "State1" - epv = EnumPV("test", "SET", "GET") - assert epv.position == "State1" - - -def test_enum_pv_resolve_enum(mock_pvs): - set_pv, _get_pv = mock_pvs - set_pv.enum_strs = ("State1", "State2") - epv = EnumPV("test", "SET", "GET") - - class MyEnum(Enum): - State1 = 1 - - res = epv._resolve(MyEnum.State1) - assert res.target == "State1" - - -def test_enum_pv_resolve_int(mock_pvs): - set_pv, _get_pv = mock_pvs - set_pv.enum_strs = ("State1", "State2") - epv = EnumPV("test", "SET", "GET") - - res = epv._resolve(0) - assert res.target == "State1" - - with pytest.raises(ValueError): - epv._resolve(5) - - -def test_enum_pv_resolve_str(mock_pvs): - set_pv, _get_pv = mock_pvs - set_pv.enum_strs = (" State1 ", "State2") - epv = EnumPV("test", "SET", "GET") - - res = epv._resolve("state1") - assert res.target == " State1 " - - with pytest.raises(ValueError): - epv._resolve("Missing") - - -def test_enum_pv_resolve_invalid_type(mock_pvs): - set_pv, _get_pv = mock_pvs - set_pv.enum_strs = ("State1", "State2") - epv = EnumPV("test", "SET", "GET") - with pytest.raises(TypeError): - epv._resolve(1.5) diff --git a/tests/unit/devices/test_experimental_hutch_shutter.py b/tests/unit/devices/test_experimental_hutch_shutter.py deleted file mode 100644 index fdfed9c8..00000000 --- a/tests/unit/devices/test_experimental_hutch_shutter.py +++ /dev/null @@ -1,60 +0,0 @@ -from unittest.mock import MagicMock, patch - -from aarecommon.models.beamline import MXBeamline - -from aare.devices.experimental_hutch_shutter import ExperimentalHutchShutter - - -@patch("aare.devices.experimental_hutch_shutter.PV") -def test_shutter_init(mock_pv): - ExperimentalHutchShutter(MXBeamline.X06DA) - assert mock_pv.call_count == 3 - # Check if PV names are correct - args = [call.args[0] for call in mock_pv.call_args_list] - assert "X06DA-EH1-PSYS:SH-A-CLOSE-SET" in args - assert "X06DA-EH1-PSYS:SH-A-OPEN-SET" in args - assert "X06DA-OP-PSH1-EMLS-0010:OPEN" in args - - -@patch("aare.devices.experimental_hutch_shutter.PV") -def test_shutter_state(mock_pv): - # Mocking self._state - mock_state_pv = MagicMock() - mock_pv.side_effect = [MagicMock(), MagicMock(), mock_state_pv] - - shutter = ExperimentalHutchShutter(MXBeamline.X06DA) - - mock_state_pv.get.return_value = "Open" - assert shutter.state() is True - - mock_state_pv.get.return_value = 1 - assert shutter.state() is True - - mock_state_pv.get.return_value = "Not Open" - assert shutter.state() is False - - mock_state_pv.get.return_value = 0 - assert shutter.state() is False - - mock_state_pv.get.return_value = "Unknown" - assert shutter.state() is False - - -@patch("aare.devices.experimental_hutch_shutter.PV") -def test_shutter_open_close(mock_pv): - mock_close = MagicMock() - mock_open = MagicMock() - mock_state = MagicMock() - mock_pv.side_effect = [mock_close, mock_open, mock_state] - - shutter = ExperimentalHutchShutter(MXBeamline.X06DA) - - shutter.open() - assert mock_open.put.call_count == 3 - mock_open.put.assert_any_call(0) - mock_open.put.assert_any_call(1) - - shutter.close() - assert mock_close.put.call_count == 2 - mock_close.put.assert_any_call(1) - mock_close.put.assert_any_call(0) diff --git a/tests/unit/devices/test_filter_transmission.py b/tests/unit/devices/test_filter_transmission.py deleted file mode 100644 index b7afb504..00000000 --- a/tests/unit/devices/test_filter_transmission.py +++ /dev/null @@ -1,69 +0,0 @@ -from unittest.mock import MagicMock, patch - -import pytest -from aarecommon.models.beamline import MXBeamline - -from aare.devices.filter_transmission import FilterTransmission - - -@patch("aare.devices.filter_transmission.PV") -def test_filter_init(mock_pv): - FilterTransmission(MXBeamline.X06DA) - assert mock_pv.call_count == 3 - - -@patch("aare.devices.filter_transmission.PV") -def test_filter_repr_str(mock_pv): - mock_set = MagicMock() - mock_get = MagicMock() - mock_done = MagicMock() - mock_pv.side_effect = [mock_set, mock_get, mock_done] - - filters = FilterTransmission(MXBeamline.X06DA) - - mock_set.get.return_value = 0.5 - assert "" in repr(filters) - - mock_get.get.return_value = 0.5 - assert "0.5000" in str(filters) - - -@patch("aare.devices.filter_transmission.poll") -@patch("aare.devices.filter_transmission.PV") -def test_filter_set_wait(mock_pv, mock_poll): - mock_set = MagicMock() - mock_get = MagicMock() - mock_done = MagicMock() - mock_pv.side_effect = [mock_set, mock_get, mock_done] - - filters = FilterTransmission(MXBeamline.X06DA, timeout=0.1) - - # Test set without wait - filters.set(0.5) - mock_set.put.assert_called_with(0.5) - - # Test set with invalid value - with pytest.raises(RuntimeError, match="out of bounds"): - filters.set(1.5) - - # Test set with wait and timeout - mock_done.value = 0 # Busy - with pytest.raises(RuntimeError, match="timeout"): - filters.set(0.5, wait=True) - - -@patch("aare.devices.filter_transmission.PV") -def test_filter_get(mock_pv): - mock_set = MagicMock() - mock_get = MagicMock() - mock_done = MagicMock() - mock_pv.side_effect = [mock_set, mock_get, mock_done] - - filters = FilterTransmission(MXBeamline.X06DA) - - mock_done.value = 1 # Done - mock_get.value = 0.123456 - assert filters.get() == 0.12346 # Rounded to 5 - - mock_done.value = 0 # Busy - assert filters.get() is None diff --git a/tests/unit/devices/test_fluorimeter.py b/tests/unit/devices/test_fluorimeter.py deleted file mode 100644 index b21b0ef1..00000000 --- a/tests/unit/devices/test_fluorimeter.py +++ /dev/null @@ -1,84 +0,0 @@ -from unittest.mock import MagicMock, patch - -import pytest -from aarecommon.models.beamline import MXBeamline - -from aare.devices.fluorimeter import Fluorimeter - - -@patch("aare.devices.fluorimeter.PV") -def test_fluorimeter_init(mock_pv): - _ = Fluorimeter(MXBeamline.X06DA) - # Lots of PVs in __init__ - assert mock_pv.call_count >= 20 - - -@patch("aare.devices.fluorimeter.PV") -def test_fluorimeter_acquisition(mock_pv): - mock_start = MagicMock() - mock_stop = MagicMock() - mock_erase_start = MagicMock() - - # We need to map which mock is which. - # __init__ order: start, stop, erase_and_start, erase, ... - mock_pv.side_effect = [mock_start, mock_stop, mock_erase_start] + [MagicMock()] * 50 - - fluo = Fluorimeter(MXBeamline.X06DA) - - fluo.start_acquisition(erase=False) - mock_start.put.assert_called_with(1) - - fluo.start_acquisition(erase=True) - mock_erase_start.put.assert_called_with(1) - - fluo.stop_acquisition() - mock_stop.put.assert_called_with(1) - - -@patch("aare.devices.fluorimeter.PV") -def test_fluorimeter_status(mock_pv): - mock_status = MagicMock() - # status is the 6th PV in __init__ - mock_pv.side_effect = [MagicMock()] * 5 + [mock_status] + [MagicMock()] * 50 - fluo = Fluorimeter(MXBeamline.X06DA) - - mock_status.get.return_value = 0 - assert fluo.check_status_done() is True - assert fluo.check_status_acquiring() is None - - mock_status.get.return_value = 1 - assert fluo.check_status_done() is None - assert fluo.check_status_acquiring() is True - - -@patch("aare.devices.fluorimeter.poll") -@patch("aare.devices.fluorimeter.PV") -def test_fluorimeter_wait_timeout(mock_pv, mock_poll): - mock_status = MagicMock() - mock_pv.side_effect = [MagicMock()] * 5 + [mock_status] + [MagicMock()] * 50 - fluo = Fluorimeter(MXBeamline.X06DA) - - mock_status.get.return_value = 1 # Acquiring (not done) - with pytest.raises(TimeoutError, match="timeout waiting for done"): - fluo.wait_till_done(timeout_s=0.1) - - -@patch("aare.devices.fluorimeter.PV") -def test_fluorimeter_properties(mock_pv): - mock_real_time = MagicMock() - # real_time is 7th PV - mock_pv.side_effect = [MagicMock()] * 6 + [mock_real_time] + [MagicMock()] * 50 - fluo = Fluorimeter(MXBeamline.X06DA) - - mock_real_time.get.return_value = 10.0 - assert fluo.real_time == 10.0 - - fluo.real_time = 20.0 - mock_real_time.put.assert_called_with(20.0) - - -def test_fluorimeter_roi_error(): - with patch("aare.devices.fluorimeter.PV"): - fluo = Fluorimeter(MXBeamline.X06DA) - with pytest.raises(ValueError, match="Invalid ROI number"): - fluo.get_roi("BL", 3) diff --git a/tests/unit/devices/test_jfjoch.py b/tests/unit/devices/test_jfjoch.py deleted file mode 100644 index f96c48ad..00000000 --- a/tests/unit/devices/test_jfjoch.py +++ /dev/null @@ -1,259 +0,0 @@ -from unittest.mock import MagicMock, PropertyMock, patch - -import pytest -from aarecommon.errors.exception_handler import JFJochCommunicationError -from aarecommon.math.coordinate import Coordinate, SmargonCoordinate -from aarecommon.math.diffraction_geometry import DiffractionGeometry -from aarecommon.math.sample_geometry import SampleGeometryModel -from aarecommon.models.beamline import MXBeamline -from aarecommon.models.models import ( - BeamlineStateEnum, - BeamlineStatus, - DAQStatusModel, - SampleCameraSettings, - SampleShortInfo, - SessionsStateEnum, - SessionStatus, -) -from aarecommon.models.raster_grid import RasterGridRequest -from aarecommon.models.rotation_scan import RotationScanRequest - -from aare.devices.jfjoch import JFJochWrapper - - -@pytest.fixture -def mock_jfjoch_client(): - with ( - patch("jfjoch_client.ApiClient"), - patch("jfjoch_client.DefaultApi") as mock_api_class, - patch("jfjoch_client.Configuration"), - ): - mock_api = mock_api_class.return_value - yield mock_api - - -@pytest.fixture -def jfjoch_wrapper(mock_jfjoch_client): - wrapper = JFJochWrapper(MXBeamline.X10SA) - # the client/api are created lazily, connect up front so tests start from a live wrapper - wrapper.connect() - return wrapper - - -def create_mock_daq_status(): - bl_status = BeamlineStatus( - name="test_beamline", - ring_current_mA=400.0, - front_light=50.0, - back_light=0.0, - cryojet_K=100.0, - shutter_open=False, - exp_shutter_open=False, - flux_ph_s=1e12, - sample_camera=SampleCameraSettings(exposure=0.001, gain=0.0), - transmission=1.0, - zoom=1.0, - commissioning_mode=False, - dtz_min=120.0, - dtz_max=1600.0, - ) - diff_geom = DiffractionGeometry( - energy_keV=12.658, - dtz_mm=200.0, - pixel_size_mm=0.075, - beam_center_pxl=(1000.0, 1000.0), - detector_size_pxl=(2000, 2000), - detector_description="Eiger", - detector_serial_number="123", - poni_rot1_rad=0.0, - poni_rot2_rad=0.0, - ) - session = SessionStatus(session=SessionsStateEnum.Vacant, current_pgroup="p12345") - - 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), phi_deg=0, chi_deg=0), - omega_deg=0.0, - beam_size_mm=Coordinate(x=0.01, y=0.01), - ) - - return DAQStatusModel( - geom=geom, - diffraction=diff_geom, - bl=bl_status, - state=BeamlineStateEnum.SampleAlignment, - busy=False, - session=session, - ) - - -def test_init_x10sa(mock_jfjoch_client): - wrapper = JFJochWrapper(MXBeamline.X10SA) - assert wrapper._url == "http://sls-gpu-002:8080" - - -def test_init_x06da(mock_jfjoch_client): - wrapper = JFJochWrapper(MXBeamline.X06DA) - assert wrapper._url == "http://sls-gpu-001:8080" - - -def test_init_simulated(mock_jfjoch_client): - wrapper = JFJochWrapper(MXBeamline.SIMULATED) - assert wrapper._simulated is True - - -def test_init_unknown(): - with pytest.raises(Exception, match="unknown beamline"): - JFJochWrapper("UNKNOWN") - - -def test_client_is_created_lazily(mock_jfjoch_client): - wrapper = JFJochWrapper(MXBeamline.X10SA) - assert wrapper._connected is False - mock_jfjoch_client.status_get.assert_not_called() - - # a decorated method connects on demand, further calls reuse the same api - wrapper.is_idle() - assert wrapper._connected is True - api = wrapper._api - wrapper.is_idle() - assert wrapper._api is api - - -def test_images_per_file_from_config(jfjoch_wrapper): - jfjoch_wrapper._config_client = MagicMock() - jfjoch_wrapper._config_client.jfjoch.n_images_per_file = 500 - assert jfjoch_wrapper._get_images_per_file() == 500 - - -def test_images_per_file_without_config_client(jfjoch_wrapper): - jfjoch_wrapper._config_client = None - assert jfjoch_wrapper._get_images_per_file() is None - - -def test_images_per_file_falls_back_when_key_not_set(jfjoch_wrapper): - # e.g. x06da, where jfjoch/n_images_per_file is not set and has no default - jfjoch_wrapper._config_client = MagicMock() - type(jfjoch_wrapper._config_client.jfjoch).n_images_per_file = PropertyMock( - side_effect=KeyError("jfjoch/n_images_per_file is not set and has no default") - ) - assert jfjoch_wrapper._get_images_per_file() is None - - -def test_initialize(jfjoch_wrapper, mock_jfjoch_client): - mock_jfjoch_client.initialize_post.reset_mock() - jfjoch_wrapper.initialize() - mock_jfjoch_client.initialize_post.assert_called_once() - - -def test_cancel(jfjoch_wrapper, mock_jfjoch_client): - mock_jfjoch_client.cancel_post.reset_mock() - jfjoch_wrapper.cancel() - mock_jfjoch_client.cancel_post.assert_called_once() - - -def test_is_idle(jfjoch_wrapper, mock_jfjoch_client): - mock_jfjoch_client.status_get.return_value.state = "Idle" - assert jfjoch_wrapper.is_idle() is True - - mock_jfjoch_client.status_get.return_value.state = "Busy" - assert jfjoch_wrapper.is_idle() is False - - -def test_measure_rotation(jfjoch_wrapper, mock_jfjoch_client): - r = RotationScanRequest( - start_omega_deg=0.0, - incr_omega_deg=0.1, - steps=100, - exp_time_s=0.01, - file_prefix="test_prefix", - dtz=200.0, - ) - s = create_mock_daq_status() - s.sample = SampleShortInfo( - sample_name="S1", - user="p12345", - db_id=1, - dewar_name="D1", - puck_name="P1", - run_number=1, - pin=1, - ) - - jfjoch_wrapper.measure_rotation(r, s) - mock_jfjoch_client.start_post.assert_called_once() - - -def test_measure_rotation_error(jfjoch_wrapper, mock_jfjoch_client): - mock_jfjoch_client.start_post.side_effect = Exception("API Error") - r = RotationScanRequest(exp_time_s=0.01, incr_omega_deg=0.1, steps=10, dtz=200.0) - s = create_mock_daq_status() - s.sample = SampleShortInfo( - sample_name="S1", - user="p12345", - db_id=1, - dewar_name="D1", - puck_name="P1", - run_number=1, - pin=1, - ) - - with pytest.raises(JFJochCommunicationError): - jfjoch_wrapper.measure_rotation(r, s) - - -def test_measure_raster(jfjoch_wrapper, mock_jfjoch_client): - r = RasterGridRequest( - n_x=10, - n_y=10, - grid_size_mm=Coordinate(x=0.01, y=0.01), - exp_time_s=0.01, - file_prefix="raster_prefix", - smargon_top_left=SmargonCoordinate(sh_mm=Coordinate(x=0, y=0)), - dtz=200.0, - ) - s = create_mock_daq_status() - s.sample = SampleShortInfo( - sample_name="S1", - user="p12345", - db_id=1, - dewar_name="D1", - puck_name="P1", - run_number=1, - pin=1, - ) - - jfjoch_wrapper.measure_raster(r, s) - mock_jfjoch_client.start_post.assert_called_once() - - -def test_wait_till_done(jfjoch_wrapper, mock_jfjoch_client): - mock_jfjoch_client.result_scan_get.return_value = MagicMock() - result = jfjoch_wrapper.wait_till_done(timeout=10) - mock_jfjoch_client.wait_till_done_post_with_http_info.assert_called_once_with(timeout=10) - assert result is not None - - -def test_detector(jfjoch_wrapper, mock_jfjoch_client): - mock_det = MagicMock() - mock_jfjoch_client.config_select_detector_get.return_value.detectors = [mock_det] - mock_jfjoch_client.config_select_detector_get.return_value.current_id = 0 - - det = jfjoch_wrapper.detector() - assert det == mock_det - - -def test_get_diffraction_image(jfjoch_wrapper, mock_jfjoch_client): - mock_jfjoch_client.image_buffer_image_jpeg_get.return_value = b"image_data" - img = jfjoch_wrapper.get_diffraction_image(image_id=1) - assert img == b"image_data" - - -def test_get_diffraction_image_retry(jfjoch_wrapper, mock_jfjoch_client): - mock_jfjoch_client.image_buffer_image_jpeg_get.side_effect = [Exception("Error"), b"image_data"] - img = jfjoch_wrapper.get_diffraction_image(image_id=1, wait_between_retries_s=0.001) - assert img == b"image_data" - assert mock_jfjoch_client.image_buffer_image_jpeg_get.call_count == 2 diff --git a/tests/unit/devices/test_mx_lib.py b/tests/unit/devices/test_mx_lib.py deleted file mode 100644 index 4baeb224..00000000 --- a/tests/unit/devices/test_mx_lib.py +++ /dev/null @@ -1,92 +0,0 @@ -from unittest.mock import MagicMock, patch - -import pytest -from epics import PV, Motor - -from aare.devices.mx_lib import clean_filename, is_epics_type, pv_wait, wait_for_movement_to_finish - - -def test_clean_filename(): - assert clean_filename("my file!.txt") == "my_file_.txt" - assert clean_filename(" /path/to/somewhere/file.txt ") == "path_to_somewhere_file.txt" - assert clean_filename("abcABC123") == "abcABC123" - assert clean_filename("file._-") == "file" - - with pytest.raises(ValueError): - clean_filename("!!!") - - -def test_is_epics_type(): - mock_pv = MagicMock(spec=PV) - mock_pv.type = "double" - assert is_epics_type(mock_pv, "double") is True - assert is_epics_type(mock_pv, "enum") is False - - class FakeType: - pass - - assert is_epics_type(mock_pv, FakeType) is False - - -@patch("aare.devices.mx_lib.poll") -def test_wait_for_movement_to_finish(mock_poll): - mock_motor = MagicMock(spec=Motor) - mock_motor.readback = 10.0 - mock_motor.slew_speed = 1.0 - mock_motor.done_moving = True - - wait_for_movement_to_finish(mock_motor) - assert mock_poll.called - - -@patch("aare.devices.mx_lib.poll") -def test_wait_for_movement_to_finish_timeout(mock_poll): - mock_motor = MagicMock(spec=Motor) - mock_motor.readback = 10.0 - mock_motor.slew_speed = 1.0 - mock_motor.done_moving = False - mock_motor.drive = 11.0 - mock_motor.units = "mm" - mock_motor._prefix = "MOT1:" - - with patch("time.time", side_effect=[0, 0, 100, 101]), pytest.raises(TimeoutError): - wait_for_movement_to_finish(mock_motor) - - -@patch("aare.devices.mx_lib.wait_motor_position") -def test_pv_wait_motor(mock_wait_motor): - mock_motor = MagicMock(spec=Motor) - pv_wait(mock_motor, 10.0) - mock_wait_motor.assert_called_once() - - -@patch("aare.devices.mx_lib.wait_float_condition") -def test_pv_wait_double(mock_wait_float): - mock_pv = MagicMock(spec=PV) - mock_pv.type = "double" - pv_wait(mock_pv, 10.0) - mock_wait_float.assert_called_once() - - -@patch("aare.devices.mx_lib.wait_enum_condition") -def test_pv_wait_enum(mock_wait_enum): - mock_pv = MagicMock(spec=PV) - mock_pv.type = "enum" - pv_wait(mock_pv, "READY") - mock_wait_enum.assert_called_once() - - -@patch("aare.devices.mx_lib.wait_string_condition") -def test_pv_wait_string(mock_wait_string): - mock_pv = MagicMock(spec=PV) - mock_pv.type = "string" - pv_wait(mock_pv, "hello") - mock_wait_string.assert_called_once() - - -def test_pv_wait_unknown_type(): - mock_pv = MagicMock(spec=PV) - mock_pv.type = "unknown" - mock_pv.pvname = "TEST:PV" - with pytest.raises(ValueError): - pv_wait(mock_pv, 1.0) diff --git a/tests/unit/devices/test_my_motor.py b/tests/unit/devices/test_my_motor.py deleted file mode 100644 index c6cb1258..00000000 --- a/tests/unit/devices/test_my_motor.py +++ /dev/null @@ -1,156 +0,0 @@ -from unittest.mock import MagicMock, PropertyMock, patch - -import pytest - -from aare.devices.my_motor import MyMotor - - -@pytest.fixture -def mock_motor_base(): - with patch("epics.motor.Motor.__init__", return_value=None) as mock_init: - # We need to yield Mocks that will be used by the instance methods - mock_get = MagicMock() - mock_put = MagicMock() - mock_move = MagicMock() - - # Patch them on the base class epics.motor.Motor - with ( - patch("epics.motor.Motor.get", mock_get), - patch("epics.motor.Motor.put", mock_put), - patch("epics.motor.Motor.move", mock_move), - patch("epics.motor.Motor.PV"), - patch("epics.motor.Motor.readback", create=True), - patch("epics.motor.Motor.drive", create=True), - patch("epics.motor.Motor.stop_motor", create=True), - patch("epics.motor.Motor.moving_flag", create=True), - ): - yield mock_init, mock_get, mock_put, mock_move - - -def test_my_motor_init(mock_motor_base): - mock_init, _, _, _ = mock_motor_base - _ = MyMotor("X10SA-DI-MTR-01") - mock_init.assert_called_with("X10SA-DI-MTR-01", timeout=5.0) - - -def test_my_motor_speed(mock_motor_base): - _, mock_get, _mock_put, _ = mock_motor_base - m = MyMotor("MTR") - with patch.object(MyMotor, "name", create=True, new_callable=PropertyMock) as mock_name: - mock_name.return_value = "MTR" - mock_get.return_value = 1.0 - assert m.speed == 1.0 - mock_get.assert_called_with("VELO") - - # When m.speed = 2.0 is called, it might use epics.motor.Motor.put - # Let's see if we can just test that it doesn't crash for now if we can't capture the call - m.speed = 2.0 - - -def test_my_motor_properties(mock_motor_base): - m = MyMotor("MTR") - with patch.object(MyMotor, "name", create=True, new_callable=PropertyMock) as mock_name: - mock_name.return_value = "MTR" - with patch("epics.motor.Motor.readback", new_callable=PropertyMock, create=True) as mock_rb: - mock_rb.return_value = 10.0 - assert m.position == 10.0 - - with patch("epics.motor.Motor.drive", new_callable=PropertyMock, create=True) as mock_drive: - mock_drive.return_value = 5.0 - assert m.value == 5.0 - # m.value = 6.0 calls self.drive = 6.0. - # In epics.Motor, drive is a PVProperty. - m.value = 6.0 - - -def test_my_motor_stop(mock_motor_base): - m = MyMotor("MTR") - with patch.object(MyMotor, "name", create=True, new_callable=PropertyMock) as mock_name: - mock_name.return_value = "MTR" - with patch("epics.motor.Motor.stop_motor", create=True) as mock_stop: - m.stop() - mock_stop.assert_called_once() - - -def test_my_motor_moving(mock_motor_base): - _, mock_get, _, _ = mock_motor_base - m = MyMotor("MTR") - with patch.object(MyMotor, "name", create=True, new_callable=PropertyMock) as mock_name: - mock_name.return_value = "MTR" - mock_get.return_value = 1 - assert m.moving is True - mock_get.return_value = 0 - assert m.moving is False - - -def test_my_motor_units(mock_motor_base): - _, mock_get, _, _ = mock_motor_base - m = MyMotor("MTR") - with patch.object(MyMotor, "name", create=True, new_callable=PropertyMock) as mock_name: - mock_name.return_value = "MTR" - mock_get.return_value = "mm" - assert m.units == "mm" - mock_get.assert_called_with("EGU", as_string=True) - - -def test_my_motor_limits(mock_motor_base): - _, mock_get, _mock_put, _ = mock_motor_base - m = MyMotor("MTR") - with patch.object(MyMotor, "name", create=True, new_callable=PropertyMock) as mock_name: - mock_name.return_value = "MTR" - mock_get.side_effect = [100, 0] - assert m.limits == (100, 0) - - m.limits = (0, 100) - - -def test_my_motor_move_motor(mock_motor_base): - _, _, _, mock_move = mock_motor_base - m = MyMotor("MTR") - with patch.object(MyMotor, "name", create=True, new_callable=PropertyMock) as mock_name: - mock_name.return_value = "MTR" - m.move_motor(10, relative=True, wait=True) - mock_move.assert_called_with(10, relative=True, wait=True, timeout=300.0) - - -def test_my_motor_home(mock_motor_base): - _, _, mock_put, _ = mock_motor_base - m = MyMotor("MTR") - with patch.object(MyMotor, "name", create=True, new_callable=PropertyMock) as mock_name: - mock_name.return_value = "MTR" - m.home(direction="forward") - mock_put.assert_called_with("HOMF", 1) - - m.home(direction="reverse") - mock_put.assert_called_with("HOMR", 1) - - -def test_my_motor_wait_for_stop(mock_motor_base): - _, mock_get, _, _ = mock_motor_base - m = MyMotor("MTR") - with patch.object(MyMotor, "name", create=True, new_callable=PropertyMock) as mock_name: - mock_name.return_value = "MTR" - # Simulate moving then stopping - # First 2 calls return 1 (moving), 3rd call returns 0 (stopped) - mock_get.side_effect = [1, 1, 0] - m.wait_for_stop(timeout=1.0, poll_rate=0.001) - - -def test_my_motor_wait_for_stop_timeout(mock_motor_base): - _, mock_get, _, _ = mock_motor_base - m = MyMotor("MTR") - with patch.object(MyMotor, "name", create=True, new_callable=PropertyMock) as mock_name: - mock_name.return_value = "MTR" - mock_get.return_value = 1 - with pytest.raises(RuntimeError): - m.wait_for_stop(timeout=0.01, poll_rate=0.001) - - -@pytest.mark.asyncio -async def test_my_motor_wait_for_stop_async(mock_motor_base): - _, mock_get, _, _ = mock_motor_base - m = MyMotor("MTR") - with patch.object(MyMotor, "name", create=True, new_callable=PropertyMock) as mock_name: - mock_name.return_value = "MTR" - mock_get.side_effect = [1, 0] - await m.wait_for_stop_async(timeout=1.0, poll_rate=0.001) diff --git a/tests/unit/devices/test_tell_client.py b/tests/unit/devices/test_tell_client.py deleted file mode 100644 index 85a671c9..00000000 --- a/tests/unit/devices/test_tell_client.py +++ /dev/null @@ -1,104 +0,0 @@ -from unittest.mock import MagicMock - -import pytest -from aarecommon.errors.exception_handler import TellCommunicationError -from aarecommon.models.models import DewarAddress, SampleDewarAddress - -from aare.devices.tell_backend import TellBackend -from aare.devices.tell_client import TellClient, TellEventValueEnum - - -@pytest.fixture -def mock_backend(): - backend = MagicMock(spec=TellBackend) - backend.get_state.return_value = "Ready" - return backend - - -@pytest.fixture -def mock_beamline(): - return MagicMock() - - -def test_get_state(mock_beamline, mock_backend): - client = TellClient(mock_beamline, backend=mock_backend) - assert client.get_state() == "Ready" - mock_backend.get_state.assert_called() - - -def test_is_in_mount_position_true(mock_beamline, mock_backend): - mock_backend.eval.return_value = "True" - client = TellClient(mock_beamline, backend=mock_backend) - assert client.is_in_mount_position() is True - mock_backend.eval.assert_called_with("in_mount_position&") - - -def test_is_in_mount_position_false(mock_beamline, mock_backend): - mock_backend.eval.return_value = "False" - client = TellClient(mock_beamline, backend=mock_backend) - assert client.is_in_mount_position() is False - - -def _mount_address(): - return SampleDewarAddress(puck=DewarAddress(segment="A", pos=3), pin=10) - - -@pytest.mark.parametrize("state_value", ["Busy", "Ready", '"Busy"', '"Ready"', "busy"]) -def test_mount_state_event_succeeds_when_command_completes( - mock_beamline, mock_backend, state_value -): - """Regression: TELL emits a "state" event (sometimes the intermediate - "Busy", quoted or unquoted) instead of a terminal event. The mount must - rely on check_command_ok rather than string-matching the event value, so a - completed command is reported as SUCCESS rather than raising.""" - mock_backend.wait_events.return_value = ("state", state_value) - mock_backend.get_result.return_value = { - "status": "completed", - "return": "A39", - "exception": None, - "id": 3017907, - } - client = TellClient(mock_beamline, backend=mock_backend) - # Robot reports the requested sample as mounted -> genuine success. - client.get_mounted_sample = lambda: _mount_address() - - result = client.mount(_mount_address(), wait=True) - - assert result == TellEventValueEnum.SUCCESS - mock_backend.get_result.assert_called() # check_command_ok consulted the result - - -def test_mount_state_event_reports_no_pin_when_nothing_mounted(mock_beamline, mock_backend): - """If the command completes but the robot reports nothing mounted, the - gripper was empty: mount() must return NO_PIN_IN_GRIPPER (so the service - raises MountingFailed) rather than reporting success.""" - mock_backend.wait_events.return_value = ("state", "Busy") - mock_backend.get_result.return_value = { - "status": "completed", - "return": "A39", - "exception": None, - "id": 3017907, - } - client = TellClient(mock_beamline, backend=mock_backend) - client.get_mounted_sample = lambda: None - - result = client.mount(_mount_address(), wait=True) - - assert result == TellEventValueEnum.NO_PIN_IN_GRIPPER - - -def test_mount_state_event_raises_when_command_not_completed(mock_beamline, mock_backend): - """A genuine failure still surfaces: if the command did not complete, - check_command_ok raises (MountingFailed) and mount() re-raises it as a - critical TellCommunicationError, even though the event value was "Busy".""" - mock_backend.wait_events.return_value = ("state", "Busy") - mock_backend.get_result.return_value = { - "status": "error", - "return": None, - "exception": "boom", - "id": 3017907, - } - client = TellClient(mock_beamline, backend=mock_backend) - - with pytest.raises(TellCommunicationError): - client.mount(_mount_address(), wait=True) diff --git a/tests/unit/devices/test_workflow_tools.py b/tests/unit/devices/test_workflow_tools.py deleted file mode 100644 index c8136951..00000000 --- a/tests/unit/devices/test_workflow_tools.py +++ /dev/null @@ -1,41 +0,0 @@ -import pytest - -from aare.devices.workflow_tools import wait_position - - -class MockMotor: - def __init__(self, position): - self.readback = position - self.name = "MockMotor" - - def __str__(self): - return self.name - - -def test_wait_position_float_no_tolerance(): - motor = MockMotor(10.0) - wait_position(motor, 10.0) - - -def test_wait_position_float_with_tolerance(): - motor = MockMotor(10.05) - wait_position(motor, 10.0, tolerance=0.1) - - -def test_wait_position_bytes(): - motor = MockMotor(b"Open") - wait_position(motor, "Open") - wait_position(motor, b"open") - - -def test_wait_position_timeout(): - motor = MockMotor(10.0) - # We want it to fail, so we set a target it will never reach - with pytest.raises(RuntimeError, match="Timeout"): - wait_position(motor, 20.0, tolerance=0.1, timeout=0.1) - - -def test_wait_position_invalid_type(): - motor = MockMotor([1, 2]) - with pytest.raises(RuntimeError, match="could not understand arguments"): - wait_position(motor, 10.0) diff --git a/tests/unit/gui/test_auth_mock.py b/tests/unit/gui/test_auth_mock.py deleted file mode 100644 index 836ef743..00000000 --- a/tests/unit/gui/test_auth_mock.py +++ /dev/null @@ -1,43 +0,0 @@ -import json - -import pytest - -from aare.gui.auth import auth - - -def test_auth_success(mocker): - mock_run = mocker.patch("aare.gui.auth.subprocess.run") - mock_run.return_value = mocker.Mock( - returncode=0, stdout=json.dumps({"access_token": "fake_token_abc.123.xyz"}), stderr="" - ) - - token = auth("http://test-server", "/tmp/test-cert.pem") - - assert token == "fake_token_abc.123.xyz" - mock_run.assert_called_once() - args, _kwargs = mock_run.call_args - assert "curl" in args[0] - assert "--cacert" in args[0] - assert "/tmp/test-cert.pem" in args[0] - assert "http://test-server/token" in args[0] - - -def test_auth_network_failure(mocker): - mock_run = mocker.patch("aare.gui.auth.subprocess.run") - mock_run.side_effect = OSError("Connection refused") - - with pytest.raises(RuntimeError) as excinfo: - auth("http://test-server", "/tmp/test-cert.pem") - - assert "Cannot reach AareDAQ server" in str(excinfo.value) - - -def test_auth_no_url_returns_dummy_jwt(mocker): - mock_run = mocker.patch("aare.gui.auth.subprocess.run") - mocker.patch("aare.gui.auth.get_user", return_value="testuser") - - token = auth(None, None) - - assert isinstance(token, str) - assert token.count(".") == 2 - mock_run.assert_not_called() diff --git a/tests/unit/gui/test_automation_progress_parser.py b/tests/unit/gui/test_automation_progress_parser.py deleted file mode 100644 index 09d06607..00000000 --- a/tests/unit/gui/test_automation_progress_parser.py +++ /dev/null @@ -1,279 +0,0 @@ -import sys -import types - -from aarecommon.models.automation import StepStatus, WorkflowStateKind - -from aare.gui.threads.daq_worker import DAQWorker - -jfjoch_client_module = types.ModuleType("jfjoch_client") -jfjoch_client_module.ScanResult = object -jfjoch_client_module.ScanResultImagesInner = object - -jfjoch_client_models_module = types.ModuleType("jfjoch_client.models") -jfjoch_client_scan_result_module = types.ModuleType("jfjoch_client.models.scan_result") -jfjoch_client_scan_result_module.ScanResult = object - -sys.modules.setdefault("jfjoch_client", jfjoch_client_module) -sys.modules.setdefault("jfjoch_client.models", jfjoch_client_models_module) -sys.modules.setdefault("jfjoch_client.models.scan_result", jfjoch_client_scan_result_module) - - -def test_parse_automation_progress_from_sse_payload(): - progress_payload = { - "current_step": "Center", - "steps": [ - { - "step": WorkflowStateKind.MOUNT.value, - "status": StepStatus.SUCCESS.value, - "message": "Mount complete", - }, - { - "step": WorkflowStateKind.LOOP_CENTRE.value, - "status": StepStatus.RUNNING.value, - "message": "Centering sample", - }, - { - "step": WorkflowStateKind.RASTER.value, - "status": StepStatus.PENDING.value, - "message": "", - }, - { - "step": WorkflowStateKind.DATA_COLLECTION.value, - "status": StepStatus.PENDING.value, - "message": "", - }, - { - "step": WorkflowStateKind.FINAL.value, - "status": StepStatus.PENDING.value, - "message": "", - }, - ], - "finished": False, - "success": None, - } - - progress = DAQWorker._parse_automation_progress(progress_payload) - - assert progress.current_step == "Center" - assert progress.finished is False - assert progress.success is None - - assert len(progress.steps) == 5 - - assert progress.steps[0].step == WorkflowStateKind.MOUNT - assert progress.steps[0].status == StepStatus.SUCCESS - assert progress.steps[0].message == "Mount complete" - - assert progress.steps[1].step == WorkflowStateKind.LOOP_CENTRE - assert progress.steps[1].status == StepStatus.RUNNING - assert progress.steps[1].message == "Centering sample" - - assert progress.steps[2].step == WorkflowStateKind.RASTER - assert progress.steps[2].status == StepStatus.PENDING - assert progress.steps[2].message == "" - - -def test_parse_automation_progress_finished_state(): - progress_payload = { - "current_step": "Paused/Finished", - "steps": [ - { - "step": WorkflowStateKind.FINAL.value, - "status": StepStatus.SUCCESS.value, - "message": "Automation complete", - } - ], - "finished": True, - "success": True, - } - - progress = DAQWorker._parse_automation_progress(progress_payload) - - assert progress.current_step == "Paused/Finished" - assert progress.finished is True - assert progress.success is True - assert len(progress.steps) == 1 - assert progress.steps[0].step == WorkflowStateKind.FINAL - assert progress.steps[0].status == StepStatus.SUCCESS - assert progress.steps[0].message == "Automation complete" - - -def test_parse_automation_progress_parses_events(): - progress_payload = { - "current_step": "Center", - "steps": [], - "events": [ - { - "ts": "2026-06-03T10:00:00+00:00", - "level": "warning", - "code": "LOOP_CENTERING_FAILED", - "exception_class": "LoopCenteringFailed", - "message": "Loop centering failed", - "sample_id": 42, - "context": {"step": "loop_centre"}, - } - ], - "finished": False, - "success": None, - } - - progress = DAQWorker._parse_automation_progress(progress_payload) - - assert len(progress.events) == 1 - assert progress.events[0].level == "WARNING" - assert progress.events[0].code == "LOOP_CENTERING_FAILED" - assert progress.events[0].sample_id == 42 - - -def test_handle_automation_progress_event_dedups_events_by_timestamp(caplog): - worker = DAQWorker(base_url=None, token="test-token") - - payload = ( - '{"seq":1,"progress":{"current_step":"Center","steps":[],"events":[' - '{"ts":"2026-06-03T10:00:00+00:00","level":"WARNING","code":"LOOP_CENTERING_FAILED",' - '"exception_class":"LoopCenteringFailed","message":"Loop centering failed","sample_id":7,' - '"context":{"step":"loop_centre"}}],"finished":false,"success":null}}' - ) - - caplog.clear() - worker._handle_automation_progress_event(payload) - worker._handle_automation_progress_event(payload) - - warning_messages = [ - record.message for record in caplog.records if record.levelname == "WARNING" - ] - assert warning_messages.count("Loop centering failed") == 1 - - worker.cleanup() - - -def test_handle_automation_progress_event_trips_recurrence_watcher(): - worker = DAQWorker(base_url=None, token="test-token") - worker._recurrence_watchers = [w for w in worker._recurrence_watchers if w.name == "alc"] - - trips: list[str] = [] - worker.automation_critical_failure.connect(trips.append) - - payload = ( - '{"seq":1,"progress":{"current_step":"Center","steps":[],"events":[' - '{"ts":"2026-06-03T10:00:00+00:00","level":"WARNING","code":"LOOP_CENTERING_FAILED",' - '"exception_class":"LoopCenteringFailed","message":"Loop centering failed","sample_id":7,' - '"context":{"step":"loop_centre"}}],"finished":false,"success":null}}' - ) - - worker._handle_automation_progress_event(payload) - worker._handle_automation_progress_event( - payload.replace('"seq":1', '"seq":2').replace("10:00:00", "10:00:01") - ) - worker._handle_automation_progress_event( - payload.replace('"seq":1', '"seq":3').replace("10:00:00", "10:00:02") - ) - - assert len(trips) == 1 - assert "consecutive alc errors" in trips[0] - - worker.cleanup() - - -def test_process_automation_progress_buffer_waits_for_complete_event(): - worker = DAQWorker(base_url=None, token="test-token") - emitted: list = [] - - worker.automation_progress.connect(emitted.append) - - worker._automation_progress_buffer = ( - 'data: {"seq":1,"progress":{"current_step":"Center","steps":[{"step":"mount",' - '"status":"success","message":"Mount complete"}],"finished":false,"success":null}}' - ) - - worker._process_automation_progress_buffer() - - assert emitted == [] - assert worker._automation_progress_buffer.startswith("data:") - - worker.cleanup() - - -def test_process_automation_progress_buffer_handles_split_sse_event(): - worker = DAQWorker(base_url=None, token="test-token") - emitted: list = [] - - worker.automation_progress.connect(emitted.append) - - first_chunk = 'data: {"seq":1,"progress":{"current_step":"Center","steps":[{"step":"mount",' - second_chunk = ( - '"status":"success","message":"Mount complete"},{"step":"loop_centre",' - '"status":"running","message":"Centering sample"}],' - '"finished":false,"success":null}}\n\n' - ) - - worker._automation_progress_buffer += first_chunk - worker._process_automation_progress_buffer() - - assert emitted == [] - - worker._automation_progress_buffer += second_chunk - worker._process_automation_progress_buffer() - - assert len(emitted) == 1 - - progress = emitted[0] - assert progress.current_step == "Center" - assert progress.finished is False - assert progress.success is None - assert len(progress.steps) == 2 - assert progress.steps[0].step == WorkflowStateKind.MOUNT - assert progress.steps[0].status == StepStatus.SUCCESS - assert progress.steps[1].step == WorkflowStateKind.LOOP_CENTRE - assert progress.steps[1].status == StepStatus.RUNNING - assert worker._automation_progress_buffer == "" - - worker.cleanup() - - -def test_process_automation_progress_buffer_handles_multiple_events(): - worker = DAQWorker(base_url=None, token="test-token") - emitted: list = [] - - worker.automation_progress.connect(emitted.append) - - worker._automation_progress_buffer = ( - 'data: {"seq":1,"progress":{"current_step":"Mount","steps":[{"step":"mount",' - '"status":"running","message":"Mounting sample"}],"finished":false,"success":null}}\n\n' - 'data: {"seq":2,"progress":{"current_step":"Paused/Finished","steps":[{"step":"final",' - '"status":"success","message":"Automation complete"}],"finished":true,"success":true}}\n\n' - ) - - worker._process_automation_progress_buffer() - - assert len(emitted) == 2 - - first = emitted[0] - assert first.current_step == "Mount" - assert first.finished is False - assert first.steps[0].step == WorkflowStateKind.MOUNT - assert first.steps[0].status == StepStatus.RUNNING - - second = emitted[1] - assert second.current_step == "Paused/Finished" - assert second.finished is True - assert second.success is True - assert second.steps[0].step == WorkflowStateKind.FINAL - assert second.steps[0].status == StepStatus.SUCCESS - - assert worker._automation_progress_buffer == "" - - worker.cleanup() - - -def test_handle_automation_progress_event_ignores_null_progress(): - worker = DAQWorker(base_url=None, token="test-token") - emitted: list = [] - - worker.automation_progress.connect(emitted.append) - - worker._handle_automation_progress_event('{"seq":3,"progress":null}') - - assert emitted == [] - - worker.cleanup() diff --git a/tests/unit/gui/test_axis_video_panel.py b/tests/unit/gui/test_axis_video_panel.py deleted file mode 100644 index d70992c2..00000000 --- a/tests/unit/gui/test_axis_video_panel.py +++ /dev/null @@ -1,36 +0,0 @@ -from aarecommon.models.models import SessionsStateEnum -from PySide6.QtWidgets import QVBoxLayout, QWidget - -from aare.gui.panels.axis_video_panel import AxisVideoPanel -from aare.gui.widgets.busy_overlay import build_busy_overlay_style -from aare.gui.widgets.video_image import VideoGraphicsView - - -def _vacant_style(): - return build_busy_overlay_style( - is_busy=False, tell_state=None, session_state=SessionsStateEnum.Vacant - ) - - -def test_badge_drawn_once_and_hint_stripped(qtbot): - # Combined-view shape: two video views stacked in one container. - container = QWidget() - layout = QVBoxLayout(container) - first, second = VideoGraphicsView(), VideoGraphicsView() - layout.addWidget(first) - layout.addWidget(second) - - panel = AxisVideoPanel("Combined", container) - qtbot.addWidget(panel) - - style = _vacant_style() - assert style is not None and style.subtext # sample camera keeps the hint - - panel.set_busy_style(style) - applied = first._busy_overlay_style - assert applied is not None - assert applied.subtext == "" # not clickable here, hint stripped - assert second._busy_overlay_style is None # one badge, not one per view - - panel.set_busy_style(None) - assert first._busy_overlay_style is None diff --git a/tests/unit/gui/test_axis_video_thread.py b/tests/unit/gui/test_axis_video_thread.py deleted file mode 100644 index 44ec9270..00000000 --- a/tests/unit/gui/test_axis_video_thread.py +++ /dev/null @@ -1,83 +0,0 @@ -from unittest.mock import MagicMock, patch - -import cv2 -import numpy as np -import pytest -from PySide6.QtGui import QImage - -from aare.gui.threads.axis_video_thread import VideoThread - - -@pytest.fixture -def video_thread(qtbot): - thread = VideoThread("127.0.0.1", camera=1) - return thread - - -def test_init(video_thread): - assert video_thread.camera_ip == "127.0.0.1" - assert video_thread.camera == 1 - assert video_thread.running is False - assert video_thread.is_busy is False - - -def test_set_camera_ip(video_thread): - video_thread.set_camera_ip("192.168.1.1") - assert video_thread.camera_ip == "192.168.1.1" - - -def test_set_busy(video_thread): - video_thread.set_busy(True) - assert video_thread.is_busy is True - - -def test_process_buffer_success(video_thread, qtbot): - # Create a small valid JPEG - img = np.zeros((10, 10, 3), dtype=np.uint8) - _, jpeg_bytes = cv2.imencode(".jpg", img) - jpeg_bytes = jpeg_bytes.tobytes() - - boundary = b"--boundary" - buffer = b"--boundary\r\nContent-Type: image/jpeg\r\n\r\n" + jpeg_bytes + b"\r\n--boundary" - - with qtbot.waitSignal(video_thread.frame_ready, timeout=1000) as blocker: - video_thread._process_buffer(buffer, boundary) - - assert isinstance(blocker.args[0], QImage) - assert blocker.args[0].width() == 10 - assert blocker.args[0].height() == 10 - - -def test_process_buffer_invalid_jpeg(video_thread): - boundary = b"--boundary" - buffer = b"--boundary\r\nContent-Type: image/jpeg\r\n\r\nNOT_A_JPEG\r\n--boundary" - - # Should not emit anything or raise exception - video_thread._process_buffer(buffer, boundary) - - -def test_stop(video_thread): - mock_session = MagicMock() - video_thread.session = mock_session - # Mocking wait and quit to avoid actual thread blocking in test - video_thread.quit = MagicMock() - video_thread.wait = MagicMock() - - video_thread.stop() - - assert video_thread.running is False - assert video_thread.session is None - mock_session.close.assert_called_once() - video_thread.quit.assert_called_once() - video_thread.wait.assert_called_once_with(5000) - - -@patch("requests.Session") -def test_run_connection_error(mock_session_class, video_thread, qtbot): - mock_session = mock_session_class.return_value - mock_session.get.side_effect = Exception("Connection Refused") - - with qtbot.waitSignal(video_thread.error_occurred, timeout=1000) as blocker: - video_thread.run() - - assert "Unexpected error" in blocker.args[0] diff --git a/tests/unit/gui/test_beamline_state_panel.py b/tests/unit/gui/test_beamline_state_panel.py deleted file mode 100644 index 1b85c3b5..00000000 --- a/tests/unit/gui/test_beamline_state_panel.py +++ /dev/null @@ -1,158 +0,0 @@ -from aarecommon.models.models import BeamlineStateEnum -from PySide6.QtCore import Qt - -from aare.gui.panels.beamline_state_panel import BeamlineStatePanel -from aare.gui.styles import STATE_AVAILABLE, STATE_MSG_ERROR, STATE_MSG_INFO, STATE_UNAVAILABLE - - -def _panel(qtbot, staff=True): - panel = BeamlineStatePanel(staff=staff) - qtbot.addWidget(panel) - return panel - - -def test_availability_from_maintenance(qtbot): - panel = _panel(qtbot) - panel.set_current_state(BeamlineStateEnum.Maintenance) - assert panel._available_targets() == frozenset({BeamlineStateEnum.SampleExchange}) - - -def test_availability_is_union_of_routes_and_menu_shortcuts(qtbot): - panel = _panel(qtbot) - panel.set_current_state(BeamlineStateEnum.SampleAlignment) - targets = panel._available_targets() - assert BeamlineStateEnum.FluxMeasurement in targets # one-hop route - assert BeamlineStateEnum.SampleExchange in targets # status-bar shortcut - assert BeamlineStateEnum.XtalSnapshot not in targets # two hops away - - -def test_non_staff_never_reach_admin_only_states(qtbot): - panel = _panel(qtbot, staff=False) - panel.set_current_state(BeamlineStateEnum.SampleAlignment) - targets = panel._available_targets() - assert BeamlineStateEnum.BeamLocation not in targets - assert BeamlineStateEnum.BeamstopAlignment not in targets - assert BeamlineStateEnum.FluxMeasurement not in targets - assert BeamlineStateEnum.DataCollection in targets # non-admin route stays - # Greyed like unreachable states, and the warning tip carries the red - # QToolTip wash while a normal-hint button does not. - gated = panel._buttons[BeamlineStateEnum.BeamLocation] - assert gated.cursor().shape() == Qt.CursorShape.ForbiddenCursor - assert "QToolTip" in gated.styleSheet() - assert "QToolTip" not in panel._buttons[BeamlineStateEnum.XtalSnapshot].styleSheet() - with qtbot.assertNotEmitted(panel.beam_location): - panel._emit_for_state(BeamlineStateEnum.BeamLocation) - panel._on_left_click(BeamlineStateEnum.BeamLocation) # shows the admin tip - - -def test_no_targets_while_moving_or_unknown(qtbot): - panel = _panel(qtbot) - panel.set_current_state(None) - assert panel._available_targets() == frozenset() - panel.set_current_state(BeamlineStateEnum.Moving) - assert panel._available_targets() == frozenset() - - -def test_emit_gated_by_availability(qtbot): - panel = _panel(qtbot) - panel.set_current_state(BeamlineStateEnum.Maintenance) - with qtbot.waitSignal(panel.sample_exchange, timeout=1000): - panel._emit_for_state(BeamlineStateEnum.SampleExchange) - with qtbot.assertNotEmitted(panel.flux_measurement): - panel._emit_for_state(BeamlineStateEnum.FluxMeasurement) - - -def test_active_maintenance_is_red_and_bold(qtbot): - panel = _panel(qtbot) - panel.set_current_state(BeamlineStateEnum.Maintenance) - maintenance = panel._buttons[BeamlineStateEnum.Maintenance] - assert maintenance.font().bold() - assert STATE_MSG_ERROR in maintenance.styleSheet() - - -def test_availability_palette_and_cursors(qtbot): - panel = _panel(qtbot) - panel.set_current_state(BeamlineStateEnum.Maintenance) - available = panel._buttons[BeamlineStateEnum.SampleExchange] - grey = panel._buttons[BeamlineStateEnum.FluxMeasurement] - assert STATE_AVAILABLE in available.styleSheet() - assert available.cursor().shape() == Qt.CursorShape.PointingHandCursor - assert not available.font().bold() - assert STATE_UNAVAILABLE in grey.styleSheet() - assert grey.cursor().shape() == Qt.CursorShape.ForbiddenCursor - assert grey.toolTip() == "" - assert available.toolTip() != "" - - -def test_active_non_maintenance_is_blue(qtbot): - panel = _panel(qtbot) - panel.set_current_state(BeamlineStateEnum.SampleAlignment) - active = panel._buttons[BeamlineStateEnum.SampleAlignment] - assert active.font().bold() - assert STATE_MSG_INFO in active.styleSheet() - - -def test_labels_wrap_when_narrow_and_unwrap_when_wide(qtbot): - panel = _panel(qtbot) - sample_exchange = panel._buttons[BeamlineStateEnum.SampleExchange] - - panel.resize(600, 60) - panel._update_label_mode() - assert not panel._single_line - assert sample_exchange.text() == "Manual sample\nexchange" - - panel.resize(4000, 60) - panel._update_label_mode() - assert panel._single_line - assert sample_exchange.text() == "Manual sample exchange" - - -def test_left_click_never_transitions_but_hints(qtbot): - panel = _panel(qtbot) - panel.set_current_state(BeamlineStateEnum.Maintenance) - with qtbot.assertNotEmitted(panel.sample_exchange): - panel._on_left_click(BeamlineStateEnum.SampleExchange) # reminder tip - panel._on_left_click(BeamlineStateEnum.FluxMeasurement) # reachability hint - panel._on_left_click(BeamlineStateEnum.Maintenance) # current: no-op - - -def test_hover_hint_timer_lifecycle(qtbot): - panel = _panel(qtbot) - panel.set_current_state(BeamlineStateEnum.Maintenance) - panel._set_hovered_state(BeamlineStateEnum.FluxMeasurement) - assert panel._hover_hint_timer.isActive() - panel._show_hover_hint() # runs the unavailable-hint path - panel._clear_hovered_state() - assert not panel._hover_hint_timer.isActive() - assert panel._hovered_state is None - - -def test_update_daq_status_sets_state(qtbot, daq_status_factory): - panel = _panel(qtbot) - panel.update_daq_status(daq_status_factory(state=BeamlineStateEnum.SampleAlignment)) - assert panel._current_state == BeamlineStateEnum.SampleAlignment - - -def test_pending_target_cleared_on_arrival(qtbot): - panel = _panel(qtbot) - panel.set_current_state(BeamlineStateEnum.Maintenance) - panel._emit_for_state(BeamlineStateEnum.SampleExchange) - assert panel._pending_target_state == BeamlineStateEnum.SampleExchange - panel.set_current_state(BeamlineStateEnum.SampleExchange) - assert panel._pending_target_state is None - - -def test_pending_target_breathes_only_while_moving(qtbot): - panel = _panel(qtbot) - panel.set_current_state(BeamlineStateEnum.Maintenance) - panel._emit_for_state(BeamlineStateEnum.SampleExchange) - target = panel._buttons[BeamlineStateEnum.SampleExchange] - assert target.graphicsEffect() is None # not Moving yet - - panel.set_current_state(BeamlineStateEnum.Moving) - assert panel._breathing_button is target - assert target.graphicsEffect() is not None - - panel.set_current_state(BeamlineStateEnum.SampleExchange) - assert panel._breathing_button is None - assert target.graphicsEffect() is None diff --git a/tests/unit/gui/test_busy_overlay.py b/tests/unit/gui/test_busy_overlay.py deleted file mode 100644 index cf188c2d..00000000 --- a/tests/unit/gui/test_busy_overlay.py +++ /dev/null @@ -1,77 +0,0 @@ -"""The Axis views' busy flag is a passive status: plain shadowed text, not -the badge pill (which reads as a button). These checks fail if the text -renderer stops painting or the video view stops routing through it.""" - -from aarecommon.models.models import SessionsStateEnum -from PySide6.QtCore import Qt -from PySide6.QtGui import QPainter, QPixmap - -from aare.gui.widgets.busy_overlay import build_busy_overlay_style, draw_busy_status_text -from aare.gui.widgets.video_image import VideoGraphicsView - - -def _busy_style(): - style = build_busy_overlay_style(is_busy=True, tell_state=None) - assert style is not None and style.text == "BEAMLINE BUSY" - return style - - -def test_status_text_paints_something(qapp): - pixmap = QPixmap(400, 300) - pixmap.fill(Qt.GlobalColor.black) - blank = pixmap.toImage() - painter = QPainter(pixmap) - draw_busy_status_text(painter, 400, 300, _busy_style()) - painter.end() - assert pixmap.toImage() != blank, "busy text must actually paint" - - -def test_video_view_paints_busy_text(qtbot): - view = VideoGraphicsView() - qtbot.addWidget(view) - view.resize(400, 300) - idle = view.grab().toImage() - view.set_busy_overlay_style(_busy_style()) - assert view.grab().toImage() != idle, "busy style must change the rendered view" - view.set_busy_overlay_style(None) - assert view.grab().toImage() == idle, "clearing the style must restore the view" - - -def test_auto_centering_flag_overrides_alignment_gate(): - # Callers pass is_busy=False during SampleAlignment; the flag must still - # produce the overlay, and the viewing-mode badge must still win. - style = build_busy_overlay_style(is_busy=False, tell_state=None, auto_centering=True) - assert style is not None and style.text == "AUTO CENTERING" - assert build_busy_overlay_style(is_busy=False, tell_state=None) is None - viewing = build_busy_overlay_style( - is_busy=False, - tell_state=None, - session_state=SessionsStateEnum.OwnedByElse, - auto_centering=True, - ) - assert viewing is not None and viewing.text.startswith("Viewing mode") - - -def test_robot_cooling_is_the_only_blue_busy_state(): - from types import SimpleNamespace - from typing import cast - - from aarecommon.models.tell import TellStateModel - - from aare.gui.styles import BUSY_BLUE, BUSY_PSI_RED - - def _style(activity: str): - # Only .activity.value is read; cast keeps basedpyright off the stand-in. - tell = cast( - TellStateModel, cast(object, SimpleNamespace(activity=SimpleNamespace(value=activity))) - ) - style = build_busy_overlay_style(is_busy=True, tell_state=tell) - assert style is not None - return style - - assert _style("cooling").text == "ROBOT COOLING" - assert _style("cooling").badge_bg == BUSY_BLUE - # Every other busy state shares the one PSI red. - for activity in ("mounting", "unmounting", "drying", "unknown"): - assert _style(activity).badge_bg == BUSY_PSI_RED - assert _style("unknown").text == "BEAMLINE BUSY" diff --git a/tests/unit/gui/test_camera_image.py b/tests/unit/gui/test_camera_image.py deleted file mode 100644 index e94814bf..00000000 --- a/tests/unit/gui/test_camera_image.py +++ /dev/null @@ -1,360 +0,0 @@ -import pytest -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, - CrystalSize, - DAQStatusModel, - SampleCameraSettings, - SessionsStateEnum, - SessionStatus, -) -from PySide6.QtCore import QEvent, QPoint, QPointF, Qt -from PySide6.QtGui import QMouseEvent - -from aare.gui.scan_logic.raster_grid_manager import RasterGridManager -from aare.gui.styles import THEME_SUNRISE, THEME_SUNSET -from aare.gui.widgets.camera_image import SampleCameraImageLabel - - -def _geom() -> SampleGeometryModel: - return SampleGeometryModel( - beam_location_pxl=Coordinate(x=1000, y=1000), - pixel_in_mm=0.001, - aerotech=Coordinate(), - aerotech_meas=Coordinate(), - smargon=SmargonCoordinate(sh_mm=Coordinate(), phi_deg=0, chi_deg=0), - omega_deg=0, - beam_size_mm=Coordinate(x=0.01, y=0.01), - ) - - -def _status( - *, - busy: bool, - session: SessionsStateEnum, - state: BeamlineStateEnum = BeamlineStateEnum.SampleAlignment, -) -> DAQStatusModel: - return DAQStatusModel( - geom=_geom(), - diffraction=DiffractionGeometry( - energy_keV=12.4, - dtz_mm=100.0, - detector_size_pxl=(1553, 1630), - pixel_size_mm=0.150, - beam_center_pxl=(750.0, 750.0), - detector_description="PILATUS 4", - detector_serial_number="1", - poni_rot1_rad=0.0, - poni_rot2_rad=0.0, - ), - bl=BeamlineStatus( - name="SIMULATED", - ring_current_mA=400.0, - front_light=50.0, - back_light=50.0, - cryojet_K=100.0, - shutter_open=False, - exp_shutter_open=False, - flux_ph_s=1e12, - sample_camera=SampleCameraSettings(gain=1.0, exposure=0.02), - transmission=1.0, - zoom=1.0, - commissioning_mode=False, - dtz_min=120.0, - dtz_max=1600.0, - ), - state=state, - busy=busy, - session=SessionStatus(session=session, current_pgroup="p123", staff=True), - crystal_size=CrystalSize(x=0, y=0, z=0), - ) - - -def _mouse_move(widget, pos: QPoint) -> None: - # qtbot.mouseMove drives the real cursor, which the offscreen platform - # ignores — deliver the move event directly instead. - event = QMouseEvent( - QEvent.Type.MouseMove, - QPointF(pos), - QPointF(widget.mapToGlobal(pos)), - Qt.MouseButton.NoButton, - Qt.MouseButton.NoButton, - Qt.KeyboardModifier.NoModifier, - ) - widget.mouseMoveEvent(event) - - -@pytest.fixture -def camera(qtbot): - geom = _geom() - label = SampleCameraImageLabel(geom=geom, raster=RasterGridManager(geom), default_image=None) - qtbot.addWidget(label) - label.resize(800, 600) - return label - - -def test_help_badge_click_toggles_cheatsheet(camera, qtbot): - camera.grab() # paint records the collapsed "?" badge hit rect - badge = camera._help_hit_rect - assert badge is not None - assert not camera._help_expanded - - qtbot.mouseClick(camera.viewport(), Qt.MouseButton.LeftButton, pos=badge.center().toPoint()) - assert camera._help_expanded - - camera.grab() # expanded overlay: hit rect grows to the whole cheatsheet box - box = camera._help_hit_rect - assert box is not None - assert box.height() > badge.height() - - qtbot.mouseClick(camera.viewport(), Qt.MouseButton.LeftButton, pos=box.center().toPoint()) - assert not camera._help_expanded - - -def test_help_overlay_folds_when_mouse_leaves_box(camera, qtbot): - camera.grab() # paint records the collapsed "?" badge hit rect - badge = camera._help_hit_rect - qtbot.mouseClick(camera.viewport(), Qt.MouseButton.LeftButton, pos=badge.center().toPoint()) - assert camera._help_expanded - camera.grab() # expanded paint records the full box rect - box = camera._help_hit_rect - - _mouse_move(camera, box.center().toPoint()) # inside the box: stays open - assert camera._help_expanded - - _mouse_move(camera, QPoint(int(box.left()) - 40, int(box.bottom()) + 40)) - assert not camera._help_expanded, "moving off the box must fold it back to the badge" - - # Leaving the widget entirely folds it too. - camera.grab() - badge = camera._help_hit_rect - qtbot.mouseClick(camera.viewport(), Qt.MouseButton.LeftButton, pos=badge.center().toPoint()) - assert camera._help_expanded - camera.leaveEvent(QEvent(QEvent.Type.Leave)) - assert not camera._help_expanded - - -def test_camera_error_message_rewords_and_draws(camera): - camera.set_camera_available(False) - camera.set_camera_error_message("Sample camera feed unavailable: cable unplugged") - assert camera._camera_error_message == ( - "Sample camera feed unavailable because cable unplugged" - ) - camera.grab() # exercises the bottom-center unavailable overlay text path - - camera.set_camera_available(True) - assert camera._camera_error_message is None - - -def test_busy_warning_is_not_a_click_target(camera): - camera.update_daq_status( - _status( - busy=True, session=SessionsStateEnum.OwnedByYou, state=BeamlineStateEnum.DataCollection - ) - ) - style = camera._busy_overlay_style - assert style is not None - assert style.text == "BEAMLINE BUSY" - camera.grab() - assert camera._session_badge_rect is None - - # Sample alignment is the exception: its busy moves ARE the alignment, - # watched in this very view — no BEAMLINE BUSY curtain over it. - camera.update_daq_status( - _status( - busy=True, session=SessionsStateEnum.OwnedByYou, state=BeamlineStateEnum.SampleAlignment - ) - ) - assert camera._busy_overlay_style is None - - -def test_vacant_badge_hover_click_and_theme(camera, qtbot): - camera.update_daq_status(_status(busy=False, session=SessionsStateEnum.Vacant)) - style = camera._busy_overlay_style - assert style is not None - assert style.subtext # the grab-baton hint line - - camera.grab() # paint records the badge rect - badge = camera._session_badge_rect - assert badge is not None - - _mouse_move(camera, badge.center()) - assert camera._session_badge_hovered - camera.grab() # hover fill, light-theme darken branch - - camera.set_theme(THEME_SUNSET) - assert camera._dark_theme - camera.grab() # hover fill, sunset brighten branch - camera.set_theme(THEME_SUNRISE) - assert not camera._dark_theme - - _mouse_move(camera, QPoint(1, 1)) - assert not camera._session_badge_hovered - - _mouse_move(camera, badge.center()) - camera.leaveEvent(QEvent(QEvent.Type.Leave)) - assert not camera._session_badge_hovered - - with qtbot.waitSignal(camera.session_badge_clicked, timeout=1000): - qtbot.mouseClick(camera.viewport(), Qt.MouseButton.LeftButton, pos=badge.center()) - - -def test_help_more_link_opens_full_dialog(camera, qtbot): - camera.grab() # paint records the "?" badge hit rect - badge = camera._help_hit_rect - qtbot.mouseClick(camera.viewport(), Qt.MouseButton.LeftButton, pos=badge.center().toPoint()) - assert camera._help_expanded - camera.grab() # expanded overlay paint records the More... link rect - more = camera._help_more_rect - assert more is not None - - opened = [] - camera.open_full_help.connect(lambda: opened.append(True)) - qtbot.mouseClick(camera.viewport(), Qt.MouseButton.LeftButton, pos=more.center().toPoint()) - assert opened, "More... must open the full F1 dialog" - assert not camera._help_expanded # cheatsheet folds behind the dialog - - -def _wheel(widget, *, x=0, y=0, modifiers=Qt.KeyboardModifier.NoModifier): - from PySide6.QtGui import QWheelEvent - - return QWheelEvent( - QPointF(5, 5), - QPointF(widget.mapToGlobal(QPoint(5, 5))), - QPoint(0, 0), - QPoint(x, y), - Qt.MouseButton.NoButton, - modifiers, - Qt.ScrollPhase.NoScrollPhase, - False, - ) - - -def test_alt_wheel_axis_swap_still_changes_exposure(camera): - """xcb/windows swap wheel axes while Alt is held: the scroll lands in - angleDelta().x(). The fallback must still reach the exposure branch — - and a genuinely empty wheel event must do nothing.""" - camera.update_daq_status(_status(busy=False, session=SessionsStateEnum.OwnedByYou)) - sent = [] - camera.samcam_updated.connect(sent.append) - - camera.wheelEvent(_wheel(camera, x=-120, modifiers=Qt.KeyboardModifier.AltModifier)) - assert sent, "Alt+wheel with x-only delta must still adjust exposure" - assert sent[0].exposure < 0.02, "negative delta must decrease exposure" - - camera.wheel_event_timer.stop() # bypass the throttle for the second event - n = len(sent) - camera.wheelEvent(_wheel(camera)) # zero delta: ignored - assert len(sent) == n - - -def test_hover_hud_coords_and_scale_bar(camera): - # Hover inside the image: bottom-right HUD paints coords + grey scale bar. - _mouse_move(camera, QPoint(400, 300)) - assert camera._hover_pos is not None - camera.grab() - - # Hover outside the image (negative scene coords): HUD skips drawing. - _mouse_move(camera, QPoint(-10, -10)) - camera.grab() - - # Leaving the view clears the readout entirely. - camera.leaveEvent(QEvent(QEvent.Type.Leave)) - assert camera._hover_pos is None - camera.grab() - - -def test_scale_bar_nice_numbers(): - # 1-2-5 progression against the ~120 px target, and the mm label swap. - assert SampleCameraImageLabel._scale_bar(1.0) == (100.0, "100 µm") - assert SampleCameraImageLabel._scale_bar(2.0) == (200.0, "200 µm") - assert SampleCameraImageLabel._scale_bar(5.0) == (500.0, "500 µm") - assert SampleCameraImageLabel._scale_bar(10.0) == (1000.0, "1 mm") - - -def test_autoscale_fits_from_the_first_frame(camera): - from PySide6.QtGui import QPixmap - - # Fit-to-view is the default; a frame whose size differs from the fitted - # one (here: the 2000x2000 startup placeholder) must refit immediately, - # not wait for the next view resize. - assert camera._autoscale - camera.update_pixmap(QPixmap(4000, 4000)) - assert camera.transform().m11() < 1.0 - - # The right-click toggle still restores 1:1. - camera._autoscale = False - camera._scaling() - assert camera.transform().isIdentity() - - -def test_unknown_session_paints_the_viewing_mode_badge(camera): - # No status yet: the busy overlay has nothing, the session overlay must - # still hand out the same click target as the known not-owned states. - assert camera._busy_overlay_style is None - camera.grab() - assert camera._session_badge_rect is not None - - -def test_mounted_sample_hud_follows_status(camera): - from aarecommon.models.models import DewarAddress, SampleShortInfo - - # No sample in the status -> no HUD line, draw path skips cleanly. - assert camera._mounted_sample_name is None - camera.grab() - - sample = SampleShortInfo( - db_id=7, - puck_name="puck1", - dewar_name="dewar", - sample_name="lyso_007", - run_number=1, - user="p123", - pin=1, - location=DewarAddress(segment="A", pos=1), - ) - status = _status(busy=False, session=SessionsStateEnum.OwnedByYou) - camera.update_daq_status(status.model_copy(update={"sample": sample})) - assert camera._mounted_sample_name == "lyso_007" - camera.grab() # paints the top-left "Currently mounted:" line - - # Unmount (sample gone from the status) clears the line again. - camera.update_daq_status(status) - assert camera._mounted_sample_name is None - - -def test_mounted_hud_ink_follows_theme(camera): - """Mounted-sample HUD: theme text ink + white halo on light themes, inverted on Sunset.""" - from aare.gui.styles import SHADOW, TEXT, THEME_SUNRISE, THEME_SUNSET, WHITE - - camera.set_theme(THEME_SUNRISE) - assert camera._mounted_hud_ink() == (TEXT, WHITE) - camera.set_theme(THEME_SUNSET) - assert camera._mounted_hud_ink() == (WHITE, SHADOW) - - -def test_beam_crosshair_toggle_draws(camera, monkeypatch): - from PySide6.QtWidgets import QMenu - - assert camera._show_beam_crosshair is False - # Pick the crosshair action out of the real menu instead of exec'ing it. - monkeypatch.setattr( - QMenu, - "exec_", - lambda self, *_: next(a for a in self.actions() if a.text() == "Show beam crosshair"), - ) - camera._camera_interaction_enabled = lambda: True - press = QMouseEvent( - QEvent.Type.MouseButtonPress, - QPointF(10, 10), - QPointF(camera.mapToGlobal(QPoint(10, 10))), - Qt.MouseButton.RightButton, - Qt.MouseButton.RightButton, - Qt.KeyboardModifier.NoModifier, - ) - camera._right_click_menu(press) - assert camera._show_beam_crosshair is True - camera.grab() # exercises the crosshair draw path diff --git a/tests/unit/gui/test_camera_thread.py b/tests/unit/gui/test_camera_thread.py deleted file mode 100644 index 70e6928d..00000000 --- a/tests/unit/gui/test_camera_thread.py +++ /dev/null @@ -1,109 +0,0 @@ -import json -from unittest.mock import MagicMock, patch - -import cv2 -import numpy as np -import pytest -import zmq - -from aare.gui.threads.camera_thread import SampleCameraThread - - -@pytest.fixture -def mock_zmq(): - with patch("zmq.Context") as mock_ctx_class: - mock_ctx = mock_ctx_class.return_value - mock_socket = mock_ctx.socket.return_value - yield mock_socket - - -@pytest.fixture -def camera_thread(mock_zmq, qtbot): - thread = SampleCameraThread("tcp://127.0.0.1:5555") - yield thread - thread.running = False - try: - thread.stop() - except RuntimeError: - pass - - -def test_init(camera_thread): - assert camera_thread.running is True - assert camera_thread._camera_available is False - - -def test_update_daq_status(camera_thread): - s = MagicMock() - s.geom.beam_location_pxl.x = 100 - s.geom.beam_location_pxl.y = 200 - camera_thread.update_daq_status(s) - assert camera_thread._beam_x == 100 - assert camera_thread._beam_y == 200 - - -def test_enable_focus_measurement(camera_thread): - camera_thread.enable_focus_measurement(True) - assert camera_thread._measure_focus is True - camera_thread.enable_focus_measurement(False) - assert camera_thread._measure_focus is False - - -def test_run_success(camera_thread, mock_zmq, qtbot): - img = np.zeros((10, 10, 3), dtype=np.uint8) - _, jpeg_bytes = cv2.imencode(".jpg", img) - header = json.dumps({"encoding": "jpeg"}).encode("utf-8") - - def side_effect(): - camera_thread.running = False - return [header, jpeg_bytes.tobytes()] - - mock_zmq.recv_multipart.side_effect = side_effect - - with qtbot.waitSignal(camera_thread.camera_image, timeout=5000): - camera_thread.run() - - assert camera_thread._camera_available is True - - -def test_run_bayer_success(camera_thread, mock_zmq, qtbot): - h, w = 10, 10 - raw = np.zeros((h, w), dtype=np.uint8) - header = json.dumps({"shape": [h, w]}).encode("utf-8") - - def side_effect(): - camera_thread.running = False - return [header, raw.tobytes()] - - mock_zmq.recv_multipart.side_effect = side_effect - - with qtbot.waitSignal(camera_thread.camera_image, timeout=5000): - camera_thread.run() - - assert camera_thread._camera_available is True - - -def test_run_zmq_timeout(camera_thread, mock_zmq, qtbot): - def side_effect(): - camera_thread.running = False - raise zmq.Again() - - mock_zmq.recv_multipart.side_effect = side_effect - camera_thread._fps_emit_period_s = 0.0 - - with qtbot.waitSignal(camera_thread.fps_measure, timeout=5000): - try: - camera_thread.run() - except StopIteration: - pass - - -def test_stop(camera_thread, mock_zmq): - camera_thread.quit = MagicMock() - camera_thread.wait = MagicMock() - - camera_thread.stop() - - assert camera_thread.running is False - if hasattr(camera_thread, "_SampleCameraThread__socket"): - mock_zmq.close.assert_called() diff --git a/tests/unit/gui/test_daq_worker_recovery.py b/tests/unit/gui/test_daq_worker_recovery.py deleted file mode 100644 index d4eab57b..00000000 --- a/tests/unit/gui/test_daq_worker_recovery.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Covers the recovery-response payload handling in DAQWorker. - -The server may return a bare JSON string instead of a dict during recovery -(see fix "allow str has no get when in recovery"), so the handler must not -assume ``payload.get`` exists. -""" - -import json -from unittest.mock import MagicMock - -import pytest - -from aare.gui.threads.daq_worker import DAQWorker - - -@pytest.fixture -def worker(qapp): - w = DAQWorker(base_url=None, token="test-token") - w._timer.stop() # no background polling during tests - w.send_status_request = MagicMock() - return w - - -def run_recovery(worker, response_data, default="default recovery message"): - worker.handle_response = MagicMock(return_value=response_data) - slot = MagicMock() - worker.recovery_action_completed.connect(slot) - worker._handle_recovery_action_response(MagicMock(), default) - return slot - - -def test_recovery_response_dict_payload(worker): - slot = run_recovery(worker, json.dumps({"message": "TELL recovered"})) - slot.assert_called_once_with("TELL recovered") - - -def test_recovery_response_dict_without_message_uses_default(worker): - slot = run_recovery(worker, json.dumps({"status": "ok"}), default="fallback") - slot.assert_called_once_with("fallback") - - -def test_recovery_response_str_payload(worker): - # A bare JSON string has no .get(); must be passed through as-is. - slot = run_recovery(worker, json.dumps("plain string status")) - slot.assert_called_once_with("plain string status") diff --git a/tests/unit/gui/test_data_collection_settings.py b/tests/unit/gui/test_data_collection_settings.py deleted file mode 100644 index 28046cce..00000000 --- a/tests/unit/gui/test_data_collection_settings.py +++ /dev/null @@ -1,641 +0,0 @@ -"""Tests for the scan settings panels. - -Covers where the numbers in the fields come from (the mounted sample's -spreadsheet row, the user's own values, the panel defaults), that a user value -survives a new sample all the way into the scan request while the settings the -user did not touch keep following the sample, and that a number typed but never -committed does not take effect. -""" - -import types -from typing import Any, cast - -import pytest -from aarecommon.math.coordinate import Coordinate, SmargonCoordinate -from aarecommon.math.diffraction_geometry import DiffractionGeometry -from aarecommon.models.models import ( - BeamlineStateEnum, - DataCollectionParameters, - SampleGeometryModel, - SampleShortInfo, -) -from PySide6.QtCore import Qt -from PySide6.QtWidgets import QLabel - -from aare.gui.panels.data_collection_settings import DataCollectionSettings -from aare.gui.panels.raster_data_collection import RasterDataCollectionPanel -from aare.gui.panels.rotation_data_collection import RotationDataCollectionPanel -from aare.gui.panels.scan_settings_panel import SampleParameters -from aare.gui.scan_logic.raster_grid_manager import RasterGridManager -from aare.gui.widgets.number_line_edit import NumberLineEdit - - -def _commit(field: NumberLineEdit, text: str): - """Type into a field and commit it, as Enter or leaving the field does.""" - field.setText(text) - field.on_editing_finished() - - -def _mount(panel, **params): - """Mount a sample whose spreadsheet row holds `params`; same two steps - update_daq_status takes when the parameters of the mounted sample change.""" - panel._db_params = SampleParameters(**params) - panel._refresh_fields() - - -# --------------------------------------------------------------------------- -# The spreadsheet row -> SampleParameters -# --------------------------------------------------------------------------- - - -def test_sample_parameters_translate_the_spreadsheet_row(): - # The real model, so the column names are checked against aareDB and not - # against a stand-in that agrees with whatever this file happens to say. - sample = SampleShortInfo( - db_id=1, - puck_name="puck1", - dewar_name="dewar1", - sample_name="sample1", - run_number=1, - pin=1, - aaredb_params=DataCollectionParameters( - targetresolution=1.5, - transmission=0.2, # 0-to-1 fraction; aareDB converts the percent sheets - totalangle=180, - oscillation=0.1, - exposure=0.02, - ), - ) - assert SampleParameters.from_sample(sample) == SampleParameters( - resolution_a=1.5, - transmission=0.2, - total_angle_deg=180.0, - image_angle_deg=0.1, - exp_time_s=0.02, - ) - - -def test_sample_parameters_are_empty_without_a_sample(): - assert SampleParameters.from_sample(None) == SampleParameters() - - -def test_a_column_aaredb_does_not_have_is_ignored(): - # aareDB owns these names: a renamed column must leave the panel on its - # defaults, not break the status loop it is read from. - params = types.SimpleNamespace(targetresolution=1.5) - sample = cast(Any, types.SimpleNamespace(aaredb_params=params)) - assert SampleParameters.from_sample(sample) == SampleParameters(resolution_a=1.5) - - -# --------------------------------------------------------------------------- -# Rotation panel -# --------------------------------------------------------------------------- - - -@pytest.fixture -def diffraction(): - return DiffractionGeometry( - energy_keV=12.0, - dtz_mm=150.0, - pixel_size_mm=0.075, - beam_center_pxl=(1000.0, 1000.0), - detector_size_pxl=(2000, 2000), - detector_description="Eiger 16M", - detector_serial_number="123", - poni_rot1_rad=0.0, - poni_rot2_rad=0.0, - ) - - -@pytest.fixture -def panel(qapp, diffraction): - return RotationDataCollectionPanel(diffraction=diffraction) - - -@pytest.fixture -def runnable_panel(panel, monkeypatch): - """A rotation panel whose Run button reaches the request: beamline ready - and the file path/precondition dialogs answered.""" - panel._beamline_state = BeamlineStateEnum.SampleAlignment - monkeypatch.setattr(panel, "check_before_run", lambda scan_kind: True) - return panel - - -def test_fields_follow_the_mounted_sample(panel): - _mount(panel, resolution_a=2.5, transmission=0.5, total_angle_deg=180.0, exp_time_s=0.02) - - assert panel.high_res_enter.committed_value == 2.5 - assert panel.dtz_enter.committed_value == pytest.approx(panel._res_to_dtz(2.5), abs=0.01) - assert panel.transmission_enter.committed_value == 0.5 - assert panel.total_angle.committed_value == 180.0 - assert panel.image_time_enter.committed_value == 0.02 - # An empty spreadsheet cell leaves the panel default in place. - assert panel.image_angle.committed_value == panel._default_image_angle - - -def test_editing_resolution_updates_dtz_and_selects_user_values(panel): - _commit(panel.high_res_enter, "2.00") - - assert panel._show_user_values - assert panel._user_radio.isChecked() - assert panel.dtz_enter.committed_value == pytest.approx(panel._res_to_dtz(2.0), abs=0.01) - - -def test_editing_dtz_updates_resolution(panel, diffraction): - _commit(panel.dtz_enter, "250.00") - - assert panel.high_res_enter.committed_value == pytest.approx( - diffraction.resolution_angstrom(250.0), abs=0.01 - ) - - -def test_user_value_survives_the_next_sample(runnable_panel): - panel = runnable_panel - _mount(panel, resolution_a=2.5, transmission=0.5, total_angle_deg=180.0, exp_time_s=0.02) - - # The user overrides the resolution the spreadsheet asks for. - _commit(panel.high_res_enter, "3.00") - user_dtz = panel.dtz_enter.committed_value - - # Next sample, same spreadsheet values: the user's resolution stays put... - _mount(panel, resolution_a=2.5, transmission=0.5, total_angle_deg=180.0, exp_time_s=0.02) - assert panel.high_res_enter.committed_value == 3.00 - assert panel.dtz_enter.committed_value == user_dtz - - # ...and it is what the scan actually collects at. - requests = [] - panel.rotation_scan.connect(requests.append) - panel.run_measurement() - assert requests[-1].dtz == user_dtz - - -def test_untouched_settings_keep_following_the_sample(panel): - _mount(panel, total_angle_deg=180.0, exp_time_s=0.02) - _commit(panel.image_time_enter, "0.0500") # only the image time is the user's - - _mount(panel, total_angle_deg=360.0, exp_time_s=0.02) - assert panel.image_time_enter.committed_value == 0.05 - assert panel.total_angle.committed_value == 360.0 - - -def test_toggle_swaps_between_the_two_sets(panel): - _mount(panel, resolution_a=2.5, exp_time_s=0.02) - _commit(panel.image_time_enter, "0.0500") - - panel._database_radio.setChecked(True) # back to Database values - assert panel.image_time_enter.committed_value == 0.02 - assert panel.high_res_enter.committed_value == 2.5 - - panel._user_radio.setChecked(True) # the user's set is remembered - assert panel.image_time_enter.committed_value == 0.05 - - -def test_a_new_sample_is_shown_while_on_database_values(panel): - _mount(panel, exp_time_s=0.02) - assert panel.image_time_enter.committed_value == 0.02 - _mount(panel, exp_time_s=0.03) - assert panel.image_time_enter.committed_value == 0.03 - - -def test_text_that_was_never_entered_does_not_take_effect(runnable_panel): - panel = runnable_panel - _mount(panel, resolution_a=2.5, transmission=0.5, total_angle_deg=180.0, exp_time_s=0.02) - database_dtz = panel.dtz_enter.committed_value - - requests = [] - panel.rotation_scan.connect(requests.append) - - panel.high_res_enter.setText("3.00") # typed, never entered - panel.run_measurement() - assert not panel._show_user_values - assert requests[-1].dtz == database_dtz - - # Committing it is what makes it the user's. - panel.high_res_enter.on_editing_finished() - panel.run_measurement() - assert panel._show_user_values - assert requests[-1].dtz == pytest.approx(panel._res_to_dtz(3.00), abs=0.01) - - -def test_screening_transmission_is_the_panels_own(runnable_panel): - panel = runnable_panel - _mount(panel, transmission=0.5) - _commit(panel.screening_transmission_enter, "0.1000") - - requests = [] - panel.rotation_scan.connect(requests.append) - panel.run_screening() - - assert requests[-1].transmission == 0.1 # not the 0.5 the rotation uses - - -def test_downstream_gets_the_active_values(panel): - dtz_seen = [] - transmission_seen = [] - panel.dtz_updated.connect(dtz_seen.append) - panel.transmission_updated.connect(transmission_seen.append) - - _commit(panel.dtz_enter, "250.00") - assert dtz_seen[-1] == 250.0 - - # The transmission was never touched, so it keeps following the sample. - _mount(panel, transmission=0.4) - assert transmission_seen[-1] == 0.4 - - panel._database_radio.setChecked(True) - assert dtz_seen[-1] == pytest.approx(panel.dtz_enter.committed_value) - - -# --------------------------------------------------------------------------- -# Raster panel -# --------------------------------------------------------------------------- - - -@pytest.fixture -def geom(): - return SampleGeometryModel( - beam_location_pxl=Coordinate(x=500, y=500), - pixel_in_mm=0.001, - aerotech=Coordinate(x=0, y=0, z=0), - aerotech_meas=Coordinate(x=0, y=0, z=0), - smargon=SmargonCoordinate(sh_mm=Coordinate(x=0, y=0, z=0), phi_deg=0.0, chi_deg=0.0), - omega_deg=0.0, - beam_size_mm=Coordinate(x=0.01, y=0.01), - ) - - -@pytest.fixture -def raster_panel(qapp, diffraction, geom): - mgr = RasterGridManager(geom) - return RasterDataCollectionPanel(raster_mgr=mgr, diffraction=diffraction) - - -def test_grid_element_size_is_reported_and_echoed_back(raster_panel): - emitted = [] - raster_panel.grid_size_updated.connect(lambda x, y: emitted.append((x, y))) - - _commit(raster_panel.width_enter, "20") - assert emitted[-1][0] == pytest.approx(0.020) - - # The grid manager answers with the geometry it settled on; the field - # follows it and does not emit again. - before = len(emitted) - raster_panel.grid_scan_size_change(4, 5, 0.035, 0.020) - assert raster_panel.width_enter.committed_value == 35.0 - assert len(emitted) == before - - -def test_raster_exposure_follows_the_toggle(raster_panel): - _mount(raster_panel, exp_time_s=0.04) - assert raster_panel.image_time_enter.committed_value == 0.04 - - _commit(raster_panel.image_time_enter, "0.0800") - _mount(raster_panel, exp_time_s=0.04) - assert raster_panel.image_time_enter.committed_value == 0.08 - - raster_panel._database_radio.setChecked(True) - assert raster_panel.image_time_enter.committed_value == 0.04 - - -def test_grid_element_size_stays_out_of_the_toggle(raster_panel): - _commit(raster_panel.width_enter, "20") - # A panel-only field must not take the panel to user values. - assert not raster_panel._show_user_values - - -# --------------------------------------------------------------------------- -# DataCollectionSettings: per-tab grid button + auto-center after mount -# --------------------------------------------------------------------------- - - -@pytest.fixture -def settings_panel(qapp, diffraction, geom): - return DataCollectionSettings(geom, RasterGridManager(geom), diffraction) - - -def test_grid_button_only_on_raster_tab(settings_panel): - assert not settings_panel.bounding_box.isHidden() # Raster is the default tab - for idx in (1, 2, 3): - settings_panel._tab_bar.setCurrentIndex(idx) - assert settings_panel.bounding_box.isHidden() - settings_panel._tab_bar.setCurrentIndex(0) - assert not settings_panel.bounding_box.isHidden() - - -def test_auto_center_fires_on_mount_only_when_armed(settings_panel): - clicks = [] - settings_panel.find_tip.clicked.connect(lambda: clicks.append(1)) - settings_panel.auto_center_after_mount.setChecked(True) - - # First status with a sample already mounted = GUI (re)start: hardware - # must not move, only the id is recorded. - settings_panel._track_sample(1) - assert not clicks - - # Real mount after an unmount fires the centering. - settings_panel._track_sample(None) - settings_panel._track_sample(2) - assert len(clicks) == 1 - - # Direct sample exchange (no unmount tick in between) also fires. - settings_panel._track_sample(3) - assert len(clicks) == 2 - - # Remounting the SAME sample counts as a fresh mount. - settings_panel._track_sample(None) - settings_panel._track_sample(3) - assert len(clicks) == 3 - - # Disarmed: mounts no longer trigger. - settings_panel.auto_center_after_mount.setChecked(False) - settings_panel._track_sample(None) - settings_panel._track_sample(4) - assert len(clicks) == 3 - - -def test_auto_center_waits_for_hw_lock_after_mount(settings_panel): - clicks = [] - settings_panel.find_tip.clicked.connect(lambda: clicks.append(1)) - settings_panel.auto_center_after_mount.setChecked(True) - settings_panel._track_sample(None) - - # The mount still holds the hw lock when the sample id first shows up: - # /alc/center_loop would be refused, so no click yet. - settings_panel._track_sample(1, busy=True) - settings_panel._track_sample(1, busy=True) - assert not clicks - # First idle tick fires it, exactly once. - settings_panel._track_sample(1, busy=False) - settings_panel._track_sample(1, busy=False) - assert len(clicks) == 1 - - # Unmount while still pending drops the request. - settings_panel._track_sample(None) - settings_panel._track_sample(2, busy=True) - settings_panel._track_sample(None, busy=False) - assert len(clicks) == 1 - - # Queue automation mounts and centers on its own: never fire in its gaps. - settings_panel.set_automation_running(True) - settings_panel._track_sample(3, busy=True) - settings_panel._track_sample(3, busy=False) - assert len(clicks) == 1 - settings_panel.set_automation_running(False) - settings_panel._track_sample(None) - settings_panel._track_sample(4, busy=False) - assert len(clicks) == 2 - - -# --------------------------------------------------------------------------- -# Pending color while typing (movestate property, committed on Enter/focus-out) -# --------------------------------------------------------------------------- - - -def _type(qtbot, box, text): - box.clear() - qtbot.keyClicks(box, text) - - -@pytest.fixture -def tracked_box(qtbot): - box = NumberLineEdit(-720, 720, default=100.0, decimals=2, track_pending=True) - qtbot.addWidget(box) - return box - - -def test_typing_marks_pending_and_enter_commits(tracked_box, qtbot): - seen = [] - tracked_box.newValue.connect(seen.append) - _type(qtbot, tracked_box, "300") - assert tracked_box.property("movestate") == "pending" - assert not seen # nothing is applied until Enter/focus-out - assert tracked_box.committed_value == 100.0 - qtbot.keyClick(tracked_box, Qt.Key.Key_Return) - assert seen == [300.0] - assert tracked_box.committed_value == 300.0 - assert tracked_box.property("movestate") == "" - - -def test_typing_back_the_applied_value_cancels_pending(tracked_box, qtbot): - _type(qtbot, tracked_box, "300") - qtbot.keyClick(tracked_box, Qt.Key.Key_Return) - _type(qtbot, tracked_box, "300") # same as what is applied now - assert tracked_box.property("movestate") == "" - - -def test_incomplete_entry_is_pending(tracked_box, qtbot): - _type(qtbot, tracked_box, "-") # not a number (yet) - assert tracked_box.property("movestate") == "pending" - - -def test_untracked_box_never_touches_movestate(qtbot): - # MotorMoveGroup owns movestate on the boxes it registers; the default - # NumberLineEdit must therefore stay away from the property entirely. - box = NumberLineEdit(-720, 720, default=100.0, decimals=2) - qtbot.addWidget(box) - _type(qtbot, box, "300") - assert box.property("movestate") is None - - -def test_programmatic_update_clears_pending(tracked_box, qtbot): - _type(qtbot, tracked_box, "300") - tracked_box.force_update_value(120.0) - assert tracked_box.property("movestate") == "" - _type(qtbot, tracked_box, "300") - tracked_box.update_value(500.0) - assert tracked_box.property("movestate") == "" - - -def test_set_committed_value_keeps_a_value_that_did_not_change(tracked_box, qtbot): - _type(qtbot, tracked_box, "300") # typing, no commit - tracked_box.set_committed_value(100.0) # what the field already holds - assert tracked_box.text() == "300" # the typing survives - tracked_box.set_committed_value(120.0) # a real change wins - assert tracked_box.committed_value == 120.0 - assert tracked_box.property("movestate") == "" - - -def test_energy_spin_motor_move_semantics(settings_panel, daq_status_factory): - # same placeholder limits as the Beamline setup row (shared constants) - assert settings_panel.energy_spin.minimum() == 4.0 - assert settings_panel.energy_spin.maximum() == 20.0 - assert "Beamline Scientist" in settings_panel.energy_spin.toolTip() - - # Same MotorMoveGroup wiring as the Beamline setup row (full state walk - # tested there); here: stage -> pending, button sends -> moving, readback - # arrival -> neutral. - box = settings_panel.energy_spin # movestate sits on the spin itself - assert not settings_panel.change_energy_button.isEnabled() - - settings_panel.update_daq_status(daq_status_factory()) # readback 12.0 keV - assert settings_panel.energy_spin.value() == 12.0 - - settings_panel.energy_spin.setValue(12.4) - assert box.property("movestate") == "pending" - assert settings_panel.change_energy_button.isEnabled() - - sent = [] - settings_panel.change_energy.connect(sent.append) - settings_panel.change_energy_button.click() - assert sent and sent[-1] == pytest.approx(12400.0) - assert box.property("movestate") == "moving" - - settings_panel._energy_state.update_actual(12.3995) - assert box.property("movestate") == "" - - -def _grid_widget(grid, row: int, col: int): - item = grid.itemAtPosition(row, col) - assert item is not None - widget = item.widget() - assert widget is not None - return widget - - -def test_transmission_rows_are_per_mode(panel, qapp, diffraction): - # Rotation tab: the rotation transmission moved out of the shared top - # rows into the Rotation section (row 11, right under the header), below - # the Screening block and its Run button (row 9). - grid = panel._layout - label = _grid_widget(grid, 11, 0) - assert isinstance(label, QLabel) - assert label.text() == "Rotation transmission" - assert _grid_widget(grid, 11, 1) is panel.transmission_enter - assert _grid_widget(grid, 9, 0) is panel.screening_button - - # Gridscan tab keeps its own transmission in the top rows, without the - # misleading "Rotation" prefix. - geom = SampleGeometryModel( - beam_location_pxl=Coordinate(x=500, y=500), - pixel_in_mm=0.001, - aerotech=Coordinate(), - aerotech_meas=Coordinate(), - smargon=SmargonCoordinate(sh_mm=Coordinate(), phi_deg=0.0, chi_deg=0.0), - omega_deg=0.0, - beam_size_mm=Coordinate(x=0.01, y=0.01), - ) - raster = RasterDataCollectionPanel(RasterGridManager(geom), diffraction) - raster_label = _grid_widget(raster._layout, 2, 0) - assert isinstance(raster_label, QLabel) - assert raster_label.text() == "Transmission" - - -# --------------------------------------------------------------------------- -# File path panel: the Run buttons must not overwrite an existing dataset -# --------------------------------------------------------------------------- - - -@pytest.fixture -def file_panel(qapp): - from aare.gui.panels.file_path_panel import FilePathPanel - - p = FilePathPanel() - p.directory_edit.setText("d") - p.file_prefix_edit.setText("x") - p.run_number_edit.setValue(1) - return p - - -def _taken(monkeypatch, *suffixes): - from aare.gui.panels import file_path_panel - - monkeypatch.setattr( - file_path_panel.os.path, "exists", lambda path: any(path.endswith(s) for s in suffixes) - ) - - -def test_run_is_blocked_with_a_popup_when_the_file_exists(file_panel, monkeypatch): - from PySide6.QtWidgets import QMessageBox - - _taken(monkeypatch, "data/d/x_001_master.h5") - boxes = [] - monkeypatch.setattr(QMessageBox, "warning", lambda *a, **k: boxes.append(a)) - - # Editing never skips a taken run silently: the name stays literal. - file_panel.set_scan_kind("rotation") - assert file_panel.run_number_edit.value() == 1 - - assert file_panel.file_path_error_box(scan_kind="rotation") is False - assert len(boxes) == 1 - assert "data/d/x_001_master.h5" in boxes[0][2] - # Run number went up by one, so the next click can go ahead. - assert file_panel.run_number_edit.value() == 2 - assert file_panel.file_path_error_box(scan_kind="rotation") is True - assert len(boxes) == 1 - - -def test_run_proceeds_when_the_file_is_free(file_panel, monkeypatch): - from PySide6.QtWidgets import QMessageBox - - _taken(monkeypatch) - monkeypatch.setattr(QMessageBox, "warning", lambda *a, **k: pytest.fail("no popup expected")) - - assert file_panel.file_path_error_box(scan_kind="rotation") is True - assert file_panel.run_number_edit.value() == 1 - - -def test_a_derived_dataset_counts_as_taken(file_panel, monkeypatch): - # X-ray centering writes _raster2d_master.h5, not _master.h5. - from aare.gui.panels import file_path_panel - - _taken(monkeypatch, "raster/d/x_001_raster2d_master.h5") - monkeypatch.setattr(file_path_panel.QMessageBox, "warning", lambda *a, **k: None) - - assert file_panel.file_path_error_box(scan_kind="raster") is False - assert file_panel.run_number_edit.value() == 2 - - -def test_a_directory_or_a_sibling_run_is_not_taken(file_panel, monkeypatch): - # Only the exact master files count; anything else would block runs that - # nothing will write. - _taken(monkeypatch, "raster/d/x_001", "raster/d/x_0011_master.h5", "raster/d/x_001_data.h5") - file_panel.set_scan_kind("raster") - assert file_panel.file_path_error_box(scan_kind="raster") is True - - -def test_every_tab_reaches_the_file_guard(settings_panel, monkeypatch): - # The tabs live in a QStackedWidget, which reparents them: a parent() - # lookup of file_path_panel found nothing and every Run skipped the guard. - from aare.gui.panels import scan_settings_panel - - asked = [] - monkeypatch.setattr( - settings_panel.file_path_panel, - "file_path_error_box", - lambda scan_kind: asked.append(scan_kind) or False, - ) - monkeypatch.setattr(scan_settings_panel, "precondition_check", lambda *a, **k: True) - scans = [] - for panel in (settings_panel.screening, settings_panel.raster): - panel._beamline_state = BeamlineStateEnum.SampleAlignment - settings_panel.screening.rotation_scan.connect(scans.append) - settings_panel.simple.rotation_scan.connect(scans.append) - settings_panel.raster.evaluate_grid.connect(lambda: scans.append("grid")) - settings_panel.raster.evaluate_grid_auto.connect(lambda: scans.append("auto")) - - settings_panel.screening.run_screening() - settings_panel.screening.run_measurement() - settings_panel.simple.run_measurement() - settings_panel.raster._on_evaluate_clicked() - settings_panel.raster._on_evaluate_auto_clicked() - - assert asked == ["screening", "rotation", "rotation", "raster", "raster"] - assert scans == [] - - -def test_simple_tab_run_is_blocked_by_the_file_guard(qapp): - from PySide6.QtWidgets import QWidget - - from aare.gui.panels.smart_rotation_panel import SimpleRotationSettingsPanel - - holder = QWidget() - cast(Any, holder).file_path_panel = types.SimpleNamespace( - file_path_error_box=lambda scan_kind: False - ) - panel = SimpleRotationSettingsPanel(parent=holder) - requests = [] - panel.rotation_scan.connect(requests.append) - - panel.run_measurement() - - assert requests == [] diff --git a/tests/unit/gui/test_error_classifier.py b/tests/unit/gui/test_error_classifier.py deleted file mode 100644 index 25206679..00000000 --- a/tests/unit/gui/test_error_classifier.py +++ /dev/null @@ -1,63 +0,0 @@ -import sys -import types - -from aare.gui.threads.daq_worker import DAQWorker - -jfjoch_client_module = types.ModuleType("jfjoch_client") -jfjoch_client_module.ScanResult = object -jfjoch_client_module.ScanResultImagesInner = object - -jfjoch_client_models_module = types.ModuleType("jfjoch_client.models") -jfjoch_client_scan_result_module = types.ModuleType("jfjoch_client.models.scan_result") -jfjoch_client_scan_result_module.ScanResult = object - -sys.modules.setdefault("jfjoch_client", jfjoch_client_module) -sys.modules.setdefault("jfjoch_client.models", jfjoch_client_models_module) -sys.modules.setdefault("jfjoch_client.models.scan_result", jfjoch_client_scan_result_module) - - -def test_is_critical_uses_body_flag_when_present(): - assert DAQWorker._is_critical({"critical": False}) is False - assert DAQWorker._is_critical({"critical": True}) is True - - -def test_is_critical_fails_safe_when_missing_or_unparseable(): - assert DAQWorker._is_critical({}) is True - assert DAQWorker._is_critical(None) is True - - -def test_classify_reply_error_builds_structured_error_info(): - info = DAQWorker._classify_reply_error( - status=422, - err_msg="mount failed", - body_json={ - "critical": False, - "code": "MOUNTING_FAILED", - "exception_class": "MountingFailed", - "message": "mount failed", - "context": {"sample_id": 7}, - }, - ) - - assert info.critical is False - assert info.code == "MOUNTING_FAILED" - assert info.exception_class == "MountingFailed" - assert info.message == "mount failed" - assert info.context == {"sample_id": 7} - - -def test_classify_reply_error_fails_safe_defaults(): - info = DAQWorker._classify_reply_error(status=500, err_msg="broken", body_json=None) - - assert info.critical is True - assert info.code is None - assert info.exception_class is None - assert info.message == "broken" - assert info.context == {} - - -def test_is_auth_error_code_detects_auth_codes_only(): - assert DAQWorker._is_auth_error_code("INVALID_TOKEN") is True - assert DAQWorker._is_auth_error_code("SESSION_ALREADY_ACTIVE") is True - assert DAQWorker._is_auth_error_code("MOUNTING_FAILED") is False - assert DAQWorker._is_auth_error_code(None) is False diff --git a/tests/unit/gui/test_gui_entry.py b/tests/unit/gui/test_gui_entry.py deleted file mode 100644 index a29a0d14..00000000 --- a/tests/unit/gui/test_gui_entry.py +++ /dev/null @@ -1,23 +0,0 @@ -"""gui.main() startup path: the splash banner is a PNG again (the SVG -rendered wrong on RHEL9 consoles), so the resource block must resolve it — -and a failed startup must exit through the graceful error path, not crash.""" - -from unittest.mock import MagicMock, patch - -import pytest - - -def test_main_resolves_banner_and_exits_gracefully(qapp): - from aare.gui import gui - - with ( - # A second QApplication would abort; hand main() a stand-in instead. - patch.object(gui, "QApplication", return_value=MagicMock()), - # process() on the stand-in app exits the interpreter at C level - # ("argument list cannot be empty") — option defaults still apply. - patch.object(gui.QCommandLineParser, "process", lambda self, app: None), - patch.object(gui, "QMessageBox"), - patch.object(gui, "auth", side_effect=RuntimeError("no server")), - pytest.raises(SystemExit), - ): - gui.main() diff --git a/tests/unit/gui/test_illumination_panel.py b/tests/unit/gui/test_illumination_panel.py deleted file mode 100644 index 897509cb..00000000 --- a/tests/unit/gui/test_illumination_panel.py +++ /dev/null @@ -1,80 +0,0 @@ -"""Send/readback wiring for the light sliders (was a __main__ self-check in -the panel; promoted here so CI counts it). Every deliberate input path must -emit, and the status-poll readback must neither clobber a fresh user change -nor echo a PUT back to the server.""" - -import time -from types import SimpleNamespace - -import pytest -from PySide6.QtCore import QPoint, QPointF, Qt -from PySide6.QtGui import QWheelEvent -from PySide6.QtWidgets import QApplication - -from aare.gui.panels.illumination_panel import READBACK_GRACE_S, IlluminationPanel - - -@pytest.fixture -def panel(qtbot): - panel = IlluminationPanel() - qtbot.addWidget(panel) - return panel - - -def _wheel_notch(slider): - # One wheel notch; sliderReleased never fires for this path, which is - # exactly the case the valueChanged wiring exists for. - QApplication.sendEvent( - slider, - QWheelEvent( - QPointF(5, 5), - QPointF(5, 5), - QPoint(0, 0), - QPoint(0, 120), - Qt.MouseButton.NoButton, - Qt.KeyboardModifier.NoModifier, - Qt.ScrollPhase.NoScrollPhase, - False, - ), - ) - - -def _status(front=90.0, back=10.0): - return SimpleNamespace(bl=SimpleNamespace(front_light=front, back_light=back)) - - -def test_wheel_notch_emits_both_lights(panel): - front, back = [], [] - panel.front_light.connect(front.append) - panel.back_light.connect(back.append) - _wheel_notch(panel.front_light_slider) - _wheel_notch(panel.back_light_slider) - assert front, "wheel adjustment must emit front_light" - assert back, "wheel adjustment must emit back_light" - - -def test_readback_grace_holds_user_value(panel): - _wheel_notch(panel.front_light_slider) - held = panel.front_light_slider.value() - panel.update_daq_status(_status()) - assert panel.front_light_slider.value() == held, "grace window must hold user value" - - -def test_readback_applies_after_grace_without_echo(panel): - sent = [] - panel.front_light.connect(sent.append) - panel._last_user_change = time.monotonic() - READBACK_GRACE_S - 1 - panel.update_daq_status(_status()) - assert panel.front_light_slider.value() == 90, "readback must apply after grace" - assert panel.back_light_slider.value() == 10 - assert not sent, "readback must not echo a PUT" - - -def test_readback_skipped_while_sliding(panel): - panel.on_slider_pressed() - panel._last_user_change = 0.0 - panel.update_daq_status(_status(front=55.0)) - assert panel.front_light_slider.value() != 55 - panel.on_slider_released() - panel.update_daq_status(_status(front=55.0)) - assert panel.front_light_slider.value() == 55 diff --git a/tests/unit/gui/test_log_panel.py b/tests/unit/gui/test_log_panel.py deleted file mode 100644 index 8b8df096..00000000 --- a/tests/unit/gui/test_log_panel.py +++ /dev/null @@ -1,42 +0,0 @@ -"""A log mirror view is a second view on the same emitter: history is copied -on creation, live lines reach both views, and clear() empties them all.""" - -from aare.gui.panels.log_panel import LogPanel - - -def test_log_mirror_view_and_clear(qtbot): - panel = LogPanel() - qtbot.addWidget(panel) - panel.emitter.message.emit("first line") - assert "first line" in panel.view.toPlainText() - - mirror = panel.make_mirror_view() - qtbot.addWidget(mirror) - # History copied on creation, live lines reach both views. - assert "first line" in mirror.toPlainText() - panel.emitter.message.emit("second line") - assert "second line" in panel.view.toPlainText() - assert "second line" in mirror.toPlainText() - - panel.clear() - assert panel.view.toPlainText() == "" - assert mirror.toPlainText() == "" - - -def test_notification_requests_reveal(qtbot): - panel = LogPanel() - qtbot.addWidget(panel) - with qtbot.waitSignal(panel.reveal_requested, timeout=1000): - panel.show_notification(title="Boom", message="it broke") - assert panel.notification._title.text() == "Boom" - - -def test_sticky_notification_is_dismissable(qtbot): - # Sticky means "no auto-clear timer", not "undismissable": the Clear - # button must stay so users can get rid of stale warnings by hand. - panel = LogPanel() - qtbot.addWidget(panel) - panel.show_notification(title="Warn", message="stuck", level="warning", sticky=True) - assert not panel.notification._clear_button.isHidden() - panel.notification._clear_button.click() - assert not panel.notification.isVisible() diff --git a/tests/unit/gui/test_login.py b/tests/unit/gui/test_login.py deleted file mode 100644 index 12f2d50c..00000000 --- a/tests/unit/gui/test_login.py +++ /dev/null @@ -1,48 +0,0 @@ -from unittest.mock import MagicMock, patch - -import jwt -import pytest -from PySide6.QtCore import Qt - -from aare.gui.widgets.login import LoginDialog - - -@pytest.fixture -def login_dialog(qtbot): - dialog = LoginDialog(base_url=None) - qtbot.add_widget(dialog) - return dialog - - -def test_login_dialog_init(login_dialog): - assert login_dialog.windowTitle() == "User Authentication" - assert login_dialog.name_entry.text() != "" - - -def test_login_dialog_authenticate_no_url(login_dialog, qtbot): - login_dialog.name_entry.setText("testuser") - - with qtbot.wait_signal(login_dialog.accepted): - qtbot.mouseClick(login_dialog.ok_button, Qt.LeftButton) - - assert login_dialog.token != "" - decoded = jwt.decode(login_dialog.token, "ABC123", algorithms=["HS256"]) - assert decoded["sub"] == "testuser" - - -@patch("aare.gui.widgets.login.QNetworkAccessManager") -def test_login_dialog_authenticate_with_url(mock_nam, qtbot): - dialog = LoginDialog(base_url="http://test") - qtbot.add_widget(dialog) - - mock_instance = mock_nam.return_value - mock_reply = MagicMock() - mock_instance.post.return_value = mock_reply - - dialog.authenticate() - mock_instance.post.assert_called_once() - - -def test_login_dialog_cancel(login_dialog, qtbot): - with qtbot.wait_signal(login_dialog.rejected): - qtbot.mouseClick(login_dialog.cancel_button, Qt.LeftButton) diff --git a/tests/unit/gui/test_main_window.py b/tests/unit/gui/test_main_window.py deleted file mode 100644 index 67d04901..00000000 --- a/tests/unit/gui/test_main_window.py +++ /dev/null @@ -1,613 +0,0 @@ -from typing import cast -from unittest.mock import MagicMock, patch - -import pytest -from PySide6.QtCore import QSettings, Qt -from PySide6.QtWidgets import QApplication, QDockWidget, QWidget, QWidgetItem - -from aare.gui import styles -from aare.gui.main_window import ClickableCursorFilter, MainWindow -from aare.gui.styles import THEME_BLUEBIRD, THEME_SUNRISE, THEME_SUNSET - - -@pytest.fixture -def mock_ui_state(): - with patch("aare.gui.main_window.UIStateManager") as mock: - yield mock - - -def test_main_window_init(qtbot, mock_ui_state, daq_status_factory, sample_info): - with ( - patch("requests.get") as mock_get, - patch("aare.gui.main_window.DAQWorker"), - patch("aare.gui.main_window.PredictionSubscriber"), - patch("aare.gui.main_window.VideoThread"), - patch("aare.gui.main_window.JFJochDBusClient"), - patch("aare.gui.main_window.jwt.decode") as mock_jwt, - ): - mock_get.return_value.status_code = 200 - mock_get.return_value.json.return_value = {"status": "ok"} - mock_jwt.return_value = { - "sub": "testuser", - "staff": True, - "pgroups": ["p123"], - "session": 15, - } - - fake_token = "header.payload.signature" - - win = MainWindow( - base_url="http://localhost:5210", - token=fake_token, - default_image=None, - zmq_addr=None, - pred_zmq_addr=None, - beamline_cam_addr="localhost", - gonio_cam_addr="localhost", - gonio_cam_id=1, - ) - win.show() - qtbot.addWidget(win) - - assert win.windowTitle() == "AareGUI" - assert win.isVisible() - - # Staff-side gate behaviors piggyback on this window: every extra - # MainWindow construction raises the odds of the PySide SystemError - # flake, so don't build another one just for these. - from aarecommon.models.models import BeamlineStateEnum - - with patch("aare.gui.main_window.QMessageBox") as popup: - win._show_beamline_tab_gated_popup() - assert popup.information.called, "staff popup must explain the visitor pgroup" - - win._apply_default_sample_tab(BeamlineStateEnum.BeamLocation) - assert win.sample_lists_tabs.currentIndex() == 1 # Auxiliary puck - win._apply_default_sample_tab(BeamlineStateEnum.DataCollection) - assert win.sample_lists_tabs.currentIndex() == 0 - - # Energy row inside Exp. Config. emits eV (the GUI shows keV) - sent = [] - win.data_collection.change_energy.connect(sent.append) - win.data_collection.energy_spin.setValue(12.4) - win.data_collection._emit_change_energy() - assert sent and abs(sent[0] - 12400.0) < 1e-6 - - # Side panels collapse from the View menu (no on-screen buttons). - # The clamp lets a narrow window shrink the camera region well below - # the natural minimum the tab labels + controls rows would demand. - assert 0 < win.video_tab.minimumWidth() < win.video_tab.minimumSizeHint().width() - win._show_left_panel_action.trigger() - assert win.collection_controls_scroll.isHidden() - win._show_left_panel_action.trigger() - assert not win.collection_controls_scroll.isHidden() - win._show_right_panel_action.trigger() - assert win.beamline_controls_scroll.isHidden() - win._show_right_panel_action.trigger() - assert not win.beamline_controls_scroll.isHidden() - - # Alert routers land straight in the runtime notification dock (the - # portrait-mode interceptors are gone with Playlist Mode). - with patch.object(win, "_show_runtime_notification") as note: - win._runtime_alert_primary("beam lost", True) - win._runtime_alert_secondary("shutter", False) - win._on_http_error("boom") - win._on_sample_camera_error("no frames") - assert note.call_count == 4 - - assert ( - win._detector_error_banner_text(automation=True, message="x") - == "Automation halted: detector error." - ) - assert ( - win._detector_error_banner_text(automation=False, message="x") - == "Manual collection stopped: detector error." - ) - - # Manual unmount respects the hutch PSS gate. cast: win.daq is a - # patched-in MagicMock, but pyright sees the real DAQWorker type. - unmount_mock = cast(MagicMock, win.daq.unmount) - with ( - patch.object(win, "_hutch_blocks_mount", return_value="hutch open"), - patch("aare.gui.main_window.QMessageBox"), - ): - win._on_manual_unmount_requested() - unmount_mock.assert_not_called() - with patch.object(win, "_hutch_blocks_mount", return_value=None): - win._on_manual_unmount_requested() - unmount_mock.assert_called_once() - - # Mount next: the mounted head stays queued until /status confirms it - # left the gonio, so a failed unmount never drops it from the queue. - head = sample_info - nxt = sample_info.model_copy(update={"db_id": 2, "sample_name": "sample2"}) - win.job_list_panel.table_model.updateData([head, nxt]) - mount_mock = cast(MagicMock, win.daq.mount) - win.update_daq_status(daq_status_factory(sample=head)) - win.sample_logic.update_daq_status(daq_status_factory(sample=head)) - with patch.object(win, "_hutch_blocks_mount", return_value=None): - win._mount_next_from_queue() - mount_mock.assert_called_once_with(nxt, False) - queued = lambda: [s.db_id for s in win.job_list_panel.table_model.samples] - assert queued() == [1, 2], "head must stay queued until unmount confirmed" - win.sample_logic.update_daq_status(daq_status_factory(sample=head)) - assert queued() == [1, 2], "head still mounted (unmount failed) -> keep it" - win.sample_logic.update_daq_status(daq_status_factory(sample=nxt)) - assert queued() == [2], "exchange confirmed by /status -> head popped" - - # Motion watch: only the robot station switches to the combined - # beamline view. Moving no longer does (users kept losing the sample - # camera on short gonio moves), and busy alone never does — Sample - # alignment, Beam location etc. run busy while the user watches the - # sample camera itself. - win.update_daq_status( - daq_status_factory(state=BeamlineStateEnum.RobotSampleExchange, busy=True) - ) - assert win._watching_motion - assert win.video_tab.currentWidget() is win.beamline_combined_panel - win.update_daq_status( - daq_status_factory(state=BeamlineStateEnum.SampleAlignment, busy=True) - ) - assert not win._watching_motion - assert win.video_tab.currentWidget() is win.sample_camera - win.update_daq_status(daq_status_factory(state=BeamlineStateEnum.BeamLocation, busy=True)) - assert not win._watching_motion - win.update_daq_status(daq_status_factory(state=BeamlineStateEnum.Moving, busy=True)) - assert not win._watching_motion - assert win.video_tab.currentWidget() is win.sample_camera - win.update_daq_status( - daq_status_factory(state=BeamlineStateEnum.DataCollection, busy=False) - ) - assert not win._watching_motion - assert win.video_tab.currentWidget() is win.sample_camera - - -def test_main_window_mount_view(qtbot, mock_ui_state): - with ( - patch("requests.get"), - patch("aare.gui.main_window.DAQWorker"), - patch("aare.gui.main_window.PredictionSubscriber"), - patch("aare.gui.main_window.VideoThread"), - patch("aare.gui.main_window.JFJochDBusClient"), - patch("aare.gui.main_window.jwt.decode") as mock_jwt, - ): - mock_jwt.return_value = { - "sub": "testuser", - "staff": True, - "pgroups": ["p123"], - "session": 15, - } - fake_token = "header.payload.signature" - - win = MainWindow( - base_url=None, - token=fake_token, - default_image=None, - zmq_addr=None, - pred_zmq_addr=None, - beamline_cam_addr=None, - gonio_cam_addr=None, - gonio_cam_id=None, - ) - qtbot.addWidget(win) - - win.mount_view() - - -def test_mark_user_interaction_reports_backend(qtbot, mock_ui_state): - with ( - patch("requests.get"), - patch("aare.gui.main_window.DAQWorker"), - patch("aare.gui.main_window.PredictionSubscriber"), - patch("aare.gui.main_window.VideoThread"), - patch("aare.gui.main_window.JFJochDBusClient"), - patch("aare.gui.main_window.jwt.decode") as mock_jwt, - ): - mock_jwt.return_value = { - "sub": "testuser", - "staff": True, - "pgroups": ["p123"], - "session": 15, - } - fake_token = "header.payload.signature" - - win = MainWindow( - base_url=None, - token=fake_token, - default_image=None, - zmq_addr=None, - pred_zmq_addr=None, - beamline_cam_addr=None, - gonio_cam_addr=None, - gonio_cam_id=None, - ) - qtbot.addWidget(win) - - win._last_interaction_report_ts = -999.0 - win._mark_user_interaction() - - win.daq.report_gui_interaction.assert_called_once_with(15) - - -def test_automation_activity_refreshes_idle_timestamp(qtbot, mock_ui_state): - with ( - patch("requests.get"), - patch("aare.gui.main_window.DAQWorker"), - patch("aare.gui.main_window.PredictionSubscriber"), - patch("aare.gui.main_window.VideoThread"), - patch("aare.gui.main_window.JFJochDBusClient"), - patch("aare.gui.main_window.jwt.decode") as mock_jwt, - ): - 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, - CrystalSize, - DAQStatusModel, - SampleCameraSettings, - SessionsStateEnum, - SessionStatus, - ) - - mock_jwt.return_value = { - "sub": "testuser", - "staff": True, - "pgroups": ["p123"], - "session": 15, - } - fake_token = "header.payload.signature" - - win = MainWindow( - base_url=None, - token=fake_token, - default_image=None, - zmq_addr=None, - pred_zmq_addr=None, - beamline_cam_addr=None, - gonio_cam_addr=None, - gonio_cam_id=None, - ) - qtbot.addWidget(win) - - win.job_list_panel.is_running = MagicMock(return_value=True) - win._last_user_interaction_ts = 100.0 - - status = DAQStatusModel( - geom=SampleGeometryModel( - beam_location_pxl=Coordinate(x=1000, y=1000), - pixel_in_mm=0.001, - aerotech=Coordinate(), - aerotech_meas=Coordinate(), - smargon=SmargonCoordinate(sh_mm=Coordinate(), phi_deg=0, chi_deg=0), - omega_deg=0, - beam_size_mm=Coordinate(x=0.01, y=0.01), - ), - diffraction=DiffractionGeometry( - energy_keV=12.4, - dtz_mm=100.0, - detector_size_pxl=(1553, 1630), - pixel_size_mm=0.150, - beam_center_pxl=(750.0, 750.0), - detector_description="PILATUS 4", - detector_serial_number="1", - poni_rot1_rad=0.0, - poni_rot2_rad=0.0, - ), - bl=BeamlineStatus( - name="SIMULATED", - ring_current_mA=400.0, - front_light=50.0, - back_light=50.0, - cryojet_K=100.0, - shutter_open=False, - exp_shutter_open=False, - flux_ph_s=1e12, - sample_camera=SampleCameraSettings(gain=1.0, exposure=0.02), - transmission=1.0, - zoom=1.0, - commissioning_mode=False, - dtz_min=120.0, - dtz_max=1600.0, - ), - state=BeamlineStateEnum.SampleAlignment, - busy=False, - session=SessionStatus( - session=SessionsStateEnum.Vacant, current_pgroup="p123", staff=True - ), - crystal_size=CrystalSize(x=0, y=0, z=0), - ) - - with patch("aare.gui.main_window.time.time", return_value=250.0): - win.update_daq_status(status) - - assert win._last_user_interaction_ts == 250.0 - - # Remote-close bookkeeping in the same status loop: an unreadable - # session entry is skipped, a close request for THIS session starts - # the countdown, and its disappearance clears it again. - from types import SimpleNamespace - - unreadable = status.model_copy(update={"open_guis": [SimpleNamespace(session="bad")]}) - win.update_daq_status(unreadable) - assert win._remote_close_deadline_ts is None - - close_req = status.model_copy( - update={ - "open_guis": [ - SimpleNamespace( - session=15, - close_requested=True, - close_requested_by="ops", - close_grace_seconds=5, - ) - ] - } - ) - win.update_daq_status(close_req) - assert win._remote_close_deadline_ts is not None - - win.update_daq_status(status) - assert win._remote_close_deadline_ts is None - - -def _make_window(qtbot): - win = MainWindow( - base_url=None, - token="header.payload.signature", - default_image=None, - zmq_addr=None, - pred_zmq_addr=None, - beamline_cam_addr=None, - gonio_cam_addr=None, - gonio_cam_id=None, - ) - qtbot.addWidget(win) - return win - - -def test_theme_settings_migrate_and_slots_switch(qtbot, mock_ui_state): - with ( - patch("requests.get"), - patch("aare.gui.main_window.DAQWorker"), - patch("aare.gui.main_window.PredictionSubscriber"), - patch("aare.gui.main_window.VideoThread"), - patch("aare.gui.main_window.JFJochDBusClient"), - patch("aare.gui.main_window.jwt.decode") as mock_jwt, - ): - mock_jwt.return_value = { - "sub": "testuser", - "staff": True, - "pgroups": ["p123"], - "session": 15, - } - win = _make_window(qtbot) - - settings = QSettings("PSI", "AareGUI") - saved = settings.value("appearance/theme") - try: - # Pre-rename tokens saved by older builds must map to the new ones. - settings.setValue("appearance/theme", "portrait") - win._restore_theme_settings() - assert win._theme_mode == THEME_SUNSET - - settings.setValue("appearance/theme", "original") - win._restore_theme_settings() - assert win._theme_mode == THEME_SUNRISE - - settings.setValue("appearance/theme", THEME_BLUEBIRD) - win._restore_theme_settings() - assert win._theme_mode == THEME_BLUEBIRD - finally: - if saved is None: - settings.remove("appearance/theme") - else: - settings.setValue("appearance/theme", saved) - - win.use_bluebird_theme() - assert win._theme_mode == THEME_BLUEBIRD - win.use_portrait_theme() # exercises the sunset palette flip - assert win._theme_mode == THEME_SUNSET - win.use_legacy_theme() - assert win._theme_mode == THEME_SUNRISE - - -def test_font_zoom_steps_clamps_and_resets(qtbot, mock_ui_state): - with ( - patch("requests.get"), - patch("aare.gui.main_window.DAQWorker"), - patch("aare.gui.main_window.PredictionSubscriber"), - patch("aare.gui.main_window.VideoThread"), - patch("aare.gui.main_window.JFJochDBusClient"), - patch("aare.gui.main_window.jwt.decode") as mock_jwt, - ): - mock_jwt.return_value = { - "sub": "testuser", - "staff": True, - "pgroups": ["p123"], - "session": 15, - } - win = _make_window(qtbot) - - settings = QSettings("PSI", "AareGUI") - saved = settings.value("appearance/font_scale") - try: - base_pt = win._default_app_font.pointSizeF() - win._change_font_zoom(1) - assert styles.font_scale() == pytest.approx(1.25) - # Part 2 of the zoom: the app default font scales with the ladder. - app = QApplication.instance() - assert isinstance(app, QApplication) # narrow from QCoreApplication|None - assert app.font().pointSizeF() == pytest.approx(base_pt * 1.25) - # Part 3: the fixed-width side boxes follow the ladder, else the - # zoomed text clips inside them. - assert win.data_collection.minimumWidth() == round(win.data_collection.set_width * 1.25) - assert win.collection_controls_scroll.maximumWidth() == ( - round(win.data_collection.set_width * 1.25) + 10 - ) - assert win.beamline.minimumWidth() == round(win.beamline.set_width * 1.25) - for _ in range(5): - win._change_font_zoom(1) - assert styles.font_scale() == styles.FONT_SCALE_LADDER[-1] - win._change_font_zoom(0) - assert styles.font_scale() == 1.0 - assert app.font().pointSizeF() == pytest.approx(base_pt) - assert win.data_collection.minimumWidth() == win.data_collection.set_width - for _ in range(5): - win._change_font_zoom(-1) - assert styles.font_scale() == styles.FONT_SCALE_LADDER[0] # floor is 100% - finally: - styles.set_font_scale(1.0) - if saved is None: - settings.remove("appearance/font_scale") - else: - settings.setValue("appearance/font_scale", saved) - - -def test_restore_window_state_heals_all_hidden_docks(qtbot, mock_ui_state): - with ( - patch("requests.get"), - patch("aare.gui.main_window.DAQWorker"), - patch("aare.gui.main_window.PredictionSubscriber"), - patch("aare.gui.main_window.VideoThread"), - patch("aare.gui.main_window.JFJochDBusClient"), - patch("aare.gui.main_window.jwt.decode") as mock_jwt, - ): - mock_jwt.return_value = { - "sub": "testuser", - "staff": True, - "pgroups": ["p123"], - "session": 15, - } - win = _make_window(qtbot) - - for dock in win.findChildren(QDockWidget): - dock.hide() - assert all(d.isHidden() for d in win.findChildren(QDockWidget)) - - # state_manager is mocked, so restore_window is a no-op and the - # all-hidden layout survives to the heal check. - win._restore_window_state() - - assert not win.tell_samples_dock.isHidden() - - -def test_close_restores_pre_watch_layout(qtbot, mock_ui_state): - with ( - patch("requests.get"), - patch("aare.gui.main_window.DAQWorker"), - patch("aare.gui.main_window.PredictionSubscriber"), - patch("aare.gui.main_window.VideoThread"), - patch("aare.gui.main_window.JFJochDBusClient"), - patch("aare.gui.main_window.jwt.decode") as mock_jwt, - ): - mock_jwt.return_value = { - "sub": "testuser", - "staff": True, - "pgroups": ["p123"], - "session": 15, - } - win = _make_window(qtbot) - - pre_watch = win.saveState() - for dock in win.findChildren(QDockWidget): - dock.hide() - win._session_operations_enabled = False - win._pre_watch_dock_state = pre_watch - - win.close() - - # closeEvent put the pre-watch layout back before saving state, so - # the all-hidden fold was not persisted. - assert not win.tell_samples_dock.isHidden() - - -def test_nonstaff_beamline_gate_popups(qtbot, mock_ui_state): - """Non-staff must SEE the staff-only Beamline panels (as locked banners) - and get an explanation on click — both on a banner and on the - pgroup-gated (disabled) Beamline tab, which used to eat clicks silently.""" - with ( - patch("requests.get"), - patch("aare.gui.main_window.DAQWorker"), - patch("aare.gui.main_window.PredictionSubscriber"), - patch("aare.gui.main_window.VideoThread"), - patch("aare.gui.main_window.JFJochDBusClient"), - patch("aare.gui.main_window.jwt.decode") as mock_jwt, - ): - mock_jwt.return_value = { - "sub": "visitor", - "staff": False, - "pgroups": ["p123"], - "session": 15, - } - win = _make_window(qtbot) - - # Locked stand-ins exist in place of the real staff panels - titles = [b.text() for b in win._locked_beamline_banners] - assert titles == ["Beamline setup", "ABR meas. pos.", "Beam configuration"] - assert not hasattr(win, "monochromator_panel") - - # Staff-gate denials are passive red tips now, not QMessageBoxes. - with patch("aare.gui.main_window.QToolTip") as tip: - qtbot.mousePress(win._locked_beamline_banners[0], Qt.MouseButton.LeftButton) - assert tip.showText.called, "banner click must explain the staff gate" - # The tip anchor carries the red warning wash (per-widget QToolTip QSS). - assert "QToolTip" in win._admin_tip_anchor.styleSheet() - - # Active pgroup outside the token disables the whole Beamline tab; - # a click on the disabled tab must explain itself, not vanish. - win._apply_pgroup_gate("p999") - assert not win.left_column_tabs.isTabEnabled(0) - bar = win.left_column_tabs.tabBar() - with patch("aare.gui.main_window.QToolTip") as tip: - qtbot.mousePress(bar, Qt.MouseButton.LeftButton, pos=bar.tabRect(0).center()) - assert tip.showText.called, "gated tab click must explain the gate" - - # The greyed-out Auxiliary-puck tab explains itself the same way. - aux_bar = win.sample_lists_tabs.tabBar() - with patch("aare.gui.main_window.QToolTip") as tip: - qtbot.mousePress(aux_bar, Qt.MouseButton.LeftButton, pos=aux_bar.tabRect(1).center()) - assert tip.showText.called, "aux-puck tab click must explain the lock" - - -def test_sample_camera_frame_paints_visible_views_and_acks(qtbot, mock_ui_state, monkeypatch): - from PySide6.QtGui import QImage - - with ( - patch("requests.get"), - patch("aare.gui.main_window.DAQWorker"), - patch("aare.gui.main_window.PredictionSubscriber"), - patch("aare.gui.main_window.VideoThread"), - patch("aare.gui.main_window.JFJochDBusClient"), - patch("aare.gui.main_window.jwt.decode") as mock_jwt, - ): - mock_jwt.return_value = { - "sub": "testuser", - "staff": True, - "pgroups": ["p123"], - "session": 15, - } - win = _make_window(qtbot) - - # Nothing is shown in tests, so pretend the view is on screen to reach - # the paint branch. - monkeypatch.setattr(type(win.sample_camera), "isVisible", lambda self: True) - win.prediction_thread = MagicMock() - - win._on_sample_camera_frame(QImage(4, 6, QImage.Format.Format_RGB888)) - - assert win.sample_camera.pixmap_item.pixmap().width() == 4 - # The ack is what paces the subscriber; it must fire after every frame. - win.prediction_thread.notify_frame_displayed.assert_called_once() - - # No subscriber (GUI started without a sample feed): the slot must not blow up. - win.prediction_thread = None - win._on_sample_camera_frame(QImage(4, 6, QImage.Format.Format_RGB888)) - - -def test_cursor_filter_ignores_a_non_event_argument(qapp): - # PySide 6.9 can hand an app-level filter a QWidgetItem instead of a - # QEvent during layout teardown; raising there fails a random test. - widget = QWidget() - assert ClickableCursorFilter().eventFilter(widget, QWidgetItem(widget)) is False diff --git a/tests/unit/gui/test_message_box.py b/tests/unit/gui/test_message_box.py deleted file mode 100644 index b2b95082..00000000 --- a/tests/unit/gui/test_message_box.py +++ /dev/null @@ -1,48 +0,0 @@ -from unittest.mock import MagicMock, patch - -import pytest -from PySide6.QtWidgets import QMessageBox - -from aare.gui.widgets.message_box import ( - experiment_hutch_shutter_check, - reply_box, - ring_current_low_check, -) - - -def test_reply_box(qtbot): - parent = MagicMock() - with patch("PySide6.QtWidgets.QMessageBox.question") as mock_question: - mock_question.return_value = QMessageBox.StandardButton.Yes - res = reply_box(parent, "Title", "Message") - assert res == QMessageBox.StandardButton.Yes - mock_question.assert_called_once() - - -@pytest.mark.timeout(10) -def test_ring_current_low_check_ok(qtbot): - # Should return True immediately if current is high enough - assert ring_current_low_check(None, 361.0) is True - - -def test_ring_current_low_check_low_yes(qtbot): - with patch("aare.gui.widgets.message_box.reply_box") as mock_reply: - mock_reply.return_value = QMessageBox.StandardButton.Yes - assert ring_current_low_check(None, 50.0) is True - mock_reply.assert_called_once() - - -def test_ring_current_low_check_low_no(qtbot): - with patch("aare.gui.widgets.message_box.reply_box") as mock_reply: - mock_reply.return_value = QMessageBox.StandardButton.No - assert ring_current_low_check(None, 50.0) is False - - -def test_experiment_hutch_shutter_check_open(qtbot): - assert experiment_hutch_shutter_check(None, True) is True - - -def test_experiment_hutch_shutter_check_closed_yes(qtbot): - with patch("aare.gui.widgets.message_box.reply_box") as mock_reply: - mock_reply.return_value = QMessageBox.StandardButton.Yes - assert experiment_hutch_shutter_check(None, False) is True diff --git a/tests/unit/gui/test_models.py b/tests/unit/gui/test_models.py deleted file mode 100644 index a1ac5f71..00000000 --- a/tests/unit/gui/test_models.py +++ /dev/null @@ -1,322 +0,0 @@ -import pytest -from aarecommon.models.models import DewarAddress, SampleShortInfo -from PySide6.QtCore import Qt - -from aare.gui.models.sample_queue_model import SampleQueueSpreadsheet -from aare.gui.models.user_sample_model import UserSampleSpreadsheet - - -@pytest.fixture -def sample_list(): - return [ - SampleShortInfo( - db_id=1, - puck_name="P1", - dewar_name="D1", - sample_name="S1", - run_number=1, - user="U1", - pin=1, - location=DewarAddress(segment="A", pos=1), - ), - SampleShortInfo( - db_id=2, - puck_name="P2", - dewar_name="D2", - sample_name="S2", - run_number=2, - user="U2", - pin=2, - location=DewarAddress(segment="A", pos=2), - ), - SampleShortInfo( - db_id=3, - puck_name="P1", - dewar_name="D1", - sample_name="S3", - run_number=3, - user="U1", - pin=3, - location=DewarAddress(segment="A", pos=1), - ), - ] - - -def test_user_sample_model_init(sample_list): - model = UserSampleSpreadsheet(samples=sample_list) - model.set_show_all_pgroups(True) # Ensure all pgroups are shown for testing - assert model.rowCount() == 3 - # Check if filtering works - # "User" is column 5 - model.set_filter("User", "U2") - assert model.rowCount() == 1 - model.clear_filter() - assert model.rowCount() == 3 - - -def test_user_sample_model_column_filter(sample_list): - model = UserSampleSpreadsheet(samples=sample_list) - model.set_show_all_pgroups(True) - # Column 6 is User (column 0 is the frozen #+status cell) - model.set_column_filter(6, "U1") - assert model.rowCount() == 2 - model.clear_all_column_filters() - assert model.rowCount() == 3 - - -def test_user_sample_model_unique_values(sample_list): - model = UserSampleSpreadsheet(samples=sample_list) - model.set_show_all_pgroups(True) - # Column 6 is User (column 0 is the frozen #+status cell) - users = model.unique_values_for_column(6) - assert "U1" in users - assert "U2" in users - assert len(users) == 2 - - -def test_sample_queue_model_init(sample_list): - model = SampleQueueSpreadsheet(samples=sample_list[:2]) - assert model.rowCount() == 2 - assert model.columnCount() == 3 - assert model.data(model.index(0, 0), Qt.ItemDataRole.DisplayRole) == "D1" - assert model.data(model.index(1, 2), Qt.ItemDataRole.DisplayRole) == "S2" - - -def test_sample_queue_model_update(sample_list): - model = SampleQueueSpreadsheet() - assert model.rowCount() == 0 - model.updateData(sample_list[:2]) - assert model.rowCount() == 2 - - -def test_sample_queue_model_remove(sample_list): - model = SampleQueueSpreadsheet(samples=sample_list[:2]) - model.remove_sample(1) - assert model.rowCount() == 1 - assert model.samples[0].db_id == 2 - - -def test_sample_queue_model_clear(sample_list): - model = SampleQueueSpreadsheet(samples=sample_list[:2]) - model.clearSamples() - assert model.rowCount() == 0 - - -def test_sample_queue_model_set_running(sample_list): - model = SampleQueueSpreadsheet(samples=sample_list[:2]) - # Background color role for first row - color_not_running = model.data(model.index(0, 0), Qt.ItemDataRole.BackgroundRole) - model.set_running(True) - color_running = model.data(model.index(0, 0), Qt.ItemDataRole.BackgroundRole) - assert color_not_running != color_running - - -def test_sample_queue_model_header(sample_list): - model = SampleQueueSpreadsheet(samples=sample_list[:2]) - assert model.headerData(0, Qt.Orientation.Horizontal, Qt.ItemDataRole.DisplayRole) == "Dewar" - assert model.headerData(1, Qt.Orientation.Vertical, Qt.ItemDataRole.DisplayRole) == "2" - - -def test_sample_queue_model_flags(sample_list): - model = SampleQueueSpreadsheet(samples=sample_list[:2]) - flags = model.flags(model.index(0, 0)) - assert flags & Qt.ItemFlag.ItemIsDropEnabled - - -# --- Status logic of the combined dewar/queue view --------------------------- -# The dewar table doubles as the queue view: the frozen "#" column carries a -# status fill (mounted > queued > flagged > measured) and the chip row filters -# by status. This is the logic a local contact trusts at a glance, so it gets -# its own tests. - - -def _status(model, row): - brush = model.data(model.index(row, 0), Qt.ItemDataRole.BackgroundRole) - return None if brush is None else brush.color().name().lower() - - -def _row_of(model, db_id): - return next(r for r in range(model.rowCount()) if model.get_id(r).db_id == db_id) - - -@pytest.fixture -def status_model(sample_list): - from aarecommon.models.models import DewarAddress, SampleShortInfo - - # A measured sample: any rotation data counts (exactly 1 MUST count; - # unmeasured is rotation_count 0, like the fixture's samples 1-3). - sample_list.append( - SampleShortInfo( - db_id=4, - puck_name="P3", - dewar_name="D3", - sample_name="S4", - run_number=4, - user="U1", - pin=4, - rotation_count=1, - location=DewarAddress(segment="B", pos=1), - ) - ) - model = UserSampleSpreadsheet(samples=sample_list) - model.set_show_all_pgroups(True) - return model - - -def test_status_color_priority(status_model): - from aare.gui.styles import ( - SAMPLE_ROW_QUEUED_BG, - SAMPLE_STATUS_FLAGGED_BG, - SAMPLE_STATUS_MEASURED_BG, - SAMPLE_STATUS_QUEUED_BG, - ) - - model = status_model - assert _status(model, _row_of(model, 1)) is None - - model.set_queued_ids({1}) - model.set_flagged(1, True) - # Queued beats flagged in the All view. - assert _status(model, _row_of(model, 1)) == SAMPLE_STATUS_QUEUED_BG.lower() - model.set_queued_ids(set()) - assert _status(model, _row_of(model, 1)) == SAMPLE_STATUS_FLAGGED_BG.lower() - - # Measured is automatic: rotation_count 1 counts, the 0s of 1-3 don't. - assert _status(model, _row_of(model, 4)) == SAMPLE_STATUS_MEASURED_BG.lower() - assert _status(model, _row_of(model, 2)) is None - - # Mounted always wins. - model.updateCurrentSample(current_puck="P1", current_sample=1) - assert _status(model, _row_of(model, 1)) == SAMPLE_ROW_QUEUED_BG.lower() - - -def test_status_filter_selects_rows(status_model): - model = status_model - model.set_queued_ids({1, 2}) - model.set_flagged(3, True) - - model.set_status_filter("queued") - assert {model.get_id(r).db_id for r in range(model.rowCount())} == {1, 2} - model.set_status_filter("flagged") - assert {model.get_id(r).db_id for r in range(model.rowCount())} == {3} - model.set_status_filter("measured") - assert {model.get_id(r).db_id for r in range(model.rowCount())} == {4} - # Unmeasured is the complement: everything still to be done. - model.set_status_filter("unmeasured") - assert {model.get_id(r).db_id for r in range(model.rowCount())} == {1, 2, 3} - model.set_status_filter(None) - assert model.rowCount() == 4 - - -def test_queued_view_shows_queue_order(status_model): - model = status_model - # Queue order deliberately different from location/db order. - model.set_queued_ids([3, 1, 2]) - model.set_status_filter("queued") - assert [model.get_id(r).db_id for r in range(model.rowCount())] == [3, 1, 2] - # Header sorts must not reorder the queue view — row 1 runs next. - model.sort(1, Qt.SortOrder.AscendingOrder) - assert [model.get_id(r).db_id for r in range(model.rowCount())] == [3, 1, 2] - # Other views keep the normal header sort. - model.set_status_filter(None) - assert [model.get_id(r).db_id for r in range(model.rowCount())] != [3, 1, 2] - - -def test_status_tints_are_context_dependent(status_model): - from aare.gui.styles import SAMPLE_STATUS_FLAGGED_BG, SAMPLE_STATUS_QUEUED_BG - - model = status_model - model.set_queued_ids({1, 2}) - model.set_flagged(1, True) - - # Queued view: own tint suppressed, only the also-flagged mark shows. - model.set_status_filter("queued") - assert _status(model, _row_of(model, 1)) == SAMPLE_STATUS_FLAGGED_BG.lower() - assert _status(model, _row_of(model, 2)) is None - - # Flagged view: a re-queued sample wears the queued mark. - model.set_status_filter("flagged") - assert _status(model, _row_of(model, 1)) == SAMPLE_STATUS_QUEUED_BG.lower() - - -def test_status_sets_refilter_while_chip_active(status_model): - model = status_model - model.set_status_filter("queued") - assert model.rowCount() == 0 - model.set_queued_ids({2}) - assert {model.get_id(r).db_id for r in range(model.rowCount())} == {2} - - -def test_status_column_is_display_only(status_model): - model = status_model - assert model.data(model.index(0, 0), Qt.ItemDataRole.DisplayRole) == 1 - before = [model.get_id(r).db_id for r in range(model.rowCount())] - model.sort(0, Qt.SortOrder.DescendingOrder) # no-op on the "#" column - assert [model.get_id(r).db_id for r in range(model.rowCount())] == before - - -def test_mime_data_round_trips_for_chip_drops(status_model): - from aarecommon.models.models import SampleShortInfoList - - model = status_model - payload = model.mimeData([model.index(0, 1), model.index(1, 1)]) - samples = SampleShortInfoList.model_validate_json(payload.text()) - assert len(samples.s) == 2 - assert samples.s[0].db_id == model.get_id(0).db_id - - -def test_mounted_row_is_blue_across_all_columns(status_model): - # Whole-row blue (not just "#") so the mounted sample is findable at a - # glance; the blue keeps the theme's own ink (no dark override). - model = status_model - model.updateCurrentSample(current_puck="P1", current_sample=1) - row = _row_of(model, 1) - for col in range(model.columnCount()): - assert model.data(model.index(row, col), Qt.ItemDataRole.ForegroundRole) is None - # Other rows: still "#"-only tint, other columns untouched. - other = _row_of(model, 2) - assert model.data(model.index(other, 1), Qt.ItemDataRole.BackgroundRole) is None - - -def test_spreadsheet_param_columns(status_model): - from aarecommon.models.models import DataCollectionParameters - - model = status_model - hdr = model.header - osc, exp, tot, trans = ( - hdr.index("Oscillation (°)"), - hdr.index("Exposure (s)"), - hdr.index("Total range (°)"), - hdr.index("Transmission"), - ) - model.get_id(_row_of(model, 1)).aaredb_params = DataCollectionParameters( - oscillation=0.1, exposure=0.01, totalangle=360, transmission=0.125 - ) - row = _row_of(model, 1) - d = lambda c: model.data(model.index(row, c), Qt.ItemDataRole.DisplayRole) - # Transmission shown as stored, no percent conversion. - assert (d(osc), d(exp), d(tot), d(trans)) == (0.1, 0.01, 360, 0.125) - # No params -> blank, and sorting a mostly-None column must not raise; - # the real value sorts first. - assert model.data(model.index(_row_of(model, 2), osc), Qt.ItemDataRole.DisplayRole) is None - model.sort(osc, Qt.SortOrder.AscendingOrder) - assert model.get_id(0).db_id == 1 - assert model.headerData(hdr.index("Comment"), Qt.Orientation.Horizontal, 0) == "Comment" - - -def test_glyph_count_headers_have_full_name_tooltips(status_model): - model = status_model - tip = lambda glyph: model.headerData( - model.header.index(glyph), Qt.Orientation.Horizontal, Qt.ItemDataRole.ToolTipRole - ) - assert tip("⧂") == "Mount count" - assert tip("▦") == "Gridscan count" - assert tip("⌕") == "Screening count" - assert tip("↻") == "Rotation count" - # Text headers explain themselves: no tooltip. - assert ( - model.headerData( - model.header.index("Comment"), Qt.Orientation.Horizontal, Qt.ItemDataRole.ToolTipRole - ) - is None - ) diff --git a/tests/unit/gui/test_monochromator_panel.py b/tests/unit/gui/test_monochromator_panel.py deleted file mode 100644 index 3785eaeb..00000000 --- a/tests/unit/gui/test_monochromator_panel.py +++ /dev/null @@ -1,89 +0,0 @@ -import pytest - -from aare.gui.panels.monochromator_panel import MonochromatorPanel - - -def test_current_energy_readout(qtbot, daq_status_factory): - panel = MonochromatorPanel() - qtbot.addWidget(panel) - - status = daq_status_factory() - panel.update_daq_status(status) - assert panel.current_energy_label.text() == "12.000 keV / 1.0332 Å" - - -def test_fast_shutter_row(qtbot, daq_status_factory): - panel = MonochromatorPanel() - qtbot.addWidget(panel) - - # Placeholder until the first DAQ tick. - assert panel.shutter_status_label.text() == "Fast Shutter: —" - - status = daq_status_factory() - panel.update_daq_status(status) - assert "Closed" in panel.shutter_status_label.text() - - status.bl = status.bl.model_copy(update={"shutter_open": True}) - panel.update_daq_status(status) - assert "Open" in panel.shutter_status_label.text() - - # Buttons relay to the same DAQ signals the status-bar menu uses. - with qtbot.waitSignal(panel.open_shutter, timeout=1000): - panel.open_shutter_button.click() - with qtbot.waitSignal(panel.close_shutter, timeout=1000): - panel.close_shutter_button.click() - - -def test_energy_spin_placeholder_limits(qtbot): - # 4-20 keV is a placeholder pending Beamline Scientist confirmation; the - # tooltip must say so because nothing downstream validates the request. - panel = MonochromatorPanel() - qtbot.addWidget(panel) - assert panel.energy_spin.minimum() == 4.0 - assert panel.energy_spin.maximum() == 20.0 - assert "Beamline Scientist" in panel.energy_spin.toolTip() - - -def test_energy_spin_motor_move_semantics(qtbot, daq_status_factory): - # Same protection UX as MotorMoveGroup: the spin stages, only the button - # sends, and the color walks neutral -> pending -> moving -> neutral. - panel = MonochromatorPanel() - qtbot.addWidget(panel) - box = panel.energy_spin # movestate sits on the spin, not its inner edit - sent = [] - panel.change_energy.connect(sent.append) - assert not panel.change_energy_button.isEnabled() # nothing staged yet - - status = daq_status_factory() - panel.update_daq_status(status) # readback 12.0 keV syncs the neutral spin - assert panel.energy_spin.value() == 12.0 - assert not box.property("movestate") - - panel.energy_spin.setValue(12.4) # user staging - assert box.property("movestate") == "pending" - assert panel.change_energy_button.isEnabled() - - panel.energy_spin.setValue(12.0) # back to the readback cancels - assert box.property("movestate") == "" - assert not panel.change_energy_button.isEnabled() - - panel.energy_spin.setValue(12.4) - panel.change_energy_button.click() - assert sent and sent[-1] == pytest.approx(12400.0) # keV -> eV on emit - assert box.property("movestate") == "moving" - assert not panel.change_energy_button.isEnabled() - - # travelling: the spin keeps showing the target, not the readback - status.diffraction = status.diffraction.model_copy(update={"energy_keV": 12.1}) - panel.update_daq_status(status) - assert panel.energy_spin.value() == 12.4 - assert box.property("movestate") == "moving" - - # arrival within tol returns to neutral and readback tracking resumes - # 12.3995 sits safely inside tol (the 12.399 boundary loses to float - # error: 12.4-12.399 > 0.001); the spin then rounds to its 3 decimals, - # hence the loose abs window on the value check. - status.diffraction = status.diffraction.model_copy(update={"energy_keV": 12.3995}) - panel.update_daq_status(status) - assert box.property("movestate") == "" - assert panel.energy_spin.value() == pytest.approx(12.3995, abs=1e-3) diff --git a/tests/unit/gui/test_motor_move_group.py b/tests/unit/gui/test_motor_move_group.py deleted file mode 100644 index fac30cf6..00000000 --- a/tests/unit/gui/test_motor_move_group.py +++ /dev/null @@ -1,140 +0,0 @@ -"""MotorMoveGroup is motor protection UX: typing must never start a move — -targets are staged (orange), sent only by the Move button (green), and the -box returns to neutral when the motor actually arrives.""" - -import pytest -from PySide6.QtCore import Qt - -from aare.gui.widgets.motor_move_group import MotorMoveGroup -from aare.gui.widgets.number_line_edit import NumberLineEdit - - -@pytest.fixture -def chi(qtbot): - box = NumberLineEdit(-0.2, 40, decimals=1) - qtbot.addWidget(box) - group = MotorMoveGroup() - group.add_box("chi", box) - return group, box - - -def _type(qtbot, box, text): - box.clear() - qtbot.keyClicks(box, text) - - -def test_stage_apply_settle(chi, qtbot): - group, box = chi - sent = [] - group.applied.connect(sent.append) - - _type(qtbot, box, "25.0") - assert box.property("movestate") == "pending" - assert group.button.isEnabled() - assert not sent # typing (even Enter) must not move the motor - - group.button.click() - assert sent == [{"chi": 25.0}] - assert box.property("movestate") == "moving" - assert not group.button.isEnabled() - - group.update_actual("chi", 10.0) # still travelling - assert box.property("movestate") == "moving" - assert box.value == 25.0 # box keeps showing the target - - group.update_actual("chi", 25.05) # within tol -> arrived - assert box.property("movestate") == "" - group.update_actual("chi", 3.0) # neutral boxes track the actual again - assert box.value == 3.0 - - -def test_edit_back_to_current_cancels_pending(chi, qtbot): - group, box = chi - _type(qtbot, box, "5.0") - assert group.button.isEnabled() - _type(qtbot, box, "0.0") # back to the actual position - assert box.property("movestate") == "" - assert not group.button.isEnabled() - - -def test_over_max_is_invalid_and_never_sent(chi, qtbot): - group, box = chi - sent = [] - group.applied.connect(sent.append) - _type(qtbot, box, "500") - assert box.property("invalid") is True # red via existing validator path - group.button.click() - assert not sent # out-of-range target is never applied - assert box.property("movestate") == "pending" - - -def test_incomplete_entry_stays_pending(chi, qtbot): - _group, box = chi - _type(qtbot, box, "-") # not a number (yet): no tips, no crash - assert box.property("movestate") == "pending" - # Enter on the incomplete text must be swallowed just as quietly - qtbot.keyClick(box, Qt.Key.Key_Return) - assert box.property("movestate") == "pending" - - -def test_below_min_enter_hints_but_never_sends(chi, qtbot): - group, box = chi - sent = [] - group.applied.connect(sent.append) - _type(qtbot, box, "-5") # below the -0.2 bottom - qtbot.keyClick(box, Qt.Key.Key_Return) # triggers the min-value tooltip path - assert not sent # Enter must never start a move - - -def test_update_limits_reranges_box(chi, qtbot): - _group, box = chi - box.update_limits(-1.0, 50.0) - assert box.range_validator.bottom() == -1.0 - assert box.range_validator.top() == 50.0 - assert "50" in box.toolTip() - - -def test_spin_move_state_colors_actually_render(qtbot): - # Regression: movestate used to sit on the spin's inner QLineEdit, which - # the theme paints transparent — the property asserts passed while no - # color ever showed. Sample real pixels through the theme stylesheet. - from PySide6.QtGui import QColor - from PySide6.QtWidgets import QDoubleSpinBox, QPushButton - - from aare.gui.styles import ( - INPUT_MOVING_BG, - INPUT_PENDING_BG, - THEME_SUNRISE, - build_app_stylesheet, - ) - from aare.gui.widgets.motor_move_group import SpinMoveState - - spin = QDoubleSpinBox() - spin.setRange(4.0, 20.0) - spin.setStyleSheet(build_app_stylesheet(THEME_SUNRISE)) - button = QPushButton() - qtbot.addWidget(spin) - qtbot.addWidget(button) - state = SpinMoveState(spin, button, tol=0.01) - spin.resize(140, 24) - spin.show() - - def value_area_color(): - # Sample inside the left padding (1px border + 6px QSS padding), not - # the text area: glyph positions are font-dependent and on CI's Linux - # fonts x=20 lands on a digit of "12.40", returning an antialiased - # glyph/background blend instead of the plain background color. - img = spin.grab().toImage() - return img.pixelColor(4, img.height() // 2) - - state.update_actual(12.0) - neutral = value_area_color() - - spin.setValue(12.4) # user staging - assert value_area_color() == QColor(INPUT_PENDING_BG) - - button.click() - assert value_area_color() == QColor(INPUT_MOVING_BG) - - state.update_actual(12.398) # arrived within tol - assert value_area_color() == neutral diff --git a/tests/unit/gui/test_panels.py b/tests/unit/gui/test_panels.py deleted file mode 100644 index c4463105..00000000 --- a/tests/unit/gui/test_panels.py +++ /dev/null @@ -1,107 +0,0 @@ -import pytest -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, - DAQStatusModel, - SampleCameraSettings, - SessionStatus, -) - -from aare.gui.panels.status_panel import StatusPanel -from aare.gui.styles import STATUS_ALERT - - -@pytest.fixture -def mock_daq_status(): - 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, - ) - return status - - -def test_status_panel_update(qtbot, mock_daq_status): - panel = StatusPanel() - qtbot.addWidget(panel) - - # Initial state check (some values from __init__ defaults) - assert "400" in panel.ring_current.text() - - # Update with mock status - panel.update_daq_status(mock_daq_status) - - assert panel.omega.text() == "10.50" - assert "20.0" in panel.beam_size.text() # 0.02 * 1000 - assert "10.0" in panel.beam_size.text() # 0.01 * 1000 - assert "400.0" in panel.ring_current.text() - assert "1000.00" in panel.flux.text() # 1e12 / 1e9 = 1000 - assert "0.979" in panel.wavelength.text() - - -def test_status_panel_low_current(qtbot, mock_daq_status): - panel = StatusPanel() - qtbot.addWidget(panel) - - mock_daq_status.bl.ring_current_mA = 300.0 - panel.update_daq_status(mock_daq_status) - - assert f"color: {STATUS_ALERT}" in panel.ring_current.text() - assert "300.0" in panel.ring_current.text() - - -def test_smargon_staged_axes_move_and_actual_tracking(qtbot, mock_daq_status): - """_move_axes sends only the staged axes (absent keys stay None = no - motion) and the status tick feeds actuals back into the move group.""" - from aare.gui.panels.smargon_panel import SmargonPanel - - panel = SmargonPanel() - qtbot.addWidget(panel) - sent = [] - panel.smargon.connect(sent.append) - - panel._move_axes({"chi": 2.0}) - assert sent and sent[0].chi_deg == 2.0 - assert sent[0].phi_deg is None # phi was not staged: must not move - - panel.update_daq_status(mock_daq_status) - assert panel._geom is mock_daq_status.geom diff --git a/tests/unit/gui/test_popout_window.py b/tests/unit/gui/test_popout_window.py deleted file mode 100644 index f42fdca2..00000000 --- a/tests/unit/gui/test_popout_window.py +++ /dev/null @@ -1,171 +0,0 @@ -"""PopoutWindow replaces dock floating: an additional top-level window whose -edge band resizes, whose close only hides, and whose first show lands near -the cursor. DockTitleBar puts the pop-out button next to the close box.""" - -from PySide6.QtCore import QEvent, QPoint, QPointF, Qt -from PySide6.QtGui import QMouseEvent -from PySide6.QtWidgets import QDockWidget, QLabel - -from aare.gui.widgets.popout_window import DockTitleBar, PopoutWindow - - -def _window(qtbot): - w = PopoutWindow("test", QLabel("content")) - qtbot.addWidget(w) - w.resize(400, 300) - return w - - -def test_edges_at(qtbot): - w = _window(qtbot) - band = PopoutWindow.RESIZE_MARGIN + PopoutWindow.OUTER_GRIP - assert w._edges_at(QPoint(band - 1, 150)) == Qt.Edge.LeftEdge - assert w._edges_at(QPoint(200, band - 1)) == Qt.Edge.TopEdge - assert w._edges_at(QPoint(399, 299)) == (Qt.Edge.RightEdge | Qt.Edge.BottomEdge) - assert w._edges_at(QPoint(200, 150)) == Qt.Edge(0) - - -def test_cursor_for(qtbot): - w = _window(qtbot) - assert w._cursor_for(Qt.Edge.LeftEdge) == Qt.CursorShape.SizeHorCursor - assert w._cursor_for(Qt.Edge.BottomEdge) == Qt.CursorShape.SizeVerCursor - assert w._cursor_for(Qt.Edge.LeftEdge | Qt.Edge.TopEdge) == Qt.CursorShape.SizeFDiagCursor - assert w._cursor_for(Qt.Edge.RightEdge | Qt.Edge.TopEdge) == Qt.CursorShape.SizeBDiagCursor - assert w._cursor_for(Qt.Edge(0)) is None - - -def test_close_hides_and_keeps_geometry(qtbot): - w = _window(qtbot) - w.show() - qtbot.waitExposed(w) - w.move(120, 130) - geometry = w.geometry() - w.close() - assert not w.isVisible() - # Reopen: the first-show placement must not run again (geometry kept). - w.show() - assert w._placed - assert w.geometry() == geometry - - -def test_manual_resize_fallback(qtbot): - w = _window(qtbot) - w.show() - qtbot.waitExposed(w) - w.resize(400, 300) - start = w.geometry() - - grab = QPointF(399.0, 299.0) # bottom-right band - press = QMouseEvent( - QEvent.Type.MouseButtonPress, - grab, - w.mapToGlobal(grab.toPoint()).toPointF(), - Qt.MouseButton.LeftButton, - Qt.MouseButton.LeftButton, - Qt.KeyboardModifier.NoModifier, - ) - w.mousePressEvent(press) - if not w._manual_edges: - # The platform accepted startSystemResize; the manual path is not - # reachable here, and the press must not have moved the window. - assert w.geometry() == start - return - - move_to = grab + QPointF(40.0, 25.0) - move = QMouseEvent( - QEvent.Type.MouseMove, - move_to, - w.mapToGlobal(move_to.toPoint()).toPointF(), - Qt.MouseButton.NoButton, - Qt.MouseButton.LeftButton, - Qt.KeyboardModifier.NoModifier, - ) - w.mouseMoveEvent(move) - assert w.width() == start.width() + 40 - assert w.height() == start.height() + 25 - - release = QMouseEvent( - QEvent.Type.MouseButtonRelease, - move_to, - w.mapToGlobal(move_to.toPoint()).toPointF(), - Qt.MouseButton.LeftButton, - Qt.MouseButton.NoButton, - Qt.KeyboardModifier.NoModifier, - ) - w.mouseReleaseEvent(release) - assert not w._manual_edges - - -def test_hover_sets_resize_cursor(qtbot): - w = _window(qtbot) - w.show() - qtbot.waitExposed(w) - - def hover(pos): - w.mouseMoveEvent( - QMouseEvent( - QEvent.Type.MouseMove, - pos, - w.mapToGlobal(pos.toPoint()).toPointF(), - Qt.MouseButton.NoButton, - Qt.MouseButton.NoButton, - Qt.KeyboardModifier.NoModifier, - ) - ) - - hover(QPointF(2.0, 150.0)) - assert w.cursor().shape() == Qt.CursorShape.SizeHorCursor - hover(QPointF(200.0, 150.0)) - assert w.cursor().shape() == Qt.CursorShape.ArrowCursor - - -def test_dock_title_bar_buttons(qtbot): - dock = QDockWidget("Console Log") - qtbot.addWidget(dock) - opened = [] - bar = DockTitleBar(dock, on_popout=lambda: opened.append(True)) - dock.setTitleBarWidget(bar) - dock.show() - qtbot.waitExposed(dock) - - qtbot.mouseClick(bar.popout_button, Qt.MouseButton.LeftButton) - assert opened == [True] - assert dock.isVisible() - - -def test_manual_resize_from_top_left(qtbot): - w = _window(qtbot) - w.show() - qtbot.waitExposed(w) - w.resize(400, 300) - # Drive the manual path directly; whether startSystemResize is available - # is platform luck and the top/left arithmetic deserves coverage either way. - w._manual_edges = Qt.Edge.LeftEdge | Qt.Edge.TopEdge - w._press_global = w.mapToGlobal(QPoint(2, 2)) - w._press_geom = w.geometry() - move_to = QPointF(2.0 + 30.0, 2.0 + 20.0) - w.mouseMoveEvent( - QMouseEvent( - QEvent.Type.MouseMove, - move_to, - w.mapToGlobal(move_to.toPoint()).toPointF(), - Qt.MouseButton.NoButton, - Qt.MouseButton.LeftButton, - Qt.KeyboardModifier.NoModifier, - ) - ) - assert w.width() == 400 - 30 - assert w.height() == 300 - 20 - - -def test_paint_border_knob(qtbot, monkeypatch): - from PySide6.QtGui import QPixmap - - from aare.gui.widgets import popout_window as mod - - w = _window(qtbot) - # Default FRAME_L1_WIDTH "0px": render must take the paint-nothing path. - w.render(QPixmap(w.size())) - # With a visible level-1 border the painter path runs. - monkeypatch.setattr(mod, "FRAME_L1_WIDTH", "2px") - w.render(QPixmap(w.size())) diff --git a/tests/unit/gui/test_prediction_subscriber.py b/tests/unit/gui/test_prediction_subscriber.py deleted file mode 100644 index 092dfed4..00000000 --- a/tests/unit/gui/test_prediction_subscriber.py +++ /dev/null @@ -1,120 +0,0 @@ -"""Checks the binary-frame sniff in _try_parse_json: JPEG frames (0xff lead -byte) must be rejected without attempting utf-8 decode (previously raised -UnicodeDecodeError on every frame).""" - -from typing import cast - -from aare.gui.threads.prediction_subscriber import PredictionSubscriber - - -def _parse(part: bytes): - # Called unbound: _try_parse_json touches no instance state, so no - # QThread/zmq construction is needed. cast keeps basedpyright happy - # about the stand-in self. - return PredictionSubscriber._try_parse_json(cast(PredictionSubscriber, object()), part) - - -def test_binary_jpeg_frame_is_not_json(): - assert _parse(b"\xff\xd8\xff\xe0somejpegbytes") is None - - -def test_json_dict_is_parsed(): - assert _parse(b'{"encoding": "jpeg"}') == {"encoding": "jpeg"} - - -def test_json_non_dict_is_rejected(): - assert _parse(b"[1, 2]") is None - assert _parse(b"") is None - - -# --- Frame pacing and the multipart-safe conflate ------------------------- -# Real socket on an inproc endpoint: the drain and the in-flight cap are the -# fix, so they run against libzmq rather than a mock. - -import time - -import cv2 -import numpy as np -import pytest -import zmq -from PySide6.QtGui import QImage - - -@pytest.fixture -def sub(qapp): - s = PredictionSubscriber("inproc://samcam-test") - yield s - # run() nulls both on its own cleanup; only tear down what is left. - if s._sock is not None: - s._sock.close(0) - if s._ctx is not None: - s._ctx.term() - - -def test_emit_image_caps_frames_in_flight(sub): - image = QImage(4, 4, QImage.Format.Format_RGB888) - for _ in range(sub.MAX_FRAMES_IN_FLIGHT + 1): - sub._emit_image(image) - assert sub._frames_in_flight == sub.MAX_FRAMES_IN_FLIGHT - assert sub._dropped == 1 - - for _ in range(sub.MAX_FRAMES_IN_FLIGHT + 1): - sub.notify_frame_displayed() - assert sub._frames_in_flight == 0 # floors at zero, never negative - - -def test_recv_latest_keeps_only_the_newest_message(sub): - pub = sub._ctx.socket(zmq.PUB) - pub.bind("inproc://samcam-test") - try: - # Slow joiner: publish probes until the subscription has propagated. - deadline = time.monotonic() + 5 - while True: - pub.send_multipart([b"probe"]) - try: - sub._sock.recv_multipart(zmq.NOBLOCK) - break - except zmq.Again: - assert time.monotonic() < deadline, "subscription never propagated" - time.sleep(0.01) - while True: # flush any extra probes - try: - sub._sock.recv_multipart(zmq.NOBLOCK) - except zmq.Again: - break - sub._dropped = 0 - - for payload in (b"old", b"stale", b"newest"): - pub.send_multipart([b"hdr", payload]) - assert sub._recv_latest() == [b"hdr", b"newest"] - assert sub._dropped == 2 - finally: - pub.close(0) - - -def test_run_decodes_one_frame_and_reports_the_drops(sub, qtbot): - ok, jpeg = cv2.imencode(".jpg", np.zeros((4, 6, 3), dtype=np.uint8)) - assert ok - frame = [b'{"encoding": "jpeg"}', jpeg.tobytes()] - calls = [] - - def one_frame_then_stop(): - calls.append(1) - if len(calls) == 1: - return frame - sub.running = False - raise zmq.Again - - sub._recv_latest = one_frame_then_stop # type: ignore[method-assign] - sub._fps_window_start = time.perf_counter() - 10 # force the fps report - sub._dropped = 3 - images = [] - sub.image.connect(images.append) - - sub.run() - - assert len(images) == 1 and images[0].width() == 6 and images[0].height() == 4 - assert sub._frames_in_flight == 1 - assert sub._dropped == 0 # reported alongside the fps, then reset - assert sub._camera_available - assert sub._sock is None and sub._ctx is None # run() cleaned up diff --git a/tests/unit/gui/test_qt_override_reduction.py b/tests/unit/gui/test_qt_override_reduction.py deleted file mode 100644 index 99231ec8..00000000 --- a/tests/unit/gui/test_qt_override_reduction.py +++ /dev/null @@ -1,94 +0,0 @@ -"""Covers the code paths touched by the reduce-overwriting-qt-method -refactor: Qt-native replacements (signals, shortcuts, underMouse) for -virtual-method overrides, so the diff-coverage gate sees them executed.""" - -from PySide6.QtCore import QEvent, QPointF, Qt -from PySide6.QtGui import QMouseEvent - -from aare.gui.panels.fluorescence_panel import FluorescencePanel -from aare.gui.widgets.baton_request_dialog import BatonPendingDialog, BatonRequestDialog -from aare.gui.widgets.value_label import ValueLabel -from aare.gui.widgets.video_image import VideoGraphicsView - - -def test_baton_dialogs_stop_timer_via_finished(qtbot): - """finished.connect replaced the closeEvent overrides: the timer must - stop on accept, reject AND plain close — the path closeEvent used to - handle.""" - req = BatonRequestDialog("someone") - qtbot.addWidget(req) - assert req._timer.isActive() - req._on_accept() - assert not req._timer.isActive() - - req2 = BatonRequestDialog("someone") - qtbot.addWidget(req2) - req2._on_refuse() - assert not req2._timer.isActive() - - # close() only delivers a close event to a SHOWN dialog — same held for - # the old closeEvent override, so showing first keeps the test honest. - pend = BatonPendingDialog("user") - qtbot.addWidget(pend) - pend.show() - qtbot.waitExposed(pend) - assert pend._timer.isActive() - pend.close() - assert not pend._timer.isActive() - - -def test_fluorescence_hover_snaps_to_peak(qtbot): - """Drives a MouseMove through the viewport filter: event.position() - (the PyQt5-era hasattr fallback is gone) and the max(range) peak snap.""" - panel = FluorescencePanel() - qtbot.addWidget(panel) - panel.resize(500, 400) - panel.show() - qtbot.waitExposed(panel) - - panel.axis_x.setRange(0.0, 10.0) - panel.axis_y.setRange(0.0, 100.0) - for i in range(50): - panel.series.append(i * 0.2, 90.0 if i == 25 else 10.0) - - plot = panel.chart.plotArea() - pos = QPointF(plot.center()) - ev = QMouseEvent( - QEvent.Type.MouseMove, - pos, - panel.chart_view.viewport().mapToGlobal(pos.toPoint()), - Qt.MouseButton.NoButton, - Qt.MouseButton.NoButton, - Qt.KeyboardModifier.NoModifier, - ) - assert panel.eventFilter(panel.chart_view.viewport(), ev) is False - assert "keV" in panel.chart_view.toolTip() - - -def test_video_view_shortcuts_replace_keypress_override(qtbot): - view = VideoGraphicsView() - qtbot.addWidget(view) - view.show() - qtbot.waitExposed(view) - # WidgetShortcut context needs real focus; offscreen grants it only - # after the window is active. - view.activateWindow() - view.setFocus() - qtbot.waitUntil(view.hasFocus, timeout=2000) - - qtbot.keyClick(view, Qt.Key.Key_Plus) - assert view.zoom_factor > 1.0 - qtbot.keyClick(view, Qt.Key.Key_R) - assert view.zoom_factor == 1.0 - qtbot.keyClick(view, Qt.Key.Key_Minus) - assert view.zoom_factor < 1.0 - qtbot.keyClick(view, Qt.Key.Key_F) # fit_to_view: just must not raise - - -def test_value_label_inherits_click(qtbot): - label = ValueLabel("Energy", "keV") - qtbot.addWidget(label) - label.set_value("12.4") - assert "12.4" in label.text() - with qtbot.waitSignal(label.clicked, timeout=1000): - qtbot.mousePress(label, Qt.MouseButton.LeftButton) diff --git a/tests/unit/gui/test_rotation_speed_limits.py b/tests/unit/gui/test_rotation_speed_limits.py deleted file mode 100644 index 5299fd69..00000000 --- a/tests/unit/gui/test_rotation_speed_limits.py +++ /dev/null @@ -1,103 +0,0 @@ -"""Omega speed cap (500 deg/s) and per-beamline min image time on the rotation panel. - -Why: the image angle and the image time are each fine on their own - it is the -pair that can ask the goniometer to turn too fast. So the cap is a read-out -plus a gate on the Run button, and only the per-beamline minimum image time is -a limit of the field itself. -""" - -import pytest -from aarecommon.math.diffraction_geometry import DiffractionGeometry -from aarecommon.models.models import BeamlineStateEnum -from PySide6.QtWidgets import QMessageBox - -from aare.gui.panels.rotation_data_collection import RotationDataCollectionPanel - - -def _panel(monkeypatch, beamline): - # mx_beamline() reads the env on every call, so set it before construction - monkeypatch.setenv("BEAMLINE", beamline) - diffraction = DiffractionGeometry( - energy_keV=12.0, - dtz_mm=150.0, - pixel_size_mm=0.075, - beam_center_pxl=(1000.0, 1000.0), - detector_size_pxl=(2000, 2000), - detector_description="Eiger 16M", - detector_serial_number="123", - poni_rot1_rad=0.0, - poni_rot2_rad=0.0, - ) - return RotationDataCollectionPanel(diffraction=diffraction) - - -def _runnable(panel, monkeypatch): - panel._beamline_state = BeamlineStateEnum.SampleAlignment - monkeypatch.setattr(panel, "check_before_run", lambda scan_kind: True) - return panel - - -def _commit(field, text): - field.setText(text) - field.on_editing_finished() - - -def _accepts(field, text) -> bool: - field.setText(text) - return field.hasAcceptableInput() - - -@pytest.mark.parametrize( - "beamline,too_short,ok", [("X06DA", "0.0010", "0.0012"), ("X10SA", "0.0050", "0.0090")] -) -def test_min_image_time_per_beamline(qapp, monkeypatch, beamline, too_short, ok): - panel = _panel(monkeypatch, beamline) - for field in (panel.image_time_enter, panel.screening_image_time_enter): - assert not _accepts(field, too_short) - assert _accepts(field, ok) - - -def test_speed_readout_follows_the_pair(qapp, monkeypatch): - panel = _panel(monkeypatch, "X06DA") - - _commit(panel.image_angle, "1.000") - _commit(panel.image_time_enter, "0.1000") - assert panel.omega_speed.text() == "10.0" - assert not panel.omega_speed.styleSheet() # within the cap - - _commit(panel.image_time_enter, "0.0012") # 833 deg/s - assert panel.omega_speed.text() == "833.3" - assert panel.omega_speed.styleSheet() # marked red - - -def test_run_blocked_above_the_speed_cap(qapp, monkeypatch): - panel = _runnable(_panel(monkeypatch, "X06DA"), monkeypatch) - boxes = [] - monkeypatch.setattr(QMessageBox, "critical", lambda *a, **k: boxes.append(a)) - emitted = [] - panel.rotation_scan.connect(emitted.append) - - _commit(panel.image_angle, "1.000") - _commit(panel.image_time_enter, "0.0012") # 833 deg/s, over the cap - panel.run_measurement() - assert emitted == [] - assert len(boxes) == 1 - - _commit(panel.image_time_enter, "0.0100") # 100 deg/s - panel.run_measurement() - assert len(emitted) == 1 - - -def test_run_blocked_while_field_red(qapp, monkeypatch): - panel = _panel(monkeypatch, "X06DA") - boxes = [] - monkeypatch.setattr(QMessageBox, "critical", lambda *a, **k: boxes.append(a)) - emitted = [] - panel.rotation_scan.connect(emitted.append) - panel._beamline_state = BeamlineStateEnum.SampleAlignment - - panel.image_time_enter.setText("0.0010") # below 1/900 s, stays red - panel.run_measurement() - - assert emitted == [] - assert len(boxes) == 1 diff --git a/tests/unit/gui/test_splash_screen.py b/tests/unit/gui/test_splash_screen.py deleted file mode 100644 index f701d94a..00000000 --- a/tests/unit/gui/test_splash_screen.py +++ /dev/null @@ -1,14 +0,0 @@ -from PySide6.QtGui import QPixmap - -from aare.gui.widgets.splash_screen import LoadingSplashScreen - - -def test_splash_progress_and_message(qtbot): - splash = LoadingSplashScreen(QPixmap(200, 100)) - qtbot.addWidget(splash) - - splash.set_progress(42, "Loading panels") - assert splash.progress.value() == 42 - - splash.set_progress(43) # message-less update takes the no-showMessage branch - assert splash.progress.value() == 43 diff --git a/tests/unit/gui/test_sse_client.py b/tests/unit/gui/test_sse_client.py deleted file mode 100644 index 866c208d..00000000 --- a/tests/unit/gui/test_sse_client.py +++ /dev/null @@ -1,76 +0,0 @@ -from unittest.mock import MagicMock - -import pytest -from PySide6.QtCore import QByteArray -from PySide6.QtNetwork import QNetworkReply - -from aare.gui.threads.sse_client import SSEClient - - -@pytest.fixture -def sse_client(qtbot): - client = SSEClient() - return client - - -def test_sse_client_init(sse_client): - assert not sse_client.is_connected() - assert sse_client._reconnect_delay == 1000 - - -def test_sse_client_parse_message(sse_client, qtbot): - # Test simple message - with qtbot.wait_signal(sse_client.message_received) as blocker: - sse_client._parse_sse_line("data: hello") - sse_client._parse_sse_line("") - assert blocker.args == ["hello"] - - -def test_sse_client_parse_event(sse_client, qtbot): - # Test event with data - with qtbot.wait_signal(sse_client.event_received) as blocker: - sse_client._parse_sse_line("event: update") - sse_client._parse_sse_line("data: some data") - sse_client._parse_sse_line("") - assert blocker.args == ["update", "some data"] - - -def test_sse_client_multiline_data(sse_client, qtbot): - with qtbot.wait_signal(sse_client.message_received) as blocker: - sse_client._parse_sse_line("data: line1") - sse_client._parse_sse_line("data: line2") - sse_client._parse_sse_line("") - assert blocker.args == ["line1\nline2"] - - -def test_sse_client_buffer_processing(sse_client, qtbot): - sse_client._buffer = QByteArray(b"data: chunk1\n\n") - with qtbot.wait_signal(sse_client.message_received, timeout=1000) as blocker: - sse_client._process_buffer() - assert blocker.args == ["chunk1"] - - sse_client._buffer = QByteArray(b"data: chunk2\n\n") - with qtbot.wait_signal(sse_client.message_received, timeout=1000) as blocker: - sse_client._process_buffer() - assert blocker.args == ["chunk2"] - - -def test_sse_client_retry_parsing(sse_client): - sse_client._parse_sse_line("retry: 5000") - assert sse_client._reconnect_delay == 5000 - - sse_client._parse_sse_line("retry: invalid") - assert sse_client._reconnect_delay == 5000 - - -def test_sse_client_disconnect(sse_client, qtbot): - # Mock a reply - mock_reply = MagicMock(spec=QNetworkReply) - sse_client._reply = mock_reply - sse_client._connected = True - - with qtbot.wait_signal(sse_client.disconnected): - sse_client.disconnect_from_sse() - - assert not sse_client._connected - mock_reply.abort.assert_called_once() diff --git a/tests/unit/gui/test_status_bar.py b/tests/unit/gui/test_status_bar.py deleted file mode 100644 index 86312997..00000000 --- a/tests/unit/gui/test_status_bar.py +++ /dev/null @@ -1,114 +0,0 @@ -"""Status bar layout contract: every readout lives in one wrapping flow -host (narrow windows wrap instead of clipping), and every operable label -wears the shared hover affordance.""" - -from aarecommon.models.models import TokenData -from PySide6.QtCore import QEvent, QPointF, Qt -from PySide6.QtGui import QEnterEvent - -from aare.gui.widgets.flow_layout import FlowLayout -from aare.gui.widgets.status_bar import StatusBar - - -def _bar(qtbot): - bar = StatusBar(token=TokenData(sub="u", staff=True, pgroups=["p1"], session=1)) - qtbot.addWidget(bar) - bar.show() - return bar - - -def test_operables_share_the_hover_affordance(qtbot): - bar = _bar(qtbot) - for label in (bar.shutter_label, bar.state_label, bar.pgroup_label, bar.session_label): - assert label.cursor().shape() == Qt.CursorShape.PointingHandCursor - - # Cryo is grouped with the operables but stays passive for now (TODO in - # status_bar.py); the plain readouts are passive too. - for label in (bar.cryo_label, bar.flux, bar.busy_label): - assert label.cursor().shape() != Qt.CursorShape.PointingHandCursor - - # Hover underlines, leaving restores. - enter = QEnterEvent(QPointF(1, 1), QPointF(1, 1), QPointF(1, 1)) - bar.state_label.enterEvent(enter) - assert bar.state_label.font().underline() - bar.state_label.leaveEvent(QEvent(QEvent.Type.Leave)) - assert not bar.state_label.font().underline() - - -def test_state_menu_gates_beam_location_for_non_staff(qtbot, daq_status_factory, monkeypatch): - from aarecommon.models.models import BeamlineStateEnum - from PySide6.QtWidgets import QMenu - - import aare.gui.widgets.status_bar as status_bar_module - - # exec() would block on a real popup, and PySide's method lookup ignores - # a class-attribute monkeypatch — swap in a subclass instead. The menu - # stays inspectable as a child of the bar afterwards. - class _NoExecMenu(QMenu): - def exec(self): # pyright: ignore[reportIncompatibleMethodOverride] - return None - - monkeypatch.setattr(status_bar_module, "QMenu", _NoExecMenu) - - def _state_menu_entries(bar): - bar._status = daq_status_factory(state=BeamlineStateEnum.SampleAlignment) - bar.show_state_menu() - # Plain data, not QAction refs: the menu (and its actions) only - # lives until the next GC pass once show_state_menu returns. - return {a.text(): a.isEnabled() for a in bar.findChildren(QMenu)[-1].actions()} - - assert _state_menu_entries(_bar(qtbot))["Beam location"] - - non_staff = StatusBar(token=TokenData(sub="u", staff=False, pgroups=["p1"], session=1)) - qtbot.addWidget(non_staff) - assert not _state_menu_entries(non_staff)["Beam location (admin mode only)"] - - -def test_readout_width_ratchets_so_numbers_do_not_jitter(qtbot, daq_status_factory): - bar = _bar(qtbot) - # A wide value pins the minimum width; a narrower one must NOT shrink it, - # otherwise every tick re-flows the row and neighbours jitter. - bar.update_samcam_fps(1234.5) - bar.update_sharpness(0.123) - wide = bar.samcam_fps.minimumWidth() - assert wide >= bar.samcam_fps.sizeHint().width() - bar.update_samcam_fps(5.0) - assert bar.samcam_fps.minimumWidth() == wide - # The DAQ tick ratchets the rest, session-display path included. - bar.update_daq_status(daq_status_factory()) - bar._update_session_display() - assert bar.ring_current.minimumWidth() >= bar.ring_current.sizeHint().width() - assert bar.session_label.minimumWidth() >= bar.session_label.sizeHint().width() - - -def test_readouts_wrap_instead_of_clipping(qtbot, daq_status_factory): - bar = _bar(qtbot) - # Labels are empty until a DAQ tick paints them; feed one so the flow - # measures realistic widths (empty labels never trigger a wrap). - bar.update_daq_status(daq_status_factory()) - host = bar.info_host - flow = host.layout() - assert isinstance(flow, FlowLayout) # narrows Optional for the checker - # Passive readouts wrap in the flow host; the four operables are - # addPermanentWidget so QStatusBar pins them to the right corner and - # they never move when the flow wraps. - for label in (bar.flux, bar.busy_label, bar.cryo_label): - assert label.parentWidget() is host - for label in (bar.shutter_label, bar.state_label, bar.pgroup_label, bar.session_label): - assert label.parentWidget() is bar - assert label.parentWidget() is not host - # Narrow width -> the flow reports a taller (multi-row) height than one - # row, and resizing the host pins its minimum height to the wrapped - # height so the bar grows instead of cutting labels off. - one_row = flow.heightForWidth(100_000) - wrapped = flow.heightForWidth(200) - assert wrapped > one_row - host.resize(200, wrapped) - assert host.minimumHeight() >= wrapped - # Layout bookkeeping the canonical example demands. - assert flow.count() > 0 - assert flow.itemAt(0) is not None - assert flow.itemAt(9999) is None - taken = flow.takeAt(flow.count() - 1) - assert taken is not None - assert flow.takeAt(9999) is None diff --git a/tests/unit/gui/test_styles.py b/tests/unit/gui/test_styles.py deleted file mode 100644 index 8916e62e..00000000 --- a/tests/unit/gui/test_styles.py +++ /dev/null @@ -1,20 +0,0 @@ -"""App stylesheet knobs that must track the font zoom ladder.""" - -from aare.gui import styles - - -def test_control_height_scales_with_font_ladder(): - """Buttons/inputs pinned at 16px clipped descenders at 125/150%; the pin - must scale with the ladder in both sheets.""" - - try: - styles.set_font_scale(1.0) - for theme in (styles.THEME_SUNRISE, styles.THEME_SUNSET): - assert "max-height: 16px" in styles.build_app_stylesheet(theme), theme - styles.set_font_scale(1.5) - for theme in (styles.THEME_SUNRISE, styles.THEME_SUNSET): - sheet = styles.build_app_stylesheet(theme) - assert "max-height: 24px" in sheet, theme - assert "max-height: 16px" not in sheet, theme - finally: - styles.set_font_scale(1.0) diff --git a/tests/unit/gui/test_tell_sample_panel.py b/tests/unit/gui/test_tell_sample_panel.py deleted file mode 100644 index 0ccd940a..00000000 --- a/tests/unit/gui/test_tell_sample_panel.py +++ /dev/null @@ -1,186 +0,0 @@ -"""The combined sample dock: chip row filters the table by status, chips -double as drop targets for queue/flag relabeling, and a pop-out panel shares -the docked panel's model so both stay in sync without wiring.""" - -import pytest -from aarecommon.models.models import DewarAddress, SampleShortInfo, SampleShortInfoList - -from aare.gui.panels.tell_sample_panel import TellSamplePanel - - -@pytest.fixture -def samples(): - return SampleShortInfoList( - s=[ - SampleShortInfo( - db_id=i, - puck_name=f"P{i}", - dewar_name="D1", - sample_name=f"S{i}", - run_number=i, - user="U1", - pin=i, - location=DewarAddress(segment="A", pos=i), - ) - for i in (1, 2, 3) - ] - ) - - -@pytest.fixture -def panel(qtbot, samples): - panel = TellSamplePanel(samples=samples) - qtbot.addWidget(panel) - panel.table_model.set_show_all_pgroups(True) - return panel - - -def _chip(panel, key): - return next(c for c in panel.status_chips.buttons() if c.property("status_key") == key) - - -def test_chip_click_drives_the_status_filter(panel): - panel.table_model.set_queued_ids({2}) - _chip(panel, "queued").click() - assert panel.table_model.status_filter == "queued" - assert panel.table_model.rowCount() == 1 - _chip(panel, None).click() - assert panel.table_model.status_filter is None - assert panel.table_model.rowCount() == 3 - - -def test_set_status_chip_syncs_without_filtering(panel): - panel.set_status_chip("flagged") - assert _chip(panel, "flagged").isChecked() - # Sync only checks the chip; it must not fire the filter. - assert panel.table_model.status_filter is None - - -def test_queued_chip_drop_relays_to_the_queue(panel, qtbot, samples): - chip = _chip(panel, "queued") - with qtbot.waitSignal(panel.add_to_queue) as blocker: - chip.samples_dropped.emit(samples) - assert [s.db_id for s in blocker.args[0].s] == [1, 2, 3] - - -def test_flagged_chip_drop_flags_in_the_model(panel, samples): - panel._flag_dropped_samples(SampleShortInfoList(s=samples.s[:2])) - assert panel.table_model.flagged_ids == {1, 2} - - -def test_popout_panel_shares_the_model(panel, qtbot): - popout = TellSamplePanel(model=panel.table_model) - qtbot.addWidget(popout) - assert popout.table_model is panel.table_model - panel.table_model.set_flagged(3, True) - assert 3 in popout.table_model.flagged_ids - - -def test_new_sample_list_updates_rows(panel, samples): - extra = samples.s + [ - SampleShortInfo( - db_id=9, - puck_name="P9", - dewar_name="D2", - sample_name="S9", - run_number=9, - user="U2", - pin=9, - location=DewarAddress(segment="B", pos=1), - ) - ] - panel.new_sample_list(SampleShortInfoList(s=extra)) - assert panel.table_model.rowCount() == 4 - - -def test_queue_drop_chip_accepts_sample_payloads(panel, qtbot, samples): - from PySide6.QtCore import QMimeData, QPointF, Qt - from PySide6.QtGui import QDropEvent - - from aare.gui.panels.tell_sample_panel import QueueDropChip - - chip = next(c for c in panel.status_chips.buttons() if isinstance(c, QueueDropChip)) - - # The event only borrows the QMimeData (C++ pointer), so the mime must - # outlive the dropEvent call — hence created in the test's scope. - def drop(mime): - return QDropEvent( - QPointF(1, 1), - Qt.DropAction.CopyAction, - mime, - Qt.MouseButton.NoButton, - Qt.KeyboardModifier.NoModifier, - ) - - good = QMimeData() - good.setText(samples.model_dump_json()) - with qtbot.waitSignal(chip.samples_dropped): - chip.dropEvent(drop(good)) - - # A non-sample payload is ignored, not crashed on. - bad = QMimeData() - bad.setText("not json") - with qtbot.assertNotEmitted(chip.samples_dropped): - chip.dropEvent(drop(bad)) - - -def test_status_header_click_selects_all(panel): - header = panel.table_view.frozen.horizontalHeader() - header.sectionClicked.emit(0) - assert len(panel.table_view.selectionModel().selectedRows()) == 3 - # Other sections keep their normal sort-click behavior. - panel.table_view.clearSelection() - header.sectionClicked.emit(1) - assert len(panel.table_view.selectionModel().selectedRows()) == 0 - - -def test_selected_samples_follow_the_click(panel): - view = panel.table_view - view.selectRow(0) - row_ids = [panel.table_model.get_id(r).db_id for r in range(3)] - # Click inside the selection: the selection is acted on. - assert [s.db_id for s in panel._selected_samples(0)] == [row_ids[0]] - # Click outside the selection: only the clicked row is acted on. - assert [s.db_id for s in panel._selected_samples(2)] == [row_ids[2]] - - -def test_font_zoom_keeps_frozen_column_aligned_and_reautosizes(panel, qtbot): - """Ctrl+plus zoom: the frozen "#" overlay header must stay exactly as - tall as the main header (else its rows sit 1px higher), and the columns - sized once at startup must re-autosize for the wider glyphs.""" - from PySide6.QtGui import QFont - from PySide6.QtWidgets import QApplication - - from aare.gui import styles - - app = QApplication.instance() - assert isinstance(app, QApplication) # font() lives on QApplication, not QCoreApplication - base = QFont(app.font()) - # Startup look first: under a styled ancestor (MainWindow) fonts reach - # the view through the QSS path; without any sheet Qt would not - # propagate the app font to a child that carries WA_StyleSheet. - panel.setStyleSheet(styles.build_app_stylesheet(styles.THEME_SUNRISE)) - panel.resize(600, 300) - panel.show() - qtbot.waitExposed(panel) - view = panel.table_view - width_before = view.columnWidth(1) - - def row0_top(v): - return v.viewport().mapTo(panel, v.viewport().rect().topLeft()).y() + v.rowViewportPosition( - 0 - ) - - try: - # Same three steps as MainWindow._apply_theme on a zoom change. - styles.set_font_scale(1.25) - big = QFont(base) - big.setPointSizeF(base.pointSizeF() * 1.25) - app.setFont(big) - panel.setStyleSheet(styles.build_app_stylesheet(styles.THEME_SUNRISE)) - qtbot.waitUntil(lambda: view.columnWidth(1) > width_before) - assert view.frozen.horizontalHeader().height() == view.horizontalHeader().height() - assert row0_top(view.frozen) == row0_top(view) - finally: - styles.set_font_scale(1.0) - app.setFont(base) diff --git a/tests/unit/gui/test_threads_logic.py b/tests/unit/gui/test_threads_logic.py deleted file mode 100644 index a59f21fb..00000000 --- a/tests/unit/gui/test_threads_logic.py +++ /dev/null @@ -1,77 +0,0 @@ -from unittest.mock import MagicMock - -from aarecommon.models.models import DAQStatusModel, DewarAddress, SampleShortInfo - -from aare.gui.scan_logic.sample_mount_logic import SampleMountLogic - - -def test_sample_mount_logic_emits_on_change(): - logic = SampleMountLogic() - mock_slot = MagicMock() - logic.sample_changed.connect(mock_slot) - - sample1 = SampleShortInfo( - db_id=1, - puck_name="P1", - dewar_name="D1", - sample_name="S1", - run_number=1, - user="U1", - pin=1, - location=DewarAddress(segment="A", pos=1), - ) - sample2 = SampleShortInfo( - db_id=2, - puck_name="P1", - dewar_name="D1", - sample_name="S2", - run_number=1, - user="U1", - pin=2, - location=DewarAddress(segment="A", pos=1), - ) - - status = MagicMock(spec=DAQStatusModel) - status.sample = sample1 - - # First update, should emit - logic.update_daq_status(status) - mock_slot.assert_called_once_with(sample1) - mock_slot.reset_mock() - - # Second update same sample, should NOT emit - logic.update_daq_status(status) - mock_slot.assert_not_called() - - # Third update different sample, should emit - status.sample = sample2 - logic.update_daq_status(status) - mock_slot.assert_called_once_with(sample2) - - -def test_sample_mount_logic_none_to_sample(): - logic = SampleMountLogic() - mock_slot = MagicMock() - logic.sample_changed.connect(mock_slot) - - sample1 = SampleShortInfo( - db_id=1, - puck_name="P1", - dewar_name="D1", - sample_name="S1", - run_number=1, - user="U1", - pin=1, - location=DewarAddress(segment="A", pos=1), - ) - - status = MagicMock(spec=DAQStatusModel) - status.sample = None - - logic.update_daq_status(status) - # Initial __sample is None, so if status.sample is also None, it won't emit - mock_slot.assert_not_called() - - status.sample = sample1 - logic.update_daq_status(status) - mock_slot.assert_called_once_with(sample1) diff --git a/tests/unit/gui/test_title_label.py b/tests/unit/gui/test_title_label.py deleted file mode 100644 index daf48ecf..00000000 --- a/tests/unit/gui/test_title_label.py +++ /dev/null @@ -1,91 +0,0 @@ -from PySide6.QtCore import QSettings -from PySide6.QtWidgets import QGridLayout, QHBoxLayout, QPushButton, QWidget - -from aare.gui.widgets.title_label import TitleLabel - -# Unique title so the test never clashes with real panel settings. -TITLE = "TitleLabelTestPanel" -KEY = f"panel_collapsed/{TITLE}" - - -def _remove_key(): - QSettings("PSI", "AareGUI").remove(KEY) - - -def _build_panel(qtbot): - panel = QWidget() - qtbot.addWidget(panel) - grid = QGridLayout(panel) - title = TitleLabel(TITLE, panel, collapsible=True) - grid.addWidget(title, 0, 0, 1, 2) - direct_child = QPushButton("direct", panel) - grid.addWidget(direct_child, 1, 0) - nested = QHBoxLayout() - nested_child = QPushButton("nested", panel) - nested.addWidget(nested_child) - grid.addLayout(nested, 1, 1) - return panel, title, direct_child, nested_child - - -def test_starts_collapsed_by_default_and_toggle_persists(qtbot): - _remove_key() - try: - _panel, title, direct_child, nested_child = _build_panel(qtbot) - # Default is collapsed; applied deferred with a 0 ms timer (siblings - # don't exist yet at TitleLabel construction). - qtbot.waitUntil(lambda: direct_child.isHidden(), timeout=1000) - assert nested_child.isHidden() - assert not title.isHidden() - assert title.toggle_button.text() == "+" - - title.toggle_collapsed() - assert not direct_child.isHidden() - assert not nested_child.isHidden() - assert title.toggle_button.text() == "−" - assert QSettings("PSI", "AareGUI").value(KEY, True, type=bool) is False - - title.toggle_collapsed() - assert direct_child.isHidden() - assert title.toggle_button.text() == "+" - assert QSettings("PSI", "AareGUI").value(KEY, False, type=bool) is True - finally: - _remove_key() - - -def test_saved_expanded_state_restored_on_construction(qtbot): - QSettings("PSI", "AareGUI").setValue(KEY, False) - try: - _panel, title, direct_child, nested_child = _build_panel(qtbot) - # A saved expanded state must override the collapsed default; give the - # (absent) deferred collapse a chance to run before asserting. - qtbot.wait(100) - assert not direct_child.isHidden() - assert not nested_child.isHidden() - assert title.toggle_button.text() == "−" - finally: - _remove_key() - - -def test_not_collapsible_by_default(qtbot): - panel = QWidget() - qtbot.addWidget(panel) - grid = QGridLayout(panel) - title = TitleLabel("Plain", panel) - grid.addWidget(title, 0, 0) - assert not hasattr(title, "toggle_button") - - -def test_pending_collapse_timer_dies_with_the_banner(): - """The deferred _apply_collapsed must not fire into a deleted banner — - that was the historic "QPushButton returned NULL" / SystemError flake - poisoning whichever test ran next (singleShot without receiver context - outlives the widget).""" - from PySide6.QtWidgets import QApplication - - _remove_key() - host = QWidget() - TitleLabel("DoomedBanner", host, collapsible=True, default_collapsed=True) - # Python-owned host: del cascades the C++ delete to the banner while - # its singleShot(0) is still pending. - del host - QApplication.processEvents() # must not raise into the event loop diff --git a/tests/unit/gui/test_tutorials.py b/tests/unit/gui/test_tutorials.py deleted file mode 100644 index 3f049cfb..00000000 --- a/tests/unit/gui/test_tutorials.py +++ /dev/null @@ -1,75 +0,0 @@ -import pytest -from PySide6.QtWidgets import QWidget - -from aare.gui.tutorials.tutorial_manager import TutorialManager -from aare.gui.tutorials.tutorial_models import ( - StepKind, - TargetKind, - TutorialMode, - TutorialScenario, - TutorialStepDefinition, - TutorialTarget, - TutorialTextRef, -) -from aare.gui.tutorials.tutorial_runtime import ( - DictionaryTextResolver, - DictTargetResolver, - NoOpActionExecutor, - TutorialEventBus, -) - - -@pytest.fixture -def mock_window(qapp): - return QWidget() - - -@pytest.fixture -def tutorial_scenario(): - step1 = TutorialStepDefinition( - id="step1", - kind=StepKind.INFO, - title=TutorialTextRef(key="step1_title"), - body=TutorialTextRef(key="step1_body"), - target=TutorialTarget(kind=TargetKind.NONE, target_id=""), - ) - scenario = TutorialScenario( - id="test_scenario", - title=TutorialTextRef(key="scenario_title"), - description=TutorialTextRef(key="scenario_desc"), - mode=TutorialMode.LINEAR, - steps=[step1], - ) - return scenario - - -def test_tutorial_manager_start_stop(qtbot, mock_window, tutorial_scenario): - text_resolver = DictionaryTextResolver( - { - "en": { - "step1_title": "Step 1", - "step1_body": "This is step 1", - "scenario_title": "Test", - "scenario_desc": "Test Desc", - } - } - ) - target_resolver = DictTargetResolver({}) - action_executor = NoOpActionExecutor() - event_bus = TutorialEventBus() - - manager = TutorialManager( - parent_window=mock_window, - target_resolver=target_resolver, - text_resolver=text_resolver, - action_executor=action_executor, - event_bus=event_bus, - ) - manager.add_scenario(tutorial_scenario) - - manager.start("test_scenario") - assert manager.get_current_step() is not None - assert manager.get_current_step().id == "step1" - - manager.stop() - assert manager.get_current_step() is None diff --git a/tests/unit/gui/test_wheel_value_guard.py b/tests/unit/gui/test_wheel_value_guard.py deleted file mode 100644 index 30ae245c..00000000 --- a/tests/unit/gui/test_wheel_value_guard.py +++ /dev/null @@ -1,90 +0,0 @@ -"""The wheel guard is motor protection: a bare wheel over a value widget must -never change the value (it scrolls the page instead); adjusting requires the -deliberate right-button + wheel gesture.""" - -import pytest -from PySide6.QtCore import QPoint, QPointF, Qt -from PySide6.QtGui import QWheelEvent -from PySide6.QtWidgets import ( - QApplication, - QScrollArea, - QSlider, - QSpinBox, - QVBoxLayout, - QWidget, - QWidgetItem, -) - -from aare.gui.widgets.wheel_value_guard import WheelValueGuard - - -@pytest.fixture -def guard(qapp): - guard = WheelValueGuard() - qapp.installEventFilter(guard) - yield guard - qapp.removeEventFilter(guard) - - -def _wheel(buttons): - return QWheelEvent( - QPointF(5, 5), - QPointF(5, 5), - QPoint(0, 0), - QPoint(0, 120), - buttons, - Qt.KeyboardModifier.NoModifier, - Qt.ScrollPhase.NoScrollPhase, - False, - ) - - -def test_bare_wheel_does_not_adjust(guard, qtbot): - slider = QSlider(Qt.Orientation.Horizontal) - qtbot.addWidget(slider) - slider.setRange(0, 100) - slider.setValue(50) - QApplication.sendEvent(slider, _wheel(Qt.MouseButton.NoButton)) - assert slider.value() == 50 - - -def test_right_button_wheel_adjusts(guard, qtbot): - slider = QSlider(Qt.Orientation.Horizontal) - qtbot.addWidget(slider) - slider.setRange(0, 100) - slider.setValue(50) - QApplication.sendEvent(slider, _wheel(Qt.MouseButton.RightButton)) - assert slider.value() != 50 - - -def test_bare_wheel_scrolls_the_enclosing_area(guard, qtbot): - area = QScrollArea() - qtbot.addWidget(area) - content = QWidget() - layout = QVBoxLayout(content) - spin = QSpinBox() - spin.setRange(0, 100) - spin.setValue(50) - layout.addWidget(spin) - # Tall filler so the area has something to scroll. - filler = QWidget() - filler.setFixedHeight(2000) - layout.addWidget(filler) - area.setWidget(content) - area.resize(200, 200) - area.show() - bar = area.verticalScrollBar() - bar.setValue(bar.maximum() // 2) - before = bar.value() - - QApplication.sendEvent(spin, _wheel(Qt.MouseButton.NoButton)) - assert spin.value() == 50 - assert bar.value() != before - - -def test_a_non_event_argument_is_ignored(guard, qtbot): - # PySide 6.9 can hand an app-level filter a QWidgetItem instead of a - # QEvent during layout teardown; raising there fails a random test. - widget = QWidget() - qtbot.addWidget(widget) - assert guard.eventFilter(widget, QWidgetItem(widget)) is False diff --git a/tests/unit/gui/test_widgets.py b/tests/unit/gui/test_widgets.py deleted file mode 100644 index 3b3083a9..00000000 --- a/tests/unit/gui/test_widgets.py +++ /dev/null @@ -1,47 +0,0 @@ -from aare.gui.widgets.alert_banner import AlertBanner -from aare.gui.widgets.status_label import StatusLabel - - -def test_alert_banner_show_message(qtbot): - banner = AlertBanner() - qtbot.addWidget(banner) - - assert not banner.isVisible() - - banner.show_message("Test Error", is_error=True) - assert banner.isVisible() - assert "Test Error" in banner._label.text() - assert "🛑" in banner._label.text() - - banner.show_message("Test Success", is_error=False) - assert banner.isVisible() - assert "Test Success" in banner._label.text() - assert "✅" in banner._label.text() - - banner.clear_message() - assert not banner.isVisible() - - -def test_alert_banner_waiting(qtbot): - banner = AlertBanner() - qtbot.addWidget(banner) - - banner.show_waiting("Working", countdown_seconds=10) - assert banner.isVisible() - assert "Working" in banner._label.text() - assert "⏳" in banner._label.text() - assert "(10s)" in banner._label.text() - - # Tick manually if we wanted to test timer, but usually we just test state - banner._tick_countdown() - assert "(9s)" in banner._label.text() - - -def test_status_label(qtbot): - label = StatusLabel(val=1.234, decimals=2) - qtbot.addWidget(label) - - assert label.text() == "1.23" - - label.new_value(5.6) - assert label.text() == "5.60" diff --git a/tests/unit/utils/test_beamline_dispatch.py b/tests/unit/utils/test_beamline_dispatch.py deleted file mode 100644 index 49357794..00000000 --- a/tests/unit/utils/test_beamline_dispatch.py +++ /dev/null @@ -1,88 +0,0 @@ -import importlib.util -from unittest.mock import patch - -import numpy as np -import pytest - -from aare.beamline_dispatch.beamline_dispatch import get_beamline_dispatch -from aare.beamline_dispatch.simulated import SimulatedDispatch -from aare.beamline_dispatch.x06da import X06daDispatch -from aare.beamline_dispatch.x10sa import X10saDispatch - - -def test_dispatch_cannot_be_instantiated_without_env(): - with patch.dict("os.environ", {}, clear=True), pytest.raises(ValueError) as e: - _ = get_beamline_dispatch() - assert e.match("Please set the BEAMLINE environment variable") - - -def test_simulated_dispatch_can_be_instantiated(): - with patch.dict("os.environ", {"BEAMLINE": "SIMULATED"}): - dispatch = get_beamline_dispatch() - assert isinstance(dispatch, SimulatedDispatch) - - -@pytest.mark.skipif(importlib.util.find_spec("pxi_bec") is None, reason="run only for pxi flavour") -def test_pxi_dispatch_can_be_instantiated(): - with patch.dict("os.environ", {"BEAMLINE": "X06SA"}), pytest.raises(TypeError) as e: - _ = get_beamline_dispatch() - assert e.match("Can't instantiate abstract class") - - -@pytest.mark.skipif( - importlib.util.find_spec("pxii_bec") is None, reason="run only for pxii flavour" -) -def test_pxii_dispatch_can_be_instantiated(): - with patch.dict("os.environ", {"BEAMLINE": "X10SA"}): - dispatch = get_beamline_dispatch() - assert isinstance(dispatch, X10saDispatch) - - -@pytest.mark.skipif( - importlib.util.find_spec("pxii_bec") is None, reason="run only for pxii flavour" -) -def test_pxii_dispatch_beam_center(): - with patch.dict("os.environ", {"BEAMLINE": "X10SA"}): - dispatch = get_beamline_dispatch() - beam_center = dispatch.geo.beam_centre_model.predict(300, 0) - assert np.isclose(beam_center[0][0], 2081.8, atol=1) - assert np.isclose(beam_center[1][0], 2242.05, atol=1) - - -@pytest.mark.skipif( - importlib.util.find_spec("pxii_bec") is None, reason="run only for pxii flavour" -) -def test_poni_rot_is_0(): - with patch.dict("os.environ", {"BEAMLINE": "X10SA"}): - dispatch = get_beamline_dispatch() - assert dispatch.geo.detector_tilt == (0, 0) - - -@pytest.mark.skipif( - importlib.util.find_spec("pxiii_bec") is None, reason="run only for pxiii flavour" -) -def test_pxiii_dispatch_can_be_instantiated(): - with patch.dict("os.environ", {"BEAMLINE": "X06DA"}): - dispatch = get_beamline_dispatch() - assert isinstance(dispatch, X06daDispatch) - - -@pytest.mark.skipif( - importlib.util.find_spec("pxiii_bec") is None, reason="run only for pxiii flavour" -) -def test_poni_rot_is_not_0(): - with patch.dict("os.environ", {"BEAMLINE": "X06DA"}): - dispatch = get_beamline_dispatch() - assert dispatch.geo.detector_tilt != (0, 0) - - -@pytest.mark.skipif( - importlib.util.find_spec("pxiii_bec") is None, reason="run only for pxiii flavour" -) -def test_flux_table(): - with patch.dict("os.environ", {"BEAMLINE": "X06DA"}): - dispatch = get_beamline_dispatch() - with patch.object(dispatch.bec_macros, "get_current_energy", lambda: 4100): - assert np.isclose(dispatch.bec_macros.full_flux_ph_per_s(), 1.2625e10) - with patch.object(dispatch.bec_macros, "get_current_energy", lambda: 15000): - assert np.isclose(dispatch.bec_macros.full_flux_ph_per_s(), 5.0923e10)