diff --git a/software/control/core/auto_focus_controller.py b/software/control/core/auto_focus_controller.py index 8172cf811..746193a5c 100644 --- a/software/control/core/auto_focus_controller.py +++ b/software/control/core/auto_focus_controller.py @@ -46,6 +46,17 @@ 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 + # 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 @@ -102,6 +113,8 @@ def autofocus(self, focus_map_override=False): raise RuntimeError("Previous focus thread failed to join") 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 ) @@ -124,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 f0d574397..d8398e1a6 100644 --- a/software/control/core/auto_focus_worker.py +++ b/software/control/core/auto_focus_worker.py @@ -40,6 +40,11 @@ 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 + self.report_planes = self.autofocusController.report_planes def run(self): try: @@ -49,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() @@ -75,6 +83,8 @@ def run_autofocus(self): break self.stage.move_z(self.deltaZ) steps_moved = steps_moved + 1 + # 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() @@ -106,7 +116,11 @@ 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) + 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 16fb7dc9b..c9b210da2 100644 --- a/software/control/microscope_control_server.py +++ b/software/control/microscope_control_server.py @@ -12,6 +12,8 @@ import functools import inspect import json +import math +import os import socket import threading import time @@ -208,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 " @@ -215,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. @@ -264,6 +279,7 @@ 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._connection_semaphore = threading.Semaphore(MAX_CONNECTIONS) # Auto-discover commands by finding all _cmd_* methods @@ -664,12 +680,165 @@ def _cmd_get_status(self) -> Dict[str, Any]: return status + _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(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 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") + 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") + # 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 + 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 + 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: + 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, + 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) + 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 e549ed227..63cfa5d73 100644 --- a/software/docs/mcp_integration.md +++ b/software/docs/mcp_integration.md @@ -129,6 +129,33 @@ stage until the stage reports it stopped. | `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`. +`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 3baa6d201..c6ba8c436 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 new file mode 100644 index 000000000..25e27b32c --- /dev/null +++ b/software/tests/control/test_control_server_autofocus.py @@ -0,0 +1,360 @@ +"""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 +import time +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 +from squid.stage.reservation import StageMotionRefused, StageMotionReservation + +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 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.""" + + 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 + 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 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 + 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 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 + + 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, 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 = camera_class(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), + 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._own_autofocus_controller = None # as __init__ makes it + 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_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 + + 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 + + +@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() + 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 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(): + 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 diff --git a/software/tests/test_mcp_microscope_server.py b/software/tests/test_mcp_microscope_server.py index 48efe8add..c521ce5a6 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