From ef6517dca3fd791b6dca6857432a6a9dd9bb5c9f Mon Sep 17 00:00:00 2001 From: Hongquan Li Date: Fri, 13 Nov 2026 01:39:32 -0800 Subject: [PATCH 1/3] feat(control-server): autofocus runs the contrast autofocus of Squid The command was a stub (NotImplementedError). A client that focuses with a move and acquire_image for each plane needs about 3 s for each plane, because each frame goes through a file. The sweep of the Autofocus button works on frames in memory. - autofocus(n_planes, step_um, measure, save_dir) runs that sweep with the window's own controller (the planes also go to its display), or with a controller of its own when there is no window. It waits for the end and replies with the Z, the focus measure of each plane, the index of the sharpest plane and the time. - measure selects LAPE, GLVA or TENENGRAD for one call; the default stays the setting of Squid. - save_dir saves the centre crop of each plane after the sweep. - The values of the Autofocus panel are put back. Refused during an acquisition and during another autofocus. With no frame from the camera the stage goes back to its start Z. - AutoFocusController keeps what the last sweep measured (last_planes). Checked in the application in simulation: 10 planes in 0.6 s, each plane on the display, the panel values unchanged, live view on again after a sweep that started with live on. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_0152Tv36aY3Whyz7ATrKcZX3 --- .../control/core/auto_focus_controller.py | 7 + software/control/core/auto_focus_worker.py | 10 +- software/control/microscope_control_server.py | 118 ++++++++- software/docs/mcp_integration.md | 16 ++ .../control/test_control_server_autofocus.py | 232 ++++++++++++++++++ 5 files changed, 377 insertions(+), 6 deletions(-) create mode 100644 software/tests/control/test_control_server_autofocus.py diff --git a/software/control/core/auto_focus_controller.py b/software/control/core/auto_focus_controller.py index 8172cf811d..bad33a55a3 100644 --- a/software/control/core/auto_focus_controller.py +++ b/software/control/core/auto_focus_controller.py @@ -46,6 +46,12 @@ def __init__( self.autofocus_in_progress = False self.focus_map_coords = [] self.use_focus_map = False + # For a caller that wants the result of one run (the control server's autofocus command): + # the focus measure of this run (None: the setting FOCUS_MEASURE_OPERATOR), and if the plane images are kept. + self.focus_measure_operator: Optional[control._def.FocusMeasureOperator] = None + self.keep_plane_images = False + # What the last contrast autofocus measured: (z_mm, focus measure, image or None) for each plane, from below. + self.last_planes: list = [] def set_N(self, N): self.N = N @@ -102,6 +108,7 @@ def autofocus(self, focus_map_override=False): raise RuntimeError("Previous focus thread failed to join") self._keep_running.set() + self.last_planes = [] self._autofocus_worker = AutofocusWorker( self, self._on_autofocus_completed, self._image_to_display_fn, self._keep_running ) diff --git a/software/control/core/auto_focus_worker.py b/software/control/core/auto_focus_worker.py index f0d574397a..fcc2be735c 100644 --- a/software/control/core/auto_focus_worker.py +++ b/software/control/core/auto_focus_worker.py @@ -40,6 +40,10 @@ def __init__( self.crop_width = self.autofocusController.crop_width self.crop_height = self.autofocusController.crop_height + self.focus_measure_operator = ( + self.autofocusController.focus_measure_operator or control._def.FOCUS_MEASURE_OPERATOR + ) + self.keep_plane_images = self.autofocusController.keep_plane_images def run(self): try: @@ -63,6 +67,7 @@ def run_autofocus(self): focus_measure_max = 0 z_af_offset = self.deltaZ * round(self.N / 2) + z_bottom_mm = self.stage.get_pos().z_mm - z_af_offset # the planes are one step each above this self.stage.move_z(-z_af_offset) @@ -106,7 +111,10 @@ def run_autofocus(self): self._image_to_display_fn(image) timestamp_0 = time.time() - focus_measure = utils.calculate_focus_measure(image, control._def.FOCUS_MEASURE_OPERATOR) + focus_measure = utils.calculate_focus_measure(image, self.focus_measure_operator) + self.autofocusController.last_planes.append( + (z_bottom_mm + (i + 1) * self.deltaZ, focus_measure, image if self.keep_plane_images else None) + ) timestamp_1 = time.time() self._log.info(" calculating focus measure took " + str(timestamp_1 - timestamp_0) + " second") focus_measure_vs_z[i] = focus_measure diff --git a/software/control/microscope_control_server.py b/software/control/microscope_control_server.py index 7bd7168301..ec73c65018 100644 --- a/software/control/microscope_control_server.py +++ b/software/control/microscope_control_server.py @@ -11,6 +11,8 @@ import functools import inspect import json +import math +import os import socket import threading import time @@ -259,6 +261,8 @@ def __init__( self._running = False self._thread: Optional[threading.Thread] = None self._python_exec_enabled = False # Disabled by default for security + self._own_autofocus_controller = None # autofocus with no window: made at the first use + self._autofocus_lock = threading.Lock() self._connection_semaphore = threading.Semaphore(MAX_CONNECTIONS) # Auto-discover commands by finding all _cmd_* methods @@ -622,12 +626,116 @@ def _cmd_get_status(self) -> Dict[str, Any]: return status + _AUTOFOCUS_TIMEOUT_S = 120.0 + @schema_method - def _cmd_autofocus(self) -> Dict[str, Any]: - """Run autofocus routine (not yet implemented).""" - # This would need to be implemented based on the autofocus controller - # For now, raise not implemented - raise NotImplementedError("Autofocus via control server not yet implemented") + def _cmd_autofocus( + self, + n_planes: int = Field(10, description="Number of planes (3 to 50)", ge=3, le=50), + step_um: float = Field(1.524, description="Distance between two planes in um (more than 0, at most 50)"), + measure: Optional[str] = Field( + None, description="Focus measure for this call: LAPE, GLVA or TENENGRAD. Default: the setting of Squid" + ), + save_dir: Optional[str] = Field( + None, + description="Absolute path of a folder; created if missing. The part of each plane that the measure " + "used is saved there as plane_.tiff", + ), + ) -> Dict[str, Any]: + """Run the contrast autofocus of Squid at the current position and move to the sharpest plane. + + The planes are around the current Z, n_planes steps of step_um. It is the sweep of the Autofocus button: + the frames stay in memory, the measure is taken on the centre of the image, and the sweep stops early when + the measure falls clearly below its largest value. The reply has the Z, the planes with their focus + measure (from below), the index of the sharpest plane, and the time. Refused while an acquisition or + another autofocus runs. Live view is stopped for the sweep and started again.""" + from control.core.auto_focus_controller import AutoFocusController + + # schema_method fills defaults; it does not enforce limits, so the limits are checked here. + if isinstance(n_planes, bool) or not isinstance(n_planes, int) or not 3 <= n_planes <= 50: + raise ValueError("n_planes must be a whole number from 3 to 50") + if ( + isinstance(step_um, bool) + or not isinstance(step_um, (int, float)) + or not math.isfinite(step_um) + or not 0 < step_um <= 50 + ): + raise ValueError("step_um must be a number above 0 and at most 50") + operator = None + if measure is not None: + names = [option.name for option in control._def.FocusMeasureOperator] + if str(measure).upper() not in names: + raise ValueError(f"measure must be one of {', '.join(names)}") + operator = control._def.FocusMeasureOperator[str(measure).upper()] + if save_dir is not None and not os.path.isabs(save_dir): + raise ValueError("save_dir must be an absolute path") + if self.multipoint_controller is not None and self.multipoint_controller.acquisition_in_progress(): + raise RuntimeError("an acquisition is running") + + if self.gui is not None: # the window's controller: the planes also go to its display + controller = self.gui.autofocusController + else: + if self._own_autofocus_controller is None: + self._own_autofocus_controller = AutoFocusController( + self.microscope.camera, + self.microscope.stage, + self.microscope.live_controller, + self.microscope.low_level_drivers.microcontroller, + lambda: None, + lambda image: None, + self.microscope.addons.nl5, + ) + controller = self._own_autofocus_controller + with self._autofocus_lock: # two clients at one time: one of them gets the refusal + if controller.autofocus_in_progress: + raise RuntimeError("an autofocus is running") + # The values of the window's Autofocus panel are put back after the sweep. + panel = (controller.N, controller.deltaZ, controller.focus_measure_operator, controller.keep_plane_images) + start_z_mm = self.microscope.stage.get_pos().z_mm + began = time.monotonic() + controller.set_N(n_planes) + controller.set_deltaZ(step_um) + controller.focus_measure_operator = operator + controller.keep_plane_images = save_dir is not None + try: + controller.autofocus(focus_map_override=True) # the sweep, also when the window uses a focus map + except BaseException: + controller.N, controller.deltaZ, controller.focus_measure_operator, controller.keep_plane_images = panel + raise + try: + deadline = began + self._AUTOFOCUS_TIMEOUT_S + while controller.autofocus_in_progress: + if time.monotonic() > deadline: + raise RuntimeError(f"autofocus did not end in {self._AUTOFOCUS_TIMEOUT_S:.0f} s") + time.sleep(0.005) + planes = list(controller.last_planes) + finally: + controller.N, controller.deltaZ, controller.focus_measure_operator, controller.keep_plane_images = panel + seconds = time.monotonic() - began + if not planes: + # The sweep of Squid ends at the lowest plane when no frame came: go back to where the stage was. + self.microscope.stage.move_z_to(start_z_mm) + raise RuntimeError("autofocus got no frame from the camera; the stage is back at its start Z") + + measures = [float(focus_measure) for _, focus_measure, _ in planes] + reply_planes = [{"z_mm": z_mm, "focus_measure": value} for (z_mm, _, _), value in zip(planes, measures)] + if save_dir is not None: # after the sweep: a file write does not delay a plane + import tifffile + + os.makedirs(save_dir, exist_ok=True) + for index, ((_, _, image), plane) in enumerate(zip(planes, reply_planes)): + plane["path"] = os.path.join(save_dir, f"plane_{index:02d}.tiff") + tifffile.imwrite(plane["path"], image) + z_mm = self.microscope.stage.get_pos().z_mm + return { + "z_mm": z_mm, + "moved_um": (z_mm - start_z_mm) * 1000.0, + "best_index": measures.index(max(measures)), + "planes": reply_planes, + "measure": (operator or control._def.FOCUS_MEASURE_OPERATOR).name, + "stopped_early": len(planes) < n_planes, + "seconds": round(seconds, 2), + } @schema_method def _cmd_acquire_laser_af_image( diff --git a/software/docs/mcp_integration.md b/software/docs/mcp_integration.md index 0b69373bf2..585b261024 100644 --- a/software/docs/mcp_integration.md +++ b/software/docs/mcp_integration.md @@ -123,6 +123,22 @@ The `python_exec` command is disabled by default for security. To enable it: | `stop_live` | - | Stop live preview | | `acquire_image` | `save_path` | Capture single image | | `acquire_laser_af_image` | `save_path`, `use_last_frame` | Get laser autofocus camera image | +| `autofocus` | `n_planes`, `step_um`, `measure`, `save_dir` | Contrast autofocus at the current position | + +`autofocus` runs the contrast autofocus of Squid (the sweep of the Autofocus button) and moves to the sharpest +plane. The planes are around the current Z: `n_planes` steps (3 to 50, default 10) of `step_um` (default 1.524). +The frames stay in memory and the measure is taken on the centre of the image, so the command needs about the +time of `n_planes` images. The sweep stops early when the measure falls clearly below its largest value. + +`measure` selects the focus measure for this call: `LAPE`, `GLVA` or `TENENGRAD`. With no `measure`, the setting +`focus_measure_operator` of Squid is used. With `save_dir` (an absolute path), the part of each plane that the +measure used is saved there as `plane_.tiff`, after the sweep. + +The reply has `z_mm` (the Z after the autofocus), `moved_um`, `planes` (from below; each with `z_mm`, +`focus_measure`, and `path` when `save_dir` was given), `best_index`, `measure`, `stopped_early` and `seconds`. +The command is refused while an acquisition or another autofocus runs. Live view is stopped for the sweep and +started again. The values of the Autofocus panel of the window do not change. If the camera gives no frame, the +stage goes back to its start Z and the command fails. ### Channel & Illumination diff --git a/software/tests/control/test_control_server_autofocus.py b/software/tests/control/test_control_server_autofocus.py new file mode 100644 index 0000000000..aa6c250a10 --- /dev/null +++ b/software/tests/control/test_control_server_autofocus.py @@ -0,0 +1,232 @@ +"""autofocus over the control server: the contrast autofocus of Squid, on frames in memory. + +A client that focuses with move + acquire_image for each plane needs about 3 s for each plane (a file for each +frame). The window's Autofocus button does the same sweep on frames in memory in about the time of the images.""" + +import os +import threading +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import cv2 +import numpy as np +import pytest +import tifffile + +import control._def +from control._def import FocusMeasureOperator, TriggerMode +from control.core.auto_focus_controller import AutoFocusController + +FOCUS_Z_MM = 1.2000 + + +class FakeStage: + def __init__(self, z_mm): + self.z_mm = z_mm + + def move_z(self, delta_mm, blocking=True): + self.z_mm += delta_mm + + def move_z_to(self, z_mm, blocking=True): + self.z_mm = z_mm + + def get_pos(self): + return SimpleNamespace(x_mm=10.0, y_mm=20.0, z_mm=self.z_mm) + + def wait_for_idle(self, timeout_s): + pass + + +class FakeCamera: + """A fine texture that blurs with the distance from the focus plane: 1 pixel of blur for each 2 um.""" + + def __init__(self, stage, frames=True): + self._stage = stage + self._frames = frames + rng = np.random.default_rng(1) + self._scene = rng.integers(200, 4000, (400, 400)).astype(np.float32) + self.callbacks_enabled = True + self.frames_read = 0 + + def send_trigger(self, illumination_time=None): + pass + + def read_frame(self): + self.frames_read += 1 + if not self._frames: + return None + blur = abs(self._stage.z_mm - FOCUS_Z_MM) * 1000.0 / 2.0 + image = cv2.GaussianBlur(self._scene, (0, 0), blur) if blur > 0.05 else self._scene + return image.astype(np.uint16) + + def get_callbacks_enabled(self): + return self.callbacks_enabled + + def enable_callbacks(self, enabled): + self.callbacks_enabled = enabled + + def get_exposure_time(self): + return 10.0 + + +class Hold: + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def wait_until_ready(self, cancel_fn=None): + return True + + +def make_server(start_um_from_focus=4.0, frames=True, gui=False): + from control.microscope_control_server import MicroscopeControlServer + + stage = FakeStage(FOCUS_Z_MM + start_um_from_focus / 1000.0) + camera = FakeCamera(stage, frames) + live = MagicMock() + live.is_live = False + live.trigger_mode = TriggerMode.SOFTWARE + live.use_current_channel.side_effect = lambda name: Hold() + controller_board = MagicMock() + controller_board.is_busy.return_value = False + microscope = SimpleNamespace( + camera=camera, + stage=stage, + live_controller=live, + low_level_drivers=SimpleNamespace(microcontroller=controller_board), + addons=SimpleNamespace(nl5=None), + ) + with patch.object(MicroscopeControlServer, "__init__", lambda self: None): + server = MicroscopeControlServer() + server._log = MagicMock() + server.microscope = microscope + server.multipoint_controller = MagicMock() + server.multipoint_controller.acquisition_in_progress.return_value = False + server._own_autofocus_controller = None # as __init__ makes it + server._autofocus_lock = threading.Lock() + server.gui = None + if gui: # the window has its own controller, with the values of its Autofocus panel + shown = [] + window_controller = AutoFocusController(camera, stage, live, controller_board, lambda: None, shown.append, None) + server.gui = SimpleNamespace(autofocusController=window_controller, shown=shown) + return server, stage, camera + + +def test_autofocus_moves_to_the_sharpest_plane_and_reports_the_curve(): + server, stage, camera = make_server(start_um_from_focus=4.0) + start_z = stage.z_mm + result = server._cmd_autofocus(n_planes=11, step_um=1.5) + assert abs(stage.z_mm - FOCUS_Z_MM) * 1000.0 <= 1.5 # within one step of the focus plane + assert result["z_mm"] == pytest.approx(stage.z_mm) + assert result["moved_um"] == pytest.approx((stage.z_mm - start_z) * 1000.0) + planes = result["planes"] + assert 3 <= len(planes) <= 11 and all(set(plane) == {"z_mm", "focus_measure"} for plane in planes) + measures = [plane["focus_measure"] for plane in planes] + assert result["best_index"] == measures.index(max(measures)) + assert planes[result["best_index"]]["z_mm"] == pytest.approx(stage.z_mm, abs=1e-6) + steps = np.diff([plane["z_mm"] for plane in planes]) * 1000.0 + assert steps == pytest.approx([1.5] * (len(planes) - 1)) # from below, one step each + assert result["measure"] == control._def.FOCUS_MEASURE_OPERATOR.name and result["seconds"] >= 0 + assert result["stopped_early"] == (len(planes) < 11) + assert camera.frames_read == len(planes) # frames in memory: one for each plane, no file + + +def test_autofocus_uses_the_focus_measure_of_the_call_and_then_the_setting_again(monkeypatch): + import control.utils + + server, _, _ = make_server() + used = [] + measure = control.utils.calculate_focus_measure + monkeypatch.setattr( + control.utils, "calculate_focus_measure", lambda image, method: used.append(method) or measure(image, method) + ) + assert server._cmd_autofocus(n_planes=5, step_um=2.0, measure="tenengrad")["measure"] == "TENENGRAD" + assert set(used) == {FocusMeasureOperator.TENENGRAD} + used.clear() + assert server._cmd_autofocus(n_planes=5, step_um=2.0)["measure"] == control._def.FOCUS_MEASURE_OPERATOR.name + assert set(used) == {control._def.FOCUS_MEASURE_OPERATOR} + with pytest.raises(ValueError, match="LAPE, GLVA, TENENGRAD"): + server._cmd_autofocus(measure="sharpness") + + +def test_autofocus_saves_the_centre_of_each_plane_when_a_folder_is_given(tmp_path): + server, _, _ = make_server() + result = server._cmd_autofocus(n_planes=7, step_um=2.0, save_dir=str(tmp_path / "planes")) + paths = [plane["path"] for plane in result["planes"]] + assert [os.path.basename(path) for path in paths] == [f"plane_{i:02d}.tiff" for i in range(len(paths))] + assert all(tifffile.imread(path).shape == (400, 400) for path in paths) # the crop that the measure used + server2, _, _ = make_server() + assert all("path" not in plane for plane in server2._cmd_autofocus(n_planes=7, step_um=2.0)["planes"]) + + +@pytest.mark.parametrize( + "kwargs, message", + [ + ({"n_planes": 2}, "n_planes"), + ({"n_planes": 51}, "n_planes"), + ({"n_planes": 5.0}, "n_planes"), + ({"step_um": 0}, "step_um"), + ({"step_um": 51}, "step_um"), + ({"step_um": float("nan")}, "step_um"), + ({"save_dir": "relative/folder"}, "save_dir"), + ], +) +def test_autofocus_checks_its_inputs(kwargs, message): + server, stage, camera = make_server() + start_z = stage.z_mm + with pytest.raises(ValueError, match=message): + server._cmd_autofocus(**kwargs) + assert stage.z_mm == start_z and camera.frames_read == 0 + + +def test_autofocus_is_refused_during_an_acquisition_and_during_another_autofocus(): + server, stage, camera = make_server(gui=True) + server.multipoint_controller.acquisition_in_progress.return_value = True + with pytest.raises(RuntimeError, match="an acquisition is running"): + server._cmd_autofocus() + server.multipoint_controller.acquisition_in_progress.return_value = False + server.gui.autofocusController.autofocus_in_progress = True # the Autofocus button of the window + with pytest.raises(RuntimeError, match="an autofocus is running"): + server._cmd_autofocus() + assert camera.frames_read == 0 + + +def test_a_camera_that_gives_no_frame_is_an_error_and_the_stage_goes_back(): + server, stage, _ = make_server(frames=False) + start_z = stage.z_mm + with pytest.raises(RuntimeError, match="no frame"): + server._cmd_autofocus(n_planes=5, step_um=2.0) + assert stage.z_mm == pytest.approx(start_z) # not left at the bottom of the range + + +def test_with_a_window_its_controller_is_used_and_its_panel_values_stay(): + server, stage, _ = make_server(gui=True) + controller = server.gui.autofocusController + controller.set_N(10) + controller.set_deltaZ(1.524) + result = server._cmd_autofocus(n_planes=7, step_um=2.0, measure="TENENGRAD") + assert len(server.gui.shown) == len(result["planes"]) # each plane went to the display of the window + assert (controller.N, controller.deltaZ) == (10, pytest.approx(0.001524)) + assert controller.focus_measure_operator is None and controller.keep_plane_images is False + assert abs(stage.z_mm - FOCUS_Z_MM) * 1000.0 <= 2.0 + + +def test_two_clients_at_one_time_get_one_autofocus(): + server, _, _ = make_server() + results, errors = [], [] + + def client(): + try: + results.append(server._cmd_autofocus(n_planes=9, step_um=1.0)) + except RuntimeError as error: + errors.append(str(error)) + + threads = [threading.Thread(target=client) for _ in range(2)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(30) + assert len(results) + len(errors) == 2 and len(results) >= 1 + assert all("an autofocus is running" in error for error in errors) From da120de49fb8655a81bd4c4440c5f7cefe5be80f Mon Sep 17 00:00:00 2001 From: Hongquan Li Date: Fri, 13 Nov 2026 02:21:35 -0800 Subject: [PATCH 2/3] fix(control-server): autofocus reports the position of each plane as the stage gave it The Z of each plane in the reply was the nominal value (start - offset + (index + 1) x step). A stage rounds each move to its motor steps, so the reply could give a best plane that was some tenths of a micrometer from the position that the stage moved to. Each plane now has the position that the stage reported when its frame was taken. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_0152Tv36aY3Whyz7ATrKcZX3 --- software/control/core/auto_focus_worker.py | 4 +-- .../control/test_control_server_autofocus.py | 28 +++++++++++++++++-- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/software/control/core/auto_focus_worker.py b/software/control/core/auto_focus_worker.py index fcc2be735c..820619fd09 100644 --- a/software/control/core/auto_focus_worker.py +++ b/software/control/core/auto_focus_worker.py @@ -67,7 +67,6 @@ def run_autofocus(self): focus_measure_max = 0 z_af_offset = self.deltaZ * round(self.N / 2) - z_bottom_mm = self.stage.get_pos().z_mm - z_af_offset # the planes are one step each above this self.stage.move_z(-z_af_offset) @@ -80,6 +79,7 @@ def run_autofocus(self): break self.stage.move_z(self.deltaZ) steps_moved = steps_moved + 1 + plane_z_mm = self.stage.get_pos().z_mm # the stage rounds each move to its motor steps # trigger acquisition (including turning on the illumination) and read frame if self.liveController.trigger_mode == control._def.TriggerMode.SOFTWARE: self.liveController.turn_on_illumination() @@ -113,7 +113,7 @@ def run_autofocus(self): timestamp_0 = time.time() focus_measure = utils.calculate_focus_measure(image, self.focus_measure_operator) self.autofocusController.last_planes.append( - (z_bottom_mm + (i + 1) * self.deltaZ, focus_measure, image if self.keep_plane_images else None) + (plane_z_mm, focus_measure, image if self.keep_plane_images else None) ) timestamp_1 = time.time() self._log.info(" calculating focus measure took " + str(timestamp_1 - timestamp_0) + " second") diff --git a/software/tests/control/test_control_server_autofocus.py b/software/tests/control/test_control_server_autofocus.py index aa6c250a10..dfca25aa45 100644 --- a/software/tests/control/test_control_server_autofocus.py +++ b/software/tests/control/test_control_server_autofocus.py @@ -37,6 +37,15 @@ def wait_for_idle(self, timeout_s): pass +class SteppedStage(FakeStage): + """Rounds each move to its motor steps, as the real stage does.""" + + STEP_MM = 0.000136 + + def move_z(self, delta_mm, blocking=True): + self.z_mm += round(delta_mm / self.STEP_MM) * self.STEP_MM + + class FakeCamera: """A fine texture that blurs with the distance from the focus plane: 1 pixel of blur for each 2 um.""" @@ -80,10 +89,10 @@ def wait_until_ready(self, cancel_fn=None): return True -def make_server(start_um_from_focus=4.0, frames=True, gui=False): +def make_server(start_um_from_focus=4.0, frames=True, gui=False, stage_class=FakeStage): from control.microscope_control_server import MicroscopeControlServer - stage = FakeStage(FOCUS_Z_MM + start_um_from_focus / 1000.0) + stage = stage_class(FOCUS_Z_MM + start_um_from_focus / 1000.0) camera = FakeCamera(stage, frames) live = MagicMock() live.is_live = False @@ -133,6 +142,21 @@ def test_autofocus_moves_to_the_sharpest_plane_and_reports_the_curve(): assert camera.frames_read == len(planes) # frames in memory: one for each plane, no file +def test_the_z_of_each_plane_is_the_position_that_the_stage_reported_for_its_frame(): + # A real stage rounds each move to its motor steps: 1.524 um becomes 11 steps of 0.136 um = 1.496 um. + server, stage, camera = make_server(start_um_from_focus=-3.0, stage_class=SteppedStage) + z_of_frames = [] + read_frame = camera.read_frame + + def read_frame_and_note_z(): + z_of_frames.append(stage.z_mm) + return read_frame() + + camera.read_frame = read_frame_and_note_z + result = server._cmd_autofocus(n_planes=10, step_um=1.524) + assert [plane["z_mm"] for plane in result["planes"]] == pytest.approx(z_of_frames, abs=1e-9) + + def test_autofocus_uses_the_focus_measure_of_the_call_and_then_the_setting_again(monkeypatch): import control.utils From c1ebf10350c9f751df9e8232bc4dd52a1ebd44eb Mon Sep 17 00:00:00 2001 From: Hongquan Li Date: Sun, 15 Nov 2026 08:55:21 -0800 Subject: [PATCH 3/3] fix(control-server): autofocus holds the stage, reports a failed sweep, and stops a sweep that runs too long The autofocus command now takes the stage-motion reservation for its whole sweep, as a stage move of a client does: - It is refused while an acquisition (also one that prepares), a move to or from the loading position, a homing or a stage move of a client holds the stage. Each of them is refused while the sweep runs. - Two clients at one time: one gets the autofocus, the other the refusal. The reservation replaces the lock of the command, and the controller of a headless server is made after the stage is held. A sweep that fails in its middle (a camera error, a stage move that fails) is an error of the command, and the stage goes back to its start Z. Before, the command reported success with the planes that it had. A sweep that does not end in 120 s is told to stop. It stops after its plane and goes to its sharpest plane so far. If it does not stop in 30 s more (a camera that does not answer), the command fails and the stage stays held until the sweep ends. Before, the command failed and the sweep went on. The MCP bridge waits 160 s for the reply of autofocus. The camera stream is started when it is off (after stop_live): a real camera refuses a trigger when it does not stream. The position of each plane is read only for the command. The Autofocus button and the autofocus of an acquisition read no position for each plane and keep no planes, as before this pull request. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_0152Tv36aY3Whyz7ATrKcZX3 --- .../control/core/auto_focus_controller.py | 12 +- software/control/core/auto_focus_worker.py | 14 +- software/control/microscope_control_server.py | 113 +++++++++--- software/docs/mcp_integration.md | 17 +- software/mcp_microscope_server.py | 10 +- .../control/test_control_server_autofocus.py | 166 ++++++++++++++---- software/tests/test_mcp_microscope_server.py | 13 ++ 7 files changed, 278 insertions(+), 67 deletions(-) diff --git a/software/control/core/auto_focus_controller.py b/software/control/core/auto_focus_controller.py index bad33a55a3..746193a5c8 100644 --- a/software/control/core/auto_focus_controller.py +++ b/software/control/core/auto_focus_controller.py @@ -50,8 +50,13 @@ def __init__( # the focus measure of this run (None: the setting FOCUS_MEASURE_OPERATOR), and if the plane images are kept. self.focus_measure_operator: Optional[control._def.FocusMeasureOperator] = None self.keep_plane_images = False - # What the last contrast autofocus measured: (z_mm, focus measure, image or None) for each plane, from below. + # Off for the Autofocus button and for an acquisition: their sweep reads no position for each plane. + self.report_planes = False + # With report_planes, what the last contrast autofocus measured: (z_mm, focus measure, image or None) for + # each plane, from below. self.last_planes: list = [] + # The error that ended the last contrast autofocus before its end, or None. + self.last_error: Optional[BaseException] = None def set_N(self, N): self.N = N @@ -109,6 +114,7 @@ def autofocus(self, focus_map_override=False): self._keep_running.set() self.last_planes = [] + self.last_error = None self._autofocus_worker = AutofocusWorker( self, self._on_autofocus_completed, self._image_to_display_fn, self._keep_running ) @@ -131,6 +137,10 @@ def _on_autofocus_completed(self): # update the state self.autofocus_in_progress = False + def abort(self) -> None: + """Ask the sweep that runs to stop. It stops after its plane and goes to its sharpest plane so far.""" + self._keep_running.clear() + def wait_till_autofocus_has_completed(self): while self.autofocus_in_progress: time.sleep(0.005) diff --git a/software/control/core/auto_focus_worker.py b/software/control/core/auto_focus_worker.py index 820619fd09..d8398e1a66 100644 --- a/software/control/core/auto_focus_worker.py +++ b/software/control/core/auto_focus_worker.py @@ -44,6 +44,7 @@ def __init__( self.autofocusController.focus_measure_operator or control._def.FOCUS_MEASURE_OPERATOR ) self.keep_plane_images = self.autofocusController.keep_plane_images + self.report_planes = self.autofocusController.report_planes def run(self): try: @@ -53,6 +54,9 @@ def run(self): self.run_autofocus() else: self._log.error("autofocus skipped: the illumination did not become ready") + except Exception as error: + self.autofocusController.last_error = error # for a caller that waits for the result of this run + raise finally: self._finished_fn() @@ -79,7 +83,8 @@ def run_autofocus(self): break self.stage.move_z(self.deltaZ) steps_moved = steps_moved + 1 - plane_z_mm = self.stage.get_pos().z_mm # the stage rounds each move to its motor steps + # the stage rounds each move to its motor steps: a caller that wants the planes gets the position read + plane_z_mm = self.stage.get_pos().z_mm if self.report_planes else None # trigger acquisition (including turning on the illumination) and read frame if self.liveController.trigger_mode == control._def.TriggerMode.SOFTWARE: self.liveController.turn_on_illumination() @@ -112,9 +117,10 @@ def run_autofocus(self): timestamp_0 = time.time() focus_measure = utils.calculate_focus_measure(image, self.focus_measure_operator) - self.autofocusController.last_planes.append( - (plane_z_mm, focus_measure, image if self.keep_plane_images else None) - ) + if self.report_planes: + self.autofocusController.last_planes.append( + (plane_z_mm, focus_measure, image if self.keep_plane_images else None) + ) timestamp_1 = time.time() self._log.info(" calculating focus measure took " + str(timestamp_1 - timestamp_0) + " second") focus_measure_vs_z[i] = focus_measure diff --git a/software/control/microscope_control_server.py b/software/control/microscope_control_server.py index c6aade36f0..c9b210da2a 100644 --- a/software/control/microscope_control_server.py +++ b/software/control/microscope_control_server.py @@ -210,6 +210,9 @@ def wrapper(*args, **kwargs): # What a control-server move holds the stage-motion reservation as (Microscope.stage_motion) TCP_STAGE_MOVE = "a stage move from the control server is running" +# What the autofocus command holds it as, for its whole sweep +TCP_AUTOFOCUS = "an autofocus from the control server is running" +TCP_AUTOFOCUS_NOT_STOPPED = "an autofocus that did not stop still runs" _ACQUISITION_NOT_STARTED = ( "Acquisition did not start: the microcontroller stayed busy (home the stage or power-cycle the " @@ -217,6 +220,16 @@ def wrapper(*args, **kwargs): ) +class _AutofocusDoesNotStop(Exception): + """The sweep of the autofocus command was told to stop and still runs. controller: the one that runs it.""" + + def __init__(self, controller, limit_s: float): + super().__init__( + f"autofocus did not end in {limit_s:.0f} s and does not stop: stage moves are refused until it ends" + ) + self.controller = controller + + class MicroscopeControlServer: """ TCP server that exposes microscope control functions to external clients. @@ -267,7 +280,6 @@ def __init__( self._thread: Optional[threading.Thread] = None self._python_exec_enabled = False # Disabled by default for security self._own_autofocus_controller = None # autofocus with no window: made at the first use - self._autofocus_lock = threading.Lock() self._connection_semaphore = threading.Semaphore(MAX_CONNECTIONS) # Auto-discover commands by finding all _cmd_* methods @@ -668,7 +680,8 @@ def _cmd_get_status(self) -> Dict[str, Any]: return status - _AUTOFOCUS_TIMEOUT_S = 120.0 + _AUTOFOCUS_TIMEOUT_S = 120.0 # then the sweep is told to stop + _AUTOFOCUS_STOP_S = 30.0 # how long the command then waits for the sweep to stop @schema_method def _cmd_autofocus( @@ -689,10 +702,9 @@ def _cmd_autofocus( The planes are around the current Z, n_planes steps of step_um. It is the sweep of the Autofocus button: the frames stay in memory, the measure is taken on the centre of the image, and the sweep stops early when the measure falls clearly below its largest value. The reply has the Z, the planes with their focus - measure (from below), the index of the sharpest plane, and the time. Refused while an acquisition or - another autofocus runs. Live view is stopped for the sweep and started again.""" - from control.core.auto_focus_controller import AutoFocusController - + measure (from below), the index of the sharpest plane, and the time. Refused while anything else holds + the stage (an acquisition, the loading position, a homing, a stage move of a client) or while another + autofocus runs. Live view is stopped for the sweep and started again.""" # schema_method fills defaults; it does not enforce limits, so the limits are checked here. if isinstance(n_planes, bool) or not isinstance(n_planes, int) or not 3 <= n_planes <= 50: raise ValueError("n_planes must be a whole number from 3 to 50") @@ -711,8 +723,31 @@ def _cmd_autofocus( operator = control._def.FocusMeasureOperator[str(measure).upper()] if save_dir is not None and not os.path.isabs(save_dir): raise ValueError("save_dir must be an absolute path") - if self.multipoint_controller is not None and self.multipoint_controller.acquisition_in_progress(): - raise RuntimeError("an acquisition is running") + # The stage, for the whole sweep. The autofocus is refused while an acquisition (also one that prepares), a + # move to or from the loading position, a homing or a stage move of a client holds the stage, and each of + # them is refused while the sweep runs. Two clients at one time: one of them gets the refusal. + hold = self.microscope.stage_motion.take(TCP_AUTOFOCUS) + sweep_ended = True + try: + return self._autofocus_with_the_stage(n_planes, step_um, operator, save_dir) + except _AutofocusDoesNotStop as still_running: + sweep_ended = False + controller = still_running.controller + raise RuntimeError(str(still_running)) from None + finally: + if sweep_ended: + hold.release() + else: # the sweep can still move Z: the stage stays held until its thread ends + hold.reason = TCP_AUTOFOCUS_NOT_STOPPED + threading.Thread( + target=lambda: (controller.wait_till_autofocus_has_completed(), hold.release()), + daemon=True, + name="autofocus-stage-release", + ).start() + + def _autofocus_with_the_stage(self, n_planes: int, step_um: float, operator, save_dir: Optional[str]) -> dict: + """The sweep of _cmd_autofocus, for a caller that holds the stage.""" + from control.core.auto_focus_controller import AutoFocusController if self.gui is not None: # the window's controller: the planes also go to its display controller = self.gui.autofocusController @@ -728,32 +763,58 @@ def _cmd_autofocus( self.microscope.addons.nl5, ) controller = self._own_autofocus_controller - with self._autofocus_lock: # two clients at one time: one of them gets the refusal - if controller.autofocus_in_progress: - raise RuntimeError("an autofocus is running") - # The values of the window's Autofocus panel are put back after the sweep. - panel = (controller.N, controller.deltaZ, controller.focus_measure_operator, controller.keep_plane_images) - start_z_mm = self.microscope.stage.get_pos().z_mm - began = time.monotonic() - controller.set_N(n_planes) - controller.set_deltaZ(step_um) - controller.focus_measure_operator = operator - controller.keep_plane_images = save_dir is not None - try: - controller.autofocus(focus_map_override=True) # the sweep, also when the window uses a focus map - except BaseException: - controller.N, controller.deltaZ, controller.focus_measure_operator, controller.keep_plane_images = panel - raise + if controller.autofocus_in_progress: # the Autofocus button of the window + raise RuntimeError("an autofocus is running") + camera = self.microscope.camera + if not camera.get_is_streaming(): # after stop_live: a real camera refuses a trigger when it does not stream + camera.start_streaming() + # The values of the window's Autofocus panel are put back after the sweep. + panel = ( + controller.N, + controller.deltaZ, + controller.focus_measure_operator, + controller.keep_plane_images, + controller.report_planes, + ) + start_z_mm = self.microscope.stage.get_pos().z_mm + began = time.monotonic() + controller.set_N(n_planes) + controller.set_deltaZ(step_um) + controller.focus_measure_operator = operator + controller.keep_plane_images = save_dir is not None + controller.report_planes = True + stopped = False try: + controller.autofocus(focus_map_override=True) # the sweep, also when the window uses a focus map deadline = began + self._AUTOFOCUS_TIMEOUT_S while controller.autofocus_in_progress: if time.monotonic() > deadline: - raise RuntimeError(f"autofocus did not end in {self._AUTOFOCUS_TIMEOUT_S:.0f} s") + if stopped: + raise _AutofocusDoesNotStop(controller, self._AUTOFOCUS_TIMEOUT_S) + stopped = True + controller.abort() # it stops after its plane and goes to its sharpest plane so far + deadline = time.monotonic() + self._AUTOFOCUS_STOP_S time.sleep(0.005) planes = list(controller.last_planes) + error = controller.last_error finally: - controller.N, controller.deltaZ, controller.focus_measure_operator, controller.keep_plane_images = panel + ( + controller.N, + controller.deltaZ, + controller.focus_measure_operator, + controller.keep_plane_images, + controller.report_planes, + ) = panel seconds = time.monotonic() - began + if stopped: + raise RuntimeError( + f"autofocus did not end in {self._AUTOFOCUS_TIMEOUT_S:.0f} s and was stopped; " + "the stage is at its sharpest plane so far" + ) + if error is not None: + # The sweep ended in its middle, without its moves to the sharpest plane: go back to where the stage was. + self.microscope.stage.move_z_to(start_z_mm) + raise RuntimeError(f"autofocus failed: {error}; the stage is back at its start Z") from error if not planes: # The sweep of Squid ends at the lowest plane when no frame came: go back to where the stage was. self.microscope.stage.move_z_to(start_z_mm) diff --git a/software/docs/mcp_integration.md b/software/docs/mcp_integration.md index b2ed841af9..63cfa5d731 100644 --- a/software/docs/mcp_integration.md +++ b/software/docs/mcp_integration.md @@ -142,9 +142,20 @@ measure used is saved there as `plane_.tiff`, after the sweep. The reply has `z_mm` (the Z after the autofocus), `moved_um`, `planes` (from below; each with `z_mm`, `focus_measure`, and `path` when `save_dir` was given), `best_index`, `measure`, `stopped_early` and `seconds`. -The command is refused while an acquisition or another autofocus runs. Live view is stopped for the sweep and -started again. The values of the Autofocus panel of the window do not change. If the camera gives no frame, the -stage goes back to its start Z and the command fails. +`z_mm` is the position that the stage reports. With a `step_um` that is not a whole number of motor steps, it can +differ a little from the `z_mm` of the sharpest plane: the stage rounds each move. + +The command holds the stage for its whole sweep. It is refused while anything else holds the stage (an acquisition, +the loading position, a homing, a stage move of a client) and while another autofocus runs. While the sweep runs, +each of them is refused. Live view is stopped for the sweep and started again. The camera stream is started if it +is off (after `stop_live`). The values of the Autofocus panel of the window do not change. + +When the command fails, it says where the stage is: +- The camera gives no frame, or the sweep fails in its middle: the stage goes back to its start Z. +- The sweep does not end in 120 s: it is stopped, and the stage is at its sharpest plane so far. +- The sweep does not stop (a camera that does not answer): stage moves stay refused until it ends. + +The MCP bridge waits 160 s for the reply of `autofocus` (30 s for each other command). ### Channel & Illumination diff --git a/software/mcp_microscope_server.py b/software/mcp_microscope_server.py index 3baa6d2011..c6ba8c436c 100644 --- a/software/mcp_microscope_server.py +++ b/software/mcp_microscope_server.py @@ -45,13 +45,18 @@ MAX_BUFFER_SIZE = 10 * 1024 * 1024 # 10 MB limit to prevent memory exhaustion +DEFAULT_TIMEOUT_S = 30.0 # how long the bridge waits for the reply of a command +# A command that the server works on for longer than that, with its own wait. +# autofocus: the server stops a sweep after 120 s and waits 30 s more for it to stop. +COMMAND_TIMEOUT_S = {"autofocus": 160.0} + def send_command( command: str, params: Optional[dict] = None, host: str = DEFAULT_HOST, port: int = DEFAULT_PORT, - timeout: float = 30.0, + timeout: float = DEFAULT_TIMEOUT_S, ) -> dict: """Send a command to the microscope control server.""" request = {"command": command, "params": params or {}} @@ -171,7 +176,8 @@ async def call_tool(name: str, arguments: dict[str, Any]) -> list[TextContent]: # Run the blocking socket call in a thread pool loop = asyncio.get_event_loop() - response = await loop.run_in_executor(None, lambda: send_command(command, arguments)) + timeout = COMMAND_TIMEOUT_S.get(command, DEFAULT_TIMEOUT_S) + response = await loop.run_in_executor(None, lambda: send_command(command, arguments, timeout=timeout)) if response.get("success"): result = response.get("result", {}) diff --git a/software/tests/control/test_control_server_autofocus.py b/software/tests/control/test_control_server_autofocus.py index dfca25aa45..25e27b32c2 100644 --- a/software/tests/control/test_control_server_autofocus.py +++ b/software/tests/control/test_control_server_autofocus.py @@ -5,6 +5,7 @@ import os import threading +import time from types import SimpleNamespace from unittest.mock import MagicMock, patch @@ -16,6 +17,7 @@ import control._def from control._def import FocusMeasureOperator, TriggerMode from control.core.auto_focus_controller import AutoFocusController +from squid.stage.reservation import StageMotionRefused, StageMotionReservation FOCUS_Z_MM = 1.2000 @@ -56,13 +58,20 @@ def __init__(self, stage, frames=True): self._scene = rng.integers(200, 4000, (400, 400)).astype(np.float32) self.callbacks_enabled = True self.frames_read = 0 + self.streaming = True + + def get_is_streaming(self): + return self.streaming + + def start_streaming(self): + self.streaming = True def send_trigger(self, illumination_time=None): pass def read_frame(self): self.frames_read += 1 - if not self._frames: + if not self._frames or not self.streaming: # a real camera refuses a trigger when it does not stream return None blur = abs(self._stage.z_mm - FOCUS_Z_MM) * 1000.0 / 2.0 image = cv2.GaussianBlur(self._scene, (0, 0), blur) if blur > 0.05 else self._scene @@ -78,6 +87,20 @@ def get_exposure_time(self): return 10.0 +class PausedCamera(FakeCamera): + """Its frames wait until the test lets them go.""" + + def __init__(self, stage, frames=True): + super().__init__(stage, frames) + self.reading = threading.Event() + self.go = threading.Event() + + def read_frame(self): + self.reading.set() + assert self.go.wait(20) + return super().read_frame() + + class Hold: def __enter__(self): return self @@ -89,11 +112,11 @@ def wait_until_ready(self, cancel_fn=None): return True -def make_server(start_um_from_focus=4.0, frames=True, gui=False, stage_class=FakeStage): +def make_server(start_um_from_focus=4.0, frames=True, gui=False, stage_class=FakeStage, camera_class=FakeCamera): from control.microscope_control_server import MicroscopeControlServer stage = stage_class(FOCUS_Z_MM + start_um_from_focus / 1000.0) - camera = FakeCamera(stage, frames) + camera = camera_class(stage, frames) live = MagicMock() live.is_live = False live.trigger_mode = TriggerMode.SOFTWARE @@ -106,15 +129,13 @@ def make_server(start_um_from_focus=4.0, frames=True, gui=False, stage_class=Fak live_controller=live, low_level_drivers=SimpleNamespace(microcontroller=controller_board), addons=SimpleNamespace(nl5=None), + stage_motion=StageMotionReservation(), # who drives the stage: one owner at a time ) with patch.object(MicroscopeControlServer, "__init__", lambda self: None): server = MicroscopeControlServer() server._log = MagicMock() server.microscope = microscope - server.multipoint_controller = MagicMock() - server.multipoint_controller.acquisition_in_progress.return_value = False server._own_autofocus_controller = None # as __init__ makes it - server._autofocus_lock = threading.Lock() server.gui = None if gui: # the window has its own controller, with the values of its Autofocus panel shown = [] @@ -205,16 +226,118 @@ def test_autofocus_checks_its_inputs(kwargs, message): assert stage.z_mm == start_z and camera.frames_read == 0 -def test_autofocus_is_refused_during_an_acquisition_and_during_another_autofocus(): - server, stage, camera = make_server(gui=True) - server.multipoint_controller.acquisition_in_progress.return_value = True - with pytest.raises(RuntimeError, match="an acquisition is running"): +@pytest.mark.parametrize( + "holder", + ["an acquisition is running", "the stage is at the loading position", "the stage is homing"], +) +def test_autofocus_is_refused_while_something_else_holds_the_stage(holder): + server, stage, camera = make_server() + start_z = stage.z_mm + hold = server.microscope.stage_motion.take(holder) # as the acquisition, the loading position and the homing do + with pytest.raises(StageMotionRefused, match=holder): server._cmd_autofocus() - server.multipoint_controller.acquisition_in_progress.return_value = False + assert stage.z_mm == start_z and camera.frames_read == 0 and server._own_autofocus_controller is None + hold.release() + assert server._cmd_autofocus(n_planes=5, step_um=2.0)["planes"] # the stage is free: the autofocus runs + + +def test_autofocus_is_refused_while_the_autofocus_of_the_window_runs(): + server, stage, camera = make_server(gui=True) server.gui.autofocusController.autofocus_in_progress = True # the Autofocus button of the window with pytest.raises(RuntimeError, match="an autofocus is running"): server._cmd_autofocus() - assert camera.frames_read == 0 + assert camera.frames_read == 0 and server.microscope.stage_motion.holder is None + + +def test_autofocus_holds_the_stage_for_the_whole_sweep_and_a_second_client_is_refused(): + server, _, camera = make_server(camera_class=PausedCamera) + results, errors = [], [] + + def client(): + try: + results.append(server._cmd_autofocus(n_planes=5, step_um=2.0)) + except RuntimeError as error: + errors.append(error) + + first = threading.Thread(target=client) + first.start() + assert camera.reading.wait(10) # the sweep of the first client waits for its first frame + assert server.microscope.stage_motion.holder == "an autofocus from the control server is running" + client() # the second client, at the same time + camera.go.set() + first.join(20) + assert len(results) == 1 and len(errors) == 1 # exactly one autofocus, and one refusal + assert isinstance(errors[0], StageMotionRefused) and "an autofocus from the control server" in str(errors[0]) + assert server.microscope.stage_motion.holder is None + + +# The thread of the sweep raises the error of the camera, as it did before: the uncaught-exception log has it. +@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning") +def test_a_sweep_that_fails_after_some_planes_is_an_error_and_the_stage_goes_back(): + server, stage, camera = make_server() + start_z = stage.z_mm + read_frame = camera.read_frame + + def fails_at_the_third_frame(): + if camera.frames_read == 2: + raise RuntimeError("the camera lost its connection") + return read_frame() + + camera.read_frame = fails_at_the_third_frame + with pytest.raises(RuntimeError, match="autofocus failed: the camera lost its connection"): + server._cmd_autofocus(n_planes=9, step_um=2.0) + assert stage.z_mm == pytest.approx(start_z) # not left in the middle of the sweep + assert server.microscope.stage_motion.holder is None + + +def test_an_autofocus_that_runs_too_long_is_stopped_and_the_stage_is_free_again(monkeypatch): + server, _, camera = make_server() + read_frame = camera.read_frame + camera.read_frame = lambda: time.sleep(0.05) or read_frame() + monkeypatch.setattr(type(server), "_AUTOFOCUS_TIMEOUT_S", 0.12) + with pytest.raises(RuntimeError, match="did not end in .* and was stopped"): + server._cmd_autofocus(n_planes=50, step_um=0.1) + assert server._own_autofocus_controller.autofocus_in_progress is False and camera.frames_read < 50 + assert server.microscope.stage_motion.holder is None + + +def test_an_autofocus_that_does_not_stop_keeps_the_stage_until_it_ends(monkeypatch): + server, _, camera = make_server(camera_class=PausedCamera) # a camera that does not answer + monkeypatch.setattr(type(server), "_AUTOFOCUS_TIMEOUT_S", 0.1) + monkeypatch.setattr(type(server), "_AUTOFOCUS_STOP_S", 0.1) + with pytest.raises(RuntimeError, match="does not stop"): + server._cmd_autofocus(n_planes=5, step_um=2.0) + assert server.microscope.stage_motion.holder == "an autofocus that did not stop still runs" + with pytest.raises(StageMotionRefused, match="did not stop"): + server._cmd_autofocus(n_planes=5, step_um=2.0) # nothing else moves the stage under the sweep + camera.go.set() # the camera answers at last: the sweep ends + deadline = time.monotonic() + 20 + while server.microscope.stage_motion.holder is not None and time.monotonic() < deadline: + time.sleep(0.01) + assert server.microscope.stage_motion.holder is None + + +def test_autofocus_starts_the_camera_stream_when_it_is_off(): + server, _, camera = make_server() + camera.streaming = False # as after the stop_live of a client + result = server._cmd_autofocus(n_planes=5, step_um=2.0) + assert camera.streaming is True and result["planes"] # the frames came + + +def test_the_sweep_of_the_window_reads_no_position_for_each_plane_and_keeps_no_planes(): + # The Autofocus button and the autofocus of an acquisition work as before: the planes are for the command only. + server, stage, _ = make_server(gui=True) + controller = server.gui.autofocusController + reads = [] + get_pos = stage.get_pos + stage.get_pos = lambda: reads.append(1) or get_pos() + controller.set_N(5) + controller.set_deltaZ(2.0) + controller.autofocus(focus_map_override=True) + controller.wait_till_autofocus_has_completed() + assert reads == [] and controller.last_planes == [] + assert server._cmd_autofocus(n_planes=5, step_um=2.0)["planes"] # the command still gets its planes + assert controller.report_planes is False # and the window's sweep is as before again def test_a_camera_that_gives_no_frame_is_an_error_and_the_stage_goes_back(): @@ -235,22 +358,3 @@ def test_with_a_window_its_controller_is_used_and_its_panel_values_stay(): assert (controller.N, controller.deltaZ) == (10, pytest.approx(0.001524)) assert controller.focus_measure_operator is None and controller.keep_plane_images is False assert abs(stage.z_mm - FOCUS_Z_MM) * 1000.0 <= 2.0 - - -def test_two_clients_at_one_time_get_one_autofocus(): - server, _, _ = make_server() - results, errors = [], [] - - def client(): - try: - results.append(server._cmd_autofocus(n_planes=9, step_um=1.0)) - except RuntimeError as error: - errors.append(str(error)) - - threads = [threading.Thread(target=client) for _ in range(2)] - for thread in threads: - thread.start() - for thread in threads: - thread.join(30) - assert len(results) + len(errors) == 2 and len(results) >= 1 - assert all("an autofocus is running" in error for error in errors) diff --git a/software/tests/test_mcp_microscope_server.py b/software/tests/test_mcp_microscope_server.py index 48efe8addb..c521ce5a60 100644 --- a/software/tests/test_mcp_microscope_server.py +++ b/software/tests/test_mcp_microscope_server.py @@ -37,3 +37,16 @@ def test_a_tool_call_is_forwarded_as_its_command(): assert send.call_args.args[:2] == ("move_to", {"x_mm": 1.0}) assert json.loads(content[0].text) == {"moved_to": {"x_mm": 1.0}} + + +def test_the_bridge_waits_for_an_autofocus_as_long_as_the_server_works_on_it(): + from control.microscope_control_server import MicroscopeControlServer + + longest = MicroscopeControlServer._AUTOFOCUS_TIMEOUT_S + MicroscopeControlServer._AUTOFOCUS_STOP_S + with patch.object(mcp_microscope_server, "send_command", return_value={"success": True, "result": {}}) as send: + asyncio.run(mcp_microscope_server.call_tool("microscope_autofocus", {})) + asyncio.run(mcp_microscope_server.call_tool("microscope_move_to", {"x_mm": 1.0})) + + autofocus, move = send.call_args_list + assert autofocus.kwargs["timeout"] > longest # the reply of a long sweep is not lost + assert move.kwargs["timeout"] == 30.0 # each other command as before