diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3a26a48..22408a7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,7 +20,13 @@ jobs: # needed to import the Claude loops for the approval-gate tests (no # API key required - no model is ever called). - run: pip install -e ".[harness,test]" - - run: python -m pytest -v tests # -v names each test in the log + # -v names each test in the log; the coverage table shows what no test + # reaches. The floor is a tripwire, not a target: it only catches a + # large untested addition. + - run: > + python -m pytest -v tests + --cov=acquisition --cov=harness --cov=mcp_server --cov=timelapse --cov=analysis + --cov-report=term-missing --cov-fail-under=90 # The MCP server must import on a core-only install (the camera and # SDK stacks are lazy imports) - fail the build if that regresses. # (tests/test_mcp_server.py goes further and actually runs it.) diff --git a/.gitignore b/.gitignore index 6d24c61..e0128d1 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,8 @@ eaa_integration/*.sqlite-wal # Nikon Ti2 SDK documentation, originals and samples extracted from the # Nikon installers. Licensed with SDK access - kept local, not published. docs/nikon-sdk/ + +# coverage +.coverage +coverage.xml +htmlcov/ diff --git a/README.md b/README.md index beffb4f..e4bb5cf 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,7 @@ unchanged. Setup, safety rules and the on-scope test plan: ``` python -m acquisition.backends.nis_bridge status # by hand, while the bridge job runs +python -m acquisition.nis_monitor # live view: status + every action (logs/nis/) confocal-mcp-nis # the MCP server python -m mcp_server.server_nis # same, from a source checkout ``` diff --git a/acquisition/backends/nis_bridge.py b/acquisition/backends/nis_bridge.py index 695a437..8d725c3 100644 --- a/acquisition/backends/nis_bridge.py +++ b/acquisition/backends/nis_bridge.py @@ -8,6 +8,7 @@ # python -m acquisition.backends.nis_bridge status # python -m acquisition.backends.nis_bridge move 100 0 # python -m acquisition.backends.nis_bridge objective "Plan Fluor 10x Ph1 DLL" +# python -m acquisition.backends.nis_bridge optconfs # python -m acquisition.backends.nis_bridge capture D:\...\check.nd2 # python -m acquisition.backends.nis_bridge nd-run "C. elegans 3h" # python -m acquisition.backends.nis_bridge nd-finish @@ -18,6 +19,10 @@ # the NIS side having been updated. Stopping an ND run (nd-finish) and # shutting the bridge down are always allowed - they only end things. # +# Every action here is also written to the NIS event log +# (acquisition/nis_events.py), which `python -m acquisition.nis_monitor` +# shows live. Status reads are not logged (the monitor polls them). +# # CONFOCAL_NIS_BRIDGE_URL overrides the address (default # http://127.0.0.1:8766). # ------------------------------------------------------------ @@ -28,10 +33,11 @@ import json import os import sys +import time import urllib.error import urllib.request -from acquisition import estop +from acquisition import estop, nis_events DEFAULT_URL = "http://127.0.0.1:8766" @@ -67,31 +73,55 @@ def _call(self, method: str, path: str, body: dict | None = None, def status(self) -> dict: return self._call("GET", "/status") + def _act(self, action: str, params: dict, send, guarded: bool = True) -> dict: + """Run one action and write it to the NIS event log (nis_events.py): + a "start" line, then "ok", "failed", "refused" or "error".""" + nis_events.record(action, "start", params=params) + t0 = time.time() + try: + if guarded: + estop.check() + result = send() + except estop.EStopEngaged as e: + nis_events.record(action, "refused", params=params, message=str(e)) + raise + except BridgeUnavailable as e: + nis_events.record(action, "error", params=params, message=str(e)) + raise + phase = "failed" if "error" in result else "ok" + nis_events.record(action, phase, params=params, result=result, + elapsed_s=round(time.time() - t0, 1)) + return result + + def optical_configs(self) -> dict: + return self._call("GET", "/optconfs") + # Motion / acquisition: e-stop checked before anything is sent def move_relative(self, dx_um: float, dy_um: float) -> dict: - estop.check() - return self._call("POST", "/move", {"dx": dx_um, "dy": dy_um}) + return self._act("move", {"dx": dx_um, "dy": dy_um}, + lambda: self._call("POST", "/move", {"dx": dx_um, "dy": dy_um})) def change_objective(self, name: str) -> dict: - estop.check() - return self._call("POST", "/objective", {"name": name}) + return self._act("objective", {"name": name}, + lambda: self._call("POST", "/objective", {"name": name})) def capture(self, path: str) -> dict: - estop.check() - return self._call("POST", "/capture", {"path": path}, timeout_s=300) + return self._act("capture", {"path": path}, + lambda: self._call("POST", "/capture", {"path": path}, timeout_s=300)) def nd_run(self, experiment: str, timeout_s: float = 7200.0) -> dict: # ND_RunExperiment may block until the run ends (unverified), so # the answer can take as long as the run itself. - estop.check() - return self._call("POST", "/nd/run", {"experiment": experiment}, timeout_s=timeout_s) + return self._act("nd_run", {"experiment": experiment}, + lambda: self._call("POST", "/nd/run", {"experiment": experiment}, + timeout_s=timeout_s)) # Always allowed: these only end things def nd_finish(self) -> dict: - return self._call("POST", "/nd/finish") + return self._act("nd_finish", {}, lambda: self._call("POST", "/nd/finish"), guarded=False) def shutdown(self) -> dict: - return self._call("POST", "/shutdown") + return self._act("shutdown", {}, lambda: self._call("POST", "/shutdown"), guarded=False) def main() -> None: @@ -103,6 +133,7 @@ def main() -> None: m.add_argument("dx", type=float); m.add_argument("dy", type=float) o = sub.add_parser("objective", help="exact name as listed by status (4x/10x only)") o.add_argument("name") + sub.add_parser("optconfs", help="list the optical configurations") c = sub.add_parser("capture", help="capture one image and save it as .nd2") c.add_argument("path") r = sub.add_parser("nd-run", help="load a saved ND experiment by name and run it") @@ -116,6 +147,7 @@ def main() -> None: out = {"status": lambda: b.status(), "move": lambda: b.move_relative(a.dx, a.dy), "objective": lambda: b.change_objective(a.name), + "optconfs": lambda: b.optical_configs(), "capture": lambda: b.capture(a.path), "nd-run": lambda: b.nd_run(a.experiment), "nd-finish": lambda: b.nd_finish(), diff --git a/acquisition/nis_bridge/bridge_job.py b/acquisition/nis_bridge/bridge_job.py index 8704b0b..4f6be7f 100644 --- a/acquisition/nis_bridge/bridge_job.py +++ b/acquisition/nis_bridge/bridge_job.py @@ -15,6 +15,7 @@ # POST /move {"dx", "dy"} relative XY move, um # POST /objective {"name"} Stg_SetNosepiecePosition (turns the turret) then ChangeObjective # (NIS calibration), allow-listed names only +# GET /optconfs names of the optical configurations (read-only) # POST /capture {"path"} Capture, save as ND2, close the document # POST /nd/run {"experiment"} ND_LoadExperiment + ND_RunExperiment(0) # POST /nd/finish ND_FinishExperiment (stop after this loop) @@ -39,10 +40,14 @@ # (Docs/nis/eng_ar on the microscope PC). A macro char* is wchar_t* in # this build (limpy passes WaitText's text as c_wchar_p). # -# THREADING. NIS is not known to be thread-safe, so every NIS call runs on -# the job's own thread in run(); the HTTP threads only queue requests and -# wait for the answer. A call that takes long (ND_RunExperiment may block -# until the run ends - unverified) delays the requests queued behind it. +# THREADING. A JOBS Python task runs on NIS's main thread, and serving there +# froze NIS (2026-10-15). So run() starts serve() on a worker thread and +# returns. NIS is not known to be thread-safe, so every NIS call still runs +# on that one worker thread; the HTTP threads only queue requests and wait +# for the answer. Whether macro calls (Ti2 moves, Capture) are allowed off +# the main thread is UNVERIFIED. A call that takes long (ND_RunExperiment +# may block until the run ends - unverified) delays the requests queued +# behind it. # # SAFETY, enforced here as well as in the client: # * motion and acquisition only on POST, so a browser cannot trigger them @@ -93,6 +98,8 @@ class Macro: "GetCurrentObjName": [ct.c_wchar_p], "Stg_SetNosepiecePosition": [ct.c_int], "ChangeObjective": [ct.c_wchar_p], + "GetOptConfCount": [], + "GetOptConfName": [ct.c_int, ct.c_wchar_p, ct.c_int], "Capture": [], "ImageSaveAs": [ct.c_wchar_p, ct.c_int, ct.c_int], "CloseCurrentDocument": [ct.c_int], @@ -192,6 +199,20 @@ def objective(self, name: str) -> dict: "nosepiece_before": before["nosepiece_position"], "nosepiece_after": after["nosepiece_position"]} + def optical_configs(self) -> dict: + names = [] + for i in range(0, self.m.GetOptConfCount() + 1): # index base unverified: try 0..n + b = ct.create_unicode_buffer(255) + self.m.GetOptConfName(i, b, 255) + if b.value and b.value not in names: + names.append(b.value) + return {"optical_configs": names} + + # No select: SelectOptConf called from this worker thread switched the + # devices ("end success" in NIS's log) and then froze NIS's main thread + # until the bridge was shut down (2026-10-15). Set the optical + # configuration in NIS, or find a way to run it on the UI thread first. + def capture(self, path: str) -> dict: if (r := self._refuse_if_stopped("capture")): return r @@ -230,6 +251,7 @@ def nd_finish(self) -> dict: ("GET", "/status"): lambda b, body: b.status(), ("POST", "/move"): lambda b, body: b.move(float(body.get("dx", 0)), float(body.get("dy", 0))), ("POST", "/objective"): lambda b, body: b.objective(str(body.get("name", ""))), + ("GET", "/optconfs"): lambda b, body: b.optical_configs(), ("POST", "/capture"): lambda b, body: b.capture(str(body.get("path", ""))), ("POST", "/nd/run"): lambda b, body: b.nd_run(str(body.get("experiment", ""))), ("POST", "/nd/finish"): lambda b, body: b.nd_finish(), @@ -289,6 +311,10 @@ def serve(bridge: Bridge, port: int = PORT, should_abort=lambda: False, last_request = time.time() jobs = queue.Queue() stop = stop or threading.Event() + # On Windows SO_REUSEADDR (the default here) lets a second bridge bind the + # same port, so re-running the job started a duplicate whose shutdown had + # to be sent twice (seen 2026-10-15). Without it a second run fails to bind. + http.server.ThreadingHTTPServer.allow_reuse_address = False srv = http.server.ThreadingHTTPServer(("127.0.0.1", port), make_handler(jobs, stop)) threading.Thread(target=srv.serve_forever, daemon=True).start() print(f"NIS bridge v{VERSION} listening on 127.0.0.1:{srv.server_address[1]}, pid {os.getpid()}") @@ -316,7 +342,13 @@ def serve(bridge: Bridge, port: int = PORT, should_abort=lambda: False, def run(imgs: "tuple[limjob.Image]", Job: "limjob.JobParam", macro: "limjob.MacroParam", ctx: "limjob.RunContext"): - """JOBS entry point: serve until POST /shutdown (or the idle backstop). - The Abort button cannot stop it - see the header. The hints are the - JOBS template's own, as strings so this file imports off NIS.""" - serve(Bridge(Macro())) + """JOBS entry point. Serving on the job's own thread froze NIS (step 0 of + docs/nis-bridge.md, 2026-10-15): a Python task runs on NIS's main thread, + so a loop that never returns blocks the UI. So serve on a worker thread + and return at once; the job shows as finished while the bridge keeps + listening. Stop it with POST /shutdown (or the idle backstop). Whether + NIS macro calls work from a non-main thread is UNVERIFIED: try status + first, then the moves. The hints are the JOBS template's own, as strings + so this file imports off NIS.""" + threading.Thread(target=serve, args=(Bridge(Macro()),), name="nis-bridge", + daemon=True).start() diff --git a/acquisition/nis_events.py b/acquisition/nis_events.py new file mode 100644 index 0000000..db939ee --- /dev/null +++ b/acquisition/nis_events.py @@ -0,0 +1,100 @@ +# nis_events.py +# ------------------------------------------------------------ +# The NIS event log: one JSON line per thing done through the NIS bridge, +# appended to logs/nis/events-YYYY-MM-DD.jsonl. Whoever drives the bridge +# (the NIS MCP server, a script, the command line) writes here, and +# acquisition/nis_monitor.py tails the file, so the monitor shows what +# Claude is doing from another process. +# +# One action is logged as a "start" line, then one closing line: "ok", or +# "failed" (the bridge refused it or NIS reported an error), "refused" (the +# client's e-stop check stopped it before anything was sent) or "error" +# (the bridge was not reachable). The start line is what lets the monitor +# say "nd_run has been running for 42 s" while the bridge is busy. +# +# Logging must never get in the way of the microscope, so a failed write +# is swallowed. +# ------------------------------------------------------------ + +from __future__ import annotations + +import datetime +import json +from pathlib import Path + +from acquisition import paths + +PHASES = ("start", "ok", "failed", "refused", "error") + + +def events_dir() -> Path: + return paths.logs_dir() / "nis" + + +def events_path(day: datetime.date | None = None) -> Path: + day = day or datetime.date.today() + return events_dir() / f"events-{day.isoformat()}.jsonl" + + +def record(action: str, phase: str, **fields) -> dict: + """Append one event and return it. Never raises.""" + event = {"ts": datetime.datetime.now().isoformat(timespec="milliseconds"), + "action": action, "phase": phase, **fields} + try: + path = events_path() + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as f: + f.write(json.dumps(event, ensure_ascii=False) + "\n") + except OSError: + pass + return event + + +def read_from(path: Path, offset: int = 0) -> tuple[list[dict], int]: + """Events appended to `path` after byte `offset`, and the new offset. + A half-written last line is left for the next call; a missing file is + an empty log.""" + try: + with path.open("rb") as f: + f.seek(offset) + data = f.read() + except OSError: + return [], offset + end = data.rfind(b"\n") + 1 + events = [] + for line in data[:end].splitlines(): + try: + events.append(json.loads(line)) + except ValueError: + continue + return events, offset + end + + +def summarize(event: dict) -> str: + """One short line of detail for an event, for the monitor.""" + p, r = event.get("params") or {}, event.get("result") or {} + action, phase = event.get("action"), event.get("phase") + if phase == "start": + return " ".join(f"{k}={v}" for k, v in p.items()) + if phase in ("refused", "error"): + return str(event.get("message", "")) + if phase == "failed": + return str(r.get("error", r)) + took = f" ({event['elapsed_s']} s)" if "elapsed_s" in event else "" + if action == "move": + return f"{_xy(r.get('before_um'))} -> {_xy(r.get('after_um'))}{took}" + if action == "objective": + return (f"{r.get('before')} -> {r.get('after')}, arrived={r.get('arrived')}" + f", nosepiece {r.get('nosepiece_before')}->{r.get('nosepiece_after')}{took}") + if action == "capture": + return f"saved={r.get('saved')} {r.get('path', '')}{took}" + if action == "nd_run": + return f"nd_running={r.get('nd_running')}{took}" + return took.strip() + + +def _xy(xy) -> str: + try: + return f"({xy[0]:.1f}, {xy[1]:.1f})" + except (TypeError, IndexError, ValueError): + return "?" diff --git a/acquisition/nis_monitor.py b/acquisition/nis_monitor.py new file mode 100644 index 0000000..29afb69 --- /dev/null +++ b/acquisition/nis_monitor.py @@ -0,0 +1,197 @@ +# nis_monitor.py +# ------------------------------------------------------------ +# Live terminal view of the NIS bridge. Run it in its own window: +# +# python -m acquisition.nis_monitor # refresh every 1 s, Ctrl+C to leave +# python -m acquisition.nis_monitor --once # print one snapshot and exit +# +# It shows the stage, objective, ND state and e-stop (polled from the bridge's +# /status) above a scrolling list of what was done through the bridge (the NIS +# event log, acquisition/nis_events.py). It only reads: it never moves +# anything, and it does not log its own status polls. +# +# It also opens by itself in its own console window when the NIS MCP server +# starts (launch(), same pattern as the STOP panel) - you should not have to +# remember it. One window only: a named mutex stops a second copy. +# CONFOCAL_NO_NIS_MONITOR=1 turns the automatic launch off. +# +# While the bridge is busy with one long NIS call (an ND run or a capture +# blocks the bridge's single worker) /status cannot answer, so the monitor +# says so and names the action it is waiting on, from the event log. +# ------------------------------------------------------------ + +from __future__ import annotations + +import argparse +import datetime +import json +import os +import shutil +import subprocess +import sys +import time +import urllib.error +import urllib.request + +from acquisition import estop, nis_events +from acquisition.backends.nis_bridge import DEFAULT_URL + +ON_WINDOWS = sys.platform == "win32" +MONITOR_MUTEX = r"Local\confocal-mcp-nis-monitor" +STATUS_TIMEOUT_S = 2.0 +EVENTS_KEPT = 200 + +RESET, DIM, RED, GREEN, YELLOW = "\x1b[0m", "\x1b[2m", "\x1b[31m", "\x1b[32m", "\x1b[33m" +PHASE_COLOUR = {"start": DIM, "ok": GREEN, "failed": RED, "refused": RED, "error": RED} + + +def monitor_running() -> bool: + """True if a monitor window is already open (Windows only).""" + if sys.platform != "win32": + return False + import ctypes + k32 = ctypes.windll.kernel32 + h = k32.OpenMutexW(0x00100000, False, MONITOR_MUTEX) # SYNCHRONIZE + if h: + k32.CloseHandle(h) + return True + return False + + +def launch() -> None: + """Open the monitor in a new console window unless one is already open. + + Called when the NIS MCP server starts. Detached, so the window outlives + the server; failures go to stderr (stdout is the MCP JSON-RPC channel) + and never stop the caller. + """ + if os.environ.get("CONFOCAL_NO_NIS_MONITOR") or not ON_WINDOWS: + return + try: + if monitor_running(): + return + subprocess.Popen([sys.executable, "-m", "acquisition.nis_monitor"], + stdin=subprocess.DEVNULL, stdout=None, stderr=None, + creationflags=getattr(subprocess, "CREATE_NEW_CONSOLE", 0)) + except Exception as exc: + print(f"[nis_monitor] could not open the monitor window ({exc}). " + f"Start it with: python -m acquisition.nis_monitor", file=sys.stderr) + + +def _hold_mutex(): + """Take the single-instance mutex for this process's life; None if + another monitor already holds it. Windows only.""" + if sys.platform != "win32": + return True + import ctypes + h = ctypes.windll.kernel32.CreateMutexW(None, False, MONITOR_MUTEX) + if ctypes.windll.kernel32.GetLastError() == 183: # ERROR_ALREADY_EXISTS + return None + return h + + +def fetch_status(url: str) -> tuple[str, dict | None]: + """("up", status) / ("busy", None) when the bridge accepts the connection + but does not answer in time / ("down", None) when nothing is listening.""" + try: + with urllib.request.urlopen(url + "/status", timeout=STATUS_TIMEOUT_S) as r: + return "up", json.loads(r.read()) + except TimeoutError: + # urllib lets only a timeout while *reading* the answer through bare: + # the connection was made and NIS did not answer. (A connect that + # times out - Windows retries a closed port for seconds - arrives + # wrapped in URLError, below.) + return "busy", None + except (OSError, ValueError): + return "down", None + + +def pending(events: list[dict]) -> dict | None: + """The latest action that has a "start" line and no closing line yet.""" + open_starts: dict[str, dict] = {} + for e in events: + if e.get("phase") == "start": + open_starts[e["action"]] = e + else: + open_starts.pop(e["action"], None) + return max(open_starts.values(), key=lambda e: e["ts"], default=None) + + +def _short_objective(name: str | None) -> str: + return (name or "?").replace("PLAN APO ", "").replace("λD ", "") + + +def render(link: str, status: dict | None, events: list[dict], estop_text: str, + now: datetime.datetime, width: int = 100, rows: int = 20, + colour: bool = True) -> str: + c = (lambda code, s: f"{code}{s}{RESET}") if colour else (lambda code, s: s) + lines = [c(DIM, "NIS monitor ") + now.strftime("%Y-%m-%d %H:%M:%S")] + bridge = {"up": c(GREEN, "UP"), "down": c(RED, "DOWN (job not running in NIS?)"), + "busy": c(YELLOW, "BUSY (NIS is inside one long call)")}[link] + estop_part = c(RED, estop_text) if estop.is_engaged() else c(GREEN, estop_text) + lines.append(f"bridge: {bridge} e-stop: {estop_part}") + if status: + x, y = status.get("xy_um", [float("nan")] * 2) + lines.append(f"XY {x:.1f}, {y:.1f} um Z {status.get('z_um', float('nan')):.2f} um " + f"objective {_short_objective(status.get('current_objective'))} " + f"[nosepiece {status.get('nosepiece_position')}] " + f"ND run: {'RUNNING' if status.get('nd_running') else 'idle'}") + wait = pending(events) + if wait: + since = datetime.datetime.fromisoformat(wait["ts"]) + secs = max(0, int((now - since).total_seconds())) + detail = nis_events.summarize(wait) + lines.append(c(YELLOW, f"now: {wait['action']} {detail} - {secs} s so far")) + lines.append(c(DIM, "-" * min(width, 100))) + for e in events[-rows:]: + phase = e.get("phase", "?") + stamp = e.get("ts", "")[11:19] + text = f"{stamp} {e.get('action', '?'):<10} {c(PHASE_COLOUR.get(phase, ''), f'{phase:<7}')} " + body = nis_events.summarize(e) + room = max(10, width - len(stamp) - 22) + lines.append(text + (body if len(body) <= room else body[:room - 1] + "…")) + if not events: + lines.append(c(DIM, "(no NIS actions logged today yet)")) + return "\n".join(lines) + + +def main() -> None: + ap = argparse.ArgumentParser(description="Live terminal view of the NIS bridge.") + ap.add_argument("--url", default=os.environ.get("CONFOCAL_NIS_BRIDGE_URL", DEFAULT_URL)) + ap.add_argument("--interval", type=float, default=1.0, help="seconds between refreshes") + ap.add_argument("--once", action="store_true", help="print one snapshot and exit") + a = ap.parse_args() + held = None if a.once else _hold_mutex() # kept for the life of the process + if not a.once and held is None: + raise SystemExit("A NIS monitor is already open.") + url = a.url.rstrip("/") + + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + os.system("") # lets a Windows console read ANSI codes + events: list[dict] = [] + path, offset = nis_events.events_path(), 0 + try: + while True: + today = nis_events.events_path() + if today != path: # past midnight: start the new day's file + path, offset = today, 0 + new, offset = nis_events.read_from(path, offset) + events = (events + new)[-EVENTS_KEPT:] + link, status = fetch_status(url) + estop_text = "ENGAGED" if estop.is_engaged() else "clear" + size = shutil.get_terminal_size((100, 30)) + frame = render(link, status, events, estop_text, datetime.datetime.now(), + width=size.columns, rows=max(5, size.lines - 7), + colour=sys.stdout.isatty()) + if a.once: + print(frame) + return + sys.stdout.write("\x1b[H\x1b[2J" + frame + "\n") + sys.stdout.flush() + time.sleep(a.interval) + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/docs/nis-bridge.md b/docs/nis-bridge.md index 901fa67..af4a46c 100644 --- a/docs/nis-bridge.md +++ b/docs/nis-bridge.md @@ -60,6 +60,17 @@ separate server, `confocal-mcp-nis`. by it and NIS freezes (seen 2026-10-14; `limjob.RunContext` has no abort flag). The job also ends by itself after 4 h with no request. +## Live monitor + +`python -m acquisition.nis_monitor` in a second terminal shows the bridge +state (stage, Z, objective, ND run, e-stop) above a scrolling list of every +action sent through the bridge, from any process, so you can watch what +Claude does. Actions are logged to `logs/nis/events-.jsonl` as a +`start` line and then `ok`, `failed`, `refused` or `error`. While one long +call (an ND run, a capture) holds the bridge, the monitor shows BUSY and +names the action and how long it has run. Use it while working through the +test plan below. + ## Test plan for the microscope Run each step from a terminal in the repo (`.venv\Scripts\python -m @@ -97,6 +108,37 @@ before changing anything. `arrived` once position and name both match. **Re-run step 5 with the new job.** - Steps 6-10 not run yet. +## Results on the microscope (2026-10-15) + +- **Step 0 failed.** With the first design NIS did not respond while the job + ran. A JOBS Python task runs on NIS's main thread, and the serving loop + never returned. JOBS has no background option (the Python task has no + options besides its code; `ctx` is "currently not implemented"), and + NIS exposes no outside automation interface we could find, so the loop + cannot be moved out of NIS by configuration. +- **Change:** `run()` now starts `serve()` on a worker thread and returns, so + the job finishes at once and NIS stays free. **Unverified:** whether NIS + macro calls work from a non-main thread. Re-run the plan from step 0, then + `status` (read-only), then the moves, and stop at the first odd result. + If calls fail or misbehave off the main thread, the fallback is a short job + that handles one queued request per run, started from a JOBS loop or timer. + +## Results on the microscope (2026-10-15, worker-thread bridge) + +- Step 0 passes: NIS stays responsive; the job window closes at once while + the bridge keeps serving on a worker thread. Reads work off the main thread. +- Steps 1-4 pass: `move 100 0` and back (X 137.5 -> 237.5 -> 137.5), a + 1500 um move refused, and the e-stop refused in both the client and, via + `curl`, the bridge. Moves from the worker thread work. +- **Step 5 passes.** Turret turned 4x -> 10x -> 4x (nosepiece 0 -> 1 -> 0), + `arrived: true` each way. NIS's objective display is the blue text in the + bottom status bar and it follows: `PLAN APO lambdaD 4x OFN25 (8.67 um/px @ 512 x 512)` + and `PLAN APO lambdaD 10x OFN25 DIC N1 (1.72 um/px @ 512 x 512)`; the Ti2 Pad + highlights the matching nosepiece slot. **Open question:** 8.67 / 1.72 is + about 5x, not the 2.5x the magnifications imply. Probably the AX scan + field differs per objective, but check it with a capture at each. +- Steps 6-10 not run yet. + ## Safety rules (enforced in code) - Motion and acquisition answer **POST** only, so a browser cannot trigger them. diff --git a/harness/context.py b/harness/context.py index 02a3895..b25a6b0 100644 --- a/harness/context.py +++ b/harness/context.py @@ -26,27 +26,49 @@ IMAGE_BLOCK_TYPES = {"image", "image_url"} +def _is_image(block: Any) -> bool: + return isinstance(block, dict) and block.get("type") in IMAGE_BLOCK_TYPES + + +def _block_has_image(block: Any) -> bool: + """An image block, or a tool_result whose own content holds one. The + harnesses return get_image()'s picture inside a tool_result, so looking + only at top-level blocks would never find a single frame.""" + if _is_image(block): + return True + return (isinstance(block, dict) and block.get("type") == "tool_result" + and isinstance(block.get("content"), list) + and any(_is_image(inner) for inner in block["content"])) + + def _message_has_image(message: dict[str, Any]) -> bool: content = message.get("content") if not isinstance(content, list): return False - return any( - isinstance(block, dict) and block.get("type") in IMAGE_BLOCK_TYPES - for block in content - ) + return any(_block_has_image(block) for block in content) + + +def _strip_block(block: Any) -> Any: + """`block` without images; a tool_result is copied with its images + removed, and says so if nothing else was left in it.""" + if not (isinstance(block, dict) and block.get("type") == "tool_result" + and isinstance(block.get("content"), list)): + return block + inner = [b for b in block["content"] if not _is_image(b)] + if not inner: + inner = [{"type": "text", "text": "[image removed to save context]"}] + return {**block, "content": inner} def _strip_images(message: dict[str, Any]) -> dict[str, Any]: """Return a copy of `message` with any image blocks removed from its - content, keeping every other block (text, tool-use, etc.) as-is. + content - top-level, or inside a tool_result - keeping every other block + (text, tool-use, etc.) as-is. """ content = message.get("content") if not isinstance(content, list): return dict(message) - kept = [ - block for block in content - if not (isinstance(block, dict) and block.get("type") in IMAGE_BLOCK_TYPES) - ] + kept = [_strip_block(block) for block in content if not _is_image(block)] return {**message, "content": kept} diff --git a/mcp_server/nis_tools.py b/mcp_server/nis_tools.py index 6227974..8c68960 100644 --- a/mcp_server/nis_tools.py +++ b/mcp_server/nis_tools.py @@ -91,12 +91,19 @@ def nis_change_objective(name: str, confirm: bool = False) -> dict: return _checked(_bridge().change_objective(name)) +def nis_list_optical_configs() -> dict: + """Read-only: the names of the optical configurations defined in + NIS-Elements, named "Group:Configuration". There is no tool to select + one: set it in NIS-Elements before nis_capture.""" + return _bridge().optical_configs() + + _SAFE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9 _.\-]{0,80}$") def nis_capture(filename: str, confirm: bool = False) -> dict: """Capture one image with the current NIS-Elements acquisition settings - (lasers, channels, scan) and save it as an ND2 file in the NIS capture + (the optical configuration active in NIS - lasers, channels, scan) and save it as an ND2 file in the NIS capture folder. `filename` is a plain name such as "aml18_check" - no folders; ".nd2" is added if missing and an existing file is never overwritten. Returns the saved path. Requires confirm=True.""" diff --git a/mcp_server/server_nis.py b/mcp_server/server_nis.py index ba1b98d..05909e2 100644 --- a/mcp_server/server_nis.py +++ b/mcp_server/server_nis.py @@ -14,7 +14,7 @@ from mcp.server.mcpserver import MCPServer -from acquisition import estop +from acquisition import estop, nis_monitor from mcp_server import loop_tools, nis_tools mcp = MCPServer("ConfocalOrchestrator-NIS") @@ -22,6 +22,7 @@ mcp.add_tool(nis_tools.nis_status) mcp.add_tool(nis_tools.nis_move_relative) mcp.add_tool(nis_tools.nis_change_objective) +mcp.add_tool(nis_tools.nis_list_optical_configs) mcp.add_tool(nis_tools.nis_capture) mcp.add_tool(nis_tools.nis_run_experiment) mcp.add_tool(nis_tools.nis_finish_experiment) @@ -31,6 +32,7 @@ def main() -> None: """Console entry point (``confocal-mcp-nis``): serve the NIS tools over stdio.""" estop.launch_panel() + nis_monitor.launch() # live view of what this server does mcp.run(transport="stdio") diff --git a/pyproject.toml b/pyproject.toml index a0d7d60..ddf67b1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,6 +39,15 @@ sdk = [ # Running the test suite (tests/ - mock backend only, no hardware). test = [ "pytest==9.1.1", + "pytest-cov==7.1.0", + # Real OpenCV: mosaic.py and worm_follow.py run against a simulated scene. + # Headless, so a CI runner needs no GL libraries. + "opencv-python-headless==5.0.0.93", + # The analysis/ scripts' tests (worm survey) use these for real; the ND2 + # reader and ffmpeg are faked, so neither nd2 nor imageio-ffmpeg is needed. + # Ranges: scipy 1.18.1 needs Python 3.12 and CI also runs 3.11. + "scipy>=1.11,<2", + "scikit-image>=0.24,<1", ] # The standalone Claude harness loops in harness/ (not the MCP server). harness = [ @@ -69,3 +78,10 @@ Repository = "https://github.com/BioNanomics/microscope-agent" [tool.hatch.build.targets.wheel] packages = ["mcp_server", "acquisition", "harness", "timelapse"] + +[tool.pytest.ini_options] +# `python -m` entry points are exercised with runpy, which re-executes a module +# that is already imported; that is intended and the warning is noise. +filterwarnings = [ + "ignore:.*found in sys.modules after import of package:RuntimeWarning", +] diff --git a/tests/fakes.py b/tests/fakes.py new file mode 100644 index 0000000..426473d --- /dev/null +++ b/tests/fakes.py @@ -0,0 +1,97 @@ +# Fake hardware for the tests: a Ti2 ActiveX microscope and the modules +# nis_sdk imports at the top (pythoncom, win32com, NkTi2Ax), so nis_sdk - +# and everything built on it - can be imported and run on a plain CI runner. +import importlib +import sys +import types + +import pytest + + +class _Setting: + def __init__(self, lower, higher): + self.Lower, self.Higher = lower, higher + self.Control, self.Enabled, self.Unit, self.Scale = 1, 1, "u", 1.0 + + +class _Objective: + IsPFSEnabled = True + Model = "Fake 10x" + Magnification = 10 + WorkingDistance = 4.0 + + +class _Data: + """What DataGet fills in: _prop_map_get_ names the readable properties.""" + _prop_map_get_ = {"iLIGHTPATH": 1, "iDIA_LAMP_Switch": 1, "iXPOSITION": 1, + "iNOSEPIECE": 1, "iBROKEN": 1} + iLIGHTPATH = 2 + iDIA_LAMP_Switch = 1 + iXPOSITION = 5 + iNOSEPIECE = 3 + + @property + def iBROKEN(self): + raise RuntimeError("unreadable") + + +class FakeMicroscope: + """Counts: X/Y 0.1 um, Z 0.01 um (see nis_sdk). Writes land at once.""" + + def __init__(self): + self.iXPOSITION = 1000 # 100.0 um + self.iYPOSITION = 2000 # 200.0 um + self.iZPOSITION = 461900 # 4619.00 um + self.XPosition = _Setting(-570000, 570000) + self.YPosition = _Setting(-375000, 375000) + self.ZPosition = _Setting(0, 1000000) + self.PfsOffset = _Setting(0, 40000) + self.iPFS_OFFSET = 18966 + self.iPFS_STATUS = 7 + self.iNOSEPIECE = 1 + self.objective = _Objective() + self.iLIGHTPATH = 1 + self.iDIA_LAMP_Switch = 0 + self.uiDataUsageMask = 2 + self.commands = [] + + def DedicatedCommand(self, name, arg): + self.commands.append((name, arg)) + if name.startswith("GET"): + raise RuntimeError("not supported") + return "ok" + + def Objective(self, n): + return self.objective + + def DataGet(self, data, flag): + return _Data() + + +@pytest.fixture +def fake_ti2(monkeypatch): + """Import a fresh acquisition.backends.nis_sdk bound to a FakeMicroscope. + Yields (nis_sdk module, microscope).""" + micro = FakeMicroscope() + pythoncom = types.ModuleType("pythoncom") + pythoncom.CoInitialize = lambda: None + pythoncom.PumpWaitingMessages = lambda: None + pythoncom.CoInitializeEx = lambda flag: None + pythoncom.COINIT_MULTITHREADED = 0 + win32com = types.ModuleType("win32com") + client = types.ModuleType("win32com.client") + client.Dispatch = lambda *a, **k: micro + client.DispatchWithEvents = lambda clsid, events: micro + win32com.client = client + nk = types.ModuleType("NkTi2Ax") + nk.NikonTi2AxAutoConnectMicroscope = types.SimpleNamespace(CLSID="fake-clsid") + nk.INikonTi2AxData = object + for name, mod in (("pythoncom", pythoncom), ("win32com", win32com), + ("win32com.client", client), ("NkTi2Ax", nk)): + monkeypatch.setitem(sys.modules, name, mod) + from acquisition import estop + monkeypatch.setattr(estop, "launch_panel", lambda: None) # no STOP window on a test run + sys.modules.pop("acquisition.backends.nis_sdk", None) + sdk = importlib.import_module("acquisition.backends.nis_sdk") + yield sdk, micro + sys.modules.pop("acquisition.backends.nis_sdk", None) diff --git a/tests/fakes_camera.py b/tests/fakes_camera.py new file mode 100644 index 0000000..dbda18e --- /dev/null +++ b/tests/fakes_camera.py @@ -0,0 +1,112 @@ +# Fake Baumer / GenICam stack: cv2 and harvesters stand-ins plus a .cti +# folder, so acquisition.backends.baumer_genicam imports and runs on a plain +# CI runner with no camera and no opencv. +import importlib +import sys +import types + + +class _Node: + def __init__(self, value, lo=None, hi=None): + self.value, self.min, self.max = value, lo, hi + + +class FakeNodeMap: + def __init__(self, pixel_format="Mono8", with_auto=True, with_white_balance=True): + self.ExposureTime = _Node(10000.0, 28.0, 60_000_000.0) + self.Gain = _Node(1.0, 1.0, 251.0) + self.PixelFormat = _Node(pixel_format) + if with_auto: + self.ExposureAuto = _Node("Continuous") + self.GainAuto = _Node("Continuous") + if with_white_balance: + self.BalanceWhiteAuto = _Node("Off") + + +class _Buffer: + def __init__(self, data, h, w): + comp = types.SimpleNamespace(height=h, width=w, data=data) + self.payload = types.SimpleNamespace(components=[comp]) + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + +class FakeAcquirer: + def __init__(self, node_map, h=4, w=6): + import numpy as np + self.remote_device = types.SimpleNamespace(node_map=node_map) + self.h, self.w, self.started, self.stopped = h, w, False, False + self._np = np + self._stale = 2 # frames queued before the capture: must be drained + + def start(self): + self.started = True + + def stop(self): + self.stopped = True + + def destroy(self): + self.destroyed = True + + def fetch(self, timeout=0): + if timeout == 0.01: + if self._stale <= 0: + raise TimeoutError("no more frames") + self._stale -= 1 + return _Buffer(self._np.zeros(1, dtype="uint8"), 1, 1) + fmt = self.remote_device.node_map.PixelFormat.value + n = self.h * self.w * (3 if fmt in ("BGR8", "RGB8") else 1) + return _Buffer(self._np.arange(n, dtype="uint8"), self.h, self.w) + + +def install_fake_camera_stack(monkeypatch, tmp_path, pixel_format="Mono8", devices=1, **node_kw): + """Fake cv2, harvesters and a .cti folder, then import a fresh + baumer_genicam. Returns (module, acquirer, harvester_log).""" + import numpy as np + cv2 = types.ModuleType("cv2") + cv2.COLOR_BGR2RGB, cv2.COLOR_GRAY2RGB, cv2.COLOR_BayerBG2RGB = 1, 3, 4 + + def cvt(a, code): + if code == cv2.COLOR_BGR2RGB: + return a[..., ::-1].copy() + return np.stack([a, a, a], axis=-1) + + cv2.cvtColor = cvt + acquirer = FakeAcquirer(FakeNodeMap(pixel_format, **node_kw)) + log = {"files": [], "reset": False} + + class Harvester: + device_info_list = [object()] * devices + + def add_file(self, f): + log["files"].append(f) + + def update(self): + pass + + def create(self, i): + return acquirer + + def reset(self): + log["reset"] = True + + harv_core = types.ModuleType("harvesters.core") + harv_core.Harvester = Harvester + harv = types.ModuleType("harvesters") + harv.core = harv_core + for name, mod in (("cv2", cv2), ("harvesters", harv), ("harvesters.core", harv_core)): + monkeypatch.setitem(sys.modules, name, mod) + cti_dir = tmp_path / "gentl" + cti_dir.mkdir(exist_ok=True) + (cti_dir / "producer.CTI").write_text("") + (cti_dir / "readme.txt").write_text("") + monkeypatch.setenv("GENICAM_GENTL64_PATH", str(cti_dir)) + sys.modules.pop("acquisition.backends.baumer_genicam", None) + mod = importlib.import_module("acquisition.backends.baumer_genicam") + monkeypatch.setattr(mod, "CAPTURE_DIR", tmp_path / "caps") + monkeypatch.setattr(mod, "FALLBACK_CTI_DIRS", []) + return mod, acquirer, log diff --git a/tests/fakes_nd2.py b/tests/fakes_nd2.py new file mode 100644 index 0000000..5edccb3 --- /dev/null +++ b/tests/fakes_nd2.py @@ -0,0 +1,76 @@ +# A stand-in for the `nd2` reader and a synthetic worm scene, so the analysis +# scripts run without ND2 files: brightfield (TD) with a dark worm on agar, +# and a fluorescence channel (RFP) with glowing neurons at the worm's head. +import sys +import types + +import cv2 +import numpy as np + +UM_PX = 3.0 + + +def worm_td(size=256, p0=(60, 128), p1=(200, 140), width=10, value=70.0, seed=0, blur=0.0): + rng = np.random.default_rng(seed) + img = 190.0 + rng.normal(0, 1.5, (size, size)).astype(np.float32) + cv2.line(img, p0, p1, float(value), width, cv2.LINE_AA) + if blur: + img = cv2.GaussianBlur(img, (0, 0), blur) + return img.astype(np.float32) + + +def neurons(size=256, centres=((62, 128), (70, 129), (78, 129)), amp=400.0, sigma=2.5): + yy, xx = np.mgrid[0:size, 0:size] + out = np.zeros((size, size), np.float32) + for cx, cy in centres: + out += amp * np.exp(-((xx - cx) ** 2 + (yy - cy) ** 2) / (2 * sigma ** 2)) + return out + + +class FakeND2File: + config = {} + + def __init__(self, path): + self.path = path + c = FakeND2File.config + self._arr, self._dims = c["array"], c["dims"] + self.sizes = dict(zip(c["dims"], c["array"].shape)) + self.sizes.update(c.get("extra_sizes", {})) + self.metadata = types.SimpleNamespace(channels=[ + types.SimpleNamespace(channel=types.SimpleNamespace(name=n)) for n in c["channels"]]) + self._um_px, self._times = c.get("um_px", UM_PX), c.get("times") + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def asarray(self): + return self._arr + + def voxel_size(self): + return types.SimpleNamespace(x=self._um_px, y=self._um_px, z=1.0) + + def events(self): + if self._times is None: + raise RuntimeError("no events in this file") + return [{"Time [s]": t} for t in self._times] + + +def install_nd2(monkeypatch, array, dims, channels, **config): + FakeND2File.config = dict(array=array, dims=dims, channels=channels, **config) + mod = types.ModuleType("nd2") + mod.ND2File = FakeND2File + monkeypatch.setitem(sys.modules, "nd2", mod) + return mod + + +def two_channel_stack(t=2, z=3, size=256, **kw): + """T, Z, C, Y, X: brightfield sharpest at the middle plane, neurons at the head.""" + arr = np.zeros((t, z, 2, size, size), np.float32) + for ti in range(t): + for zi in range(z): + arr[ti, zi, 0] = worm_td(size, seed=ti, blur=0.0 if zi == z // 2 else 4.0, **kw) + arr[ti, zi, 1] = neurons(size) if zi == z // 2 else 0.3 * neurons(size) + return arr diff --git a/tests/fakes_scene.py b/tests/fakes_scene.py new file mode 100644 index 0000000..59e0957 --- /dev/null +++ b/tests/fakes_scene.py @@ -0,0 +1,143 @@ +# A simulated microscope for mosaic.py and worm_follow.py: a textured agar +# "world" with one dark worm on it, a stage that moves the camera's window +# across it (stage +X slides features left, +Y moves them down - the same +# signs as worm_follow.M_4X), and a camera that renders the window with +# exposure-dependent brightness and defocus blur. Real OpenCV, no hardware. +import sys +import types +from pathlib import Path + +import cv2 +import numpy as np +from PIL import Image + +from acquisition import estop + +UM_PER_PX = 1.0 / 0.6717 # what worm_follow.M_4X implies +WORLD = 2400 +Z_FOCUS = 4619.0 + + +class _Node: + def __init__(self, value="Off", symbolics=None): + self.value, self.symbolics = value, symbolics + + +class RigNodeMap: + """The GenICam nodes force_camera_autos_off and mosaic.run touch.""" + + def __init__(self, white_balance="Off", full=True): + self.BalanceWhiteAuto = _Node(white_balance) + self.ColorTransformationAuto = _Node("Once") + self.ExposureAuto = _Node("Off") + self.GainAuto = _Node("Continuous") + if full: + self.Gamma = _Node(0.5) + self.ColorTransformationValueSelector = _Node("Gain00", ["Gain00", "Gain01", "Gain10", "Gain11"]) + self.ColorTransformationValue = _Node(0.3) + self.GainSelector = _Node("All") + self.Gain = _Node(1.0) + + +class RigStage: + def __init__(self, rig): + self.rig = rig + self.x = self.y = 0.0 + self.z = Z_FOCUS + self.moves, self.z_moves, self.frozen = [], [], False + self.micro = types.SimpleNamespace(iNOSEPIECE=2) + self._thread = types.SimpleNamespace(call=lambda fn: fn(self.micro)) + + def XY_GetPosition(self): + return self.x, self.y + + def XY_Move(self, x, y): + estop.check() + if np.hypot(x - self.x, y - self.y) > 5000: + raise ValueError("per-call safety limit") + self.moves.append((x, y)) + if not self.frozen: + self.x, self.y = float(x), float(y) + + def Z_GetPosition(self): + return self.z + + def Z_Move(self, z): + estop.check() + if abs(z - self.z) > 50: + raise ValueError("per-call safety limit") + self.z_moves.append(z) + self.z = float(z) + + +class RigCamera: + def __init__(self, rig, w=320, h=240, white_balance="Off", full_nodes=True): + self.rig, self.w, self.h = rig, w, h + self.exposure_us, self.settings_calls, self.closed = 1600.0, [], False + self.captures = 0 + self.on_capture = None + self.blur_per_um = 1 / 8 # defocus blur; 0 makes every Z look alike + self._acquirer = types.SimpleNamespace( + remote_device=types.SimpleNamespace(node_map=RigNodeMap(white_balance, full_nodes))) + + def set_settings(self, exposure_time_us=None, gain=None): + self.settings_calls.append((exposure_time_us, gain)) + if exposure_time_us is not None: + self.exposure_us = exposure_time_us + return self.get_settings() + + def get_settings(self): + return {"exposure_time_us": self.exposure_us, "gain": 1.0} + + def frame(self) -> np.ndarray: + st = self.rig.stage + cx = WORLD / 2 + st.x / UM_PER_PX + cy = WORLD / 2 - st.y / UM_PER_PX + x0 = int(np.clip(round(cx - self.w / 2), 0, WORLD - self.w)) + y0 = int(np.clip(round(cy - self.h / 2), 0, WORLD - self.h)) + img = self.rig.world[y0:y0 + self.h, x0:x0 + self.w].copy() + defocus = abs(st.z - Z_FOCUS) + if defocus > 2 and self.blur_per_um: + img = cv2.GaussianBlur(img, (0, 0), defocus * self.blur_per_um) + img = img * (self.exposure_us / 1600.0) + return np.clip(img, 0, 255).astype(np.uint8) + + def capture(self) -> Path: + self.captures += 1 + if self.on_capture: + self.on_capture(self.captures) + folder = self.rig.tmp / "rig-captures" + folder.mkdir(exist_ok=True) + path = folder / f"c{self.captures:05d}.png" + Image.fromarray(self.frame()).save(path) + return path + + def close(self): + self.closed = True + + +class SceneRig: + def __init__(self, tmp_path, worm_um=(60.0, 30.0), worm=True, seed=1, **camera_kw): + self.tmp = tmp_path + rng = np.random.default_rng(seed) + noise = cv2.GaussianBlur(rng.normal(0, 1, (WORLD, WORLD)).astype(np.float32), (0, 0), 2.0) + agar = 190.0 + 6.0 * noise / noise.std() + world = np.stack([agar] * 3, axis=-1).astype(np.float32) + self.worm_um = worm_um + if worm: + wx = int(WORLD / 2 + worm_um[0] / UM_PER_PX) + wy = int(WORLD / 2 - worm_um[1] / UM_PER_PX) + cv2.ellipse(world, (wx, wy), (45, 11), 20, 0, 360, (45, 45, 45), -1) + self.world = np.clip(world, 0, 255) + self.stage = RigStage(self) + self.camera = RigCamera(self, **camera_kw) + + def install(self, monkeypatch): + """Make `from acquisition.backends.X import ...` hand out this rig.""" + cam = types.ModuleType("acquisition.backends.baumer_genicam") + cam.BaumerGenICam = lambda: self.camera + sdk = types.ModuleType("acquisition.backends.nis_sdk") + sdk.NISSdk = lambda: self.stage + monkeypatch.setitem(sys.modules, "acquisition.backends.baumer_genicam", cam) + monkeypatch.setitem(sys.modules, "acquisition.backends.nis_sdk", sdk) + return self diff --git a/tests/test_analysis_physarum.py b/tests/test_analysis_physarum.py new file mode 100644 index 0000000..ec7b295 --- /dev/null +++ b/tests/test_analysis_physarum.py @@ -0,0 +1,491 @@ +# analysis/make_movie.py, oat_approach.py, physarum_rhythm.py and live_view.py +# against small synthetic Physarum series. +import csv +import datetime +import json +import os +import runpy +import sys +import time + +import cv2 +import numpy as np +import pytest +from PIL import Image + +from analysis import live_view, make_movie as mm, oat_approach as oa, physarum_rhythm as pr + + +def can_write_mp4(tmp_path): + w = cv2.VideoWriter(str(tmp_path / "probe.mp4"), cv2.VideoWriter_fourcc(*"mp4v"), 5, (64, 48)) + ok = w.isOpened() + w.release() + return ok + + +@pytest.fixture +def mp4(tmp_path): + if not can_write_mp4(tmp_path): + pytest.skip("this OpenCV build cannot write mp4v video") + + +def write_png(path, value=120, size=(48, 96), bgr=None): + img = np.full((*size, 3), value, np.uint8) + if bgr is not None: + img[:] = bgr + cv2.imwrite(str(path), img) + return path + + +# ---- make_movie ------------------------------------------------------------------------------ + +def mosaic_series(tmp_path, rounds=3, missing=(), scale=None): + d = tmp_path / "mosaic_run" + d.mkdir() + t0 = datetime.datetime(2026, 9, 21, 10, 0, 0) + with (d / "tiles.csv").open("w", newline="", encoding="utf-8") as f: + w = csv.writer(f) + w.writerow(["round", "tile", "wall_clock"]) + for r in range(rounds): + for tile in range(2): + w.writerow([r, tile, (t0 + datetime.timedelta(minutes=5 * r, seconds=tile)).isoformat()]) + for r in range(rounds): + if r not in missing: + write_png(d / f"mosaic_{r:03d}.png", 100 + r * 20) + meta = {"um_per_px": 3.0} + if scale is not None: + meta["mosaic_scale"] = scale + (d / "mosaic.json").write_text(json.dumps(meta), encoding="utf-8") + return d + + +def frames_series(tmp_path, n=4): + d = tmp_path / "tl" + d.mkdir() + with (d / "frames.csv").open("w", newline="", encoding="utf-8") as f: + w = csv.DictWriter(f, fieldnames=["frame", "t_seconds", "filename", "error"]) + w.writeheader() + for i in range(n): + w.writerow({"frame": i, "t_seconds": i * 10, "filename": f"f{i:05d}.png", "error": ""}) + write_png(d / f"f{i:05d}.png", 80 + 10 * i) + w.writerow({"frame": n, "t_seconds": n * 10, "filename": "", "error": "fetch timed out"}) + w.writerow({"frame": n + 1, "t_seconds": (n + 1) * 10, "filename": "gone.png", "error": ""}) + return d + + +def test_mosaic_rows_are_timed_from_the_first_round(tmp_path): + d = mosaic_series(tmp_path, rounds=3, missing=(1,)) + assert mm._mosaic_rows(d) == [{"filename": "mosaic_000.png", "t_seconds": 0.0}, + {"filename": "mosaic_002.png", "t_seconds": 600.0}] + (d / "tiles.csv").write_text("round,tile,wall_clock\n", encoding="utf-8") + assert mm._mosaic_rows(d) == [] + + +def test_mosaic_pixel_size_defaults_to_the_old_half_scale(tmp_path): + assert mm.mosaic_um_per_px(tmp_path) is None + assert mm.mosaic_um_per_px(mosaic_series(tmp_path)) == 6.0 + other = tmp_path / "b" + other.mkdir() + (other / "mosaic.json").write_text(json.dumps({"um_per_px": 3.0, "mosaic_scale": 0.25})) + assert mm.mosaic_um_per_px(other) == 12.0 + + +def test_rows_skip_failed_and_missing_frames(tmp_path): + rows = mm._rows(frames_series(tmp_path)) + assert [r["filename"] for r in rows] == ["f00000.png", "f00001.png", "f00002.png", "f00003.png"] + + +def test_rows_prefer_the_mosaic_rounds_when_there_are_any(tmp_path): + assert [r["filename"] for r in mm._rows(mosaic_series(tmp_path))] == [ + "mosaic_000.png", "mosaic_001.png", "mosaic_002.png"] + + +def blue_cast(h=100, w=100): + """Agar with the camera's blue-biased cast (BGR 237/168/145) and a little texture.""" + noise = np.random.default_rng(0).integers(-6, 7, (h, w, 1)) + return np.clip(np.array([237, 168, 145]) + noise, 0, 249).astype(np.uint8) + + +def test_white_balance_neutralises_the_bright_background(): + img = blue_cast() + g = mm.wb_gains(img) + assert g[0] < 1 < g[2] # blue turned down, red turned up + balanced = (img.astype(float) * g).reshape(-1, 3).mean(axis=0) + assert np.ptp(balanced) < 0.1 * balanced.mean() + + +def test_white_balance_refuses_to_trust_clipped_or_tiny_references(): + assert np.array_equal(mm.wb_gains(np.full((100, 100, 3), 255, np.uint8)), np.ones(3)) # all clipped + small = np.full((10, 10, 3), 200, np.uint8) + assert np.array_equal(mm.wb_gains(small), np.ones(3)) # under 1000 pixels + img = np.full((100, 100, 3), 100, np.uint8) + img[:3, :3] = 240 # a handful of bright pixels + assert np.array_equal(mm.wb_gains(img), np.ones(3)) + no_blue = blue_cast() + no_blue[:, :, 0] = 0 + assert np.array_equal(mm.wb_gains(no_blue), np.ones(3)) # a dead channel + + +def test_scale_bar_uses_a_round_number_of_microns(): + for um_per_px, label in ((1.0, "20 um"), (4.0, "100 um"), (60.0, "2 mm"), (0.01, "10 um")): + img = np.full((200, 400, 3), 128, np.uint8) + before = img.copy() + mm._scale_bar(img, um_per_px) + assert not np.array_equal(img, before), label + + +def test_timestamp_overlay_draws_something(): + img = np.full((100, 300, 3), 50, np.uint8) + mm._stamp(img, 3725.0, 4, 10) + assert (img != 50).any() + + +def test_build_writes_a_video_from_a_timelapse(tmp_path, mp4, capsys): + d = frames_series(tmp_path) + out = mm.build(d, tmp_path / "out.mp4", fps=5, scale=1.0, um_per_px=1.5, overlay=True) + assert out.exists() and out.stat().st_size > 0 + text = capsys.readouterr().out + assert "white balance gains" in text and "4 frames spanning" in text + + +def test_build_variants(tmp_path, mp4): + d = frames_series(tmp_path) + mm.build(d, tmp_path / "a.mp4", 5, 0.5, 1.5, overlay=False, white_balance=False) + assert (tmp_path / "a.mp4").exists() + m = mosaic_series(tmp_path) + mm.build(m, tmp_path / "b.mp4", 5, 1.0, 6.0, overlay=True) + assert (tmp_path / "b.mp4").exists() + + +def test_build_skips_an_unreadable_frame_but_not_a_missing_first_one(tmp_path, mp4): + d = frames_series(tmp_path) + (d / "f00002.png").write_bytes(b"not an image") + assert mm.build(d, tmp_path / "c.mp4", 5, 1.0, 1.5, overlay=False).exists() + (d / "f00000.png").write_bytes(b"not an image") + with pytest.raises(SystemExit, match="could not read"): + mm.build(d, tmp_path / "d.mp4", 5, 1.0, 1.5, overlay=False) + + +def test_build_needs_frames_and_a_working_codec(tmp_path, monkeypatch): + empty = tmp_path / "empty" + empty.mkdir() + (empty / "frames.csv").write_text("frame,t_seconds,filename,error\n", encoding="utf-8") + with pytest.raises(SystemExit, match="no usable frames"): + mm.build(empty, tmp_path / "x.mp4", 5, 1.0, 1.5, True) + d = frames_series(tmp_path) + + class NoCodec: + def __init__(self, *a): + pass + + def isOpened(self): + return False + + monkeypatch.setattr(mm.cv2, "VideoWriter", NoCodec) + with pytest.raises(SystemExit, match="could not open the video writer"): + mm.build(d, tmp_path / "y.mp4", 5, 1.0, 1.5, True) + + +def test_movie_main_picks_the_pixel_size_and_flags(tmp_path, monkeypatch): + seen = [] + monkeypatch.setattr(mm, "build", lambda *a: seen.append(a)) + d = mosaic_series(tmp_path) + monkeypatch.setattr(sys, "argv", ["make_movie", str(d), "--fps", "10", "--no-overlay", "--no-white-balance"]) + mm.main() + assert seen[0][1] == d / "movie.mp4" and seen[0][4] == 6.0 and seen[0][5:] == (False, False) + monkeypatch.setattr(sys, "argv", ["make_movie", str(d), "--um-per-px", "2.5", "--out", str(tmp_path / "o.mp4")]) + mm.main() + assert seen[1][4] == 2.5 and seen[1][1] == tmp_path / "o.mp4" + plain = frames_series(tmp_path) + monkeypatch.setattr(sys, "argv", ["make_movie", str(plain)]) + mm.main() + assert seen[2][4] == mm.UM_PER_PX + + +# ---- oat_approach ------------------------------------------------------------------------------ + +def dish_image(growth=40, size=800): + """Glass disc, an agar block on it, a black oat on the agar and a plasmodium patch.""" + img = np.zeros((size, size), np.uint8) + cv2.circle(img, (400, 400), 340, 250, -1) # bare glass + cv2.circle(img, (400, 400), 200, 150, -1) # agar + cv2.circle(img, (300, 400), 20, 0, -1) # the oat + cv2.circle(img, (420, 400), growth, 60, -1) # plasmodium + return img + + +def oat_series(tmp_path, rounds=2): + d = tmp_path / "oat_run" + d.mkdir() + t0 = datetime.datetime(2026, 9, 21, 10, 0, 0) + with (d / "tiles.csv").open("w", newline="", encoding="utf-8") as f: + w = csv.writer(f) + w.writerow(["round", "tile", "wall_clock"]) + for r in range(rounds): + w.writerow([r, 0, (t0 + datetime.timedelta(minutes=10 * r)).isoformat()]) + for r in range(rounds): + img = dish_image(growth=40 + 30 * r) + if r == 1: + img = cv2.resize(img, (400, 400), interpolation=cv2.INTER_AREA) # a later round at another size + cv2.imwrite(str(d / f"mosaic_{r:03d}.png"), img) + (d / "mosaic.json").write_text(json.dumps({"um_per_px": 2.0, "mosaic_scale": 0.5}), encoding="utf-8") + return d + + +def test_masks_find_the_dish_agar_and_oat(): + g = cv2.resize(dish_image(), None, fx=oa.WORK_SCALE, fy=oa.WORK_SCALE, interpolation=cv2.INTER_AREA) + dish = oa.dish_mask(g) + assert dish[100, 100] == 1 and dish[2, 2] == 0 + agar = oa.agar_mask(g, dish) + assert agar[100, 100] == 1 and agar[100, 190] == 0 + oat = oa.oat_mask(g, dish, (250, 350, 350, 450)) + assert oat[100, 75] == 1 and oat.sum() < 200 + with pytest.raises(SystemExit, match="no black object"): + oa.oat_mask(g, dish, (600, 600, 700, 700)) + + +def test_run_measures_how_far_the_plasmodium_is_from_the_oat(tmp_path, capsys): + d = oat_series(tmp_path) + out = oa.run(d, (250, 350, 350, 450)) + rows = list(csv.DictReader(out.open(encoding="utf-8"))) + assert [r["round"] for r in rows] == ["0", "1"] and (d / "oat_approach_check.png").exists() + assert float(rows[1]["total_mm2"]) > float(rows[0]["total_mm2"]) > 0 + assert float(rows[0]["nearest_mm"]) < float(rows[0]["mean_dist_mm"]) + assert any(float(rows[0][k]) > 0 for k in rows[0] if k.startswith("band_")) + assert "oat area" in capsys.readouterr().out + + +def test_run_without_stitched_rounds_stops(tmp_path): + d = oat_series(tmp_path) + for p in d.glob("mosaic_*.png"): + p.unlink() + with pytest.raises(SystemExit, match="no stitched rounds"): + oa.run(d, (250, 350, 350, 450)) + + +def test_oat_main_parses_the_box(tmp_path, monkeypatch): + seen = [] + monkeypatch.setattr(oa, "run", lambda d, box: seen.append((d, box))) + monkeypatch.setattr(sys, "argv", ["oat", str(tmp_path), "--oat-box", "1,2,3,4"]) + oa.main() + assert seen == [(tmp_path, (1, 2, 3, 4))] + + +# ---- physarum_rhythm ------------------------------------------------------------------------------- + +def rhythm_series(tmp_path, n=60, dt=10.0, period=120.0, calibrated=True, osc=True): + """Left half: dark organism pulsing with `period`; right half: steady bright agar.""" + d = tmp_path / "rhythm" + d.mkdir() + rng = np.random.default_rng(0) + with (d / "frames.csv").open("w", newline="", encoding="utf-8") as f: + w = csv.DictWriter(f, fieldnames=["frame", "t_seconds", "filename", "error"]) + w.writeheader() + for i in range(n): + t = i * dt + img = np.full((100, 100), 200.0) + img[:, :50] = 80 + (18 * np.sin(2 * np.pi * t / period) if osc else 0) + img[:, :50] += np.linspace(-12, 12, 50) # a real image is never two flat values + img[:, 50:] += np.linspace(-12, 12, 50) + img += rng.normal(0, 0.6, img.shape) + Image.fromarray(np.clip(np.stack([img] * 3, -1), 0, 255).astype(np.uint8)).save(d / f"f{i:05d}.png") + w.writerow({"frame": i, "t_seconds": t, "filename": f"f{i:05d}.png", "error": ""}) + if calibrated: + (d / "calibration.json").write_text(json.dumps({"um_per_px": 1.5}), encoding="utf-8") + return d + + +def test_pixel_size_comes_only_from_a_measurement(tmp_path): + assert pr._um_per_px(tmp_path) is None + (tmp_path / "calibration.json").write_text("{not json") + assert pr._um_per_px(tmp_path) is None + (tmp_path / "calibration.json").write_text(json.dumps({"um_per_px": 0})) + assert pr._um_per_px(tmp_path) is None + (tmp_path / "calibration.json").write_text(json.dumps({"um_per_px": 1.49})) + assert pr._um_per_px(tmp_path) == 1.49 + + +def test_series_loading_skips_bad_rows_and_demands_enough_frames(tmp_path): + d = rhythm_series(tmp_path) + with (d / "frames.csv").open("a", encoding="utf-8") as f: + f.write("60,600,,boom\n61,610,missing.png,\n") + times, stack, names = pr._load_series(d) + assert len(times) == 60 and stack.shape == (60, 20, 20) and names[0] == "f00000.png" + few = tmp_path / "few" + few.mkdir() + (few / "frames.csv").write_text("frame,t_seconds,filename,error\n", encoding="utf-8") + with pytest.raises(SystemExit, match="too few to analyse"): + pr._load_series(few) + + +def test_dominant_period_finds_the_pulse_and_rejects_noise(): + t = np.arange(60) * 10.0 + pulse = np.sin(2 * np.pi * t / 120.0) + noise = np.random.default_rng(1).normal(0, 1, 60) + period, strength = pr._dominant_period(np.column_stack([pulse, noise]), 10.0) + assert period[0] == pytest.approx(120.0, rel=0.1) and strength[0] > 0.5 > strength[1] + + +def test_dominant_period_needs_a_search_band(): + with pytest.raises(SystemExit, match="no FFT bins"): + pr._dominant_period(np.random.default_rng(0).normal(size=(10, 3)), 5000.0) + + +def test_regions_split_bright_from_dark(tmp_path): + _, stack, _ = pr._load_series(rhythm_series(tmp_path)) + bright, dark = pr._regions(stack) + assert dark[:, :8].all() and bright[:, 12:].all() and not (bright & dark).any() + + +def test_the_pulsing_region_is_identified_as_the_organism(tmp_path): + res = pr.analyse(rhythm_series(tmp_path)) + assert res["organism_region"] == "dark" and res["organism_identified_by"] == "rhythmicity" + assert res["period_s"] == pytest.approx(120.0, rel=0.15) and res["rhythmic_margin"] > 0.3 + assert res["frames_used"] == 60 and res["interval_s"] == 10.0 and res["um_per_px"] == 1.5 + assert res["area_start_mm2"] is not None and res["growth_rate_mm2_per_h"] is not None + assert len(res["trace_t_s"]) == len(res["trace_intensity"]) == len(res["trace_area_px"]) == 60 + assert set(res["period_map_percentiles"]) == {"5", "25", "50", "75", "95"} + assert res["region_scores"]["dark"]["rhythmic_fraction"] > res["region_scores"]["bright"]["rhythmic_fraction"] + + +def test_without_calibration_areas_stay_in_pixels(tmp_path): + res = pr.analyse(rhythm_series(tmp_path, calibrated=False)) + assert res["um_per_px"] is None and res["area_start_mm2"] is None and res["growth_rate_mm2_per_h"] is None + assert res["area_start_px"] > 0 + + +def test_rhythm_main_reports_and_writes_json(tmp_path, monkeypatch, capsys): + d = rhythm_series(tmp_path) + out = tmp_path / "res.json" + monkeypatch.setattr(sys, "argv", ["physarum_rhythm", str(d), "--json", str(out)]) + pr.main() + text = capsys.readouterr().out + assert "contraction period" in text and "growth rate" in text and "measured" in text + assert json.loads(out.read_text())["organism_region"] == "dark" + + +def test_rhythm_main_warns_when_the_regions_cannot_be_told_apart(tmp_path, monkeypatch, capsys): + d = rhythm_series(tmp_path, calibrated=False, osc=False) # nothing pulses anywhere + monkeypatch.setattr(sys, "argv", ["physarum_rhythm", str(d)]) + pr.main() + text = capsys.readouterr().out + assert "WARNING" in text and "no calibration.json" in text + + +# ---- live_view --------------------------------------------------------------------------------------------- + +def touch(path, age_s): + path.parent.mkdir(parents=True, exist_ok=True) + Image.new("RGB", (40, 30), (9, 9, 9)).save(path) + t = time.time() - age_s + os.utime(path, (t, t)) + return path + + +def test_newest_image_ignores_the_published_copy(tmp_path): + assert live_view.newest_image(tmp_path) is None + touch(tmp_path / "a.png", 100) + new = touch(tmp_path / "sub" / "b.png", 10) + touch(tmp_path / "latest.jpg", 0) + assert live_view.newest_image(tmp_path) == new + + +def test_newest_run_looks_only_at_mosaic_and_timelapse_folders(tmp_path): + assert live_view.newest_run(tmp_path) is None + old = tmp_path / "mosaic_a" + new = tmp_path / "timelapse_b" + other = tmp_path / "notes" + for p, age in ((old, 100), (new, 10), (other, 0)): + p.mkdir() + os.utime(p, (time.time() - age,) * 2) + (tmp_path / "mosaic_file").write_text("x") + assert live_view.newest_run(tmp_path) == new + + +class Stop(BaseException): + pass + + +def run_serve(monkeypatch, watch, out, ticks): + calls = [] + + def sleep(s): + calls.append(s) + if len(calls) >= ticks: + raise Stop + + monkeypatch.setattr(live_view.time, "sleep", sleep) + with pytest.raises(Stop): + live_view.serve(watch, out, fps=2.0, width=32) + return calls + + +def test_serve_publishes_a_frame_only_once_its_size_has_settled(tmp_path, monkeypatch, capsys): + watch = tmp_path / "mosaic_run" + touch(watch / "mosaic_000.png", 5) + out = tmp_path / "live" + calls = run_serve(monkeypatch, watch, out, ticks=3) + assert calls == [0.5, 0.5, 0.5] + assert Image.open(out / "latest.jpg").size[0] <= 32 + page = (out / "index.html").read_text(encoding="utf-8") + assert "mosaic_run" in page and "500" in page and "__DIR__" not in page + assert "OPEN THIS" in capsys.readouterr().out + + +def test_serve_retries_a_truncated_image(tmp_path, monkeypatch): + watch = tmp_path / "timelapse_run" + watch.mkdir() + (watch / "f.png").write_bytes(b"\x89PNG not finished") + run_serve(monkeypatch, watch, tmp_path / "live", ticks=4) + assert not (tmp_path / "live" / "latest.jpg").exists() + + +def test_live_main_needs_a_run_to_watch(tmp_path, monkeypatch): + monkeypatch.setattr(live_view, "data_root", lambda: tmp_path) + monkeypatch.setattr(sys, "argv", ["live_view"]) + with pytest.raises(SystemExit, match="no run folder"): + live_view.main() + + +def test_live_main_serves_the_given_or_newest_run(tmp_path, monkeypatch): + seen = [] + monkeypatch.setattr(live_view, "serve", lambda *a: seen.append(a)) + monkeypatch.setattr(sys, "argv", ["live_view", str(tmp_path), "--fps", "4", "--width", "640"]) + live_view.main() + assert seen[0] == (tmp_path, tmp_path / "_live", 4.0, 640) + newest = tmp_path / "data" / "mosaic_x" + newest.mkdir(parents=True) + monkeypatch.setattr(live_view, "data_root", lambda: tmp_path) + monkeypatch.setattr(sys, "argv", ["live_view"]) + live_view.main() + assert seen[1][0] == newest + + +def test_analysis_scripts_run_with_dash_m(monkeypatch): + for module in ("analysis.make_movie", "analysis.oat_approach", "analysis.physarum_rhythm", "analysis.live_view"): + monkeypatch.setattr(sys, "argv", ["x", "--help"]) + with pytest.raises(SystemExit) as exc: + runpy.run_module(module, run_name="__main__") + assert exc.value.code == 0 + + +class FakeEntry: + name = "x.png" + + def stat(self): + raise OSError("vanished") + + +def test_a_file_that_vanishes_mid_scan_is_skipped(tmp_path, monkeypatch): + keep = touch(tmp_path / "keep.png", 5) + monkeypatch.setattr(live_view.Path, "rglob", lambda self, pattern: [FakeEntry(), keep]) + assert live_view.newest_image(tmp_path) == keep + + +def test_serve_keeps_watching_after_an_error(tmp_path, monkeypatch): + def boom(root): + raise RuntimeError("disk hiccup") + + monkeypatch.setattr(live_view, "newest_image", boom) + calls = run_serve(monkeypatch, tmp_path, tmp_path / "live", ticks=3) + assert len(calls) == 3 diff --git a/tests/test_analysis_video.py b/tests/test_analysis_video.py new file mode 100644 index 0000000..be3e312 --- /dev/null +++ b/tests/test_analysis_video.py @@ -0,0 +1,413 @@ +# analysis/make_soundtrack.py, short_video.py, physarum_short.py and +# worm_short.py: audio synthesis, the video writer (against a fake ffmpeg) and +# both "short" builders on tiny synthetic inputs, with the durations shrunk so +# a run renders a couple of dozen frames instead of a thousand. +import csv +import datetime +import importlib +import runpy +import sys +import types +import wave +from pathlib import Path +from types import SimpleNamespace as NS + +import cv2 +import numpy as np +import pytest +from PIL import Image + +from analysis import make_soundtrack as ms, physarum_short as ps, short_video as sv +from tests.fakes_nd2 import UM_PX, install_nd2, neurons, worm_td + + +# ---- fake ffmpeg --------------------------------------------------------------------------- + +class FakeProc: + def __init__(self, cmd, code=0): + self.cmd, self.code, self.written, self.closed = cmd, code, 0, False + proc = self + + class Stdin: + def write(self, data): + proc.written += len(data) + + def close(self): + proc.closed = True + + self.stdin = Stdin() + + def wait(self): + return self.code + + +@pytest.fixture +def ffmpeg(monkeypatch): + procs, runs = [], [] + mod = types.ModuleType("imageio_ffmpeg") + mod.get_ffmpeg_exe = lambda: "ffmpeg" + mod.count_frames_and_secs = lambda path: (300, 12.5) + monkeypatch.setitem(sys.modules, "imageio_ffmpeg", mod) + monkeypatch.setattr(sv.subprocess, "Popen", lambda cmd, **kw: procs.append(FakeProc(cmd)) or procs[-1]) + monkeypatch.setattr(ms.subprocess, "run", lambda cmd, check: runs.append(cmd)) + return NS(procs=procs, runs=runs) + + + +# ---- make_soundtrack ----------------------------------------------------------------------------- + +def test_midi_pitches(): + assert ms.midi(69) == 440.0 and ms.midi(57) == pytest.approx(220.0) and ms.midi(81) == pytest.approx(880.0) + + +def test_render_is_a_normalised_stereo_mix_with_fades(): + mix = ms.render(2.0) + assert mix.shape == (int(ms.SR * 2.0), 2) + assert np.abs(mix).max() == pytest.approx(10 ** (-1 / 20)) + assert abs(mix[0]).max() < 0.01 and abs(mix[-50:]).max() < 0.05 # faded in and out + assert np.array_equal(mix, ms.render(2.0)) and not np.array_equal(mix, ms.render(2.0, seed=8)) + + +def test_wav_round_trip(tmp_path): + mix = np.stack([np.sin(np.linspace(0, 60, 4410)), np.cos(np.linspace(0, 60, 4410))], axis=1) + path = tmp_path / "t.wav" + ms.write_wav(mix, path) + with wave.open(str(path)) as w: + assert (w.getnchannels(), w.getsampwidth(), w.getframerate(), w.getnframes()) == (2, 2, ms.SR, 4410) + + +def test_movie_length_and_muxing_use_ffmpeg(ffmpeg, tmp_path): + assert ms.movie_seconds(tmp_path / "m.mp4") == 12.5 + ms.mux(tmp_path / "m.mp4", tmp_path / "a.wav", tmp_path / "out.mp4") + cmd = ffmpeg.runs[0] + assert cmd[0] == "ffmpeg" and "-shortest" in cmd and cmd[-1] == str(tmp_path / "out.mp4") + + +def test_soundtrack_main_for_a_plain_duration(tmp_path, monkeypatch, capsys): + monkeypatch.setattr(ms, "render", lambda dur, seed: np.zeros((100, 2))) + out = tmp_path / "s.wav" + monkeypatch.setattr(sys, "argv", ["make_soundtrack", "--duration", "3", "--out", str(out), "--seed", "9"]) + ms.main() + assert out.exists() and "wrote" in capsys.readouterr().out + + +def test_soundtrack_main_matches_the_movie(tmp_path, monkeypatch, ffmpeg): + seen = [] + monkeypatch.setattr(ms, "render", lambda dur, seed: (seen.append(dur), np.zeros((100, 2)))[1]) + movie = tmp_path / "clip.mp4" + monkeypatch.setattr(sys, "argv", ["make_soundtrack", "--movie", str(movie)]) + ms.main() + assert seen == [12.5] and (tmp_path / "clip_soundtrack.wav").exists() + assert ffmpeg.runs[0][-1] == str(tmp_path / "clip_music.mp4") + + +def test_soundtrack_main_defaults_to_the_score_length(tmp_path, monkeypatch): + seen = [] + monkeypatch.setattr(ms, "render", lambda dur, seed: (seen.append(dur), np.zeros((10, 2)))[1]) + monkeypatch.chdir(tmp_path) + monkeypatch.setattr(sys, "argv", ["make_soundtrack"]) + ms.main() + assert seen == [ms.SCORE_S] and (tmp_path / "soundtrack.wav").exists() + + +# ---- short_video --------------------------------------------------------------------------------------- + +def test_fonts_fall_back_and_are_cached(): + a = sv.font("C:/definitely/not/here.ttf", 30) + assert a is sv.font("C:/definitely/not/here.ttf", 30) and a is not sv.font("C:/definitely/not/here.ttf", 31) + assert sv.font(sv.FONT_B, 24) is not None + + +def test_canvas_and_centred_text(): + c = sv.canvas() + assert c.size == (sv.VW, sv.VH) and c.getpixel((0, 0)) == sv.BG + from PIL import ImageDraw + d = ImageDraw.Draw(c) + sv.centred(d, 100, "hello", sv.font(sv.FONT_R, 60)) + xs = np.nonzero((np.asarray(c)[100:200] != np.array(sv.BG)).any(axis=2))[1] + assert xs.size and abs((xs.min() + xs.max()) / 2 - sv.VW / 2) < 40 # drawn around the middle + + +def test_short_wav_clips_instead_of_wrapping(tmp_path): + sv.write_wav(np.array([[2.0, -2.0], [0.5, -0.5]]), tmp_path / "c.wav") + with wave.open(str(tmp_path / "c.wav")) as w: + data = np.frombuffer(w.readframes(2), np.int16) + assert list(data[:2]) == [32767, -32767] + + +def test_preview_writer_saves_only_the_chosen_stills(tmp_path): + w = sv.ShortWriter(tmp_path / "o.mp4", None, preview=True, stills={1, 3}) + img = sv.canvas() + assert [w.wants(i) for i in range(4)] == [False, True, False, True] + for i in range(4): + w.emit(img, i) + w.close() + assert sorted(p.name for p in tmp_path.glob("_preview_*.png")) == ["_preview_0001.png", "_preview_0003.png"] + + +def test_writer_pipes_raw_frames_to_ffmpeg(ffmpeg, tmp_path): + with sv.ShortWriter(tmp_path / "o.mp4", tmp_path / "a.wav") as w: + w.emit(sv.canvas()) + w.emit(sv.canvas()) + assert w.index == 2 and w.wants(0) + p = ffmpeg.procs[0] + assert p.written == 2 * sv.VW * sv.VH * 3 and p.closed + assert "-i" in p.cmd and str(tmp_path / "a.wav") in p.cmd and "aac" in p.cmd and p.cmd[-1] == str(tmp_path / "o.mp4") + + +def test_writer_without_audio_and_ffmpeg_failure(ffmpeg, tmp_path, monkeypatch): + with sv.ShortWriter(tmp_path / "o.mp4", None) as w: + w.emit(sv.canvas()) + assert "aac" not in ffmpeg.procs[0].cmd + monkeypatch.setattr(sv.subprocess, "Popen", lambda cmd, **kw: FakeProc(cmd, code=1)) + with pytest.raises(RuntimeError, match="ffmpeg failed"): + with sv.ShortWriter(tmp_path / "bad.mp4", None) as w: + w.emit(sv.canvas()) + + +# ---- physarum_short ------------------------------------------------------------------------------------------ + +def test_phase_names_follow_the_hours(): + assert [ps.phase(h) for h in (1, 10, 21, 30)] == [ + "Exploring in every direction", "Spreading toward the food", + "Pulling back & rebuilding", "Holding its network overnight"] + + +def combined_dir(tmp_path): + d = tmp_path / "combined" + d.mkdir() + runs = [] + t0 = datetime.datetime(2026, 9, 23, 8, 0, 0) + for n in range(2): + run = tmp_path / f"run{n}" + run.mkdir() + with (run / "tiles.csv").open("w", newline="", encoding="utf-8") as f: + w = csv.writer(f) + w.writerow(["round", "tile", "wall_clock"]) + for r in range(3): + w.writerow([r, 0, (t0 + datetime.timedelta(hours=n * 3 + r)).isoformat()]) + for r in range(3): + cv2.imwrite(str(run / f"mosaic_{r:03d}.png"), np.full((150, 200, 3), 90 + 30 * r, np.uint8)) + runs.append(run) + (d / "combined_all_script.py").write_text( + "from pathlib import Path\n" + f"RUNS = [Path(r'{runs[0]}'), Path(r'{runs[1]}')]\n" + f"REF = Path(r'{runs[0]}')\n" + "W, H, UM_PX = 200, 150, 8.0\n" + "def to_ref(img, run):\n return img\n" + "# ---- movie setup\nraise RuntimeError('the movie half must never run')\n", encoding="utf-8") + with (d / "oat_approach_all.csv").open("w", newline="", encoding="utf-8") as f: + w = csv.writer(f) + w.writerow(["t_h", "total_mm2"]) + for i in range(12): + w.writerow([i * 0.5, 120 + 5 * i - (i > 8) * 20]) + Image.new("RGB", (200, 200), (30, 160, 60)).save(d / "growth_start_to_end_colour.jpg") + return d + + +@pytest.fixture +def tiny_physarum(monkeypatch): + for name, v in dict(S_HOOK=1, S_INTRO=1, S_TL=2, S_REVEAL=5, S_END=1, FPS=2, DURATION=10, REVEAL_AT=4).items(): + monkeypatch.setattr(ps, name, v) + monkeypatch.setattr(ps, "soundtrack", lambda: np.zeros((100, 2))) + + +def test_the_analysis_script_setup_is_read_but_not_the_movie_half(tmp_path): + ns = ps.load_alignment(combined_dir(tmp_path)) + assert ns["W"] == 200 and len(ns["RUNS"]) == 2 and callable(ns["to_ref"]) + + +def test_the_theme_gets_a_swell_into_the_reveal(monkeypatch): + monkeypatch.setattr(ps, "render", lambda dur: np.random.default_rng(0).normal(0, 0.1, (ps.SR * 2, 2))) + mix = ps.soundtrack() + assert mix.shape == (ps.SR * 2, 2) and np.abs(mix).max() == pytest.approx(10 ** (-1 / 20)) + + +def test_preview_saves_stills_without_encoding(tmp_path, tiny_physarum, capsys): + d = combined_dir(tmp_path) + out = tmp_path / "shorts" / "p.mp4" + out.parent.mkdir() + ps.make(d, out, "caption text", preview=True) + stills = sorted(out.parent.glob("_preview_*.png")) + assert stills and Image.open(stills[0]).size == (1080, 1920) and not out.exists() + assert "preview stills" in capsys.readouterr().out + + +def test_full_render_pipes_every_frame_to_the_encoder(tmp_path, tiny_physarum, ffmpeg, capsys): + d = combined_dir(tmp_path) + out = tmp_path / "shorts" / "p.mp4" + out.parent.mkdir() + ps.make(d, out, "caption text", preview=False) + p = ffmpeg.procs[0] + assert p.written == ps.DURATION * ps.FPS * 1080 * 1920 * 3 and (out.with_suffix(".wav")).exists() + assert "wrote" in capsys.readouterr().out + + +def test_physarum_main_makes_the_output_folder(tmp_path, monkeypatch): + seen = [] + monkeypatch.setattr(ps, "make", lambda *a: seen.append(a)) + d = combined_dir(tmp_path) + monkeypatch.setattr(sys, "argv", ["physarum_short", str(d), "--preview", "--caption", "hi"]) + ps.main() + assert (d / "shorts").is_dir() and seen[0][1] == (d / "shorts" / "physarum_short_growth.mp4").resolve() + assert seen[0][2:] == ("hi", True) + + +# ---- worm_short ------------------------------------------------------------------------------------------------------- + +ws = importlib.import_module("analysis.worm_short") + + +def worm_files(tmp_path, nt=12, dt=60.0, size=128, short_track=False): + """A time series ND2 (via the fake reader) plus a survey worms.csv with three adults.""" + stack = np.zeros((nt, 2, size, size), np.float32) + for t in range(nt): + stack[t, 0] = worm_td(size, p0=(20, 60), p1=(90, 70), seed=t) + stack[t, 1] = neurons(size, centres=((22, 60), (30, 62))) + rows = [] + speeds = {1: 6, 2: 3, 3: 0.5} # px per frame: Explorer, Wanderer, Homebody + for t in range(nt): + for wid, sp in speeds.items(): + if short_track and wid == 3 and t >= 5: + continue # the Homebody leaves the field after frame 4 + rows.append({"t_index": t, "t_s": t * dt, "x_px": 20 + 25 * wid + sp * t, "y_px": 20 + 30 * wid, + "length_mm": 1.0, "stage_estimate": "adult"}) + survey = tmp_path / "scene_survey" + survey.mkdir() + with (survey / "worms.csv").open("w", newline="", encoding="utf-8") as f: + w = csv.DictWriter(f, fieldnames=list(rows[0])) + w.writeheader() + w.writerows(rows) + return stack, survey, [t * dt for t in range(nt)] + + +@pytest.fixture +def tiny_worms(monkeypatch): + consts = dict(S_DARK=1.0, S_FADE=1.0, S_TL=2.0, S_HOLD=1.0, S_MAP=2.0, S_END=1.0, + T_FADE=1.0, T_TL=2.0, T_HOLD=4.0, T_MAP=5.0, T_END=7.0, DURATION=8.0, FPS=2) + for k, v in consts.items(): + monkeypatch.setattr(ws, k, v) + + +def test_nd2_is_split_into_brightfield_and_neuron_channels(tmp_path, monkeypatch): + stack, survey, times = worm_files(tmp_path) + install_nd2(monkeypatch, stack, list("TCYX"), ["TD", "RFP"], times=times) + td, neu, um_px, t_s = ws.load(Path("x.nd2"), "RFP") + assert td.shape == neu.shape == (12, 128, 128) and um_px == UM_PX and t_s[-1] == 660.0 + assert np.allclose(td, stack[:, 0]) and neu.max() > 300 + + +def test_composites_glow_only_where_neurons_are(tmp_path): + stack, _, _ = worm_files(tmp_path) + frames, dark = ws.make_composites(stack[:, 0], stack[:, 1]) + assert len(frames) == 12 and frames[0].shape == (ws.P, ws.P, 3) and frames[0].dtype == np.uint8 + glow_px = dark[int(60 * ws.P / 128), int(22 * ws.P / 128)] + assert glow_px[0] > 100 and glow_px[2] > 100 and glow_px[1] < glow_px[0] # pink on black + assert dark[10, 10].max() < 30 and frames[0][10, 10].mean() > 100 + + +def test_tracks_are_linked_smoothed_and_summarised(tmp_path): + _, survey, _ = worm_files(tmp_path) + tracks, raw_rate, summary = ws.build_tracks(survey / "worms.csv", UM_PX, 2.0, 1.0, 0.5) + assert sorted(tracks) == [1, 2, 3] and all(len(v) == 12 for v in tracks.values()) + assert raw_rate[1] > raw_rate[2] > raw_rate[3] > 0 and summary[1]["frames"] == 12 + assert tracks[1][0][3] == 0.0 and tracks[1][-1][0] == 11.0 + + +def test_stars_are_ranked_by_speed(tmp_path): + _, survey, _ = worm_files(tmp_path) + tracks, raw_rate, summary = ws.build_tracks(survey / "worms.csv", UM_PX, 2.0, 1.0, 0.5) + stars, rate = ws.pick_stars(tracks, summary, []) + assert {n for n, _ in stars.values()} == {"Explorer", "Wanderer", "Homebody"} + assert stars[1][0] == "Explorer" and stars[3][0] == "Homebody" + two, _ = ws.pick_stars(tracks, summary, [1, 3]) + assert [n for n, _ in two.values()] == ["Explorer", "Homebody"] + with pytest.raises(SystemExit, match="at least two tracks"): + ws.pick_stars(tracks, summary, [1]) + with pytest.raises(SystemExit, match="at least two tracks"): + ws.pick_stars({}, {}, []) + + +def test_position_is_interpolated_inside_a_track_only(): + tr = [(0.0, 0.0, 0.0, 0.0), (10.0, 100.0, 50.0, 1.0), (20.0, 100.0, 150.0, 1.0)] + assert ws.pos_at(tr, 5.0) == (50.0, 25.0) + assert ws.pos_at(tr, 20.0) == (100.0, 150.0) + assert ws.pos_at(tr, -1.0) is None and ws.pos_at(tr, 21.0) is None + + +def test_soundtrack_is_a_normalised_stereo_bed(tiny_worms): + mix = ws.soundtrack(12) + assert mix.shape == (int(ws.SR * ws.DURATION), 2) and np.abs(mix).max() == pytest.approx(10 ** (-1 / 20)) + + +def make_args(tmp_path, monkeypatch, **kw): + stack, survey, times = worm_files(tmp_path, **kw) + install_nd2(monkeypatch, stack, list("TCYX"), ["TD", "RFP"], times=times) + return survey + + +def test_preview_saves_stills(tmp_path, monkeypatch, tiny_worms, capsys): + survey = make_args(tmp_path, monkeypatch) + out = tmp_path / "shorts" / "w.mp4" + out.parent.mkdir() + ws.make(Path("x.nd2"), survey, out, "RFP", 0.5, [], preview=True) + text = capsys.readouterr().out + assert list(out.parent.glob("_preview_*.png")) and "Explorer/Homebody" in text and "at least" in text + assert not out.exists() + + +def test_a_full_render_encodes_every_frame(tmp_path, monkeypatch, tiny_worms, ffmpeg): + survey = make_args(tmp_path, monkeypatch) + out = tmp_path / "shorts" / "w.mp4" + out.parent.mkdir() + ws.make(Path("x.nd2"), survey, out, "RFP", 0.5, [1, 2, 3], preview=False) + p = ffmpeg.procs[0] + assert p.written == int(ws.DURATION * ws.FPS) * 1080 * 1920 * 3 and out.with_suffix(".wav").exists() + + +def test_an_hour_long_run_is_described_as_such(tmp_path, monkeypatch, tiny_worms, capsys): + survey = make_args(tmp_path, monkeypatch, nt=7, dt=600.0) # 6 intervals of 10 min = 60 min + out = tmp_path / "shorts" / "w.mp4" + out.parent.mkdir() + ws.make(Path("x.nd2"), survey, out, "RFP", 5.0, [1, 2], preview=True) + assert "10.00 min apart" in capsys.readouterr().out + + +def test_worm_main_builds_default_paths(tmp_path, monkeypatch): + seen = [] + monkeypatch.setattr(ws, "make", lambda *a: seen.append(a)) + nd2 = tmp_path / "scene.nd2" + monkeypatch.setattr(sys, "argv", ["worm_short", str(nd2), "--stars", "1,2,3", "--preview", "--channel", "GFP"]) + ws.main() + nd2_, survey, out, channel, step, stars, preview = seen[0] + assert survey == tmp_path / "scene_survey" and out == (tmp_path / "shorts" / "scene_short.mp4").resolve() + assert (channel, step, stars, preview) == ("GFP", 0.5, [1, 2, 3], True) + assert (tmp_path / "shorts").is_dir() + + +def test_video_scripts_run_with_dash_m(monkeypatch, tmp_path): + for module in ("analysis.make_soundtrack", "analysis.physarum_short", "analysis.worm_short"): + monkeypatch.setattr(sys, "argv", ["x", "--help"]) + with pytest.raises(SystemExit) as exc: + runpy.run_module(module, run_name="__main__") + assert exc.value.code == 0 + + +def test_a_track_that_ends_early_gets_a_hollow_marker_and_every_caption_shows(tmp_path, monkeypatch, capsys): + consts = dict(S_DARK=2.0, S_FADE=1.0, S_TL=2.0, S_HOLD=3.0, S_MAP=2.0, S_END=1.0, + T_FADE=2.0, T_TL=3.0, T_HOLD=5.0, T_MAP=8.0, T_END=10.0, DURATION=11.0, FPS=2) + for k, v in consts.items(): + monkeypatch.setattr(ws, k, v) + stack, survey, times = worm_files(tmp_path, short_track=True) + install_nd2(monkeypatch, stack, list("TCYX"), ["TD", "RFP"], times=times) + out = tmp_path / "shorts" / "w.mp4" + out.parent.mkdir() + ws.make(Path("x.nd2"), survey, out, "RFP", 0.5, [1, 2, 3], preview=True) + assert len(list(out.parent.glob("_preview_*.png"))) >= 4 + + +def test_ticks_and_notes_past_the_end_of_the_track_are_dropped(monkeypatch): + for k, v in dict(DURATION=3.0, T_END=7.0).items(): + monkeypatch.setattr(ws, k, v) + mix = ws.soundtrack(12) + assert mix.shape == (int(ws.SR * 3.0), 2) and np.isfinite(mix).all() diff --git a/tests/test_analysis_worms.py b/tests/test_analysis_worms.py new file mode 100644 index 0000000..677c96d --- /dev/null +++ b/tests/test_analysis_worms.py @@ -0,0 +1,291 @@ +# analysis/aml18_survey.py and analysis/aml18_track.py on a synthetic worm scene +# (a dark worm on agar, glowing neurons at its head) behind a fake ND2 reader. +import csv +import importlib +import sys +import types +from pathlib import Path + +import cv2 +import numpy as np +import pytest + +from tests.fakes_nd2 import UM_PX, install_nd2, neurons, two_channel_stack, worm_td + +PATH = Path("scene.nd2") + + +@pytest.fixture +def survey(monkeypatch): + install_nd2(monkeypatch, two_channel_stack(), list("TZCYX"), ["TD", "RFP"], times=[0.0, 600.0]) + sys.modules.pop("analysis.aml18_survey", None) + mod = importlib.import_module("analysis.aml18_survey") + yield mod + sys.modules.pop("analysis.aml18_survey", None) + + +def channels(td, rfp): + return {"TD": td, "RFP": rfp} + + +# ---- loading ------------------------------------------------------------------------- + +def test_load_collapses_z_and_reads_times(survey): + frames, um_px = survey.load(PATH) + assert um_px == UM_PX and [t for t, _ in frames] == [0.0, 600.0] + td, rfp = frames[0][1]["TD"], frames[0][1]["RFP"] + expected = two_channel_stack()[0, 1] + assert np.allclose(td, expected[0]) # the sharp (middle) plane + assert np.allclose(rfp, expected[1]) # max projection of the stack + + +def test_load_falls_back_to_frame_numbers_without_event_times(monkeypatch, survey): + install_nd2(monkeypatch, two_channel_stack(), list("TZCYX"), ["TD", "RFP"], times=None) + assert [t for t, _ in survey.load(PATH)[0]] == [0.0, 1.0] + + +def test_load_adds_missing_axes(monkeypatch, survey): + install_nd2(monkeypatch, worm_td()[None], ["C", "Y", "X"], ["TD"]) + frames, _ = survey.load(PATH) + assert len(frames) == 1 and frames[0][1]["TD"].shape == (256, 256) + + +def test_load_refuses_multipoint_files(monkeypatch, survey): + install_nd2(monkeypatch, two_channel_stack(), list("TZCYX"), ["TD", "RFP"], extra_sizes={"P": 4}) + with pytest.raises(SystemExit, match="unsupported dimensions"): + survey.load(PATH) + + +# ---- segmentation and measurement ------------------------------------------------------- + +def test_segment_worms_keeps_the_worm_and_drops_debris(survey): + td = worm_td() + cv2.circle(td, (200, 40), 3, 60.0, -1) # a speck well under 2000 um2 + mask = survey.segment_worms(td, UM_PX, 0.85) + assert mask[128, 100] and not mask[40, 200] and mask.dtype == bool + + +def test_longest_path_length_counts_diagonals(survey): + skel = np.zeros((20, 20), bool) + skel[5, 2:12] = True # 9 steps of 1 + path, length = survey.longest_path(skel) + assert length == pytest.approx(9.0) and len(path) == 10 + diag = np.eye(10, dtype=bool) + assert survey.longest_path(diag)[1] == pytest.approx(9 * np.sqrt(2)) + + +def test_neuron_mask_threshold_sits_above_the_background(survey): + mask, thr = survey.neuron_mask(neurons(), UM_PX) + assert thr >= 5.0 and mask[128, 62] and not mask[10, 10] + flat, thr = survey.neuron_mask(np.zeros((32, 32), np.float32), UM_PX) + assert not flat.any() and thr == 5.0 + + +# ---- one frame ------------------------------------------------------------------------------ + +def test_survey_frame_finds_the_worm_and_its_head(survey): + rows, img, thr = survey.survey_frame(channels(worm_td(), neurons()), UM_PX, "RFP", 150, 0.85, "t") + assert len(rows) == 1 and img.shape == (512, 512, 3) and img.dtype == np.uint8 + w = rows[0] + assert w["found_by"] == "TD" and w["stage_estimate"] == "L3" and 0.4 < w["length_mm"] < 0.5 + assert abs(w["head_x_px"] - 62) < 8 and abs(w["head_y_px"] - 128) < 8 # the end with the neurons + assert w["neuron_px"] > 0 and w["width_um"] > 0 + + +def test_survey_frame_needs_both_channels(survey): + with pytest.raises(SystemExit, match="need TD and RFP"): + survey.survey_frame({"TD": worm_td()}, UM_PX, "RFP", 150, 0.85, "t") + + +def test_a_dark_object_with_no_neurons_is_not_a_worm(survey): + rows, _, _ = survey.survey_frame(channels(worm_td(), np.zeros((256, 256), np.float32)), UM_PX, "RFP", 150, 0.85, "t") + assert rows == [] + + +def test_short_objects_and_eggs_are_dropped(survey): + short = worm_td(p0=(100, 128), p1=(120, 128)) # 60 um long + assert survey.survey_frame(channels(short, neurons()), UM_PX, "RFP", 150, 0.85, "t")[0] == [] + egg = np.full((256, 256), 190.0, np.float32) + cv2.circle(egg, (128, 128), 18, 60.0, -1) # as wide as it is long + rows, _, _ = survey.survey_frame(channels(egg, neurons(centres=((128, 128),))), UM_PX, "RFP", 50, 0.85, "t") + assert rows == [] + + +def test_neurons_at_both_ends_give_no_head_call(survey): + both = neurons(centres=((62, 128), (70, 129), (190, 139), (198, 140))) + rows, _, _ = survey.survey_frame(channels(worm_td(), both), UM_PX, "RFP", 150, 0.85, "t") + assert rows[0]["head_x_px"] == "" + + +def test_a_head_at_the_frame_edge_is_not_called(survey): + td = worm_td(p0=(0, 128), p1=(140, 140)) + rows, _, _ = survey.survey_frame(channels(td, neurons(centres=((1, 128), (6, 128), (12, 128)))), + UM_PX, "RFP", 150, 0.85, "t") + assert rows and rows[0]["head_x_px"] == "" and "cut by edge" in rows[0]["stage_estimate"] + + +def test_larvae_seen_only_by_their_neurons_are_found(survey): + flat = np.full((256, 256), 190.0, np.float32) + chain = neurons(centres=[(60 + 8 * i, 128) for i in range(10)], amp=300.0, sigma=2.0) + rows, img, _ = survey.survey_frame(channels(flat, chain), UM_PX, "RFP", 100, 0.85, "t") + assert len(rows) == 1 and rows[0]["found_by"] == "neurons" and rows[0]["width_um"] == "" + + +@pytest.mark.parametrize("p1_x,stage", [(77, "L1"), (130, "L2"), (170, "L3"), (243, "L4")]) +def test_stage_follows_body_length(survey, p1_x, stage): + td = worm_td(p0=(10, 128), p1=(p1_x, 128)) + rows, _, _ = survey.survey_frame(channels(td, neurons(centres=((14, 128), (22, 128), (30, 128)))), + UM_PX, "RFP", 150, 0.85, "t") + assert len(rows) == 1 and rows[0]["stage_estimate"] == stage + + +# ---- whole file ----------------------------------------------------------------------------------- + +def test_analyse_a_time_series_writes_images_and_tables(survey, tmp_path, capsys): + out = survey.analyse(PATH, "RFP", 150, 0.85, out=tmp_path / "out") + assert (out / "survey_t000.png").exists() and (out / "survey_t001.png").exists() + rows = list(csv.DictReader((out / "worms.csv").open(encoding="utf-8"))) + assert [r["t_index"] for r in rows] == ["0", "1"] and "_path" not in rows[0] + counts = list(csv.DictReader((out / "counts.csv").open(encoding="utf-8"))) + assert counts[0]["worms"] == "1" and counts[0]["heads_found"] == "1" + assert "t= 0.0 min" in capsys.readouterr().out + + +def test_analyse_a_single_image_reports_each_worm(monkeypatch, survey, tmp_path, capsys): + install_nd2(monkeypatch, two_channel_stack(t=1), list("TZCYX"), ["TD", "RFP"], times=[0.0]) + monkeypatch.chdir(tmp_path) # the default folder is created next to the file + out = survey.analyse(PATH, "RFP", 150, 0.85) + assert (out / "survey.png").exists() and not (out / "counts.csv").exists() + assert "head found" in capsys.readouterr().out and out.name == "scene_survey" + assert out.resolve().parent == tmp_path.resolve() + + +def test_analyse_with_no_worms_still_writes_a_table(monkeypatch, survey, tmp_path): + empty = np.full((1, 1, 2, 64, 64), 190.0, np.float32) + empty[:, :, 1] = 0 + install_nd2(monkeypatch, empty, list("TZCYX"), ["TD", "RFP"], times=[0.0]) + out = survey.analyse(PATH, "RFP", 150, 0.85, out=tmp_path / "o") + assert (out / "worms.csv").read_text(encoding="utf-8").startswith("t_index,t_s,worm") + + +def test_analyse_stops_if_the_image_cannot_be_written(survey, tmp_path, monkeypatch): + monkeypatch.setattr(survey.cv2, "imwrite", lambda *a: False) + with pytest.raises(SystemExit, match="could not write"): + survey.analyse(PATH, "RFP", 150, 0.85, out=tmp_path / "o") + + +def test_survey_main_parses_the_command_line(survey, tmp_path, monkeypatch): + seen = [] + monkeypatch.setattr(survey, "analyse", lambda *a: seen.append(a)) + monkeypatch.setattr(sys, "argv", ["aml18_survey", "f.nd2", "--neuron-channel", "GFP", "--min-length-um", "99", + "--dark-ratio", "0.7", "--out", str(tmp_path)]) + survey.main() + assert seen == [(Path("f.nd2"), "GFP", 99.0, 0.7, tmp_path)] + + +# ---- aml18_track -------------------------------------------------------------------------------------- + +@pytest.fixture +def track(survey): + sys.modules.pop("analysis.aml18_track", None) + mod = importlib.import_module("analysis.aml18_track") + yield mod + sys.modules.pop("analysis.aml18_track", None) + + +def row(t, x, y, length, stage="L3 ", t_s=None): + return {"t_index": t, "t_s": t * 60 if t_s is None else t_s, "x_px": x, "y_px": y, + "length_mm": length, "stage_estimate": stage} + + +def test_link_follows_a_worm_and_starts_new_tracks_for_strangers(track): + rows = [row(0, 100, 100, 0.5), row(0, 800, 800, 0.5), + row(1, 110, 100, 0.5), # moved 10 px (~15 um): same worm + row(1, 1500, 100, 0.5), # far from everything: a new worm + row(2, 112, 100, 1.5)] # 3x longer: not the same worm + out = track.link(rows, um_px=1.5, max_step_mm=1.0) + assert out[2]["track"] == out[0]["track"] and out[2]["step_mm"] == pytest.approx(0.015) + assert len({r["track"] for r in out}) == 4 + assert out[0]["step_mm"] == "" and out[4]["track"] not in (out[0]["track"], out[2]["track"]) + + +def test_link_gives_each_worm_at_most_one_match(track): + rows = [row(0, 100, 100, 0.5), row(1, 105, 100, 0.5), row(1, 108, 100, 0.5)] + out = track.link(rows, um_px=1.5, max_step_mm=1.0) + assert out[1]["track"] == out[0]["track"] and out[2]["track"] != out[0]["track"] + + +def test_summarise_gives_distance_speed_and_stage(track): + rows = track.link([row(0, 0, 0, 0.5, "L2 x"), row(1, 100, 0, 0.5, "L3 y"), row(2, 200, 0, 0.5, "L3 y"), + row(0, 900, 900, 0.4, "L1 ")], 2.0, 1.0) + s = {r["track"]: r for r in track.summarise(rows)} + first = s[min(s)] + assert first["frames"] == 3 and first["distance_mm"] == 0.4 and first["stage"] == "L3" + assert first["mean_speed_mm_per_min"] == pytest.approx(0.2) and first["median_length_mm"] == 0.5 + lone = s[max(s)] + assert lone["frames"] == 1 and lone["mean_speed_mm_per_min"] == "" + + +def test_draw_tracks_writes_an_overlay_or_nothing(track, tmp_path): + base = tmp_path / "survey_t000.png" + cv2.imwrite(str(base), np.full((200, 200, 3), 90, np.uint8)) + rows = track.link([row(0, 20, 20, 0.5), row(1, 30, 25, 0.5), row(0, 80, 80, 0.5)], 1.5, 1.0) + dest = tmp_path / "tracks.png" + track.draw_tracks(base, rows, dest) + assert dest.exists() + track.draw_tracks(tmp_path / "missing.png", rows, tmp_path / "none.png") + assert not (tmp_path / "none.png").exists() + + +def fake_ffmpeg(monkeypatch): + sent = [] + + class Writer: + def send(self, frame): + sent.append(frame) + + def close(self): + sent.append("closed") + + mod = types.ModuleType("imageio_ffmpeg") + mod.write_frames = lambda dest, size, **kw: (sent.append(("open", dest, size, kw["fps"])), Writer())[1] + monkeypatch.setitem(sys.modules, "imageio_ffmpeg", mod) + return sent + + +def test_movie_needs_two_frames_and_writes_even_dimensions(track, tmp_path, monkeypatch): + sent = fake_ffmpeg(monkeypatch) + assert track.movie(tmp_path, 6) is None + for i in range(3): + cv2.imwrite(str(tmp_path / f"survey_t{i:03d}.png"), np.full((101, 99, 3), i * 40, np.uint8)) + dest = track.movie(tmp_path, 6) + assert dest == tmp_path / "survey_movie.mp4" + assert sent[0] == ("open", str(dest), (98, 100), 6) and sent[-1] == "closed" + assert sum(isinstance(s, np.ndarray) for s in sent) == 3 + + +def test_signal_per_frame_reports_the_brightest_neurons(track): + sig = track.signal_per_frame(PATH, "RFP") + assert [s["t_min"] for s in sig] == [0.0, 10.0] and sig[0]["max"] > 300 and sig[0]["p99_9"] > 0 + + +def test_track_main_end_to_end(survey, track, tmp_path, monkeypatch, capsys): + folder = survey.analyse(PATH, "RFP", 150, 0.85, out=tmp_path / "scene_survey") + fake_ffmpeg(monkeypatch) + monkeypatch.setattr(sys, "argv", ["aml18_track", str(PATH), "--survey", str(folder), "--fps", "4"]) + track.main() + out = capsys.readouterr().out + assert "tracks" in out and "RFP brightest-neuron level" in out + for name in ("tracks.csv", "track_summary.csv", "tracks.png", "signal.csv"): + assert (folder / name).exists(), name + summary = list(csv.DictReader((folder / "track_summary.csv").open(encoding="utf-8"))) + assert summary[0]["frames"] == "2" and summary[0]["stage"] == "L3" + + +def test_modules_run_as_scripts(survey, track, monkeypatch): + import runpy + for mod in ("analysis.aml18_survey", "analysis.aml18_track"): + monkeypatch.setattr(sys, "argv", ["x", "--help"]) + with pytest.raises(SystemExit) as exc: + runpy.run_module(mod, run_name="__main__") + assert exc.value.code == 0 diff --git a/tests/test_baumer_genicam.py b/tests/test_baumer_genicam.py new file mode 100644 index 0000000..05e084c --- /dev/null +++ b/tests/test_baumer_genicam.py @@ -0,0 +1,110 @@ +import sys + +import pytest +from PIL import Image + +from tests.fakes_camera import install_fake_camera_stack + + +@pytest.fixture(autouse=True) +def cleanup_module(): + yield + sys.modules.pop("acquisition.backends.baumer_genicam", None) + + +def test_find_cti_files_lists_only_producers(monkeypatch, tmp_path): + mod, _, _ = install_fake_camera_stack(monkeypatch, tmp_path) + found = mod.find_cti_files() + assert len(found) == 1 and found[0].lower().endswith(".cti") + monkeypatch.setenv("GENICAM_GENTL64_PATH", str(tmp_path / "does-not-exist")) + assert mod.find_cti_files() == [] + + +def test_no_producer_is_a_clear_error(monkeypatch, tmp_path): + mod, _, _ = install_fake_camera_stack(monkeypatch, tmp_path) + monkeypatch.setenv("GENICAM_GENTL64_PATH", "") + with pytest.raises(RuntimeError, match="No GenTL producer"): + mod.BaumerGenICam() + + +def test_no_camera_found_resets_harvester(monkeypatch, tmp_path): + mod, _, log = install_fake_camera_stack(monkeypatch, tmp_path, devices=0) + with pytest.raises(RuntimeError, match="no camera was found"): + mod.BaumerGenICam() + assert log["reset"] is True + + +def test_connect_starts_acquisition_and_close_stops_it(monkeypatch, tmp_path): + mod, acq, log = install_fake_camera_stack(monkeypatch, tmp_path) + cam = mod.BaumerGenICam() + assert acq.started and len(log["files"]) == 1 + cam.close() + assert acq.stopped and log["reset"] + + +def test_get_settings(monkeypatch, tmp_path): + mod, _, _ = install_fake_camera_stack(monkeypatch, tmp_path) + s = mod.BaumerGenICam().get_settings() + assert s["exposure_time_us"] == 10000.0 and s["exposure_time_range_us"] == [28.0, 60_000_000.0] + assert s["gain_range"] == [1.0, 251.0] and s["pixel_format"] == "Mono8" + assert s["balance_white_auto"] == "Off" + + +def test_get_settings_without_white_balance(monkeypatch, tmp_path): + mod, _, _ = install_fake_camera_stack(monkeypatch, tmp_path, with_white_balance=False) + assert mod.BaumerGenICam().get_settings()["balance_white_auto"] is None + + +def test_set_settings_turns_autos_off_and_writes(monkeypatch, tmp_path): + mod, acq, _ = install_fake_camera_stack(monkeypatch, tmp_path) + nm = acq.remote_device.node_map + out = mod.BaumerGenICam().set_settings(exposure_time_us=1600, gain=2.0) + assert nm.ExposureTime.value == 1600 and nm.Gain.value == 2.0 + assert nm.ExposureAuto.value == "Off" and nm.GainAuto.value == "Off" + assert out["exposure_time_us"] == 1600 + + +def test_set_settings_touches_only_what_was_passed(monkeypatch, tmp_path): + mod, acq, _ = install_fake_camera_stack(monkeypatch, tmp_path) + nm = acq.remote_device.node_map + mod.BaumerGenICam().set_settings(gain=3.0) + assert nm.Gain.value == 3.0 and nm.ExposureTime.value == 10000.0 + assert nm.ExposureAuto.value == "Continuous" + + +def test_set_settings_without_auto_nodes(monkeypatch, tmp_path): + mod, acq, _ = install_fake_camera_stack(monkeypatch, tmp_path, with_auto=False) + mod.BaumerGenICam().set_settings(exposure_time_us=500, gain=2.0) + assert acq.remote_device.node_map.ExposureTime.value == 500 + + +def test_set_settings_never_clamps(monkeypatch, tmp_path): + mod, acq, _ = install_fake_camera_stack(monkeypatch, tmp_path) + cam = mod.BaumerGenICam() + with pytest.raises(ValueError, match="exposure"): + cam.set_settings(exposure_time_us=1) + with pytest.raises(ValueError, match="gain"): + cam.set_settings(gain=999) + assert acq.remote_device.node_map.ExposureTime.value == 10000.0 + + +@pytest.mark.parametrize("fmt", ["Mono8", "RGB8", "BGR8", "BayerRG8"]) +def test_capture_saves_an_rgb_png_for_each_pixel_format(monkeypatch, tmp_path, fmt): + mod, acq, _ = install_fake_camera_stack(monkeypatch, tmp_path, pixel_format=fmt) + cam = mod.BaumerGenICam() + first, second = cam.capture(), cam.capture() + assert first != second and first.suffix == ".png" + img = Image.open(first) + assert img.mode == "RGB" and img.size == (acq.w, acq.h) + + +def test_capture_drains_stale_frames_first(monkeypatch, tmp_path): + mod, acq, _ = install_fake_camera_stack(monkeypatch, tmp_path) + mod.BaumerGenICam().capture() + assert acq._stale == 0 + + +def test_capture_rejects_unknown_pixel_format(monkeypatch, tmp_path): + mod, _, _ = install_fake_camera_stack(monkeypatch, tmp_path, pixel_format="Weird16") + with pytest.raises(RuntimeError, match="Unsupported camera PixelFormat"): + mod.BaumerGenICam().capture() diff --git a/tests/test_calibration.py b/tests/test_calibration.py new file mode 100644 index 0000000..cc1735b --- /dev/null +++ b/tests/test_calibration.py @@ -0,0 +1,304 @@ +import ctypes +import http.server +import json +import sys +import threading +import time +import types +import urllib.request +from types import SimpleNamespace as NS + +import pytest + +from acquisition import estop +from acquisition.calibration import ti2_config, ti2_inventory +from tests.fakes import fake_ti2 # noqa: F401 (fixture) +from tests.test_nis_bridge import FakeNIS + + +def make_setting(name, control, value=1, lower=0, higher=10, unit="u", enabled=True, long_name=None): + """A COM-style Setting: readable fields named in _prop_map_get_, plus accessor methods.""" + attrs = {"_prop_map_get_": {"Name": 1, "Value": 1, "Lower": 1, "Higher": 1, "Unit": 1, "Enabled": 1, + "Control": 1, "Broken": 1}, + "Name": name, "Value": value, "Lower": lower, "Higher": higher, "Unit": unit, + "Enabled": enabled, "Control": control, + "Broken": property(lambda self: (_ for _ in ()).throw(RuntimeError("unreadable"))), + "LongName": lambda self: long_name or name.upper(), + "ShortName": lambda self: (_ for _ in ()).throw(RuntimeError("no short name"))} + return type("Setting", (), attrs)() + + +@pytest.fixture +def scope(fake_ti2): + sdk, m = fake_ti2 + m.Settings = [make_setting("DiaLampSwitch", 1), make_setting("LightPath", 0, value=2), + make_setting("XPosition", 1, value=5), make_setting("Locked", -1), + make_setting("Mystery", None)] + return sdk, m + + +# ---- ti2_inventory ------------------------------------------------------------- + +def test_setting_fields_come_from_the_type_library(): + fields = ti2_inventory._setting_fields(make_setting("A", 1)) + assert "Name" in fields and "LongName" in fields and "ShortName" in fields + + +def test_read_field_calls_accessors_and_tolerates_failures(): + s = make_setting("A", 1) + assert ti2_inventory._read_field(s, "Name") == "A" + assert ti2_inventory._read_field(s, "LongName") == "A".upper() + assert ti2_inventory._read_field(s, "ShortName") is None + assert ti2_inventory._read_field(s, "Broken") is None + assert ti2_inventory._read_field(s, "Missing") is None + + +def test_inventory_snapshots_every_setting(scope): + rows = ti2_inventory.inventory() + assert [r["Name"] for r in rows] == ["DiaLampSwitch", "LightPath", "XPosition", "Locked", "Mystery"] + assert rows[0]["index"] == 0 and rows[0]["Broken"] is None and rows[1]["Value"] == 2 + + +def test_inventory_reuses_a_given_sdk(scope): + sdk, _ = scope + assert len(ti2_inventory.inventory(sdk.NISSdk())) == 5 + + +def test_inventory_reports_an_unreadable_settings_list(fake_ti2): + sdk, m = fake_ti2 + m.__class__ = type("NoSettings", (type(m),), {"Settings": property(lambda self: (_ for _ in ()).throw(RuntimeError("busy")))}) + rows = ti2_inventory.inventory() + assert rows[0]["_error"] == "RuntimeError: busy" + assert ti2_inventory.format_inventory(rows) == "could not read Settings: RuntimeError: busy" + + +def test_format_inventory_groups_by_control(scope): + text = ti2_inventory.format_inventory(ti2_inventory.inventory()) + assert "Control = 1 (writes took effect)" in text and "writes refused" in text + assert "Control unknown" in text and "5 devices. Fields discovered" in text + custom = ti2_inventory.format_inventory(ti2_inventory.inventory(), columns=["Name"]) + assert "DiaLampSwitch" in custom and "Unit" not in custom.splitlines()[1] + + +def test_inventory_main_prints_and_writes_json(scope, tmp_path, monkeypatch, capsys): + out = tmp_path / "inv.json" + monkeypatch.setattr(sys, "argv", ["inv", "--json", str(out), "--columns", "Name,Control"]) + ti2_inventory.main() + assert "wrote" in capsys.readouterr().out and len(json.loads(out.read_text())) == 5 + monkeypatch.setattr(sys, "argv", ["inv"]) + ti2_inventory.main() + assert "devices" in capsys.readouterr().out + + +# ---- ti2_config ---------------------------------------------------------------- + +def test_motion_and_name_helpers(): + assert ti2_config._is_motion("iXPOSITION") and ti2_config._is_motion("iNOSEPIECE") and ti2_config._is_motion("iZESCAPE") + assert not ti2_config._is_motion("iLIGHTPATH") + assert ti2_config._normalise("iDIA_LAMP_Switch") == ti2_config._normalise("DiaLampSwitch") + + +def test_save_config_joins_values_with_settings_metadata(scope): + cfg = ti2_config.save_config() + assert cfg["property_count"] == 4 and "iBROKEN" not in cfg["properties"] + lamp = cfg["properties"]["iDIA_LAMP_Switch"] + assert lamp["value"] == 1 and lamp["control"] == 1 and lamp["friendly_name"] == "DiaLampSwitch" + assert lamp["lower"] == 0 and lamp["higher"] == 10 + assert cfg["properties"]["iLIGHTPATH"]["control"] == 0 + + +def test_format_config_filters_writable(scope): + cfg = ti2_config.save_config() + both = ti2_config.format_config(cfg) + only = ti2_config.format_config(cfg, only_writable=True) + assert "iDIA_LAMP_Switch" in both and "iDIA_LAMP_Switch" in only + assert "iNOSEPIECE" in both and "iNOSEPIECE" not in only # no matching setting: control unknown + assert "0 .. 10" in both + + +def test_diff_config_lists_what_changed(scope): + sdk, m = scope + cfg = ti2_config.save_config() + assert ti2_config.diff_config(cfg) == [] + cfg["properties"]["iLIGHTPATH"]["value"] = 99 + cfg["properties"]["iXPOSITION"]["value"] = 77 + rows = {r["property"]: r for r in ti2_config.diff_config(cfg)} + assert rows["iLIGHTPATH"]["saved"] == 99 and rows["iLIGHTPATH"]["now"] == 2 and not rows["iLIGHTPATH"]["motion"] + assert rows["iXPOSITION"]["motion"] is True + + +def entry(value, control=1): + return {"value": value, "control": control} + + +@pytest.fixture +def quick(monkeypatch): + monkeypatch.setattr(ti2_config.time, "sleep", lambda s: None) + monkeypatch.setattr(ti2_config, "SETTLE_SECONDS", 0.01) + + +def test_apply_config_reports_each_outcome(scope, quick): + sdk, m = scope + m.__class__ = type("Ignores", (type(m),), { + "iPFS_STATUS": property(lambda self: 7, lambda self, v: None)}) # accepts the write, keeps the value + cfg = {"properties": { + "iLIGHTPATH": entry(4), # written + "iDIA_LAMP_Switch": entry(0), # unchanged (already 0) + "iPFS_STATUS": entry(9), # not-applied + "iNOSEPIECE": entry(5), # motion: skipped + "iXPOSITION": entry(7, control=-1), # not writable: skipped + "iMISSING": entry(1)}} # error + report = ti2_config.apply_config(cfg, sdk.NISSdk()) + assert report["iLIGHTPATH"]["status"] == "written" and m.iLIGHTPATH == 4 + assert report["iDIA_LAMP_Switch"]["status"] == "unchanged" + assert report["iPFS_STATUS"]["status"] == "not-applied" + assert report["iNOSEPIECE"] == {"status": "skipped", "why": "motion device"} + assert report["iXPOSITION"]["why"] == "control=-1" + assert report["iMISSING"]["status"] == "error" and m.iNOSEPIECE == 1 + + +def test_apply_config_with_motion_allowed(scope, quick): + sdk, m = scope + report = ti2_config.apply_config({"properties": {"iNOSEPIECE": entry(5)}}, include_motion=True) + assert report["iNOSEPIECE"]["status"] == "written" and m.iNOSEPIECE == 5 + + +def test_apply_config_waits_for_a_slow_axis_to_settle(scope, monkeypatch): + sdk, m = scope + reads = {"n": 0} + + def slow_get(self): + reads["n"] += 1 + return 4 if reads["n"] > 4 else 1 + + m.__class__ = type("Slow", (type(m),), {"iLIGHTPATH": property(slow_get, lambda self, v: None)}) + slept = [] + monkeypatch.setattr(ti2_config.time, "sleep", lambda s: slept.append(s)) + report = ti2_config.apply_config({"properties": {"iLIGHTPATH": entry(4)}}) + assert report["iLIGHTPATH"]["status"] == "written" and slept + + +def test_apply_config_bulk_uses_dataset(scope): + sdk, m = scope + sent = [] + m.DataSet = lambda data, a, b: sent.append((data, a, b)) + report = ti2_config.apply_config({"properties": {"iLIGHTPATH": entry(4), "iBROKEN": entry(1)}}, bulk=True) + assert report == {"_bulk": {"status": "DataSet issued", "properties": 2}} and len(sent) == 1 + + +def run_main(monkeypatch, *argv): + monkeypatch.setattr(sys, "argv", ["ti2_config", *argv]) + ti2_config.main() + + +def test_config_cli_save_show_diff_apply(scope, quick, tmp_path, monkeypatch, capsys): + path = tmp_path / "cfg.json" + run_main(monkeypatch, "save", "--out", str(path)) + assert path.exists() and "wrote" in capsys.readouterr().out + run_main(monkeypatch, "show", str(path), "--writable") + assert "PROPERTY" in capsys.readouterr().out + run_main(monkeypatch, "diff", str(path)) + assert "no differences" in capsys.readouterr().out + + cfg = json.loads(path.read_text()) + cfg["properties"]["iLIGHTPATH"]["value"] = 4 # restorable + cfg["properties"]["iXPOSITION"]["value"] = 77 # motion + cfg["properties"]["iXPOSITION"]["control"] = 1 + cfg["properties"]["iDIA_LAMP_Switch"]["value"] = 5 + cfg["properties"]["iDIA_LAMP_Switch"]["control"] = -1 # not restorable + path.write_text(json.dumps(cfg)) + run_main(monkeypatch, "diff", str(path)) + out = capsys.readouterr().out + assert "yes" in out and "only with --include-motion" in out and "no (control=-1)" in out and "3 properties differ" in out + cfg["properties"].pop("iXPOSITION") + cfg["properties"].pop("iDIA_LAMP_Switch") + path.write_text(json.dumps(cfg)) + run_main(monkeypatch, "diff", str(path)) + assert "1 property differ" in capsys.readouterr().out + + with pytest.raises(SystemExit, match="--confirm"): + run_main(monkeypatch, "apply", str(path)) + run_main(monkeypatch, "apply", str(path), "--confirm") + out = capsys.readouterr().out + assert "iLIGHTPATH" in out and "written: 1" in out + + +def test_config_cli_default_output_path(scope, tmp_path, monkeypatch, capsys): + monkeypatch.chdir(tmp_path) + run_main(monkeypatch, "save") + assert list((tmp_path / "protocols").glob("optical_config_*.json")) + + +# ---- nis_port_probe (runs inside NIS; here against the fake DLL) ----------------- + +@pytest.fixture +def probe(monkeypatch, tmp_path): + dll = FakeNIS() + limjob = types.ModuleType("limjob") # NIS's job API; the probe annotates with its types + limjob.Image = limjob.JobParam = limjob.MacroParam = limjob.RunContext = object + monkeypatch.setitem(sys.modules, "limjob", limjob) + monkeypatch.setattr(ctypes, "cdll", NS(g5_regprocs=dll), raising=False) + sys.modules.pop("acquisition.calibration.nis_port_probe", None) + import importlib + mod = importlib.import_module("acquisition.calibration.nis_port_probe") + monkeypatch.setattr(mod, "ESTOP", str(tmp_path / "ESTOP")) + yield mod, dll + sys.modules.pop("acquisition.calibration.nis_port_probe", None) + + +def test_probe_status(probe): + mod, dll = probe + s = mod.status() + assert s["xy_um"] == [100.0, 200.0] and s["z_um"] == 4619.0 and s["nosepiece_position"] == 1 + assert s["nosepiece_objectives"] == {i: n for i, n in dll.objectives.items()} + + +def test_probe_move_is_capped_and_blocked_by_estop(probe, tmp_path): + mod, dll = probe + r = mod.move(50, -20) + assert r["after_um"] == [150.0, 180.0] + assert "refused" in mod.move(1000.1, 0)["error"] + (tmp_path / "ESTOP").write_text("{}") + assert "e-stop" in mod.move(1, 0)["error"] and "e-stop" in mod.objective("Plan Fluor 10x Ph1 DLL")["error"] + + +def test_probe_objective_allow_list(probe): + mod, dll = probe + assert "allowed" in mod.objective("Plan Apo 60x Oil")["error"] + r = mod.objective("Plan Fluor 10x Ph1 DLL") + assert r["after"] == "Plan Fluor 10x Ph1 DLL" and r["rc"] == 1 + + +def test_probe_serves_the_three_endpoints_from_run(probe, monkeypatch, tmp_path): + mod, dll = probe + servers = [] + + class Rec(http.server.ThreadingHTTPServer): + def __init__(self, *a, **k): + super().__init__(("127.0.0.1", 0), a[1]) + servers.append(self) + + monkeypatch.setattr(mod.http.server, "ThreadingHTTPServer", Rec) + done = threading.Event() + ctx = NS(shouldAbort=lambda: done.is_set()) + t = threading.Thread(target=mod.run, args=((), None, None, ctx), daemon=True) + t.start() + deadline = time.time() + 5 + while not servers and time.time() < deadline: + time.sleep(0.01) + assert servers, "the probe never started its server" + base = f"http://127.0.0.1:{servers[0].server_address[1]}" + + def get(path): + with urllib.request.urlopen(base + path, timeout=5) as r: + return json.loads(r.read()) + + assert get("/status")["xy_um"] == [100.0, 200.0] + assert get("/move?dx=10&dy=0")["after_um"][0] == 110.0 + assert "allowed" in get("/objective?name=Plan%20Apo%2060x%20Oil")["error"] + assert "use /status" in get("/nothing")["error"] + dll.StgGetPosXY = lambda *a: (_ for _ in ()).throw(RuntimeError("dll fell over")) + assert "RuntimeError" in get("/status")["error"] # a failing call is reported, not fatal + done.set() + t.join(5) + assert not t.is_alive() diff --git a/tests/test_context.py b/tests/test_context.py index 4b2aa67..7126d9f 100644 --- a/tests/test_context.py +++ b/tests/test_context.py @@ -75,3 +75,44 @@ def test_negative_counts_rejected(): prune_context_images([], keep_last_n=-1) with pytest.raises(ValueError): prune_context_images([], keep_first_n=-1) + + +def _tool_result(frame, with_text=True): + inner = ([{"type": "text", "text": f"metadata {frame}"}] if with_text else []) + [ + {"type": "image", "source": {"type": "base64", "data": f"<{frame}>"}}] + return {"role": "user", "content": [{"type": "tool_result", "tool_use_id": frame, "content": inner}]} + + +def _nested_images(msg): + return sum(1 for b in msg["content"] if b.get("type") == "tool_result" + for c in b["content"] if c["type"] == "image") + + +def test_images_inside_tool_results_are_pruned_and_their_text_kept(): + history = [_tool_result("f1"), _tool_result("f2"), _tool_result("f3"), _tool_result("f4")] + pruned = prune_context_images(history, keep_last_n=2) + assert [_nested_images(m) for m in pruned] == [0, 0, 1, 1] + assert pruned[0]["content"][0]["content"] == [{"type": "text", "text": "metadata f1"}] + assert pruned[0]["content"][0]["tool_use_id"] == "f1" # the result still answers its tool call + + +def test_a_tool_result_that_was_only_an_image_is_not_left_empty(): + pruned = prune_context_images([_tool_result("f1", with_text=False), _tool_result("f2")], keep_last_n=1) + assert pruned[0]["content"][0]["content"] == [{"type": "text", "text": "[image removed to save context]"}] + + +def test_nested_pruning_does_not_mutate_the_history_and_mixes_with_top_level_images(): + history = [_tool_result("f1"), _img("f2"), _tool_result("f3")] + snapshot = copy.deepcopy(history) + pruned = prune_context_images(history, keep_last_n=1) + assert history == snapshot + assert _nested_images(pruned[0]) == 0 and not _has_image(pruned[1]) and _nested_images(pruned[2]) == 1 + + +def test_tool_results_without_images_or_with_string_content_are_left_alone(): + plain = {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "a", "content": "just text"}]} + textual = {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "b", + "content": [{"type": "text", "text": "ok"}]}]} + history = [plain, textual, _tool_result("f1")] + pruned = prune_context_images(history, keep_last_n=0) + assert pruned[0] is plain and pruned[1] is textual and _nested_images(pruned[2]) == 0 diff --git a/tests/test_estop.py b/tests/test_estop.py new file mode 100644 index 0000000..526f0cf --- /dev/null +++ b/tests/test_estop.py @@ -0,0 +1,109 @@ +import json +import sys + +import pytest + +from acquisition import estop + + +@pytest.fixture +def flag(tmp_path, monkeypatch): + path = tmp_path / "sub" / "ESTOP" + monkeypatch.setattr(estop, "ESTOP_PATH", path) + return path + + +def test_clear_by_default(flag): + assert estop.is_engaged() is False + assert estop.details() is None + estop.check() # no raise + + +def test_engage_writes_flag_and_blocks_motion(flag): + info = estop.engage("test reason") + assert flag.exists() and info["reason"] == "test reason" + assert estop.is_engaged() + assert estop.details()["reason"] == "test reason" + with pytest.raises(estop.EStopEngaged, match="test reason"): + estop.check() + + +def test_release_allows_motion_and_is_idempotent(flag): + estop.engage() + estop.release() + assert not estop.is_engaged() + estop.release() # already clear: no error + estop.check() + + +def test_unreadable_flag_still_counts_as_engaged(flag): + flag.parent.mkdir(parents=True) + flag.write_text("not json") + assert estop.is_engaged() + assert "unreadable" in estop.details()["reason"] + with pytest.raises(estop.EStopEngaged): + estop.check() + + +def test_fails_safe_when_state_cannot_be_determined(monkeypatch): + class Broken: + def exists(self): + raise PermissionError("denied") + + monkeypatch.setattr(estop, "ESTOP_PATH", Broken()) + assert estop.is_engaged() is True + + +def test_panel_not_running_off_windows(monkeypatch): + monkeypatch.setattr(estop.sys, "platform", "linux") + assert estop.panel_running() is False + + +def test_launch_panel_opt_out_and_already_running(monkeypatch): + opened = [] + monkeypatch.setattr(estop.subprocess, "Popen", lambda *a, **k: opened.append(a)) + monkeypatch.setenv("CONFOCAL_NO_ESTOP_PANEL", "1") + estop.launch_panel() + monkeypatch.delenv("CONFOCAL_NO_ESTOP_PANEL") + monkeypatch.setattr(estop, "panel_running", lambda: True) + estop.launch_panel() + assert opened == [] + + +def test_launch_panel_starts_detached_process(monkeypatch): + opened = [] + monkeypatch.delenv("CONFOCAL_NO_ESTOP_PANEL", raising=False) + monkeypatch.setattr(estop, "panel_running", lambda: False) + monkeypatch.setattr(estop.subprocess, "Popen", lambda *a, **k: opened.append(a[0])) + estop.launch_panel() + assert opened[0][-2:] == ["-m", "acquisition.estop_panel"] + + +def test_launch_panel_failure_goes_to_stderr(monkeypatch, capsys): + def boom(*a, **k): + raise OSError("nope") + + monkeypatch.delenv("CONFOCAL_NO_ESTOP_PANEL", raising=False) + monkeypatch.setattr(estop, "panel_running", lambda: False) + monkeypatch.setattr(estop.subprocess, "Popen", boom) + estop.launch_panel() + out = capsys.readouterr() + assert "could not start the STOP panel" in out.err and out.out == "" + + +def run_cli(monkeypatch, *argv): + monkeypatch.setattr(sys, "argv", ["estop", *argv]) + estop.main() + + +def test_cli_engage_status_release(flag, monkeypatch, capsys): + run_cli(monkeypatch, "status") + assert "clear" in capsys.readouterr().out + run_cli(monkeypatch, "engage", "--reason", "cli") + assert "E-STOP ENGAGED" in capsys.readouterr().out + assert json.loads(flag.read_text())["reason"] == "cli" + with pytest.raises(SystemExit) as exc: + run_cli(monkeypatch, "status") + assert exc.value.code == 2 and "ENGAGED" in capsys.readouterr().out + run_cli(monkeypatch, "release") + assert "released" in capsys.readouterr().out and not flag.exists() diff --git a/tests/test_estop_panel.py b/tests/test_estop_panel.py new file mode 100644 index 0000000..ac06650 --- /dev/null +++ b/tests/test_estop_panel.py @@ -0,0 +1,299 @@ +# The STOP panel against a fake tkinter (no display, no tk needed), plus the +# Windows single-instance mutex paths of the panel and the NIS monitor against +# a fake kernel32, so they run on a Linux CI runner too. +import ctypes +import importlib +import sys +import types +from types import SimpleNamespace as NS + +import pytest + +from acquisition import estop, nis_monitor + + +class Widget: + def __init__(self, master=None, **kw): + self.master, self.opts, self.binds, self.packed = master, dict(kw), {}, None + self.x, self.y = 5, 7 + + def pack(self, **kw): + self.packed = kw + + def configure(self, **kw): + self.opts.update(kw) + + config = configure + + def bind(self, event, fn): + self.binds[event] = fn + + def click(self): + self.opts["command"]() + + +class FakeTk(Widget): + def __init__(self): + super().__init__() + self.geometry_calls, self.attrs, self.after_calls = [], {}, [] + self.destroyed = self.looped = self.borderless = False + + def title(self, t): + self.opts["title"] = t + + def resizable(self, a, b): + pass + + def attributes(self, name, value): + self.attrs[name] = value + + def overrideredirect(self, flag): + self.borderless = flag + + def geometry(self, g): + self.geometry_calls.append(g) + + def after(self, ms, fn): + self.after_calls.append((ms, fn)) + + def winfo_x(self): + return self.x + + def winfo_y(self): + return self.y + + def mainloop(self): + self.looped = True + + def destroy(self): + self.destroyed = True + + +class TclError(Exception): + pass + + +@pytest.fixture +def panel_mod(monkeypatch, tmp_path): + asked = {"yes": True, "errors": []} + tk = types.ModuleType("tkinter") + tk.Tk, tk.Button, tk.Label, tk.Frame, tk.TclError = FakeTk, Widget, Widget, Widget, TclError + mb = types.ModuleType("tkinter.messagebox") + mb.askyesno = lambda title, msg: asked["yes"] + mb.showerror = lambda title, msg: asked["errors"].append(msg) + tk.messagebox = mb + monkeypatch.setitem(sys.modules, "tkinter", tk) + monkeypatch.setitem(sys.modules, "tkinter.messagebox", mb) + monkeypatch.setattr(estop, "ESTOP_PATH", tmp_path / "ESTOP") + sys.modules.pop("acquisition.estop_panel", None) + mod = importlib.import_module("acquisition.estop_panel") + mod.real_claim = mod._claim_single_instance # the tests of the mutex use this + monkeypatch.setattr(mod, "_claim_single_instance", lambda: True) # a real mutex would outlive the test + yield mod, asked + sys.modules.pop("acquisition.estop_panel", None) + + +def make_panel(mod, **kw): + root = FakeTk() + return mod.Panel(root, **kw), root + + +def test_panel_starts_clear_and_polls(panel_mod): + mod, _ = panel_mod + p, root = make_panel(mod) + assert p.status.opts["text"] == "clear - motion permitted" + assert p.release_btn.opts["state"] == "disabled" and p.button.opts["text"] == "STOP" + assert root.attrs["-topmost"] is True and root.borderless is True + assert root.after_calls[0][0] == mod.POLL_MS + + +def test_panel_window_options(panel_mod): + mod, _ = panel_mod + p, root = make_panel(mod, topmost=False, borderless=False) + assert "-topmost" not in root.attrs and root.borderless is False + + +def test_stop_button_engages_and_the_panel_shows_it(panel_mod): + mod, _ = panel_mod + p, _ = make_panel(mod) + p.button.click() + assert estop.is_engaged() and estop.details()["reason"] == "STOP button" + assert p.status.opts["text"].startswith("ENGAGED") and p.button.opts["text"] == "STOPPED" + assert p.release_btn.opts["state"] == "normal" + + +def test_stop_failure_is_reported_but_never_raises(panel_mod, monkeypatch): + mod, asked = panel_mod + p, _ = make_panel(mod) + monkeypatch.setattr(estop, "engage", lambda reason: (_ for _ in ()).throw(OSError("disk full"))) + p.on_stop() + assert "disk full" in asked["errors"][0] + + +def test_release_needs_confirmation(panel_mod): + mod, asked = panel_mod + p, _ = make_panel(mod) + p.on_release() # nothing engaged: nothing to ask + estop.engage("t") + asked["yes"] = False + p.on_release() + assert estop.is_engaged() + asked["yes"] = True + p.release_btn.click() + assert not estop.is_engaged() and p.button.opts["text"] == "STOP" + + +def test_refresh_only_redraws_on_change(panel_mod): + mod, _ = panel_mod + p, _ = make_panel(mod) + p.status.opts["text"] = "sentinel" + p.refresh() + assert p.status.opts["text"] == "sentinel" # unchanged state: left alone + p.refresh(force=True) + assert p.status.opts["text"] == "clear - motion permitted" + + +def test_tick_reschedules_itself_and_sees_an_outside_engage(panel_mod): + mod, _ = panel_mod + p, root = make_panel(mod) + estop.engage("from a terminal") + root.after_calls[-1][1]() + assert p.status.opts["text"].startswith("ENGAGED") and len(root.after_calls) == 2 + + +def test_dragging_moves_the_window(panel_mod): + mod, _ = panel_mod + p, root = make_panel(mod) + p.status.binds[""](NS(x_root=100, y_root=100)) + p.status.binds[""](NS(x_root=130, y_root=150)) + assert root.geometry_calls[-1] == "+35+57" + + +def test_single_instance_claim_off_windows_is_always_true(panel_mod, monkeypatch): + mod, _ = panel_mod + monkeypatch.setattr(sys, "platform", "linux") + assert mod.real_claim() is True + + +def fake_kernel(monkeypatch, *, exists, last_error=0): + calls = [] + k32 = NS(OpenMutexW=lambda *a: 99 if exists else 0, + CloseHandle=lambda h: calls.append(("close", h)), + CreateMutexW=NS(restype=None) and (lambda *a: 7), + GetLastError=lambda: last_error) + # CreateMutexW needs a settable .restype, so use a callable object + class Create: + restype = None + + def __call__(self, *a): + calls.append(("create", a[-1] if a else None)) + return 7 + + k32.CreateMutexW = Create() + monkeypatch.setattr(sys, "platform", "win32") + monkeypatch.setattr(ctypes, "windll", NS(kernel32=k32), raising=False) + return calls + + +def test_panel_claims_the_windows_mutex_once(panel_mod, monkeypatch): + mod, _ = panel_mod + fake_kernel(monkeypatch, exists=False, last_error=0) + assert mod.real_claim() is True + fake_kernel(monkeypatch, exists=True, last_error=183) + assert mod.real_claim() is False + + +def test_main_opens_the_panel(panel_mod, monkeypatch): + mod, _ = panel_mod + made = [] + monkeypatch.setattr(mod.tk, "Tk", lambda: made.append(FakeTk()) or made[-1]) + monkeypatch.setattr(sys, "argv", ["estop_panel", "--no-topmost", "--titlebar"]) + mod.main() + assert made[0].looped and "-topmost" not in made[0].attrs and made[0].borderless is False + + +def test_main_does_nothing_if_a_panel_is_already_open(panel_mod, monkeypatch, capsys): + mod, _ = panel_mod + monkeypatch.setattr(mod, "_claim_single_instance", lambda: False) + monkeypatch.setattr(sys, "argv", ["estop_panel"]) + mod.main() + assert "already open" in capsys.readouterr().err + + +def test_main_explains_a_missing_display(panel_mod, monkeypatch, capsys): + mod, _ = panel_mod + + def no_display(): + raise TclError("no display name") + + monkeypatch.setattr(mod.tk, "Tk", no_display) + monkeypatch.setattr(sys, "argv", ["estop_panel"]) + with pytest.raises(SystemExit) as exc: + mod.main() + assert exc.value.code == 1 and "no display available" in capsys.readouterr().err + + +# ---- Windows mutex probes in estop and nis_monitor ---------------------------------- + +def test_estop_panel_running_reads_the_windows_mutex(monkeypatch): + calls = fake_kernel(monkeypatch, exists=True) + assert estop.panel_running() is True and ("close", 99) in calls + fake_kernel(monkeypatch, exists=False) + assert estop.panel_running() is False + + +def test_monitor_running_reads_the_windows_mutex(monkeypatch): + calls = fake_kernel(monkeypatch, exists=True) + assert nis_monitor.monitor_running() is True and ("close", 99) in calls + fake_kernel(monkeypatch, exists=False) + assert nis_monitor.monitor_running() is False + + +def test_monitor_mutex_is_single_instance(monkeypatch): + monkeypatch.setattr(sys, "platform", "linux") + assert nis_monitor._hold_mutex() is True + fake_kernel(monkeypatch, exists=False, last_error=0) + assert nis_monitor._hold_mutex() == 7 + fake_kernel(monkeypatch, exists=True, last_error=183) + assert nis_monitor._hold_mutex() is None + + +def test_monitor_main_refuses_a_second_window(monkeypatch): + monkeypatch.setattr(nis_monitor, "_hold_mutex", lambda: None) + monkeypatch.setattr(sys, "argv", ["nis_monitor"]) + with pytest.raises(SystemExit, match="already open"): + nis_monitor.main() + + +def test_monitor_main_loop_runs_until_interrupted(monkeypatch, tmp_path, capsys): + monkeypatch.setattr(nis_monitor, "_hold_mutex", lambda: 1) + monkeypatch.setattr(nis_monitor.nis_events, "events_dir", lambda: tmp_path / "ev") + monkeypatch.setattr(nis_monitor, "fetch_status", lambda url: ("down", None)) + monkeypatch.setattr(estop, "ESTOP_PATH", tmp_path / "ESTOP") + sleeps = [] + + def sleep(s): + sleeps.append(s) + if len(sleeps) >= 2: + raise KeyboardInterrupt + + monkeypatch.setattr(nis_monitor.time, "sleep", sleep) + monkeypatch.setattr(sys, "argv", ["nis_monitor", "--interval", "0.5"]) + nis_monitor.main() + assert sleeps == [0.5, 0.5] and "NIS monitor" in capsys.readouterr().out + + +def test_monitor_main_starts_a_new_log_after_midnight(monkeypatch, tmp_path, capsys): + import datetime + days = iter([datetime.date(2026, 10, 15), datetime.date(2026, 10, 15), datetime.date(2026, 10, 16), + datetime.date(2026, 10, 16), datetime.date(2026, 10, 16)]) + monkeypatch.setattr(nis_monitor, "_hold_mutex", lambda: 1) + monkeypatch.setattr(nis_monitor.nis_events, "events_dir", lambda: tmp_path / "ev") + monkeypatch.setattr(nis_monitor.nis_events, "events_path", + lambda day=None: tmp_path / f"{next(days).isoformat()}.jsonl") + monkeypatch.setattr(nis_monitor, "fetch_status", lambda url: ("down", None)) + monkeypatch.setattr(estop, "ESTOP_PATH", tmp_path / "ESTOP") + n = [] + monkeypatch.setattr(nis_monitor.time, "sleep", lambda s: (n.append(1), n.__len__() > 1 and (_ for _ in ()).throw(KeyboardInterrupt))[0]) + monkeypatch.setattr(sys, "argv", ["nis_monitor"]) + nis_monitor.main() diff --git a/tests/test_hardware_scripts.py b/tests/test_hardware_scripts.py new file mode 100644 index 0000000..081a7fe --- /dev/null +++ b/tests/test_hardware_scripts.py @@ -0,0 +1,236 @@ +# The hardware experiment scripts (estop_inflight_test, read_during_move_test) +# and every module's `python -m` entry point, run against the fake Ti2 and +# the mock stage. Their 60 s / 20 s safety timers and os._exit calls are +# replaced so nothing waits and the test process is never killed. +import importlib +import os +import runpy +import sys +import threading +import time +from pathlib import Path + +import pytest + +from acquisition import estop +from acquisition.backends import nis_mock +from tests.fakes import fake_ti2 # noqa: F401 (fixture) + +ROOT = Path(__file__).parent.parent + + +class InstantTimer: + """threading.Timer that runs its function at start() (or never, if told to).""" + fire = True + started = [] + + def __init__(self, interval, fn, *a): + self.interval, self.fn, self.a = interval, fn, a + + def start(self): + InstantTimer.started.append(self.interval) + if InstantTimer.fire and self.interval < 10: # the 20 s and 60 s safety timers never fire + self.fn(*self.a) + + def is_alive(self): + return False + + +@pytest.fixture +def scripts(fake_ti2, monkeypatch, tmp_path): + sdk, m = fake_ti2 + InstantTimer.fire, InstantTimer.started = True, [] + monkeypatch.setattr(threading, "Timer", InstantTimer) + real_sleep = time.sleep + monkeypatch.setattr(time, "sleep", lambda s: real_sleep(0.001)) + exits = [] + monkeypatch.setattr(os, "_exit", lambda code: exits.append(code)) + monkeypatch.setattr(estop, "ESTOP_PATH", tmp_path / "ESTOP") + monkeypatch.setattr(sys, "coinit_flags", 0, raising=False) + sys.modules.pop("acquisition.estop_inflight_test", None) + mod = importlib.import_module("acquisition.estop_inflight_test") + yield mod, m, exits + sys.modules.pop("acquisition.estop_inflight_test", None) + + +def sticky(m, attr, setter): + """Make `attr` on the fake microscope store through `setter`.""" + store = {"v": getattr(m, attr)} + m.__class__ = type("Sticky", (type(m),), { + attr: property(lambda self: store["v"], lambda self, v: store.__setitem__("v", setter(store["v"], v)))}) + return store + + +# ---- estop_inflight_test ------------------------------------------------------ + +def test_log_names_the_thread(scripts, capsys): + mod, m, _ = scripts + mod.log("hello") + assert "hello" in capsys.readouterr().out + + +def test_z_test_reports_a_move_the_halt_did_not_stop(scripts, capsys): + mod, m, _ = scripts + start = m.iZPOSITION + mod.test_z() + out = capsys.readouterr().out + assert m.iZPOSITION == start - 100_000 and "halt did not stop it" in out + + +def test_z_test_reports_a_halt_that_reverses_the_move(scripts, capsys): + mod, m, _ = scripts + sticky(m, "iZPOSITION", lambda old, new: old) # every write is ignored: back at the start + mod.test_z() + assert "Z back at start" in capsys.readouterr().out + + +def test_z_test_reports_a_partial_move(scripts, capsys): + mod, m, _ = scripts + sticky(m, "iZPOSITION", lambda old, new: (old + new) // 2) # only half way + mod.test_z() + assert "halt works on Z" in capsys.readouterr().out + + +def test_z_test_logs_a_failed_write_and_a_failed_halt(scripts, capsys): + mod, m, _ = scripts + + def boom(old, new): + raise RuntimeError("controller busy") + + sticky(m, "iZPOSITION", boom) + mod.test_z() + out = capsys.readouterr().out + assert "set iZPOSITION failed" in out and "write-back failed: controller busy" in out + + +def test_z_test_will_not_move_below_the_travel_range(scripts, capsys): + mod, m, _ = scripts + m.ZPosition.Lower = m.iZPOSITION # no room to drop 1 mm + start = m.iZPOSITION + mod.test_z() + assert m.iZPOSITION == start and "not moving" in capsys.readouterr().out + + +def test_z_test_refuses_under_estop(scripts): + mod, m, _ = scripts + estop.engage("t") + with pytest.raises(estop.EStopEngaged): + mod.test_z() + + +def test_xy_test_is_stopped_by_the_estop_engaging_mid_move(scripts, capsys): + mod, m, _ = scripts + mod.test_xy() + out = capsys.readouterr().out + assert "stopped by e-stop" in out and "kept moving" in out and estop.is_engaged() + + +def test_xy_test_reports_a_move_that_nothing_stopped(scripts, capsys): + mod, m, _ = scripts + InstantTimer.fire = False + mod.test_xy() + assert "WITHOUT being stopped" in capsys.readouterr().out and m.iXPOSITION == round((100 + 20000) * 10) + + +def test_xy_test_refuses_under_estop(scripts): + mod, m, _ = scripts + estop.engage("t") + with pytest.raises(estop.EStopEngaged): + mod.test_xy() + + +def run_inflight(argv): + sys.argv = ["estop_inflight_test", *argv] + runpy.run_path(str(ROOT / "acquisition" / "estop_inflight_test.py"), run_name="__main__") + + +def test_inflight_entry_point_needs_z_or_xy(scripts, monkeypatch): + monkeypatch.setattr(sys, "argv", sys.argv) + for argv in ([], ["q"], ["z", "extra"]): + with pytest.raises(SystemExit) as exc: + run_inflight(argv) + assert exc.value.code == 2 + + +def test_inflight_entry_point_runs_the_chosen_test(scripts, monkeypatch, capsys): + mod, m, exits = scripts + monkeypatch.setattr(sys, "argv", sys.argv) + run_inflight(["z"]) + assert exits == [0] and "RESULT: Z" in capsys.readouterr().out and 60.0 in InstantTimer.started + estop.release() + run_inflight(["xy"]) + assert exits == [0, 0] and "RESULT: kept moving" in capsys.readouterr().out + + +# ---- read_during_move_test -------------------------------------------------------- + +def test_read_during_move_script_runs_and_logs_events(scripts, monkeypatch, capsys): + mod, m, exits = scripts + sys.modules.pop("acquisition.read_during_move_test", None) + rd = importlib.import_module("acquisition.read_during_move_test") + try: + out = capsys.readouterr().out + assert exits == [0] and "set iXPOSITION done" in out and "read done" in out + assert (m.iXPOSITION, m.iYPOSITION) == (0, 0) + assert [c[0] for c in m.commands] == ["SET_MOVING_STATE_NOTIFICATION", "GET_MOVING_STATE_NOTIFICATION"] + assert "GET_MOVING_STATE_NOTIFICATION failed" in out # the fake refuses the read-back + ev = rd.Events() + ev.OnGeneralCallback(3, object()) + ev.OnDedicatedCallback(25, "busy") + ev.OnMetaDataCallback(0x10) + ev.OnEnabledCallback(0x20) + out = capsys.readouterr().out + assert "XYStageLogicalLimitsReached" in out and "Ti2_IsBusy" in out and "metadata 0x10" in out + finally: + sys.modules.pop("acquisition.read_during_move_test", None) + + +# ---- python -m entry points of the other modules ---------------------------------- + +@pytest.fixture +def entry(monkeypatch, tmp_path): + monkeypatch.setattr(nis_mock.time, "sleep", lambda s: None) + monkeypatch.setattr(estop, "ESTOP_PATH", tmp_path / "ESTOP") + monkeypatch.setenv("CONFOCAL_NO_ESTOP_PANEL", "1") + monkeypatch.setenv("CONFOCAL_MCP_DATA_DIR", str(tmp_path)) + from acquisition import paths + paths.data_root.cache_clear() + yield + paths.data_root.cache_clear() + + +def test_nis_mock_demo(entry, capsys): + runpy.run_module("acquisition.backends.nis_mock", run_name="__main__") + out = capsys.readouterr().out + assert "Starting position" in out and "Expected error on out-of-range move" in out + + +def test_stage_positions_demo(entry, capsys): + runpy.run_module("acquisition.orchestration.stage_positions", run_name="__main__") + out = capsys.readouterr().out + assert "sample_edge" in out and "Summary of all saved positions" in out + + +def test_nis_sdk_demo(fake_ti2, entry, capsys): + runpy.run_module("acquisition.backends.nis_sdk", run_name="__main__") + assert "Current position: (100.0, 200.0) 4619.0" in capsys.readouterr().out + + +def test_estop_cli_entry_point(entry, monkeypatch, capsys): + monkeypatch.setattr(sys, "argv", ["estop", "status"]) + runpy.run_module("acquisition.estop", run_name="__main__") + assert "clear" in capsys.readouterr().out + + +def test_orchestration_entry_points_reach_their_argument_parsers(entry, monkeypatch): + for module in ("acquisition.orchestration.timelapse",): + monkeypatch.setattr(sys, "argv", ["x"]) # no --minutes/--frames: the parser refuses + with pytest.raises(SystemExit) as exc: + runpy.run_module(module, run_name="__main__") + assert exc.value.code == 2 + for module in ("acquisition.orchestration.mosaic", "acquisition.orchestration.worm_follow", + "acquisition.move_xy"): + monkeypatch.setattr(sys, "argv", ["x", "--help"]) + with pytest.raises(SystemExit) as exc: + runpy.run_module(module, run_name="__main__") + assert exc.value.code == 0 diff --git a/tests/test_harness_loops.py b/tests/test_harness_loops.py new file mode 100644 index 0000000..7361090 --- /dev/null +++ b/tests/test_harness_loops.py @@ -0,0 +1,316 @@ +# The harness conversation loops (run_turn / main) and the tool plumbing around +# the approval gate, driven by a scripted stand-in for the Anthropic client. +# No API key, no network, no hardware. +import asyncio +import json +import runpy +import sys +from pathlib import Path +from types import SimpleNamespace as NS + +import anthropic +import pytest +from PIL import Image + +from acquisition import estop +from acquisition.backends import nis_mock +from acquisition.orchestration import stage_positions +from harness import agent, mcp_agent +from mcp_server import loop_tools + +ROOT = Path(__file__).parent.parent + + +def tool_use(name, input_, id_="t1"): + return NS(type="tool_use", id=id_, name=name, input=input_) + + +def text(t): + return NS(type="text", text=t) + + +@pytest.fixture(autouse=True) +def mock_stage(tmp_path, monkeypatch): + monkeypatch.setattr(loop_tools, "MOVE_HISTORY_PATH", tmp_path / "move.jsonl") + monkeypatch.setattr(loop_tools, "FRAME_HISTORY_PATH", tmp_path / "frame.jsonl") + monkeypatch.setattr(estop, "ESTOP_PATH", tmp_path / "ESTOP") + monkeypatch.setattr(nis_mock.time, "sleep", lambda s: None) + monkeypatch.setattr(nis_mock, "CAPTURE_DIR", tmp_path / "caps") + monkeypatch.setattr(nis_mock, "SAMPLE_FRAME_PATH", tmp_path / "none.png") + monkeypatch.setattr(stage_positions, "nis", nis_mock.MockNIS(1, 2, 3)) + + +# ---- shared: scripted model ---------------------------------------------------- + +class ScriptedMessages: + def __init__(self, scripted, is_async): + self.scripted, self.calls, self._async = list(scripted), [], is_async + + def create(self, **kw): + self.calls.append(kw) + out = self.scripted.pop(0) + if self._async: + async def done(): + return out + return done() + return out + + +def sync_client(*responses): + return NS(messages=ScriptedMessages([NS(content=r) for r in responses], False)) + + +def async_client(*responses): + return NS(messages=ScriptedMessages([NS(content=r) for r in responses], True)) + + +# ---- agent.py ------------------------------------------------------------------- + +def test_agent_gate_prompt_accepts_only_yes(monkeypatch): + for answer, ok in (("y", True), ("YES", True), ("n", False), ("", False), ("sure", False)): + monkeypatch.setattr("builtins.input", lambda prompt, a=answer: a) + assert agent._confirm_real_hardware_action("move", {"x": 1}) is ok + + +def test_agent_executes_read_tools_and_reports_errors(): + content, err = agent._execute_tool("get_pos", {}) + assert not err and json.loads(content[0]["text"])["position"] == {"x": 1.0, "y": 2.0, "z": 3.0} + content, err = agent._execute_tool("move", {"x": 5, "y": 6}) + assert not err and json.loads(content[0]["text"])["position"]["x"] == 5.0 + content, err = agent._execute_tool("get_move_history", {"limit": 1}) + assert not err and json.loads(content[0]["text"])["returned"] == 1 + content, err = agent._execute_tool("fly", {}) + assert err and "Unknown tool: fly" in content[0]["text"] + content, err = agent._execute_tool("move", {"x": 99_999, "y": 0}) # outside the mock's travel + assert err and content[0]["text"].startswith("ValueError") + content, err = agent._execute_tool("get_image", {"backend": "nope"}) + assert err + + +def test_agent_mock_capture_returns_text_and_an_image_block(): + content, err = agent._execute_tool("get_image", {"backend": "mock", "max_dimension": 64}) + assert not err and [b["type"] for b in content] == ["text", "image"] + assert content[1]["source"]["media_type"] == "image/jpeg" + + +def test_agent_run_turn_executes_tools_then_returns_the_final_text(): + client = sync_client([tool_use("get_pos", {})], [text("the stage is at 1, 2")]) + messages = [{"role": "user", "content": "where is it"}] + assert agent.run_turn(client, messages) == "the stage is at 1, 2" + roles = [m["role"] for m in messages] + assert roles == ["user", "assistant", "user", "assistant"] + result = messages[2]["content"][0] + assert result["type"] == "tool_result" and result["tool_use_id"] == "t1" and "is_error" not in result + assert client.messages.calls[0]["tools"] == agent.TOOLS and client.messages.calls[0]["model"] == agent.MODEL + + +def test_agent_run_turn_marks_failed_tools_as_errors(): + client = sync_client([tool_use("fly", {})], [text("sorry")]) + messages = [{"role": "user", "content": "go"}] + agent.run_turn(client, messages) + assert messages[2]["content"][0]["is_error"] is True + + +def test_agent_run_turn_prunes_old_images(monkeypatch): + client = sync_client(*([[tool_use("get_image", {"backend": "mock", "max_dimension": 32}, f"t{i}")] for i in range(4)] + + [[text("done")]])) + messages = [{"role": "user", "content": "shoot"}] + agent.run_turn(client, messages) + with_images = [m for m in messages if m["role"] == "user" and isinstance(m["content"], list) + and any(b["type"] == "tool_result" and any(c["type"] == "image" for c in b["content"]) for b in m["content"])] + assert len(with_images) == agent.KEEP_LAST_N_IMAGES + first = messages[2]["content"][0]["content"] # an old frame: text survives, picture gone + assert [c["type"] for c in first] == ["text"] and "frame_id" in first[0]["text"] + + +def test_agent_run_turn_stops_at_the_round_cap(monkeypatch, capsys): + monkeypatch.setattr(agent, "MAX_TOOL_ROUNDS", 2) + client = sync_client(*([[tool_use("get_pos", {}), text("still going")]] * 2)) + assert agent.run_turn(client, [{"role": "user", "content": "loop"}]) == "still going" + assert "hit MAX_TOOL_ROUNDS" in capsys.readouterr().out + + +def scripted_input(monkeypatch, lines): + it = iter(lines) + + def fake(prompt=""): + v = next(it) + if isinstance(v, BaseException): + raise v + return v + + monkeypatch.setattr("builtins.input", fake) + + +def test_agent_main_loop(monkeypatch, capsys): + monkeypatch.setattr(agent.anthropic, "Anthropic", lambda: "client") + seen = [] + monkeypatch.setattr(agent, "run_turn", lambda c, m: (seen.append(list(m)), "hello back")[1]) + scripted_input(monkeypatch, ["", "hi", "/exit"]) + agent.main() + assert len(seen) == 1 and seen[0][0] == {"role": "user", "content": "hi"} + assert "Claude: hello back" in capsys.readouterr().out + + +def api_errors(): + """The two API exceptions, built without the HTTP client library so the + tests do not depend on which one the SDK uses.""" + out = [] + for cls, msg in ((anthropic.APIStatusError, "overloaded"), (anthropic.APIConnectionError, "unreachable")): + exc = cls.__new__(cls) + Exception.__init__(exc, msg) + out.append(exc) + return out + + +def test_agent_main_survives_api_errors_and_eof(monkeypatch, capsys): + monkeypatch.setattr(agent.anthropic, "Anthropic", lambda: "client") + errors = iter(api_errors()) + + def fail(c, m): + raise next(errors) + + monkeypatch.setattr(agent, "run_turn", fail) + scripted_input(monkeypatch, ["one", "two", EOFError()]) + agent.main() + out = capsys.readouterr().out + assert "[API error]" in out and "[connection error]" in out + + +# ---- mcp_agent.py ---------------------------------------------------------------- + +def test_mcp_gate_prompt_accepts_only_yes(monkeypatch): + for answer, ok in (("y", True), (" Yes ", True), ("no", False), ("", False)): + monkeypatch.setattr("builtins.input", lambda prompt, a=answer: a) + assert asyncio.run(mcp_agent._confirm_real_hardware_action("move", {})) is ok + + +def test_mcp_content_conversion_handles_text_image_and_unknown(): + blocks = mcp_agent._mcp_content_to_anthropic_content([ + NS(type="text", text="hi"), + NS(type="image", mime_type="image/png", data="QUJD"), + NS(type="audio")]) + assert blocks[0] == {"type": "text", "text": "hi"} + assert blocks[1]["source"] == {"type": "base64", "media_type": "image/png", "data": "QUJD"} + assert "unsupported MCP content type: audio" in blocks[2]["text"] + + +def test_mcp_tools_convert_to_anthropic_tools_without_confirm(): + tools = mcp_agent._mcp_tools_to_anthropic_tools([ + NS(name="move", description=None, input_schema={"properties": {"x": {}, "confirm": {}}})]) + assert tools == [{"name": "move", "description": "", "input_schema": {"properties": {"x": {}}}}] + + +def test_mcp_execute_tool_reports_protocol_errors(): + from mcp.shared.exceptions import MCPError + + class Boom: + async def call_tool(self, name, args): + raise MCPError(-32601, "no such tool") + + content, err = asyncio.run(mcp_agent._execute_tool(Boom(), "nope", {})) + assert err and content[0]["text"].startswith("MCPError") + + +def test_mcp_run_turn_round_trip_and_error_marking(): + class Server: + async def call_tool(self, name, args): + return NS(content=[NS(type="text", text="ok")], is_error=(name == "bad")) + + client = async_client([tool_use("get_pos", {}, "a"), tool_use("bad", {}, "b")], [text("all done")]) + messages = [{"role": "user", "content": "go"}] + out = asyncio.run(mcp_agent.run_turn(client, Server(), [], messages)) + assert out == "all done" + results = messages[2]["content"] + assert "is_error" not in results[0] and results[1]["is_error"] is True + + +def test_mcp_run_turn_stops_at_the_round_cap(monkeypatch, capsys): + monkeypatch.setattr(mcp_agent, "MAX_TOOL_ROUNDS", 1) + + class Server: + async def call_tool(self, name, args): + return NS(content=[NS(type="text", text="ok")], is_error=False) + + client = async_client([tool_use("get_pos", {}), text("partial")]) + assert asyncio.run(mcp_agent.run_turn(client, Server(), [], [{"role": "user", "content": "x"}])) == "partial" + assert "hit MAX_TOOL_ROUNDS" in capsys.readouterr().out + + +def fake_mcp(monkeypatch): + class FakeClient: + protocol_version = "2026-01-01" + + def __init__(self, transport): + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *a): + return False + + async def list_tools(self): + return NS(tools=[NS(name="get_pos", description="d", input_schema={"properties": {}})]) + + seen = {} + monkeypatch.setattr(mcp_agent, "Client", FakeClient) + monkeypatch.setattr(mcp_agent, "stdio_client", lambda params: seen.setdefault("params", params)) + monkeypatch.setattr(mcp_agent.anthropic, "AsyncAnthropic", lambda: "client") + return seen + + +def test_mcp_main_loop(monkeypatch, capsys): + seen = fake_mcp(monkeypatch) + turns = [] + + async def turn(client, mcp_client, tools, messages): + turns.append((tools, list(messages))) + return "hello back" + + monkeypatch.setattr(mcp_agent, "run_turn", turn) + scripted_input(monkeypatch, ["", "hi", "exit"]) + asyncio.run(mcp_agent.main()) + assert seen["params"].args == ["-m", "mcp_server.server_loop"] + assert turns[0][0][0]["name"] == "get_pos" and len(turns) == 1 + assert "Claude: hello back" in capsys.readouterr().out + + +def test_mcp_main_survives_api_errors_and_eof(monkeypatch, capsys): + fake_mcp(monkeypatch) + errors = iter(api_errors()) + + async def fail(*a): + raise next(errors) + + monkeypatch.setattr(mcp_agent, "run_turn", fail) + scripted_input(monkeypatch, ["one", "two", KeyboardInterrupt()]) + asyncio.run(mcp_agent.main()) + out = capsys.readouterr().out + assert "[API error]" in out and "[connection error]" in out + + +# ---- the modules' own sanity-check blocks ------------------------------------------ + +def test_context_module_self_check_runs(capsys): + runpy.run_path(str(ROOT / "harness" / "context.py"), run_name="__main__") + assert "All sanity checks passed." in capsys.readouterr().out + + +def test_harness_modules_start_from_main(monkeypatch): + called = [] + monkeypatch.setattr("builtins.input", lambda prompt="": "/exit") + monkeypatch.setattr(anthropic, "Anthropic", lambda: "client") + runpy.run_path(str(ROOT / "harness" / "agent.py"), run_name="__main__") + fake_mcp(monkeypatch) + monkeypatch.setattr(anthropic, "AsyncAnthropic", lambda: "client") + import mcp.client as mc, mcp.client.stdio as ms + class Fake: + protocol_version = "x" + def __init__(self, t): pass + async def __aenter__(self): return self + async def __aexit__(self, *a): return False + async def list_tools(self): return NS(tools=[]) + monkeypatch.setattr(mc, "Client", Fake) + monkeypatch.setattr(ms, "stdio_client", lambda p: p) + runpy.run_path(str(ROOT / "harness" / "mcp_agent.py"), run_name="__main__") diff --git a/tests/test_loop_tools.py b/tests/test_loop_tools.py new file mode 100644 index 0000000..776ed5c --- /dev/null +++ b/tests/test_loop_tools.py @@ -0,0 +1,171 @@ +import sys +import types + +import pytest +from PIL import Image + +from acquisition import estop +from acquisition.backends import nis_mock +from acquisition.orchestration import stage_positions +from mcp_server import loop_tools as lt +from tests.fakes import fake_ti2 # noqa: F401 (fixture) + + +@pytest.fixture(autouse=True) +def isolated(tmp_path, monkeypatch): + monkeypatch.setattr(lt, "MOVE_HISTORY_PATH", tmp_path / "logs" / "move_history.jsonl") + monkeypatch.setattr(lt, "FRAME_HISTORY_PATH", tmp_path / "logs" / "frame_history.jsonl") + monkeypatch.setattr(lt, "_stage_revision", 0) + monkeypatch.setattr(lt, "_last_known_position", None) + monkeypatch.setattr(lt, "_frame_counter", 0) + monkeypatch.setattr(lt, "_camera", None) + monkeypatch.setattr(estop, "ESTOP_PATH", tmp_path / "ESTOP") + monkeypatch.setattr(nis_mock.time, "sleep", lambda s: None) + monkeypatch.setattr(nis_mock, "CAPTURE_DIR", tmp_path / "caps") + monkeypatch.setattr(nis_mock, "SAMPLE_FRAME_PATH", tmp_path / "none.png") + monkeypatch.setattr(stage_positions, "nis", nis_mock.MockNIS(10, 20, 30)) + + +def test_unknown_backend_everywhere(): + with pytest.raises(ValueError): + lt._get_backend("x") + with pytest.raises(ValueError): + lt._require_confirm_for_sdk("x", True) + for call in (lambda: lt.get_pos("x"), lambda: lt.move(0, 0, "x"), lambda: lt.move_focus(0, "x")): + with pytest.raises(ValueError): + call() + + +def test_get_pos_mock_and_revision(): + a = lt.get_pos() + b = lt.get_pos() + assert a["position"] == {"x": 10.0, "y": 20.0, "z": 30.0} and a["backend"] == "mock" + assert a["stage_revision"] == b["stage_revision"] == 1 # unchanged: same revision + lt.move(11, 20) + assert lt.get_pos()["stage_revision"] == 2 + + +def test_move_returns_actual_position_and_logs_history(): + r = lt.move(110, 120) + assert r["position"] == {"x": 110.0, "y": 120.0, "z": 30.0} + h = lt.get_move_history() + assert h["total_moves"] == 1 and h["history"][0]["requested"] == {"x": 110.0, "y": 120.0} + + +def test_move_history_limit_and_empty(): + assert lt.get_move_history() == {"history": [], "returned": 0, "total_moves": 0} + for i in range(5): + lt.move(10 + i, 20) + h = lt.get_move_history(limit=2) + assert h["returned"] == 2 and h["total_moves"] == 5 + assert [r["requested"]["x"] for r in h["history"]] == [13.0, 14.0] + + +def test_move_focus_mock_and_step_cap(): + r = lt.move_focus(40) + assert r["position"]["z"] == 40.0 + assert lt.get_move_history()["history"][0]["requested"] == {"z": 40.0} + with pytest.raises(ValueError, match="per-call safety limit"): + lt.move_focus(40 + 51) + + +def test_sdk_backend_needs_confirm_for_moves(fake_ti2): + with pytest.raises(PermissionError): + lt.move(0, 0, backend="sdk") + with pytest.raises(PermissionError): + lt.move_focus(0, backend="sdk") + + +def test_sdk_backend_moves_through_the_fake_ti2(fake_ti2): + sdk, m = fake_ti2 + assert lt.get_pos("sdk")["position"] == {"x": 100.0, "y": 200.0, "z": 4619.0} + assert lt.move(150, 250, backend="sdk", confirm=True)["position"]["x"] == 150.0 + assert lt.move_focus(4629, backend="sdk", confirm=True)["position"]["z"] == 4629.0 + + +def test_sdk_move_refused_by_estop(fake_ti2): + sdk, m = fake_ti2 + estop.engage("test") + with pytest.raises(estop.EStopEngaged): + lt.move(150, 250, backend="sdk", confirm=True) + assert m.iXPOSITION == 1000 + + +def test_validate_crop(): + lt._validate_crop({"x": 0.1, "y": 0.1, "width": 0.5, "height": 0.5}) + for bad in ({"x": 0}, {"x": -0.1, "y": 0, "width": 1, "height": 1}, + {"x": 0, "y": 0, "width": "a", "height": 1}, + {"x": 0.6, "y": 0, "width": 0.5, "height": 1}, + {"x": 0, "y": 0.6, "width": 1, "height": 0.5}): + with pytest.raises(ValueError): + lt._validate_crop(bad) + + +def test_preview_crop_and_downscale(tmp_path): + p = tmp_path / "big.png" + Image.new("RGB", (400, 200), (9, 9, 9)).save(p) + whole = lt._make_preview_image(p, max_dimension=100) + cropped = lt._make_preview_image(p, crop={"x": 0, "y": 0, "width": 0.5, "height": 1.0}, max_dimension=100) + import io + assert Image.open(io.BytesIO(whole.data)).size == (100, 50) + assert Image.open(io.BytesIO(cropped.data)).size == (100, 100) + + +def test_get_image_mock_records_frame_history_and_crop(): + meta, preview = lt.get_image(backend="mock", crop={"x": 0, "y": 0, "width": 0.5, "height": 0.5}) + assert meta["frame_id"] == 1 and meta["crop"]["width"] == 0.5 + assert lt.get_frame(1)["image"] == meta["image"] + meta2, _ = lt.get_image(backend="mock") + assert meta2["frame_id"] == 2 + + +def test_get_frame_unknown_id_and_blank_lines(): + with pytest.raises(KeyError): + lt.get_frame(99) # no history file yet + lt.get_image(backend="mock") + with open(lt.FRAME_HISTORY_PATH, "a") as f: + f.write("\n") + with pytest.raises(KeyError): + lt.get_frame(99) + + +def test_get_image_sdk_uses_the_camera_and_applies_settings(fake_ti2, tmp_path, monkeypatch): + img_path = tmp_path / "cam.png" + Image.new("RGB", (8, 8)).save(img_path) + seen = {} + + class Cam: + def set_settings(self, **kw): + seen["settings"] = kw + + def capture(self): + return img_path + + made = [] + mod = types.ModuleType("acquisition.backends.baumer_genicam") + mod.BaumerGenICam = lambda: (made.append(1), Cam())[1] + monkeypatch.setitem(sys.modules, "acquisition.backends.baumer_genicam", mod) + meta, _ = lt.get_image(confirm=True, exposure_time_us=1600, gain=2.0) + assert seen["settings"] == {"exposure_time_us": 1600, "gain": 2.0} + assert meta["backend"] == "sdk" and meta["image"] == str(img_path) + lt.get_image(confirm=True) + assert made == [1] # the camera connection is reused + + +def test_get_image_sdk_without_settings_leaves_camera_alone(fake_ti2, tmp_path, monkeypatch): + img_path = tmp_path / "cam.png" + Image.new("RGB", (8, 8)).save(img_path) + cam = types.SimpleNamespace(capture=lambda: img_path, + set_settings=lambda **k: pytest.fail("settings must not be touched")) + monkeypatch.setattr(lt, "_camera", cam) + lt.get_image(confirm=True) + + +def test_estop_tool_engage_status_and_unknown(): + assert lt.estop("status")["engaged"] is False + out = lt.estop("engage", reason="test") + assert out["engaged"] is True and out["detail"]["reason"] == "test" + s = lt.estop() + assert s["engaged"] is True and s["flag_file"] + with pytest.raises(ValueError, match="Releasing is a human action"): + lt.estop("release") diff --git a/tests/test_mosaic.py b/tests/test_mosaic.py new file mode 100644 index 0000000..7ed8d82 --- /dev/null +++ b/tests/test_mosaic.py @@ -0,0 +1,243 @@ +import json +import sys + +import numpy as np +import pytest +from PIL import Image + +from acquisition import estop +from acquisition.orchestration import mosaic +from tests.fakes_scene import RigStage, SceneRig, UM_PER_PX + + +@pytest.fixture(autouse=True) +def quiet(tmp_path, monkeypatch): + monkeypatch.setattr(mosaic.time, "sleep", lambda s: None) + monkeypatch.setattr(mosaic, "data_root", lambda: tmp_path / "root") + monkeypatch.setattr(estop, "ESTOP_PATH", tmp_path / "ESTOP") + + +@pytest.fixture +def rig(tmp_path, monkeypatch): + return SceneRig(tmp_path).install(monkeypatch) + + +# ---- grid and stitch ------------------------------------------------------ + +def test_grid_positions_is_a_serpentine_around_the_centre(): + pts = mosaic.grid_positions(100, 200, 3, 2, 10, 20) + assert pts == [(90.0, 190.0), (100.0, 190.0), (110.0, 190.0), + (110.0, 210.0), (100.0, 210.0), (90.0, 210.0)] + + +def test_stitch_places_tiles_by_stage_offset(): + a = np.full((10, 10, 3), 50, np.uint8) + b = np.full((10, 10, 3), 200, np.uint8) + M = np.array([[-1.0, 0.0], [0.0, 1.0]]) # +X slides features left + canvas = mosaic.stitch([(a, 0.0, 0.0), (b, 10.0, 0.0)], M, (0.0, 0.0)) + assert canvas.shape == (10, 20, 3) + assert canvas[0, 0, 0] == 50 and canvas[0, 19, 0] == 200 # the tile at larger X shows sample further right + + +# ---- focus plane (the 2026-09-21 incident) -------------------------------- + +def test_focus_plane_needs_three_points(): + with pytest.raises(ValueError, match="at least 3"): + mosaic.FocusPlane([(0, 0, 4600), (1000, 0, 4600)]) + + +def test_focus_plane_refuses_collinear_points(): + with pytest.raises(ValueError, match="collinear"): + mosaic.FocusPlane([(0, 0, 4600), (1000, 0, 4601), (2000, 0, 4602)]) + + +def test_focus_plane_recovers_a_tilted_plane_with_no_residual(): + f = lambda x, y: 4600 + 0.002 * x - 0.001 * y + pts = [(x, y, f(x, y)) for x, y in ((0, 0), (10000, 0), (0, 8000), (10000, 8000))] + plane = mosaic.FocusPlane(pts) + assert plane.z(5000, 4000) == pytest.approx(f(5000, 4000), abs=1e-6) + assert max(plane.residuals) < 1e-6 and "clamped to +/-400" in str(plane) + + +def test_focus_plane_never_commands_more_than_the_clamp(): + plane = mosaic.FocusPlane([(0, 0, 4600), (1000, 0, 4601), (0, 1000, 4602)], max_dev=50) + assert plane.would_clamp(1e7, 0) and not plane.would_clamp(10, 10) + assert plane.z(1e7, 0) == pytest.approx(plane.z_ref + 50) + assert plane.z(-1e7, 0) == pytest.approx(plane.z_ref - 50) + + +# ---- moves ------------------------------------------------------------------ + +def test_move_safe_walks_a_long_jump_in_legal_hops(rig): + s = rig.stage + assert mosaic._move_safe(s, 12000, 0) == (12000.0, 0.0) + assert len(s.moves) == 3 and all(abs(b - a) <= 4500 + 1e-6 for a, b in zip([0] + [m[0] for m in s.moves], [m[0] for m in s.moves])) + + +def test_move_safe_is_a_noop_when_already_there(rig): + assert mosaic._move_safe(rig.stage, 0.4, 0.0) == (0.0, 0.0) and rig.stage.moves == [] + + +def test_move_z_steps_under_the_cap(rig): + s = rig.stage + z = mosaic._move_z(s, s.z + 120) + assert z == pytest.approx(s.z) and all(abs(b - a) <= 45 + 1e-6 for a, b in zip([4619.0] + s.z_moves, s.z_moves)) + assert len(s.z_moves) == 3 + + +def test_move_z_gives_up_on_a_stuck_axis(rig, monkeypatch): + s = rig.stage + monkeypatch.setattr(s, "Z_Move", lambda z: None) # accepted, never arrives + start = s.z + assert mosaic._move_z(s, start + 10) == start + + +# ---- calibration ------------------------------------------------------------ + +def test_calibrate_axes_measures_the_stage_to_image_mapping(rig, capsys): + M = mosaic.calibrate_axes(rig.camera, rig.stage) + assert M[0, 0] == pytest.approx(-1 / UM_PER_PX, abs=0.01) and M[1, 1] == pytest.approx(1 / UM_PER_PX, abs=0.01) + assert abs(M[0, 1]) < 0.01 and abs(M[1, 0]) < 0.01 + assert rig.stage.XY_GetPosition() == (0.0, 0.0) # returned home + assert "um/px" in capsys.readouterr().out + + +def test_calibrate_axes_stops_when_the_stage_does_not_move(rig): + rig.stage.frozen = True + with pytest.raises(SystemExit, match="calibration failed"): + mosaic.calibrate_axes(rig.camera, rig.stage) + + +# ---- run -------------------------------------------------------------------- + +def run_kw(**over): + kw = dict(grid=(2, 2), overlap=0.1, rounds=1, interval_s=0.0, exposure_us=1600.0, + mosaic_scale=0.5, keep_tiles=True, scale_um_px=UM_PER_PX, tag="t") + kw.update(over) + return kw + + +def test_run_writes_tiles_csv_json_and_a_stitched_mosaic(rig, tmp_path): + out = mosaic.run(**run_kw()) + assert (out / "tiles.csv").exists() and (out / "mosaic_000.png").exists() + info = json.loads((out / "mosaic.json").read_text()) + assert info["grid"] == [2, 2] and info["um_per_px"] == pytest.approx(UM_PER_PX, abs=1e-3) + assert len(list((out / "round_000").glob("t*.png"))) == 4 + assert rig.camera.closed and rig.stage.XY_GetPosition() == (0.0, 0.0) + assert Image.open(out / "mosaic_000.png").size[0] > 100 + rows = (out / "tiles.csv").read_text().splitlines() + assert len(rows) == 5 and all(r.endswith(",") for r in rows[1:]) # no error text + + +def test_run_calibrates_when_no_scale_is_given(rig, capsys): + mosaic.run(**run_kw(scale_um_px=None, grid=(1, 1), keep_tiles=False, mosaic_scale=1.0)) + assert "calibrating stage->image mapping" in capsys.readouterr().out + + +def test_run_follows_a_focus_plane_and_a_given_centre(rig): + pts = [(0, 0, 4619.0), (300, 0, 4625.0), (0, 300, 4619.0)] + out = mosaic.run(**run_kw(grid=(1, 1), focus_points=pts, centre=(100.0, -50.0))) + assert rig.stage.z_moves, "Z should follow the plane" + assert (out / "mosaic_000.png").exists() + + +def test_run_fixed_focus_leaves_z_alone(rig): + mosaic.run(**run_kw(grid=(1, 1))) + assert rig.stage.z_moves == [] + + +def test_run_forces_balance_white_off_and_survives_a_missing_node(tmp_path, monkeypatch, capsys): + rig = SceneRig(tmp_path, white_balance="Continuous").install(monkeypatch) + mosaic.run(**run_kw(grid=(1, 1))) + assert rig.camera._acquirer.remote_device.node_map.BalanceWhiteAuto.value == "Off" + assert "forcing 'Off'" in capsys.readouterr().out + del rig.camera._acquirer.remote_device.node_map.BalanceWhiteAuto + mosaic.run(**run_kw(grid=(1, 1))) + assert "could not force BalanceWhiteAuto off" in capsys.readouterr().err + + +def test_a_failed_tile_is_logged_and_the_round_continues(rig): + rig.camera.on_capture = lambda n: (_ for _ in ()).throw(RuntimeError("fetch timed out")) if n == 3 else None + out = mosaic.run(**run_kw()) + text = (out / "tiles.csv").read_text() + assert text.count("RuntimeError: fetch timed out") == 1 + assert (out / "mosaic_000.png").exists() + + +def test_stop_file_halts_the_run_and_still_parks_and_releases(rig, tmp_path): + def stop_after_first(n): + if n == 3: # 1 = probe, 2 = first tile; 3 = second tile is refused at its start + for d in (tmp_path / "root" / "data").glob("mosaic_*"): + (d / "STOP").write_text("") + rig.camera.on_capture = stop_after_first + with pytest.raises(KeyboardInterrupt): + mosaic.run(**run_kw(rounds=3)) + assert rig.camera.closed and rig.stage.XY_GetPosition() == (0.0, 0.0) + + +def test_parking_failure_is_reported_not_raised(rig, monkeypatch, capsys): + real = mosaic._move_safe + calls = [] + + def flaky(sdk, x, y): + calls.append(1) + if len(calls) > 2: # the two tile moves work, the park at the end fails + raise RuntimeError("stage gone") + return real(sdk, x, y) + + monkeypatch.setattr(mosaic, "_move_safe", flaky) + mosaic.run(**run_kw(grid=(2, 1), keep_tiles=False)) + assert "could not return to centre" in capsys.readouterr().err and rig.camera.closed + + +def test_estop_during_a_run_is_recorded_per_tile(rig, capsys): + estop.engage("test") + out = mosaic.run(**run_kw(grid=(2, 1))) + assert (out / "tiles.csv").read_text().count("EStopEngaged") == 2 + assert not list(out.glob("mosaic_000.png")) and rig.stage.moves == [] + assert rig.camera.closed + + +def test_rounds_are_paced_by_the_interval(rig, monkeypatch): + slept = [] + monkeypatch.setattr(mosaic.time, "sleep", lambda s: slept.append(s)) + mosaic.run(**run_kw(grid=(1, 1), rounds=2, interval_s=600.0)) + assert any(s > 100 for s in slept) + + +# ---- command line ----------------------------------------------------------- + +def run_main(monkeypatch, *argv): + monkeypatch.setattr(sys, "argv", ["mosaic", *argv]) + mosaic.main() + + +def test_dry_run_prints_the_plan_and_moves_nothing(rig, monkeypatch, capsys): + run_main(monkeypatch, "--dry-run", "--grid", "3x2", "--hours", "1", "--interval-min", "20") + out = capsys.readouterr().out + assert "3x2 = 6 tiles" in out and "3 rounds every 20.0 min" in out + assert rig.stage.moves == [] and rig.camera.captures == 0 + + +def test_main_hands_parsed_arguments_to_run(monkeypatch): + seen = [] + monkeypatch.setattr(mosaic, "run", lambda *a: seen.append(a)) + run_main(monkeypatch, "--grid", "4x3", "--rounds", "2", "--no-tiles", "--scale", "1.5", + "--focus-plane", "0,0,4600;100,0,4601;0,100,4602", "--centre", "10,20", "--tag", "x") + (grid, overlap, rounds, interval, exposure, mscale, keep, scale, tag, fpts, centre), = seen + assert grid == (4, 3) and rounds == 2 and keep is False and scale == 1.5 and tag == "x" + assert fpts == [(0.0, 0.0, 4600.0), (100.0, 0.0, 4601.0), (0.0, 100.0, 4602.0)] + assert centre == (10.0, 20.0) and interval == 20 * 60 + + +def test_main_defaults_to_one_round(monkeypatch): + seen = [] + monkeypatch.setattr(mosaic, "run", lambda *a: seen.append(a)) + run_main(monkeypatch) + assert seen[0][2] == 1 and seen[0][9] is None and seen[0][10] is None + + +def test_main_rejects_a_focus_point_that_is_not_xyz(monkeypatch): + with pytest.raises(SystemExit) as exc: + run_main(monkeypatch, "--focus-plane", "0,0;1,1,1") + assert exc.value.code == 2 diff --git a/tests/test_move_and_timelapse.py b/tests/test_move_and_timelapse.py new file mode 100644 index 0000000..2f11f60 --- /dev/null +++ b/tests/test_move_and_timelapse.py @@ -0,0 +1,236 @@ +import csv +import runpy +import sys +from pathlib import Path + +import pytest +from PIL import Image + +from acquisition import estop, move_xy +from acquisition.orchestration import timelapse +from tests.fakes import fake_ti2 # noqa: F401 (fixture) +from tests.fakes_camera import install_fake_camera_stack + + +@pytest.fixture +def clear_estop(tmp_path, monkeypatch): + monkeypatch.setattr(estop, "ESTOP_PATH", tmp_path / "ESTOP") + monkeypatch.setattr(move_xy.time, "sleep", lambda s: None) + + +# ---- move_xy ------------------------------------------------------------ + +class FlatStage: + def __init__(self): + self.pos, self.moves = (0.0, 0.0), [] + + def XY_GetPosition(self): + return self.pos + + def XY_Move(self, x, y): + self.moves.append((x, y)) + self.pos = (x, y) + + +def test_move_to_splits_long_moves_into_legal_hops(clear_estop, capsys): + s = FlatStage() + end = move_xy.move_to(s, 15000, 0) + assert end == (15000.0, 0.0) + assert len(s.moves) == 4 and all(b[0] - a[0] <= move_xy.HOP_UM + 1e-6 + for a, b in zip([(0, 0)] + s.moves, s.moves)) + assert "um to go" in capsys.readouterr().out + + +def test_move_to_quiet_and_already_there(clear_estop, capsys): + s = FlatStage() + assert move_xy.move_to(s, 0.5, 0.0) == (0.0, 0.0) and s.moves == [] + move_xy.move_to(s, 9000, 0, quiet=True) + assert "to go" not in capsys.readouterr().out + + +def run_main(monkeypatch, *argv): + monkeypatch.setattr(sys, "argv", ["move_xy", *argv]) + move_xy.main() + + +def test_main_only_reports_position(fake_ti2, clear_estop, monkeypatch, capsys): + sdk, m = fake_ti2 + run_main(monkeypatch) + assert "current: X=100.00 Y=200.00" in capsys.readouterr().out + assert m.iXPOSITION == 1000 + + +def test_main_relative_move_in_hops_through_the_sdk(fake_ti2, clear_estop, monkeypatch, capsys): + sdk, m = fake_ti2 + run_main(monkeypatch, "--by", "9000", "0", "--yes") + assert m.iXPOSITION == round((100 + 9000) * 10) + assert "arrived" in capsys.readouterr().out + + +def test_main_absolute_move(fake_ti2, clear_estop, monkeypatch): + sdk, m = fake_ti2 + run_main(monkeypatch, "--to", "300", "400") + assert (m.iXPOSITION, m.iYPOSITION) == (3000, 4000) + + +def test_main_long_move_needs_yes_when_not_interactive(fake_ti2, clear_estop, monkeypatch, capsys): + sdk, m = fake_ti2 + monkeypatch.setattr(sys.stdin, "isatty", lambda: False, raising=False) + with pytest.raises(SystemExit) as exc: + run_main(monkeypatch, "--by", "5000", "0") + assert exc.value.code == 3 and m.iXPOSITION == 1000 + + +@pytest.mark.parametrize("answer,moved", [("y", True), ("n", False)]) +def test_main_long_move_asks_when_interactive(fake_ti2, clear_estop, monkeypatch, capsys, answer, moved): + sdk, m = fake_ti2 + monkeypatch.setattr(sys.stdin, "isatty", lambda: True, raising=False) + monkeypatch.setattr("builtins.input", lambda prompt: answer) + run_main(monkeypatch, "--by", "3000", "0") + assert (m.iXPOSITION != 1000) is moved + assert ("cancelled" in capsys.readouterr().out) is (not moved) + + +def test_main_refuses_when_estop_is_engaged(fake_ti2, clear_estop, monkeypatch, capsys): + sdk, m = fake_ti2 + estop.engage("test") + with pytest.raises(SystemExit) as exc: + run_main(monkeypatch, "--by", "10", "0") + assert exc.value.code == 2 and "E-STOP IS ENGAGED" in capsys.readouterr().out + + +def test_main_reports_a_stop_that_lands_mid_move(fake_ti2, clear_estop, monkeypatch, capsys): + sdk, m = fake_ti2 + real_move = sdk.NISSdk.XY_Move + calls = [] + + def move_then_stop(self, x, y): + real_move(self, x, y) + calls.append(1) + estop.engage("mid-move") + + monkeypatch.setattr(sdk.NISSdk, "XY_Move", move_then_stop) + with pytest.raises(SystemExit) as exc: + run_main(monkeypatch, "--by", "9000", "0", "--yes") + assert exc.value.code == 2 and len(calls) == 1 + assert "STOPPED BY E-STOP" in capsys.readouterr().out + + +# ---- raw_move_xy (a hardware experiment script, run top to bottom) ------- + +def test_raw_move_script_runs_against_a_fake_microscope(fake_ti2, monkeypatch, capsys): + import os + sdk, m = fake_ti2 + exits = [] + + def fake_exit(code): + exits.append(code) + raise SystemExit(code) + + monkeypatch.setattr(os, "_exit", fake_exit) + monkeypatch.setattr(sys, "coinit_flags", 0, raising=False) + sys.modules["pythoncom"].CoInitializeEx = lambda flag: None + sys.modules["pythoncom"].COINIT_MULTITHREADED = 0 + with pytest.raises(SystemExit): + runpy.run_path(str(Path(__file__).parent.parent / "acquisition" / "raw_move_xy.py"), run_name="raw_move_xy") + out = capsys.readouterr().out + assert exits == [0] and "watchdog: halted" in out and "exit" in out + assert (m.iXPOSITION, m.iYPOSITION) == (0, 0) + + +# ---- timelapse ------------------------------------------------------------ + +@pytest.fixture +def lapse(tmp_path, monkeypatch): + mod, acq, log = install_fake_camera_stack(monkeypatch, tmp_path, pixel_format="RGB8") + monkeypatch.setattr(timelapse, "data_root", lambda: tmp_path) + monkeypatch.setattr(timelapse.time, "sleep", lambda s: None) + yield mod, acq, tmp_path + sys.modules.pop("acquisition.backends.baumer_genicam", None) + + +def rows(out): + with (out / "frames.csv").open(newline="", encoding="utf-8") as f: + return list(csv.DictReader(f)) + + +def test_series_dir_name_carries_the_tag(tmp_path, monkeypatch): + monkeypatch.setattr(timelapse, "data_root", lambda: tmp_path) + assert timelapse._series_dir("oats").name.endswith("_oats") + assert "_oats" not in timelapse._series_dir(None).name + + +def test_stats_describe_exposure_and_focus(tmp_path): + p = tmp_path / "f.png" + Image.new("RGB", (8, 8), (255, 255, 255)).save(p) + s = timelapse._stats(p) + assert s["mean"] == 255.0 and s["sat_frac"] == 1.0 and s["focus"] == 0.0 + + +def test_run_writes_frames_and_csv(lapse, capsys): + mod, acq, tmp = lapse + out = timelapse.run(frames=3, interval=0, exposure_us=1600, gain=2.0, tag="t") + r = rows(out) + assert [x["frame"] for x in r] == ["0", "1", "2"] + assert all((out / x["filename"]).exists() and x["error"] == "" for x in r) + assert acq.remote_device.node_map.ExposureTime.value == 1600 and acq.stopped + assert "done in" in capsys.readouterr().out + + +def test_a_failed_frame_is_recorded_and_the_run_continues(lapse, monkeypatch, capsys): + mod, acq, tmp = lapse + real = mod.BaumerGenICam.capture + state = {"n": 0} + + def flaky(self): + state["n"] += 1 + if state["n"] == 3: # 1 = throwaway, 2 = frame 0, 3 = frame 1 + raise RuntimeError("fetch timed out") + return real(self) + + monkeypatch.setattr(mod.BaumerGenICam, "capture", flaky) + out = timelapse.run(frames=3, interval=0, exposure_us=1600, gain=1.0) + r = rows(out) + assert r[1]["error"] == "RuntimeError: fetch timed out" and r[1]["filename"] == "" + assert r[0]["error"] == r[2]["error"] == "" + assert "frame 1: RuntimeError" in capsys.readouterr().out + + +def test_camera_is_closed_even_if_setup_fails(lapse, monkeypatch): + mod, acq, tmp = lapse + with pytest.raises(ValueError): + timelapse.run(frames=1, interval=0, exposure_us=1, gain=1.0) # outside the camera's range + assert acq.stopped + + +def test_late_frames_are_flagged(lapse, monkeypatch): + mod, acq, tmp = lapse + clock = iter(x * 5.0 for x in range(1000)) + monkeypatch.setattr(timelapse.time, "monotonic", lambda: next(clock)) + out = timelapse.run(frames=2, interval=1, exposure_us=1600, gain=1.0) + assert float(rows(out)[1]["late_s"]) > 0 + + +def test_sleeps_until_the_scheduled_slot(lapse, monkeypatch): + mod, acq, tmp = lapse + slept = [] + monkeypatch.setattr(timelapse.time, "sleep", lambda s: slept.append(s)) + timelapse.run(frames=2, interval=30, exposure_us=1600, gain=1.0) + assert slept and slept[0] > 0 + + +def test_main_frame_count_from_minutes_or_frames(lapse, monkeypatch): + calls = [] + monkeypatch.setattr(timelapse, "run", lambda *a: calls.append(a)) + monkeypatch.setattr(sys, "argv", ["tl", "--minutes", "1", "--interval", "10"]) + timelapse.main() + monkeypatch.setattr(sys, "argv", ["tl", "--frames", "4", "--tag", "x"]) + timelapse.main() + assert calls[0][0] == 7 and calls[1][0] == 4 and calls[1][-1] == "x" + + +def test_main_needs_minutes_or_frames(monkeypatch): + monkeypatch.setattr(sys, "argv", ["tl"]) + with pytest.raises(SystemExit) as exc: + timelapse.main() + assert exc.value.code == 2 diff --git a/tests/test_nis_bridge.py b/tests/test_nis_bridge.py index 963843b..966be66 100644 --- a/tests/test_nis_bridge.py +++ b/tests/test_nis_bridge.py @@ -8,13 +8,14 @@ import asyncio import json import os +import socket import sys import threading import urllib.request import pytest -from acquisition import estop +from acquisition import estop, nis_events, nis_monitor as monitor from acquisition.backends import nis_bridge as client_mod from acquisition.nis_bridge import bridge_job as bj from mcp_server import nis_tools @@ -43,6 +44,9 @@ def __init__(self): self.GetCurrentObjName = f("GetCurrentObjName", self._current) self.Stg_SetNosepiecePosition = f("Stg_SetNosepiecePosition", self._turn) self.ChangeObjective = f("ChangeObjective", self._change) + self.opt_confs = ["All Devices", "AX", "EPI"] + self.GetOptConfCount = f("GetOptConfCount", lambda: len(self.opt_confs)) + self.GetOptConfName = f("GetOptConfName", self._conf_name) self.Capture = f("Capture", lambda: 1) self.ImageSaveAs = f("ImageSaveAs", self._save) self.CloseCurrentDocument = f("CloseCurrentDocument", lambda save: 1) @@ -102,6 +106,10 @@ def _finish(self): self.nd_running = False return 1 + def _conf_name(self, i, buf, n): + buf.value = self.opt_confs[i] if 0 <= i < len(self.opt_confs) else "" + return 1 + def moved(self): return [c for c in self.calls if c in ("StgMoveXY", "Stg_SetNosepiecePosition", "ChangeObjective", "Capture", "ND_RunExperiment")] @@ -280,14 +288,15 @@ def test_nis_server_exposes_exactly_the_nis_tools(tmp_path): from mcp.client.stdio import StdioServerParameters, stdio_client async def names(): - env = dict(os.environ, CONFOCAL_NO_ESTOP_PANEL="1", CONFOCAL_MCP_DATA_DIR=str(tmp_path)) + env = dict(os.environ, CONFOCAL_NO_ESTOP_PANEL="1", CONFOCAL_NO_NIS_MONITOR="1", + CONFOCAL_MCP_DATA_DIR=str(tmp_path)) params = StdioServerParameters(command=sys.executable, args=["-m", "mcp_server.server_nis"], env=env) async with Client(stdio_client(params)) as client: return {t.name for t in (await client.list_tools()).tools} assert asyncio.run(names()) == {"nis_status", "nis_move_relative", "nis_change_objective", "nis_capture", "nis_run_experiment", "nis_finish_experiment", - "estop"} + "nis_list_optical_configs", "estop"} def test_idle_bridge_stops_itself(estop_file): @@ -321,3 +330,115 @@ def test_tool_raises_when_the_turret_does_not_arrive(bridge, monkeypatch): nis.Stg_SetNosepiecePosition = nis._fn("Stg_SetNosepiecePosition", lambda position: 1) with pytest.raises(RuntimeError, match='"arrived": false'): nis_tools.nis_change_objective("Plan Fluor 10x Ph1 DLL", confirm=True) + + +# ---- event log and live monitor --------------------------------------- + +@pytest.fixture +def events_log(tmp_path, monkeypatch): + monkeypatch.setattr(nis_events, "events_dir", lambda: tmp_path / "events") + return nis_events.events_path() + + +def test_actions_are_logged_start_then_outcome(bridge, events_log, estop_file): + nis, url, c = bridge + c.move_relative(100, 0) # ok + c.move_relative(5000, 0) # the bridge refuses the size: failed + estop_file.write_text("{}") + with pytest.raises(estop.EStopEngaged): + c.move_relative(10, 0) # refused by the client + c.nd_finish() # allowed under e-stop + events, _ = nis_events.read_from(events_log) + assert [(e["action"], e["phase"]) for e in events] == [ + ("move", "start"), ("move", "ok"), ("move", "start"), ("move", "failed"), + ("move", "start"), ("move", "refused"), ("nd_finish", "start"), ("nd_finish", "ok")] + assert events[1]["result"]["after_um"][0] == 200.0 and "elapsed_s" in events[1] + assert "cap" in nis_events.summarize(events[3]) or "refused" in nis_events.summarize(events[3]) + + +def test_status_reads_are_not_logged_and_unreachable_bridge_is_logged(events_log): + c = client_mod.NISBridge("http://127.0.0.1:9", timeout_s=1) + with pytest.raises(client_mod.BridgeUnavailable): + c.move_relative(1, 0) + events, _ = nis_events.read_from(events_log) + assert [(e["action"], e["phase"]) for e in events] == [("move", "start"), ("move", "error")] + + +def test_log_tail_waits_for_a_complete_line(events_log): + nis_events.record("move", "start", params={"dx": 1}) + events, offset = nis_events.read_from(events_log) + assert len(events) == 1 + with events_log.open("a", encoding="utf-8") as f: + f.write('{"action": "move", "pha') # a write in progress + assert nis_events.read_from(events_log, offset) == ([], offset) + with events_log.open("a", encoding="utf-8") as f: + f.write('se": "ok"}\n') + assert [e["phase"] for e in nis_events.read_from(events_log, offset)[0]] == ["ok"] + + +def test_monitor_names_the_call_the_bridge_is_stuck_on(estop_file): + import datetime + now = datetime.datetime(2026, 10, 15, 14, 0, 42) + start = {"ts": "2026-10-15T14:00:00.000", "action": "nd_run", "phase": "start", + "params": {"experiment": "bridge test"}} + assert monitor.pending([start]) == start + assert monitor.pending([start, {**start, "phase": "ok"}]) is None + frame = monitor.render("busy", None, [start], "clear", now, colour=False) + assert "BUSY" in frame and "nd_run" in frame and "42 s so far" in frame + up = monitor.render("up", {"xy_um": [1.0, 2.0], "z_um": 3.0, "nosepiece_position": 0, + "current_objective": "PLAN APO λD 4x OFN25", "nd_running": False}, + [], "clear", now, colour=False) + assert "XY 1.0, 2.0" in up and "4x OFN25" in up and "no NIS actions" in up + + +def test_monitor_status_poll_tells_up_from_down(bridge): + nis, url, c = bridge + link, status = monitor.fetch_status(url) + assert link == "up" and status["xy_um"] == [100.0, 200.0] + with socket.socket() as s: # a port nothing listens on: refused at once + s.bind(("127.0.0.1", 0)) + closed = s.getsockname()[1] + assert monitor.fetch_status(f"http://127.0.0.1:{closed}")[0] == "down" + + +def test_monitor_says_busy_when_the_bridge_connects_but_does_not_answer(): + with socket.socket() as s: # accepts connections, never replies + s.bind(("127.0.0.1", 0)) + s.listen(1) + old, monitor.STATUS_TIMEOUT_S = monitor.STATUS_TIMEOUT_S, 0.5 + try: + assert monitor.fetch_status(f"http://127.0.0.1:{s.getsockname()[1]}")[0] == "busy" + finally: + monitor.STATUS_TIMEOUT_S = old + + +def test_monitor_opens_once_when_the_server_starts(monkeypatch): + opened = [] + monkeypatch.setattr(monitor.subprocess, "Popen", lambda *a, **k: opened.append(a[0])) + monkeypatch.delenv("CONFOCAL_NO_NIS_MONITOR", raising=False) + monkeypatch.setattr(monitor, "monitor_running", lambda: False) + monkeypatch.setattr(monitor, "ON_WINDOWS", True) # the launch is Windows-only; CI runs on Linux + monitor.launch() + assert opened and opened[0][-2:] == ["-m", "acquisition.nis_monitor"] + opened.clear() + monkeypatch.setattr(monitor, "monitor_running", lambda: True) # already on screen + monitor.launch() + monkeypatch.setattr(monitor, "monitor_running", lambda: False) + monkeypatch.setenv("CONFOCAL_NO_NIS_MONITOR", "1") # switched off + monitor.launch() + assert opened == [] + + +def test_optical_configs_can_be_listed_but_not_selected(bridge): + nis, url, c = bridge + assert c.optical_configs()["optical_configs"] == ["All Devices", "AX", "EPI"] + assert nis_tools.nis_list_optical_configs()["optical_configs"] == ["All Devices", "AX", "EPI"] + code, out = raw(url, "POST", "/optconf", {"name": "AX"}) # selecting froze NIS: no route + assert code == 404 and nis.moved() == [] + + +def test_a_second_bridge_cannot_share_the_port(bridge): + nis, url, c = bridge + port = int(url.rsplit(":", 1)[1]) + with pytest.raises(OSError): + bj.serve(bj.Bridge(bj.Macro(FakeNIS())), port=port) diff --git a/tests/test_nis_events_monitor.py b/tests/test_nis_events_monitor.py new file mode 100644 index 0000000..d049b08 --- /dev/null +++ b/tests/test_nis_events_monitor.py @@ -0,0 +1,202 @@ +# Tests for the NIS worker-thread entry point, optical configs, event log and +# live monitor. Reuses the fake NIS and the bridge fixture from test_nis_bridge. +# No NIS, no Windows and no hardware needed, so they run on the CI runner. + +import datetime +import sys +import threading + +import pytest + +from acquisition import nis_events, nis_monitor as monitor +from acquisition.backends import nis_bridge as client_mod +from acquisition.nis_bridge import bridge_job as bj +from mcp_server import nis_tools +from tests.test_nis_bridge import bridge, estop_file, events_log, raw # noqa: F401 (fixtures) + +NOW = datetime.datetime(2026, 10, 15, 14, 0, 0) + + +# ---- JOBS entry point --------------------------------------------------- + +def test_run_returns_at_once_and_serves_from_a_worker_thread(monkeypatch): + # A JOBS Python task runs on NIS's main thread: run() must not block it. + started, release, seen = threading.Event(), threading.Event(), {} + + def fake_serve(bridge_obj): + seen["thread"], seen["bridge"] = threading.current_thread(), bridge_obj + started.set() + release.wait(5) + + monkeypatch.setattr(bj, "Macro", lambda: "macro") + monkeypatch.setattr(bj, "Bridge", lambda m: ("bridge", m)) + monkeypatch.setattr(bj, "serve", fake_serve) + bj.run((), None, None, None) # returns although fake_serve is still going + assert started.wait(5) + assert seen["thread"] is not threading.main_thread() + assert seen["thread"].daemon and seen["thread"].name == "nis-bridge" + assert seen["bridge"] == ("bridge", "macro") + release.set() + + +# ---- optical configurations ---------------------------------------------- + +def test_optical_configs_skip_blanks_and_duplicates(bridge): + nis, url, c = bridge + nis.opt_confs = ["AX", "", "AX", "EPI"] + assert c.optical_configs()["optical_configs"] == ["AX", "EPI"] + assert nis.moved() == [] + + +def test_optical_configs_are_get_only_and_not_logged(bridge, events_log): + nis, url, c = bridge + code, _ = raw(url, "POST", "/optconfs", {}) + assert code == 404 + c.optical_configs() + assert nis_events.read_from(events_log) == ([], 0) + + +def test_cli_lists_optical_configs(bridge, capsys, monkeypatch): + nis, url, c = bridge + monkeypatch.setenv("CONFOCAL_NIS_BRIDGE_URL", url) + monkeypatch.setattr(sys, "argv", ["nis_bridge", "optconfs"]) + client_mod.main() + assert "All Devices" in capsys.readouterr().out + + +# ---- MCP tool helpers ------------------------------------------------------ + +def test_checked_passes_good_answers_and_raises_on_failures(): + assert nis_tools._checked({"saved": True, "path": "a.nd2"}) == {"saved": True, "path": "a.nd2"} + for bad in ({"error": "refused"}, {"arrived": False}, {"saved": False}): + with pytest.raises(RuntimeError, match="NIS bridge"): + nis_tools._checked(bad) + + +def test_capture_folder_defaults_under_data_nis_captures(tmp_path, monkeypatch): + monkeypatch.delenv("CONFOCAL_NIS_CAPTURE_DIR", raising=False) + monkeypatch.setattr(nis_tools, "data_root", lambda: tmp_path) + d = nis_tools.capture_dir() + assert d == tmp_path / "data" / "NIS" / "captures" and d.is_dir() + + +# ---- event log ------------------------------------------------------------- + +def test_capture_and_nd_run_are_logged(bridge, events_log, tmp_path): + nis, url, c = bridge + c.capture(str(tmp_path / "log.nd2")) + c.nd_run("exp") + events, _ = nis_events.read_from(events_log) + assert [(e["action"], e["phase"]) for e in events] == [ + ("capture", "start"), ("capture", "ok"), ("nd_run", "start"), ("nd_run", "ok")] + + +def test_recording_never_raises_when_the_log_cannot_be_written(tmp_path, monkeypatch): + blocker = tmp_path / "file" + blocker.write_text("x") + monkeypatch.setattr(nis_events, "events_dir", lambda: blocker / "sub") # a folder cannot be made here + e = nis_events.record("move", "start", params={"dx": 1}) + assert e["action"] == "move" and e["phase"] == "start" + + +def test_reading_a_missing_or_damaged_log(tmp_path): + assert nis_events.read_from(tmp_path / "none.jsonl", 7) == ([], 7) + p = tmp_path / "events.jsonl" + p.write_bytes(b'not json\n{"action": "move", "phase": "ok"}\n') + events, offset = nis_events.read_from(p) + assert events == [{"action": "move", "phase": "ok"}] and offset == p.stat().st_size + + +def test_events_go_to_one_file_per_day(events_log): + assert events_log.name == f"events-{datetime.date.today().isoformat()}.jsonl" + assert nis_events.events_path(datetime.date(2026, 10, 15)).name == "events-2026-10-15.jsonl" + + +def test_summarize_each_kind_of_event(): + s = nis_events.summarize + assert s({"action": "move", "phase": "start", "params": {"dx": 1, "dy": 2}}) == "dx=1 dy=2" + assert s({"action": "move", "phase": "refused", "message": "e-stop"}) == "e-stop" + assert s({"action": "move", "phase": "failed", "result": {"error": "too far"}}) == "too far" + assert s({"action": "move", "phase": "ok", "elapsed_s": 1.5, + "result": {"before_um": [1, 2], "after_um": [3.5, 4]}}) == "(1.0, 2.0) -> (3.5, 4.0) (1.5 s)" + assert s({"action": "move", "phase": "ok", "result": {}}) == "? -> ?" + assert "arrived=True" in s({"action": "objective", "phase": "ok", "result": { + "before": "a", "after": "b", "arrived": True, "nosepiece_before": 1, "nosepiece_after": 2}}) + assert s({"action": "capture", "phase": "ok", + "result": {"saved": True, "path": "p.nd2"}}) == "saved=True p.nd2" + assert s({"action": "nd_run", "phase": "ok", "result": {"nd_running": True}}) == "nd_running=True" + assert s({"action": "shutdown", "phase": "ok", "result": {}}) == "" + + +# ---- monitor --------------------------------------------------------------- + +def test_pending_is_the_latest_unclosed_start(): + a = {"ts": "2026-10-15T14:00:00.000", "action": "capture", "phase": "start"} + b = {"ts": "2026-10-15T14:00:05.000", "action": "nd_run", "phase": "start"} + assert monitor.pending([a, b]) == b + assert monitor.pending([a, b, {**b, "phase": "failed"}]) == a + assert monitor.pending([]) is None + + +def test_render_shows_link_state_estop_and_recent_events(estop_file): + ev = [{"ts": f"2026-10-15T13:00:0{i}.000", "action": "move", "phase": "ok", + "result": {"before_um": [0, 0], "after_um": [i, 0]}} for i in range(5)] + down = monitor.render("down", None, ev, "clear", NOW, rows=2, colour=False) + assert "DOWN" in down and "e-stop: clear" in down + assert "13:00:04" in down and "13:00:03" in down and "13:00:02" not in down # only the last `rows` + assert "\x1b[" not in down + estop_file.write_text("{}") + assert "e-stop: ENGAGED" in monitor.render("up", None, [], "ENGAGED", NOW, colour=False) + assert "\x1b[" in monitor.render("up", None, [], "ENGAGED", NOW, colour=True) + + +def test_render_truncates_long_lines(estop_file): + ev = [{"ts": "2026-10-15T13:00:00.000", "action": "capture", "phase": "ok", + "result": {"saved": True, "path": "x" * 300}}] + frame = monitor.render("up", None, ev, "clear", NOW, width=60, colour=False) + assert all(len(line) <= 60 for line in frame.splitlines()) and "…" in frame + + +def test_fetch_status_treats_a_garbled_answer_as_down(monkeypatch): + class Resp: + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def read(self): + return b"" + + monkeypatch.setattr(monitor.urllib.request, "urlopen", lambda *a, **k: Resp()) + assert monitor.fetch_status("http://x") == ("down", None) + + +def test_monitor_launch_does_nothing_off_windows(monkeypatch): + opened = [] + monkeypatch.setattr(monitor.subprocess, "Popen", lambda *a, **k: opened.append(a)) + monkeypatch.delenv("CONFOCAL_NO_NIS_MONITOR", raising=False) + monkeypatch.setattr(monitor, "ON_WINDOWS", False) + monitor.launch() + assert opened == [] + + +def test_monitor_launch_failure_is_reported_not_raised(monkeypatch, capsys): + def boom(*a, **k): + raise OSError("no console") + + monkeypatch.setattr(monitor.subprocess, "Popen", boom) + monkeypatch.delenv("CONFOCAL_NO_NIS_MONITOR", raising=False) + monkeypatch.setattr(monitor, "ON_WINDOWS", True) + monkeypatch.setattr(monitor, "monitor_running", lambda: False) + monitor.launch() + assert "could not open the monitor window" in capsys.readouterr().err + + +def test_monitor_once_prints_one_snapshot(bridge, events_log, capsys, monkeypatch): + nis, url, c = bridge + c.move_relative(10, 0) + monkeypatch.setattr(sys, "argv", ["nis_monitor", "--once", "--url", url]) + monitor.main() + out = capsys.readouterr().out + assert "bridge: UP" in out and "XY 110.0, 200.0" in out and "move" in out diff --git a/tests/test_nis_mock.py b/tests/test_nis_mock.py new file mode 100644 index 0000000..0702194 --- /dev/null +++ b/tests/test_nis_mock.py @@ -0,0 +1,74 @@ +import pytest + +from acquisition.backends import nis_mock +from acquisition.backends.nis_mock import MockNIS + + +@pytest.fixture(autouse=True) +def fast(monkeypatch, tmp_path): + monkeypatch.setattr(nis_mock.time, "sleep", lambda s: None) + monkeypatch.setattr(nis_mock, "CAPTURE_DIR", tmp_path / "caps") + monkeypatch.setattr(nis_mock, "SAMPLE_FRAME_PATH", tmp_path / "missing.png") + + +def test_start_position_and_absolute_moves(): + n = MockNIS(1, 2, 3) + assert n.XY_GetPosition() == (1.0, 2.0) and n.Z_GetPosition() == 3.0 + n.XY_Move(1000, -500) + n.Z_Move(25) + assert n.XY_GetPosition() == (1000.0, -500.0) and n.Z_GetPosition() == 25.0 + + +def test_relative_moves(): + n = MockNIS() + n.XY_MoveRelative(250, 250) + n.Z_MoveRelative(-0.0) + n.Z_MoveRelative(5) + assert n.XY_GetPosition() == (250.0, 250.0) and n.Z_GetPosition() == 5.0 + + +@pytest.mark.parametrize("x,y", [(60_000, 0), (-60_000, 0), (0, 40_000), (0, -40_000)]) +def test_xy_outside_travel_is_refused(x, y): + n = MockNIS(x=0 if abs(x) > 57_000 else x, y=0) + with pytest.raises(ValueError, match="outside the stage travel limit"): + n.XY_Move(x, y) + assert n.XY_GetPosition() == (0.0 if abs(x) > 57_000 else float(x), 0.0) + + +def test_xy_step_cap(): + n = MockNIS() + with pytest.raises(ValueError, match="per-call safety limit"): + n.XY_Move(5001, 0) + assert n.XY_GetPosition() == (0.0, 0.0) + + +def test_z_limits_and_step_cap(): + n = MockNIS(z=5) + with pytest.raises(ValueError, match="outside the stage travel limit"): + n.Z_Move(-1) + with pytest.raises(ValueError, match="outside the stage travel limit"): + n.Z_Move(10_001) + with pytest.raises(ValueError, match="per-call safety limit"): + n.Z_Move(5 + 51) + assert n.Z_GetPosition() == 5.0 + + +def test_abort_is_never_requested(): + n = MockNIS() + assert n.shouldAbort() is False and n.ctx.shouldAbort() is False + + +def test_capture_makes_unique_files_with_placeholder(): + n = MockNIS() + a, b = n.capture(), n.capture() + assert a != b and a.exists() and b.exists() + assert a.suffix == ".png" and a.name.endswith("_0001.png") and b.name.endswith("_0002.png") + + +def test_capture_copies_the_sample_frame_when_present(tmp_path, monkeypatch): + from PIL import Image + sample = tmp_path / "sample.png" + Image.new("RGB", (8, 8), (1, 2, 3)).save(sample) + monkeypatch.setattr(nis_mock, "SAMPLE_FRAME_PATH", sample) + out = MockNIS().capture() + assert Image.open(out).size == (8, 8) diff --git a/tests/test_nis_sdk.py b/tests/test_nis_sdk.py new file mode 100644 index 0000000..990b786 --- /dev/null +++ b/tests/test_nis_sdk.py @@ -0,0 +1,141 @@ +import pytest + +from acquisition import estop +from tests.fakes import fake_ti2 # noqa: F401 (fixture) + + +@pytest.fixture +def clear_estop(tmp_path, monkeypatch): + monkeypatch.setattr(estop, "ESTOP_PATH", tmp_path / "ESTOP") + return tmp_path / "ESTOP" + + +def test_positions_are_converted_to_microns(fake_ti2, clear_estop): + sdk, m = fake_ti2 + s = sdk.NISSdk() + assert s.XY_GetPosition() == (100.0, 200.0) and s.Z_GetPosition() == 4619.0 + + +def test_all_instances_share_one_com_thread(fake_ti2, clear_estop): + sdk, m = fake_ti2 + assert sdk.NISSdk()._thread is sdk.NISSdk()._thread + + +def test_xy_move_writes_counts(fake_ti2, clear_estop, capsys): + sdk, m = fake_ti2 + sdk.NISSdk().XY_Move(150.5, 250.3) + assert (m.iXPOSITION, m.iYPOSITION) == (1505, 2503) + assert "XY_Move" in capsys.readouterr().out + + +def test_xy_move_step_cap_and_travel_range(fake_ti2, clear_estop): + sdk, m = fake_ti2 + s = sdk.NISSdk() + with pytest.raises(ValueError, match="per-call safety limit"): + s.XY_Move(100 + 5001, 200) + m.XPosition.Higher = 1500 # soft limit at 150 um + with pytest.raises(ValueError, match="X target"): + s.XY_Move(200, 200) + m.YPosition.Lower = 3000 + with pytest.raises(ValueError, match="Y target"): + s.XY_Move(100, 250) + assert (m.iXPOSITION, m.iYPOSITION) == (1000, 2000) + + +def test_xy_move_warns_when_readback_differs(fake_ti2, clear_estop, capsys): + sdk, m = fake_ti2 + m.__class__ = type("Sticky", (type(m),), { + "iXPOSITION": property(lambda self: 1000, lambda self, v: None)}) + sdk.NISSdk().XY_Move(110, 200) + assert "WARNING" in capsys.readouterr().out + + +def test_z_move_writes_counts_and_enforces_limits(fake_ti2, clear_estop, capsys): + sdk, m = fake_ti2 + s = sdk.NISSdk() + s.Z_Move(4619 + 10) + assert m.iZPOSITION == 462900 + with pytest.raises(ValueError, match="per-call safety limit"): + s.Z_Move(4629 + 51) + m.ZPosition.Higher = 462000 + with pytest.raises(ValueError, match="Z target"): + s.Z_Move(4629 + 5) + assert m.iZPOSITION == 462900 + + +def test_z_move_warns_when_readback_differs(fake_ti2, clear_estop, capsys): + sdk, m = fake_ti2 + m.__class__ = type("Sticky", (type(m),), { + "iZPOSITION": property(lambda self: 461900, lambda self, v: None)}) + sdk.NISSdk().Z_Move(4620) + assert "WARNING" in capsys.readouterr().out + + +def test_estop_blocks_every_motion_primitive(fake_ti2, clear_estop): + sdk, m = fake_ti2 + s = sdk.NISSdk() + estop.engage("test") + for call in (lambda: s.XY_Move(101, 200), lambda: s.Z_Move(4620), lambda: s.nudge_pfs_offset(10)): + with pytest.raises(estop.EStopEngaged): + call() + assert (m.iXPOSITION, m.iYPOSITION, m.iZPOSITION, m.iPFS_OFFSET) == (1000, 2000, 461900, 18966) + + +def test_pfs_status(fake_ti2, clear_estop): + sdk, m = fake_ti2 + st = sdk.NISSdk().pfs_status() + assert st["enabled"] is True and st["offset"] == 18966 and st["offset_higher"] == 40000 + assert st["objective_magnification"] == 10 and st["working_distance_mm"] == 4.0 + + +def test_pfs_nudge_applies_within_cap(fake_ti2, clear_estop): + sdk, m = fake_ti2 + assert sdk.NISSdk().nudge_pfs_offset(100) == {"offset_before": 18966, "offset_after": 19066} + + +def test_pfs_nudge_refusals(fake_ti2, clear_estop): + sdk, m = fake_ti2 + s = sdk.NISSdk() + with pytest.raises(ValueError, match="safety limit"): # 2% of 40000 = 800 + s.nudge_pfs_offset(801) + m.iPFS_OFFSET = 100 + with pytest.raises(ValueError, match="outside the reported"): + s.nudge_pfs_offset(-200) + m.objective.IsPFSEnabled = False + try: + with pytest.raises(PermissionError, match="PFS is not currently enabled"): + s.nudge_pfs_offset(10) + finally: + m.objective.IsPFSEnabled = True + assert m.iPFS_OFFSET == 100 + + +def test_optical_configuration_snapshot_skips_unreadable(fake_ti2, clear_estop): + sdk, m = fake_ti2 + cfg = sdk.NISSdk().get_optical_configuration() + assert cfg == {"iDIA_LAMP_Switch": 1, "iLIGHTPATH": 2, "iNOSEPIECE": 3, "iXPOSITION": 5} + + +def test_apply_configuration_skips_motion_unless_asked(fake_ti2, clear_estop): + sdk, m = fake_ti2 + s = sdk.NISSdk() + cfg = {"iLIGHTPATH": 4, "iDIA_LAMP_Switch": 1, "iNOSEPIECE": 5, "iXPOSITION": 7, "iZPOSITION": 9} + assert s.apply_optical_configuration(cfg) == {"iLIGHTPATH": 4, "iDIA_LAMP_Switch": 1} + assert (m.iNOSEPIECE, m.iXPOSITION) == (1, 1000) + out = s.apply_optical_configuration({"iNOSEPIECE": 5}, include_motion=True) + assert out == {"iNOSEPIECE": 5} and m.iNOSEPIECE == 5 + + +def test_apply_configuration_records_none_for_a_property_that_raises(fake_ti2, clear_estop): + sdk, m = fake_ti2 + m.__class__ = type("Locked", (type(m),), { + "iLIGHTPATH": property(lambda self: 1, lambda self, v: (_ for _ in ()).throw(RuntimeError("no")))}) + assert sdk.NISSdk().apply_optical_configuration({"iLIGHTPATH": 3}) == {"iLIGHTPATH": None} + + +def test_com_thread_reraises_job_errors(fake_ti2, clear_estop): + sdk, m = fake_ti2 + t = sdk.NISSdk()._thread + with pytest.raises(ZeroDivisionError): + t.call(lambda mic: 1 / 0) + assert t.call(lambda mic: 5) == 5 # thread survives diff --git a/tests/test_paths.py b/tests/test_paths.py new file mode 100644 index 0000000..36aa051 --- /dev/null +++ b/tests/test_paths.py @@ -0,0 +1,55 @@ +from pathlib import Path + +import pytest + +from acquisition import paths + + +@pytest.fixture(autouse=True) +def fresh_cache(): + paths.data_root.cache_clear() + yield + paths.data_root.cache_clear() + + +def test_env_var_is_honoured_as_is(tmp_path, monkeypatch): + monkeypatch.setenv("CONFOCAL_MCP_DATA_DIR", str(tmp_path)) + assert paths.data_root() == tmp_path.resolve() + assert paths.captures_dir() == tmp_path.resolve() / "data" / "captures" + assert paths.logs_dir() == tmp_path.resolve() / "logs" + + +def test_unset_uses_a_writable_cwd(tmp_path, monkeypatch): + monkeypatch.delenv("CONFOCAL_MCP_DATA_DIR", raising=False) + monkeypatch.chdir(tmp_path) + assert paths.data_root() == Path.cwd() + + +def test_unset_falls_back_when_cwd_is_not_writable(tmp_path, monkeypatch, capsys): + monkeypatch.delenv("CONFOCAL_MCP_DATA_DIR", raising=False) + monkeypatch.chdir(tmp_path) + monkeypatch.setattr(paths, "_is_writable", lambda p: False) + assert paths.data_root() == paths.FALLBACK_DATA_ROOT + err = capsys.readouterr().err + assert "not usable for runtime data" in err + + +def test_system_directory_is_rejected_even_if_writable(tmp_path, monkeypatch): + monkeypatch.setenv("SystemRoot", str(tmp_path / "windows")) + assert paths._is_system_dir(tmp_path / "windows") + assert paths._is_system_dir(tmp_path / "windows" / "system32") + assert not paths._is_system_dir(tmp_path / "other") + monkeypatch.delenv("SystemRoot") + assert not paths._is_system_dir(tmp_path) + + +def test_usable_data_root_rejects_system_dir(tmp_path, monkeypatch): + monkeypatch.setenv("SystemRoot", str(tmp_path)) + assert paths._usable_data_root(tmp_path / "system32") == paths.FALLBACK_DATA_ROOT + + +def test_is_writable_probes_with_a_real_file(tmp_path): + assert paths._is_writable(tmp_path / "new" / "dir") + blocker = tmp_path / "file" + blocker.write_text("x") + assert not paths._is_writable(blocker / "sub") diff --git a/tests/test_small_gaps.py b/tests/test_small_gaps.py new file mode 100644 index 0000000..878ef74 --- /dev/null +++ b/tests/test_small_gaps.py @@ -0,0 +1,298 @@ +# The last small branches: server entry points, package version fallback, +# bridge error paths, and a few `python -m` blocks. +import contextlib +import http.server +import importlib +import json +import queue +import runpy +import sys +import threading +import types +import urllib.request +from pathlib import Path +from types import SimpleNamespace as NS + +import pytest + +from acquisition import estop, nis_monitor, paths +from acquisition.backends import nis_bridge as client_mod +from acquisition.nis_bridge import bridge_job as bj +from acquisition.orchestration import stage_positions, worm_follow +from harness import context +from mcp_server import nis_tools +from tests.fakes import fake_ti2 # noqa: F401 (fixture) +from tests.fakes_camera import install_fake_camera_stack +from tests.test_nis_bridge import FakeNIS, bridge, estop_file, raw # noqa: F401 (fixtures) + + +# ---- MCP server entry points ------------------------------------------------------- + +def test_nis_server_main_opens_the_panel_and_monitor_then_serves(monkeypatch): + from mcp_server import server_nis + calls = [] + monkeypatch.setattr(server_nis.estop, "launch_panel", lambda: calls.append("panel")) + monkeypatch.setattr(server_nis.nis_monitor, "launch", lambda: calls.append("monitor")) + monkeypatch.setattr(server_nis.mcp, "run", lambda transport: calls.append(("run", transport))) + server_nis.main() + assert calls == ["panel", "monitor", ("run", "stdio")] + + +def test_loop_server_main_opens_the_panel_then_serves(monkeypatch): + from mcp_server import server_loop + calls = [] + monkeypatch.setattr(server_loop.estop, "launch_panel", lambda: calls.append("panel")) + monkeypatch.setattr(server_loop.mcp, "run", lambda transport: calls.append(("run", transport))) + server_loop.main() + assert calls == ["panel", ("run", "stdio")] + + +@pytest.mark.parametrize("module", ["mcp_server.server_loop", "mcp_server.server_nis"]) +def test_server_modules_start_when_run_with_dash_m(module, monkeypatch): + from mcp.server.mcpserver import MCPServer + ran = [] + monkeypatch.setattr(MCPServer, "run", lambda self, transport: ran.append(transport)) + monkeypatch.setattr(estop, "launch_panel", lambda: None) + monkeypatch.setattr(nis_monitor, "launch", lambda: None) + runpy.run_module(module, run_name="__main__") + assert ran == ["stdio"] + + +def test_the_nis_server_registers_the_nis_tools_in_process(): + import asyncio + from mcp_server import server_nis + names = {t.name for t in asyncio.run(server_nis.mcp.list_tools())} + assert names == {"nis_status", "nis_move_relative", "nis_change_objective", "nis_capture", + "nis_run_experiment", "nis_finish_experiment", "nis_list_optical_configs", "estop"} + + +def test_package_version_falls_back_when_not_installed(monkeypatch): + import importlib.metadata as md + import mcp_server + + def missing(name): + raise md.PackageNotFoundError(name) + + monkeypatch.setattr(md, "version", missing) + try: + importlib.reload(mcp_server) + assert mcp_server.__version__ == "0.0.0+unknown" + finally: + monkeypatch.undo() + importlib.reload(mcp_server) + + +# ---- NIS tools / client / bridge ----------------------------------------------------- + +def test_status_and_finish_tools_reach_the_bridge(bridge): + nis, url, c = bridge + assert nis_tools.nis_status()["xy_um"] == [100.0, 200.0] + nis.nd_running = True + assert nis_tools.nis_finish_experiment()["nd_running"] is False + + +def test_client_wraps_a_non_json_error_body(tmp_path): + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(500) + self.end_headers() + self.wfile.write(b"oops") + + def log_message(self, *a): + pass + + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=srv.serve_forever, daemon=True).start() + try: + out = client_mod.NISBridge(f"http://127.0.0.1:{srv.server_address[1]}").status() + finally: + srv.shutdown() + srv.server_close() + assert out["http_status"] == 500 and "error" in out + + +def run_cli(monkeypatch, *argv): + monkeypatch.setattr(sys, "argv", ["nis_bridge", *argv]) + client_mod.main() + + +def test_cli_exits_with_the_reason_when_the_bridge_is_down_or_stopped(monkeypatch, estop_file): + monkeypatch.setenv("CONFOCAL_NIS_BRIDGE_URL", "http://127.0.0.1:9") + with pytest.raises(SystemExit, match="not reachable"): + run_cli(monkeypatch, "status") + estop_file.write_text("{}") + with pytest.raises(SystemExit, match="E-STOP"): + run_cli(monkeypatch, "move", "1", "0") + + +def test_cli_prints_the_bridge_answer(bridge, monkeypatch, capsys): + nis, url, c = bridge + run_cli(monkeypatch, "--url", url, "status") + assert json.loads(capsys.readouterr().out)["xy_um"] == [100.0, 200.0] + + +def test_cli_module_runs_as_a_script(bridge, monkeypatch, capsys): + nis, url, c = bridge + monkeypatch.setattr(sys, "argv", ["nis_bridge", "--url", url, "status"]) + runpy.run_module("acquisition.backends.nis_bridge", run_name="__main__") + assert "xy_um" in capsys.readouterr().out + + +def test_bridge_treats_an_unreadable_estop_file_as_engaged(monkeypatch): + class Broken: + def exists(self): + raise PermissionError("denied") + + monkeypatch.setattr(bj, "ESTOP", Broken()) + assert bj._estop_engaged() is True + + +def test_objective_name_must_be_on_the_nosepiece_exactly_once(bridge): + nis, url, c = bridge + nis.objectives[5] = nis.objectives[2] # the same 10x in two positions + r = c.change_objective("Plan Fluor 10x Ph1 DLL") + assert "exactly once" in r["error"] and "Stg_SetNosepiecePosition" not in nis.calls + + +def test_bridge_rejects_a_body_that_is_not_json(bridge): + nis, url, c = bridge + req = urllib.request.Request(url + "/move", data=b"{not json", method="POST") + try: + urllib.request.urlopen(req, timeout=5) + status = 200 + except urllib.error.HTTPError as e: + status, body = e.code, json.loads(e.read()) + assert status == 400 and "not JSON" in body["error"] + assert nis.moved() == [] + + +def test_a_route_that_raises_is_reported_and_the_bridge_survives(bridge, monkeypatch): + nis, url, c = bridge + monkeypatch.setitem(bj.ROUTES, ("GET", "/status"), lambda b, body: 1 / 0) + assert "ZeroDivisionError" in c.status()["error"] + monkeypatch.undo() + assert c.status()["xy_um"] == [100.0, 200.0] + + +def test_a_request_the_worker_never_answers_times_out_with_504(): + jobs, stop = queue.Queue(), threading.Event() # nobody consumes the queue + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), bj.make_handler(jobs, stop, timeout_s=0.1)) + threading.Thread(target=srv.serve_forever, daemon=True).start() + try: + code, out = raw(f"http://127.0.0.1:{srv.server_address[1]}", "POST", "/move", {"dx": 1}) + finally: + srv.shutdown() + srv.server_close() + assert code == 504 and "timed out" in out["error"] + + +# ---- paths / monitor / context ---------------------------------------------------------- + +def test_system_dir_check_survives_an_os_error(monkeypatch): + class Odd: + def __eq__(self, other): + raise OSError("odd filesystem") + + @property + def parents(self): + raise OSError("odd filesystem") + + monkeypatch.setenv("SystemRoot", "C:\\Windows") + assert paths._is_system_dir(Odd()) is False + + +def test_monitor_probe_is_false_off_windows(monkeypatch): + monkeypatch.setattr(sys, "platform", "linux") + assert nis_monitor.monitor_running() is False + + +def test_monitor_module_prints_one_snapshot_as_a_script(monkeypatch, capsys): + monkeypatch.setenv("CONFOCAL_NIS_BRIDGE_URL", "http://127.0.0.1:9") + monkeypatch.setattr(sys, "argv", ["nis_monitor", "--once"]) + runpy.run_module("acquisition.nis_monitor", run_name="__main__") + assert "bridge:" in capsys.readouterr().out + + +def test_strip_images_copies_plain_string_content(): + msg = {"role": "user", "content": "just text"} + out = context._strip_images(msg) + assert out == msg and out is not msg + + +# ---- camera / stage backends ------------------------------------------------------------ + +def test_camera_demo_captures_one_frame(monkeypatch, tmp_path, capsys): + mod, acq, _ = install_fake_camera_stack(monkeypatch, tmp_path) + try: + runpy.run_module("acquisition.backends.baumer_genicam", run_name="__main__") + finally: + sys.modules.pop("acquisition.backends.baumer_genicam", None) + assert "Saved:" in capsys.readouterr().out and acq.stopped + + +def test_stage_positions_can_drive_the_sdk_backend(fake_ti2, tmp_path): + m = stage_positions.StagePositionManager(backend="sdk", positions_file=tmp_path / "p.json") + assert m.save_current("here") == {"x": 100.0, "y": 200.0, "z": 4619.0} + + +def test_force_camera_autos_off_ignores_nodes_that_raise(): + class Bad: + @property + def value(self): + raise RuntimeError("node not available") + + nm = NS(BalanceWhiteAuto=Bad(), ColorTransformationAuto=Bad(), ExposureAuto=Bad(), GainAuto=Bad()) + cam = NS(_acquirer=NS(remote_device=NS(node_map=nm))) + worm_follow.force_camera_autos_off(cam) # no exception + + +# ---- the NIS port probe's timeout and the calibration/panel scripts ------------------------- + +def test_probe_reports_a_nis_that_never_answers(monkeypatch, tmp_path): + import ctypes + limjob = types.ModuleType("limjob") + limjob.Image = limjob.JobParam = limjob.MacroParam = limjob.RunContext = object + monkeypatch.setitem(sys.modules, "limjob", limjob) + monkeypatch.setattr(ctypes, "cdll", NS(g5_regprocs=FakeNIS()), raising=False) + sys.modules.pop("acquisition.calibration.nis_port_probe", None) + mod = importlib.import_module("acquisition.calibration.nis_port_probe") + + class NeverAnswers(queue.Queue): + def get(self, timeout=None): + raise queue.Empty + + monkeypatch.setattr(mod, "queue", NS(Queue=NeverAnswers, Empty=queue.Empty)) + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), mod.H) + threading.Thread(target=srv.serve_forever, daemon=True).start() + try: + with urllib.request.urlopen(f"http://127.0.0.1:{srv.server_address[1]}/status", timeout=5) as r: + assert "timed out waiting for NIS" in json.loads(r.read())["error"] + finally: + srv.shutdown() + srv.server_close() + sys.modules.pop("acquisition.calibration.nis_port_probe", None) + + +@pytest.mark.parametrize("module", ["acquisition.calibration.ti2_config", "acquisition.calibration.ti2_inventory"]) +def test_calibration_modules_run_as_scripts(module, monkeypatch, capsys): + monkeypatch.setattr(sys, "argv", ["x", "--help"]) + with pytest.raises(SystemExit) as exc: + runpy.run_module(module, run_name="__main__") + assert exc.value.code == 0 and "usage" in capsys.readouterr().out + + +def test_estop_panel_runs_as_a_script(monkeypatch): + class TclError(Exception): + pass + + def no_display(): + raise TclError("no display") + + tk = types.ModuleType("tkinter") + tk.Tk, tk.TclError = no_display, TclError + tk.messagebox = types.ModuleType("tkinter.messagebox") + monkeypatch.setitem(sys.modules, "tkinter", tk) + monkeypatch.setitem(sys.modules, "tkinter.messagebox", tk.messagebox) + monkeypatch.setattr(sys, "argv", ["estop_panel"]) + with contextlib.suppress(SystemExit): # no display -> exit 1; already open -> returns + runpy.run_module("acquisition.estop_panel", run_name="__main__") diff --git a/tests/test_stage_positions.py b/tests/test_stage_positions.py new file mode 100644 index 0000000..36564ce --- /dev/null +++ b/tests/test_stage_positions.py @@ -0,0 +1,117 @@ +import pytest + +from acquisition.backends import nis_mock +from acquisition.backends.nis_mock import MockNIS +from acquisition.orchestration import stage_positions as sp + + +@pytest.fixture +def mgr(tmp_path, monkeypatch): + monkeypatch.setattr(nis_mock.time, "sleep", lambda s: None) + nis = MockNIS(100, 200, 10) + return sp.StagePositionManager(nis_module=nis, positions_file=tmp_path / "p.json"), nis + + +def test_validate_position_limits(): + sp.validate_position(0, 0) + sp.validate_position(57_000, -36_500) + with pytest.raises(ValueError, match="X position"): + sp.validate_position(57_001, 0) + with pytest.raises(ValueError, match="Y position"): + sp.validate_position(0, 36_501) + + +def test_to_plain_float_unwraps_numpy(): + import numpy as np + v = sp.to_plain_float(np.float32(1.5)) + assert type(v) is float and v == 1.5 + + +def test_save_list_and_persist(mgr, tmp_path): + m, nis = mgr + assert m.save_current("a") == {"x": 100.0, "y": 200.0, "z": 10.0} + assert m.list_positions() == {"a": {"x": 100.0, "y": 200.0, "z": 10.0}} + again = sp.StagePositionManager(nis_module=nis, positions_file=tmp_path / "p.json") + assert "a" in again.list_positions() # survived a restart + + +def test_save_current_refuses_an_impossible_reading(mgr): + m, nis = mgr + nis._x = 99_999.0 + with pytest.raises(ValueError): + m.save_current("bad") + assert m.list_positions() == {} + + +def test_define_position_validates_and_overwrites(mgr): + m, _ = mgr + m.define_position("p", 1, 2, 3) + m.define_position("p", 4, 5, 6) + assert m.list_positions()["p"] == {"x": 4.0, "y": 5.0, "z": 6.0} + with pytest.raises(ValueError): + m.define_position("far", 90_000, 0, 0) + assert "far" not in m.list_positions() + + +def test_go_to_moves_xy_then_z(mgr): + m, nis = mgr + m.define_position("p", 500, 600, 20) + m.go_to("p") + assert nis.XY_GetPosition() == (500.0, 600.0) and nis.Z_GetPosition() == 20.0 + + +def test_go_to_unknown_label(mgr): + m, _ = mgr + with pytest.raises(KeyError, match="No saved position"): + m.go_to("nope") + + +def test_go_to_refuses_hand_edited_out_of_range_position(mgr): + m, nis = mgr + m._positions["bad"] = {"x": 90_000.0, "y": 0.0, "z": 0.0} + with pytest.raises(ValueError): + m.go_to("bad") + assert nis.XY_GetPosition() == (100.0, 200.0) + + +def test_go_to_returns_xy_when_z_step_is_too_big(mgr): + m, nis = mgr + m.define_position("far_z", 500, 600, 10 + 51) # beyond the 50 um per-call cap + with pytest.raises(ValueError, match="per-call safety limit"): + m.go_to("far_z") + assert nis.XY_GetPosition() == (100.0, 200.0) # moved back + + +def test_delete(mgr): + m, _ = mgr + m.define_position("p", 1, 2, 3) + m.delete("p") + assert m.list_positions() == {} + with pytest.raises(KeyError): + m.delete("p") + + +def test_load_positions_from_yaml(mgr, tmp_path): + m, _ = mgr + y = tmp_path / "proto.yaml" + y.write_text("positions:\n - {label: A, x: 1, y: 2, z: 3}\n - {label: B, x: 4, y: 5, z: 6}\n") + assert m.load_positions_from_yaml(y) == {"A": {"x": 1.0, "y": 2.0, "z": 3.0}, + "B": {"x": 4.0, "y": 5.0, "z": 6.0}} + assert set(m.list_positions()) == {"A", "B"} + + +def test_print_summary(mgr, capsys): + m, _ = mgr + m.print_summary() + assert "No saved positions" in capsys.readouterr().out + m.define_position("alpha", 1, 2, 3) + out = capsys.readouterr() + m.print_summary() + out = capsys.readouterr().out + assert "alpha" in out and "x (um)" in out and "1.00" in out + + +def test_backend_selection(tmp_path): + assert sp.StagePositionManager(positions_file=tmp_path / "a.json")._nis is sp.nis + with pytest.raises(ValueError, match="Unknown backend"): + sp.StagePositionManager(backend="bogus", positions_file=tmp_path / "b.json") diff --git a/tests/test_timelapse_gaps.py b/tests/test_timelapse_gaps.py new file mode 100644 index 0000000..726fda2 --- /dev/null +++ b/tests/test_timelapse_gaps.py @@ -0,0 +1,357 @@ +# Edge cases of the timelapse package: validation, CLI, error paths, and the +# real model call (against a fake SDK). +import json +import runpy +import sys +from concurrent.futures import Future +from pathlib import Path +from types import SimpleNamespace as NS + +import numpy as np +import pytest + +from timelapse import change_detector as cd, frame_audit as fa, model_trigger as mt, scheduler as sc +from timelapse.change_detector import ChangeScore + +ROOT = Path(__file__).parent.parent + + +# ---- change_detector --------------------------------------------------------------- + +def test_otsu_of_an_empty_image_is_zero(): + assert cd.otsu_threshold(np.zeros((0, 0))) == 0.0 + + +def test_phase_correlation_refuses_mismatched_shapes(): + with pytest.raises(ValueError, match="shape mismatch"): + cd.phase_correlation_shift(np.zeros((8, 8)), np.zeros((8, 9))) + + +def test_estimate_shift_rejects_a_peak_that_does_not_improve_the_match(): + rng = np.random.default_rng(0) + a, b = rng.random((32, 32)) * 255, rng.random((32, 32)) * 255 # unrelated noise + assert cd.estimate_shift(a, b) == (0.0, 0.0) + + +def test_estimate_shift_of_identical_frames_is_zero(monkeypatch): + a = np.random.default_rng(1).random((16, 16)) * 255 + assert cd.estimate_shift(a, a.copy()) == (0.0, 0.0) + # even if the correlator reported a peak, frames with no difference at all moved nowhere + monkeypatch.setattr(cd, "phase_correlation_shift", lambda x, y: (3.0, 1.0)) + assert cd.estimate_shift(a, a.copy()) == (0.0, 0.0) + + +def test_inverted_detector_and_path_scoring(write_frame): + det = cd.ChangeDetector(invert=True) + first = det.score(write_frame("a.png", seed=1)) + assert first.interesting is False and first.baseline_frames == 0 + + +# ---- frame_audit --------------------------------------------------------------------- + +def test_parse_duration_and_timestamp_variants(): + assert fa.parse_duration("90m") == 5400 and fa.parse_duration("30") == 30 and fa.parse_duration("1.5h") == 5400 + with pytest.raises(ValueError, match="bad duration"): + fa.parse_duration("soon") + assert fa.parse_timestamp("1700000000") == 1700000000.0 + assert fa.parse_timestamp("2026-10-15T14:00:00") == pytest.approx( + __import__("datetime").datetime(2026, 10, 15, 14).timestamp()) + + +def test_frames_from_dir_needs_matching_files(tmp_path): + with pytest.raises(FileNotFoundError, match="no files matching"): + fa.frames_from_dir(tmp_path, "*.png") + + +def test_frames_from_history_skips_blank_lines_and_rejects_empty(tmp_path): + h = tmp_path / "frames.jsonl" + h.write_text('\n{"image": "a.png", "captured_at": "100"}\n\n{"image": "b.png", "captured_at": "160"}\n') + frames = fa.frames_from_history(h) + assert [(f.index, f.path.name, f.t_s) for f in frames] == [(0, "a.png", 100.0), (1, "b.png", 160.0)] + h.write_text("\n\n") + with pytest.raises(ValueError, match="no frame records"): + fa.frames_from_history(h) + + +def test_apply_timestamps_checks_the_count_and_ignores_comments(tmp_path, write_frame): + frames = fa.frames_from_dir(write_frame("a.png").parent, "*.png") + ts = tmp_path / "ts.csv" + ts.write_text("# header\n100\n") + assert fa.apply_timestamps(frames, ts)[0].t_s == 100.0 + ts.write_text("100\n200\n") + with pytest.raises(ValueError, match="2 timestamps but there are 1 frames"): + fa.apply_timestamps(frames, ts) + + +def test_audit_needs_two_frames(write_frame): + f = fa.FrameRecord(0, write_frame("a.png"), 0.0) + with pytest.raises(ValueError, match="at least 2 frames"): + fa.audit([f]) + + +def test_audit_flags_size_changes_and_time_going_backwards(write_frame): + frames = [fa.FrameRecord(0, write_frame("a.png", size=64), 100.0), + fa.FrameRecord(1, write_frame("b.png", size=96), 90.0), + fa.FrameRecord(2, write_frame("c.png", size=96), 120.0)] + r = fa.audit(frames) + assert "SIZE CHANGED" in r[0].flags and "NON-MONOTONIC TIME" in r[0].flags + assert np.isnan(r[0].shift_px) + + +def test_audit_cli_flagged_only_from_history(write_frame, tmp_path, capsys): + a, b, c = (write_frame(f"{n}.png", seed=i) for i, n in enumerate("abc")) + h = tmp_path / "h.jsonl" + h.write_text("".join(json.dumps({"image": str(p), "captured_at": str(t)}) + "\n" + for p, t in ((a, 0), (b, 60), (c, 600)))) + assert fa.main(["--history", str(h), "--flagged-only"]) == 0 + out = capsys.readouterr().out + assert "3 frames, 2 intervals" in out and "GAP" in out + + +def test_audit_cli_with_a_timestamp_file(write_frame, tmp_path, capsys): + write_frame("a.png", seed=1), write_frame("b.png", seed=2) + ts = tmp_path / "ts.csv" + ts.write_text("0\n30\n") + assert fa.main([str(tmp_path), "--timestamps", str(ts)]) == 0 + assert "2 frames, 1 intervals" in capsys.readouterr().out + + +def test_audit_module_runs_as_a_script(write_frame, tmp_path, monkeypatch, capsys): + write_frame("a.png", seed=1), write_frame("b.png", seed=2) + monkeypatch.setattr(sys, "argv", ["frame_audit", str(tmp_path)]) + with pytest.raises(SystemExit) as exc: + runpy.run_module("timelapse.frame_audit", run_name="__main__") + assert exc.value.code == 0 + + +# ---- model_trigger --------------------------------------------------------------------- + +def test_parse_decision_with_broken_json_is_no_opinion(): + assert mt.parse_decision('see {"decision": extend,} ok') == (None, 'see {"decision": extend,} ok') + + +class FakeAnthropic: + stop_reason = "end_turn" + blocks = [NS(type="thinking"), NS(type="text", text='{"decision": '), NS(type="text", text='"extend"}')] + seen = {} + + def __init__(self): + self.messages = NS(create=lambda **kw: (FakeAnthropic.seen.update(kw), + NS(stop_reason=FakeAnthropic.stop_reason, + content=FakeAnthropic.blocks))[1]) + + +def test_anthropic_ask_joins_text_blocks_and_uses_adaptive_thinking(monkeypatch): + import anthropic + import dotenv + monkeypatch.setattr(anthropic, "Anthropic", FakeAnthropic) + monkeypatch.setattr(dotenv, "load_dotenv", lambda: None) + out = mt.anthropic_ask("system", [{"type": "text", "text": "hi"}]) + assert out == '{"decision": "extend"}' + assert FakeAnthropic.seen["system"] == "system" and FakeAnthropic.seen["thinking"] == {"type": "adaptive"} + assert FakeAnthropic.seen["model"] == mt.MODEL + + +def test_anthropic_ask_returns_nothing_on_a_refusal(monkeypatch): + import anthropic + import dotenv + monkeypatch.setattr(anthropic, "Anthropic", FakeAnthropic) + monkeypatch.setattr(dotenv, "load_dotenv", lambda: None) + monkeypatch.setattr(FakeAnthropic, "stop_reason", "refusal") + assert mt.anthropic_ask("s", []) == "" + + +# ---- scheduler ------------------------------------------------------------------------------ + +@pytest.mark.parametrize("bad", [ + dict(backend="nope"), dict(slow_interval_s=0), dict(burst_interval_s=-1), + dict(burst_interval_s=90.0, slow_interval_s=60.0), dict(max_captures=0), dict(max_runtime_s=0)]) +def test_config_validation_refuses_nonsense(bad): + with pytest.raises(ValueError): + sc.TimelapseConfig(**bad).validate() + + +def score(interesting=True, shift=0.0): + return ChangeScore(diff_score=9.0, area_delta=0.2, shift_px=shift, foreground_fraction=0.3, + baseline_frames=5, interesting=interesting, reason="changed") + + +class Rig: + """A timelapse whose detector returns scripted scores.""" + + def __init__(self, tmp_path, write_frame, scores, **cfg): + self.t = 1000.0 + self.frame = str(write_frame("f.png")) + self.scores = list(scores) + config = sc.TimelapseConfig(slow_interval_s=60, burst_interval_s=5, burst_duration_s=30, + events_path=tmp_path / "ev.jsonl", **cfg) + self.n = 0 + self.tl = sc.AdaptiveTimelapse(config, capture=self.capture, clock=lambda: self.t, + sleep=self.sleep, log=lambda s: None) + self.tl.detector = NS(score_array=lambda g: self.scores.pop(0) if self.scores else score(False)) + + def capture(self): + self.n += 1 + return {"image": self.frame, "frame_id": self.n, "position": {"x": 0, "y": 0, "z": 0}} + + def sleep(self, s): + self.t += s + + def events(self): + return [json.loads(l)["event"] for l in (self.tl.events_path).read_text().splitlines()] + + +def test_max_bursts_caps_how_many_bursts_start(tmp_path, write_frame): + rig = Rig(tmp_path, write_frame, [score()], max_bursts=1) + rig.tl.step() + assert rig.tl.mode == "burst" + rig.tl._end_burst("test") + rig.scores.append(score()) + rig.tl.step() + assert rig.tl.mode == "slow" and "burst_skipped" in rig.events() and rig.tl.summary.bursts == 1 + + +def test_a_shift_never_starts_a_burst(tmp_path, write_frame): + rig = Rig(tmp_path, write_frame, [score(shift=20.0)]) + rig.tl.step() + assert rig.tl.mode == "slow" and rig.tl.summary.shifts == 1 and "shift" in rig.events() + + +def test_a_trigger_with_no_opinion_changes_nothing(tmp_path, write_frame): + rig = Rig(tmp_path, write_frame, [score()]) + calls = [] + rig.tl.on_trigger = lambda e, m, s: calls.append(1) + rig.tl.step() + assert calls == [1] and rig.tl.mode == "burst" and rig.tl.burst_until == 1030.0 + + +def test_background_consult_applies_a_reply_on_a_later_step(tmp_path, write_frame): + rig = Rig(tmp_path, write_frame, [score(), score(False)]) + rig.tl.on_trigger = lambda e, m, s: "ignore" + rig.tl.consult_in_background = True + rig.tl.step() + rig.tl._executor.shutdown(wait=True) # let the worker thread finish + rig.tl.step() + assert rig.tl.mode == "slow" and "burst_end" in rig.events() + + +def test_a_failing_background_consult_is_reported(tmp_path, write_frame): + rig = Rig(tmp_path, write_frame, [score(), score(False)]) + + def boom(e, m, s): + raise RuntimeError("model down") + + rig.tl.on_trigger = boom + rig.tl.consult_in_background = True + rig.tl.step() + rig.tl._executor.shutdown(wait=True) + rig.tl.step() + assert "consult_failed" in rig.events() + + +def test_a_reply_after_the_burst_ended_is_ignored(tmp_path, write_frame): + rig = Rig(tmp_path, write_frame, [score(False)]) + rig.tl.mode = "slow" + rig.tl._apply_decision("extend", 3, late_ok=True) + assert "consult_late" in rig.events() + rig.tl._apply_decision("extend", 3, late_ok=False) # not late_ok: silent + + +def test_run_stops_cleanly_on_ctrl_c_and_abandons_pending_replies(tmp_path, write_frame): + rig = Rig(tmp_path, write_frame, [score()]) + rig.tl.on_trigger = lambda e, m, s: "extend" + + class Manual: + def __init__(self): + self.futures = [] + + def submit(self, fn, *a): + f = Future() + self.futures.append(f) + return f + + def shutdown(self, wait=True, cancel_futures=False): + pass + + rig.tl.consult_in_background = True + rig.tl._executor = Manual() + seen = [] + + def capture(): + seen.append(1) + if len(seen) > 1: + raise KeyboardInterrupt + return rig.capture() + + rig.tl.capture = capture + summary = rig.tl.run() + assert summary.stop_reason == "interrupted" + assert {"consult_abandoned", "burst_end", "stop"} <= set(rig.events()) + + +def test_run_stops_at_the_runtime_cap(tmp_path, write_frame): + rig = Rig(tmp_path, write_frame, [], max_runtime_s=130) + assert rig.tl.run().stop_reason == "max_runtime" + + +def test_default_capture_goes_through_get_image(monkeypatch, tmp_path): + calls = [] + from mcp_server import loop_tools + monkeypatch.setattr(loop_tools, "get_image", lambda **kw: (calls.append(kw), ({"image": "x.png"}, None))[1]) + cap = sc._default_capture(sc.TimelapseConfig(backend="mock")) + assert cap() == {"image": "x.png"} and calls[0]["confirm"] is False and calls[0]["backend"] == "mock" + sc._default_capture(sc.TimelapseConfig(backend="sdk"))() + assert calls[1]["confirm"] is True + + +def test_plan_text_mentions_hardware_bursts_and_inversion(): + t = sc._plan_text(sc.TimelapseConfig(backend="sdk", max_bursts=3, invert=True)) + assert "REAL HARDWARE" in t and "at most 3 bursts" in t and "inverted" in t + + +def test_cli_dry_run_prints_the_plan(capsys): + assert sc.main(["--dry-run", "--slow", "30", "--burst", "3"]) == 0 + assert "hard caps" in capsys.readouterr().out + + +def test_cli_real_hardware_needs_whole_plan_approval(monkeypatch, capsys): + monkeypatch.setattr("builtins.input", lambda prompt: "n") + assert sc.main(["--backend", "sdk"]) == 2 + assert "Nothing captured" in capsys.readouterr().out + + +def test_cli_runs_a_short_mock_session(tmp_path, monkeypatch, capsys): + from mcp_server import loop_tools + from tests.conftest import make_blob_frame, save_frame + frame = save_frame(make_blob_frame(), tmp_path / "f.png") + monkeypatch.setattr(loop_tools, "get_image", lambda **kw: ({"image": str(frame), "frame_id": 1, "position": {}}, None)) + events = tmp_path / "ev.jsonl" + assert sc.main(["--max-captures", "2", "--slow", "0.01", "--burst", "0.01", "--events", str(events)]) == 0 + assert "done: max_captures; 2 captures" in capsys.readouterr().out and events.exists() + + +def test_cli_wires_up_the_model_trigger(tmp_path, monkeypatch): + seen = {} + + class FakeTrigger: + def __init__(self, max_calls): + seen["max_calls"] = max_calls + + def __call__(self, *a): + return None + + from mcp_server import loop_tools + from tests.conftest import make_blob_frame, save_frame + frame = save_frame(make_blob_frame(), tmp_path / "f.png") + monkeypatch.setattr(loop_tools, "get_image", lambda **kw: ({"image": str(frame), "frame_id": 1, "position": {}}, None)) + monkeypatch.setattr(mt, "ModelTrigger", FakeTrigger) + sc.main(["--max-captures", "1", "--slow", "0.01", "--burst", "0.01", "--model-trigger", + "--model-max-calls", "7", "--events", str(tmp_path / "e.jsonl")]) + assert seen["max_calls"] == 7 + + +def test_scheduler_module_runs_as_a_script(monkeypatch): + monkeypatch.setattr(sys, "argv", ["scheduler", "--dry-run"]) + with pytest.raises(SystemExit) as exc: + runpy.run_module("timelapse.scheduler", run_name="__main__") + assert exc.value.code == 0 diff --git a/tests/test_worm_follow.py b/tests/test_worm_follow.py new file mode 100644 index 0000000..32f6d02 --- /dev/null +++ b/tests/test_worm_follow.py @@ -0,0 +1,335 @@ +import csv +import json +import sys +import types + +import numpy as np +import pytest +from PIL import Image + +from acquisition import estop +from acquisition.orchestration import mosaic, worm_follow as wf +from tests.fakes_scene import RigNodeMap, SceneRig, UM_PER_PX, Z_FOCUS + +AREA = dict(min_area_mm2=0.001, max_area_mm2=0.02) # the rig's worm is ~0.004 mm2 + + +@pytest.fixture(autouse=True) +def quiet(tmp_path, monkeypatch): + monkeypatch.setattr(mosaic.time, "sleep", lambda s: None) # the same time module wf uses + monkeypatch.setattr(wf, "data_root", lambda: tmp_path / "root") + monkeypatch.setattr(estop, "ESTOP_PATH", tmp_path / "ESTOP") + + +@pytest.fixture +def rig(tmp_path, monkeypatch): + return SceneRig(tmp_path).install(monkeypatch) + + +def parse(monkeypatch, *argv): + """The real command line's defaults, with `run`/`setup`/`detect_only` captured + (only while parsing, so the real functions stay available afterwards).""" + seen = [] + with monkeypatch.context() as m: + m.setattr(wf, "run", lambda a: seen.append(("run", a))) + m.setattr(wf, "setup", lambda a: seen.append(("setup", a))) + m.setattr(wf, "detect_only", lambda *a: seen.append(("detect", a))) + m.setattr(sys, "argv", ["worm_follow", *argv]) + wf.main() + return seen + + +def track_args(monkeypatch, *argv): + kind, args = parse(monkeypatch, "--grid", "1x1", "--search-grid", "2x1", "--min-area-mm2", "0.001", + "--max-area-mm2", "0.02", "--crop-mm", "0.3", "--deadband-mm", "0.01", *argv)[0] + return args + + +def rows(out): + with (out / "track.csv").open(newline="", encoding="utf-8") as f: + return list(csv.DictReader(f)) + + +def only_run_dir(tmp_path): + return next((tmp_path / "root" / "data").glob("wormfollow_*")) + + +# ---- camera state ------------------------------------------------------------ + +def test_force_camera_autos_off_and_restores_colour(rig, capsys): + nm = rig.camera._acquirer.remote_device.node_map + wf.force_camera_autos_off(rig.camera) + assert nm.ColorTransformationAuto.value == nm.GainAuto.value == "Off" + assert nm.Gamma.value == 1.0 and nm.GainSelector.value == "All" + assert nm.ColorTransformationValue.value in (0.0, 1.0) + assert "identity matrix" in capsys.readouterr().out + + +def test_force_camera_autos_off_survives_a_camera_without_colour_nodes(tmp_path, monkeypatch, capsys): + rig = SceneRig(tmp_path, full_nodes=False).install(monkeypatch) + wf.force_camera_autos_off(rig.camera) + assert rig.camera._acquirer.remote_device.node_map.GainAuto.value == "Off" + assert "could not restore camera colour state" in capsys.readouterr().err + + +# ---- geometry ------------------------------------------------------------------ + +def test_canvas_to_stage_inverts_the_stitch_geometry(): + tiles = [(np.zeros((120, 160, 3), np.uint8), x, y) for x, y in ((0.0, 0.0), (200.0, 0.0), (0.0, 150.0))] + ref = (0.0, 0.0) + canvas, omin, twh = wf.stitch_with_origin(tiles, wf.M_4X, ref) + assert twh == (160, 120) and canvas.shape[0] > 120 and canvas.shape[1] > 160 + # the centre of the first tile is the stage position it was taken at + first_centre = -wf.M_4X @ np.array([0.0, 0.0]) - omin + np.array(twh) / 2 + sx, sy = wf.canvas_to_stage(first_centre[0], first_centre[1], wf.M_4X, ref, omin, twh) + assert (sx, sy) == pytest.approx((0.0, 0.0), abs=1e-6) + second_centre = -wf.M_4X @ np.array([200.0, 0.0]) - omin + np.array(twh) / 2 + sx, sy = wf.canvas_to_stage(second_centre[0], second_centre[1], wf.M_4X, ref, omin, twh) + assert (sx, sy) == pytest.approx((200.0, 0.0), abs=1e-6) + + +# ---- detection ------------------------------------------------------------------ + +def test_find_worms_finds_the_worm_where_the_scene_put_it(rig): + img = np.asarray(Image.open(rig.camera.capture())) + cands, mask = wf.find_worms(img, UM_PER_PX, **AREA, dark_ratio=0.85) + assert len(cands) == 1 and mask.dtype == np.uint8 and mask.max() == 255 + c = cands[0] + # worm at stage (+60, +30) um from a tile centred at the origin: right of and above centre + assert c["x"] == pytest.approx(160 + 60 / UM_PER_PX, abs=6) and c["y"] == pytest.approx(120 - 30 / UM_PER_PX, abs=6) + assert 0.001 < c["area_mm2"] < 0.02 and c["length_mm"] > 0.05 and c["width_um"] > 1 + + +def test_find_worms_ignores_objects_outside_the_size_window(rig): + img = np.asarray(Image.open(rig.camera.capture())) + assert wf.find_worms(img, UM_PER_PX, 0.1, 1.0, 0.85)[0] == [] + assert wf.find_worms(img, UM_PER_PX, 1e-6, 1e-5, 0.85)[0] == [] + + +def test_find_worms_on_empty_agar_finds_nothing(tmp_path, monkeypatch): + rig = SceneRig(tmp_path, worm=False).install(monkeypatch) + img = np.asarray(Image.open(rig.camera.capture())) + assert wf.find_worms(img, UM_PER_PX, **AREA, dark_ratio=0.85)[0] == [] + + +def test_pick_takes_the_nearest_within_range(): + cands = [{"x": 10, "y": 0, "area_mm2": 0.01}, {"x": 100, "y": 0, "area_mm2": 0.01}] + assert wf.pick(cands, (0, 0), 50)["x"] == 10 and wf.pick(cands, (0, 0), 50)["dist_px"] == 10 + assert wf.pick(cands, (95, 0), 50)["x"] == 100 + assert wf.pick(cands, (500, 0), 50) is None and wf.pick([], (0, 0), 50) is None + + +def test_pick_does_not_hop_onto_a_worm_of_a_different_size(): + cands = [{"x": 5, "y": 0, "area_mm2": 0.002}, {"x": 40, "y": 0, "area_mm2": 0.011}] + assert wf.pick(cands, (0, 0), 100, area_mm2=0.01)["x"] == 40 # the larva beside it is skipped + assert wf.pick(cands, (0, 0), 100, area_mm2=0.0001) is None # both more than 2x too big + assert wf.pick(cands, (0, 0), 100)["x"] == 5 # no history: nearest wins + + +def test_detect_only_writes_a_mask_and_reports(rig, tmp_path, monkeypatch, capsys): + path = tmp_path / "shot.png" + Image.fromarray(rig.camera.frame()).save(path) + kind, (p, umpx, args) = parse(monkeypatch, "--detect-only", str(path), "--min-area-mm2", "0.001", + "--max-area-mm2", "0.02", "--um-per-px", str(UM_PER_PX))[0] + assert kind == "detect" and p == path + wf.detect_only(p, umpx, args) + assert (tmp_path / "shot_mask.png").exists() + out = capsys.readouterr().out + assert "1 candidate(s)" in out and "area" in out + + +def test_focus_score_prefers_the_sharper_image(rig): + sharp = rig.camera.frame() + rig.stage.z = Z_FOCUS + 60 + blurred = rig.camera.frame() + assert wf._focus_score(sharp) > 5 * wf._focus_score(blurred) + + +# ---- setup ---------------------------------------------------------------------- + +def setup_args(monkeypatch, *argv): + return parse(monkeypatch, "--setup", "--min-area-mm2", "0.001", "--max-area-mm2", "0.02", *argv)[0][1] + + +def test_setup_switches_objective_focuses_and_centres_on_the_worm(rig, tmp_path, monkeypatch, capsys): + rig.stage.z = Z_FOCUS + 30 # start out of focus + out = wf.setup(setup_args(monkeypatch)) + info = json.loads((out / "setup.json").read_text()) + assert info["nosepiece"] == 1 and rig.stage.micro.iNOSEPIECE == 1 + assert info["worm_found"] is True and info["z_before_um"] == Z_FOCUS + 30 + assert abs(rig.stage.z - Z_FOCUS) <= 10 # the sweep found the sharp plane + assert np.hypot(rig.stage.x - 60, rig.stage.y - 30) < 15 # and the worm was centred + assert (out / "final.png").exists() and (out / "final_marked.jpg").exists() + assert list(out.glob("coarse_z*.jpg")) and list(out.glob("fine_z*.jpg")) + assert rig.camera.closed and "READY" in capsys.readouterr().out + + +def test_setup_leaves_the_objective_alone_when_it_is_already_right(rig, monkeypatch, capsys): + rig.stage.micro.iNOSEPIECE = 1 + wf.setup(setup_args(monkeypatch)) + assert "nosepiece 2 ->" not in capsys.readouterr().out + + +def test_setup_halves_exposure_down_from_a_clipped_start_and_raises_it_from_dark(rig, monkeypatch): + wf.setup(setup_args(monkeypatch, "--exposure-us", "8000")) + assert 700 <= rig.camera.exposure_us <= 2200 + wf.setup(setup_args(monkeypatch, "--exposure-us", "300")) + assert 1000 <= rig.camera.exposure_us <= 2200 + + +def test_setup_reports_no_worm(tmp_path, monkeypatch, capsys): + rig = SceneRig(tmp_path, worm=False).install(monkeypatch) + out = wf.setup(setup_args(monkeypatch)) + assert json.loads((out / "setup.json").read_text())["worm_found"] is False + assert "NO WORM FOUND" in capsys.readouterr().out and rig.stage.moves == [] + + +def test_setup_keeps_z_when_the_sweep_is_flat(rig, monkeypatch, capsys): + rig.camera.blur_per_um = 0 + wf.setup(setup_args(monkeypatch)) + assert "sweep is flat" in capsys.readouterr().out + + +def test_setup_refuses_under_estop(rig, monkeypatch): + estop.engage("test") + with pytest.raises(estop.EStopEngaged): + wf.setup(setup_args(monkeypatch)) + assert rig.stage.micro.iNOSEPIECE == 2 and rig.stage.moves == [] + + +def test_setup_gives_up_if_the_turret_never_arrives(rig, monkeypatch): + class Micro: + iNOSEPIECE = 2 + + def __setattr__(self, name, value): + pass # accepts the write, never turns + + rig.stage.micro = Micro() + clock = iter(range(0, 10_000, 5)) + monkeypatch.setattr(mosaic.time, "monotonic", lambda: next(clock)) + with pytest.raises(SystemExit, match="did not reach"): + wf.setup(setup_args(monkeypatch)) + assert rig.camera.closed + + +# ---- run ------------------------------------------------------------------------ + +def test_run_tracks_the_worm_and_recentres_on_it(rig, tmp_path, monkeypatch, capsys): + out = wf.run(track_args(monkeypatch, "--rounds", "3", "--tag", "t")) + r = rows(out) + assert [x["found"] for x in r] == ["1", "1", "1"] and r[0]["recentred"] == "1" + assert float(r[0]["worm_x_um"]) == pytest.approx(60, abs=15) and float(r[0]["worm_y_um"]) == pytest.approx(30, abs=15) + assert len(list((out / "crops").glob("crop_*.jpg"))) == 3 and (out / "round_0002.jpg").exists() + assert (out / "track.png").exists() and (out / "run.json").exists() + assert np.hypot(rig.stage.x - 60, rig.stage.y - 30) < 15 # parked on the worm + assert rig.camera.closed and "released" in capsys.readouterr().out + + +def test_run_widens_the_search_after_a_miss(tmp_path, monkeypatch): + rig = SceneRig(tmp_path, worm=False).install(monkeypatch) + out = wf.run(track_args(monkeypatch, "--rounds", "2")) + r = rows(out) + assert [x["grid"] for x in r] == ["1x1", "2x1"] and [x["found"] for x in r] == ["0", "0"] + assert not (out / "track.png").exists() + + +def test_run_clamps_recentring_to_the_dish_limit(rig, monkeypatch, capsys): + out = wf.run(track_args(monkeypatch, "--rounds", "1", "--dish-centre", "0,0", "--limit-mm", "0.02")) + assert "clamped to the 0.02 mm limit" in capsys.readouterr().out + assert np.hypot(rig.stage.x, rig.stage.y) <= 21 + + +def test_run_records_a_camera_error_and_carries_on(rig, monkeypatch, capsys): + rig.camera.on_capture = lambda n: (_ for _ in ()).throw(RuntimeError("fetch timed out")) if n in (2, 3) else None + out = wf.run(track_args(monkeypatch, "--rounds", "2")) + r = rows(out) + assert [x["error"] for x in r] == ["RuntimeError: fetch timed out"] * 2 + assert "ERROR RuntimeError" in capsys.readouterr().out + + +def test_run_ends_the_series_on_an_estop(rig, monkeypatch): + estop.engage("test") + out = wf.run(track_args(monkeypatch, "--rounds", "5", "--grid", "2x1")) + r = rows(out) + assert len(r) == 1 and "E-STOP" in r[0]["error"] and rig.camera.closed + + +def test_run_halts_on_a_stop_file(rig, tmp_path, monkeypatch, capsys): + def stop_at_second_round(n): + if n == 3: # 1 = probe, 2 = round 0 tile, 3 = round 1 (checked before it) + (only_run_dir(tmp_path) / "STOP").write_text("") + rig.camera.on_capture = stop_at_second_round + out = wf.run(track_args(monkeypatch, "--rounds", "9")) + assert len(rows(out)) <= 3 and "STOP file present" in capsys.readouterr().out and rig.camera.closed + + +def test_run_paces_rounds_by_interval_and_stops_on_minutes(rig, monkeypatch): + slept = [] + monkeypatch.setattr(mosaic.time, "sleep", lambda s: slept.append(s)) + wf.run(track_args(monkeypatch, "--rounds", "2", "--interval-s", "600")) + assert any(s > 100 for s in slept) + clock = iter(float(i) * 30 for i in range(10_000)) + monkeypatch.setattr(mosaic.time, "monotonic", lambda: next(clock)) + out = wf.run(track_args(monkeypatch, "--minutes", "1", "--tag", "m")) + assert 1 <= len(rows(out)) <= 3 + + +def test_run_can_remeasure_the_axes(rig, monkeypatch, capsys): + wf.run(track_args(monkeypatch, "--rounds", "1", "--calibrate")) + assert "um/px" in capsys.readouterr().out + + +@pytest.mark.parametrize("exposure,word", [("4000", "clipped"), ("300", "dark")]) +def test_run_warns_when_the_agar_is_clipped_or_dark(rig, monkeypatch, capsys, exposure, word): + wf.run(track_args(monkeypatch, "--rounds", "1", "--exposure-us", exposure)) + assert f"agar is {word}" in capsys.readouterr().err + + +def test_run_parks_even_if_parking_fails(rig, monkeypatch, capsys): + real = wf._move_safe + calls = [] + + def flaky(sdk, x, y): + calls.append(1) + if len(calls) >= 2: + raise RuntimeError("stage gone") + return real(sdk, x, y) + + monkeypatch.setattr(wf, "_move_safe", flaky) + wf.run(track_args(monkeypatch, "--rounds", "1", "--grid", "2x1")) + assert "could not park at the last centre" in capsys.readouterr().err and rig.camera.closed + + +# ---- track plot -------------------------------------------------------------------- + +def write_track(path, found_rows): + with (path / "track.csv").open("w", newline="", encoding="utf-8") as f: + w = csv.DictWriter(f, fieldnames=["found", "worm_x_um", "worm_y_um", "t_s"]) + w.writeheader() + w.writerows(found_rows) + + +def test_plot_track_draws_found_points_only(tmp_path): + write_track(tmp_path, [{"found": 0, "worm_x_um": "", "worm_y_um": "", "t_s": 0}, + {"found": 1, "worm_x_um": 0, "worm_y_um": 0, "t_s": 60}, + {"found": 1, "worm_x_um": 500, "worm_y_um": 300, "t_s": 120}, + {"found": 1, "worm_x_um": 900, "worm_y_um": 100, "t_s": 180}]) + wf.plot_track(tmp_path) + assert Image.open(tmp_path / "track.png").size == (900, 900) + + +def test_plot_track_with_nothing_found_writes_nothing(tmp_path): + write_track(tmp_path, [{"found": 0, "worm_x_um": "", "worm_y_um": "", "t_s": 0}]) + wf.plot_track(tmp_path) + assert not (tmp_path / "track.png").exists() + + +# ---- command line ------------------------------------------------------------------- + +def test_main_dispatches_setup_detect_and_run(monkeypatch, tmp_path): + assert parse(monkeypatch, "--setup")[0][0] == "setup" + assert parse(monkeypatch, "--detect-only", str(tmp_path / "x.png"))[0][0] == "detect" + kind, args = parse(monkeypatch)[0] + assert kind == "run" and args.rounds == 1 and args.grid == "3x3" and args.search_grid == "5x5" + kind, args = parse(monkeypatch, "--minutes", "5")[0] + assert args.rounds is None and args.minutes == 5