Repository navigation
Feat/sila2 unitelabs - #338
Open
beniroquai wants to merge 59 commits into
Open
beniroquai wants to merge 59 commits into
beniroquai wants to merge 59 commits into
Conversation
The server UUID was hard-coded (every unit looked like the same device to a workcell) and the UniteLabs dev cloud endpoint was compiled in. The UUID is now derived from host and port unless the setup sets serverUUID; mDNS discovery, TLS certificates and the cloud endpoint come from the sila2 block. Ported to unitelabs-cdk 0.18 / unitelabs-sila 0.14 (pinned): the local server is reported running once the connector is ready, also while the cloud connection retries. ImConMainController checked the widget key "SiLA2" instead of "SiLa2".
The features move to controllers/sila2/features.py and the controller only registers them. One variant per command, µm and ms units, defined errors a scheduler can branch on (StageLimitReached, InstrumentBusy, UnknownDevice, NotAvailable, PlateNotCalibrated) instead of False or "". Every handler runs its ImSwitch call in a worker thread (a move used to stall the SiLA event loop) and goes through the controllers, so travel limits and busy checks apply. New: SaveImage (OME-TIFF via storage.save_image), Autofocus, SetPlateOrigin, MoveToWell, ImageWells (one image per well as an ImSwitch experiment), MoveToLoadingPosition, Home, Stop. The controller module no longer breaks the import when unitelabs-cdk is missing.
A robot hands a plate to the stage with the SiLA standard sequence PrepareForInput -> LabwareDelivered and takes it with PrepareForOutput -> LabwareRemoved. Prepare switches the light off and drives the stage to the sample loading position; out-of-order calls and a second plate fail with InvalidCommandSequence. One handover position (sila2.handoverPositionName) and one internal position. getSiLA2Status reports the plate on the stage. ImageWells switches the light off when it ends.
A SiLA client in the style of the UniteLabs client tutorial: reads every property, takes one value from every observable property, calls every command of the ImSwitch features and checks the defined errors of the refusals. Steps that move the stage need --motion, light needs --light, homing --home; an element that is neither run nor skipped is a failure. --discover finds the server over mDNS, --json writes a report. CI runs it against the virtual microscope with a sila2 block (test_sila2.py, own step: the API test server is one per session). Unit tests cover the manager configuration.
… packages docs/SILA2.md: setup block, features, plate hand-over, demo flow, the check client and its flags, a prompt for extending it with a coding agent, open points. The roadmap marks S0-S3 done on the virtual microscope and adds what the first plan missed (confirm identifiers with UniteLabs, lock against the UI, persisted plate origin, hardware run of the check, quieter error logs).
PositionerController/setSampleLoadingPosition takes the current stage
position (or given axes, device frame µm) as the sample loading position and
saves it to the setup's sampleLoadingPosition{X,Y,Z};
getSampleLoadingPosition reads it. A robot puts and takes plates there. The
virtual stage now has a loading position and drives to it, so the hand-over
can be exercised without hardware.
…microscope model/workcell_lock.py: while a lock holder is set, an HTTP middleware answers 423 Locked for requests that move, switch light or start acquisitions; reads (get/is/list...) and stops (stop/cancel/abort) stay open. busy_reasons gets a "SiLa2" check, so jobs and experiments started from elsewhere refuse too. The SiLA server's thread sets a context variable, so calls made on the workcell's behalf (also in worker threads started with asyncio.to_thread) pass. SiLa2Manager gains call_soon (run on the server loop) and exposes the sila2 setup block.
The microscope is a passive device in a workcell, so the scheduler gets its functions: Objectives / CurrentObjective / MoveToObjective, and a JobController that runs saved Aufgaben jobs by name with JSON parameters (Confirmed for ask-first steps; a job stopping at an operator question fails with JobFailed). The SiLA standard Lock Controller drives the workcell lock; its timeout runs from the workcell's last call, and a 0 s timeout means none (the CDK took it as expired at once). releaseWorkcellLock frees it by hand. SetPlateOrigin is kept per labware in sila2.plateOrigins and survives a restart; MoveToWell and ImageWells name the labware, CalibratedLabware lists the taught ones. TeachLoadingPosition stores the hand-over position.
The check covers the new commands and the Lock Controller (lock, second lock, work with the identifier, wrong and repeated unlock, 0 s timeout). Steps that overwrite taught values (SetPlateOrigin, TeachLoadingPosition) need --teach, so a check on an instrument cannot replace its calibration; MoveToWell and ImageWells use an already taught plate type otherwise. --job picks the job RunJob runs. Tests: the HTTP lock rule, and against the virtual microscope that a locked microscope answers 423 to an HTTP move but not to reads and stops.
SILA2.md: what the workcell and the microscope each do, teaching the loading position and plate origins, the lock and its limits, the new features and check flags. Roadmap: S7 decided (passive device, functions exposed), S8 and S9 done on the virtual microscope, S10 open.
The Connection Configuration Service saves a workcell's server-initiated connections (e.g. to the UniteLabs cloud) with config.dump(); the connector config was built in code, so Enable/DisableServerInitiatedConnectionMode failed with NeverLoadedConfig. It now saves to and loads from <config>/sila2_connections.json, merged with the setup's cloudEndpoint. Refusals (defined and validation errors) log one line with the error instead of a rendered traceback, which took 0.1-0.3 s per refused call (now ~1 ms); real errors keep a plain traceback, no colour codes in the log file.
A coding agent given only the UniteLabs client tutorial and the running virtual server wrote its own client for all 85 elements. Fixed from its report: - moves, MoveToLoadingPosition, autofocus and new scans are refused with InstrumentBusy while an acquisition, job or calibration runs (autofocus moved Z in the middle of a scan; a second scan was an undefined error) - bad JSON in RunJob parameters, an empty well list, an unknown handover position and an internal position other than 1 are validation errors, checked before an observable command is accepted - a timed-out lock is pushed to IsLocked subscribers (the CDK noticed only on the next read) - new properties: TravelLimits, LoadingPosition (UI coordinates), Illumination (state, range, units, wavelength), ExposureTimes - Detectors lists only cameras that take images; ExperimentStatus and JobStatus are Set-constrained; positions rounded to nm; SaveImage records the exposure; ImageWells progress is estimated from the wells - descriptions say what a client can see instead of internal names
Moved to imswitch/sila_check.py: it needs only unitelabs-sila, so it runs on a workcell's computer without loading ImSwitch (it used to print ImSwitch's start-up log and create ~/ImSwitchConfig). --list shows the SiLA servers on the network; --discover finds one by --name/--uuid with Discovery.wait_for (Client.discover in unitelabs-sila 0.14 drops the TLS settings). Covers the core features too (every feature definition, an unknown feature, SetServerName, the server-initiated mode under --teach, set back), and regression tests for the faults a black-box client found: refusals during a scan, validation of bad JSON, an empty well list and wrong hand-over positions, and that a timed-out lock reaches IsLocked subscribers.
…s for UniteLabs SILA2.md: the black-box run (brief, coverage, faults found), the new properties and refusal rules, imswitch-sila-check --list / --discover, and the library issues to pass on to UniteLabs. Roadmap: S11 done, S12 added.
startPalletUpgrade(version) starts imswitch-pallet-upgrade@<version>.service (forklift plt upgrade --force --allow-downgrade @<version>), so a Pi on a deleted pallet branch can go back to edge; empty keeps the old unit and the stored upgrade query. The version must be a plain branch, tag or commit name before it becomes a unit instance. The last started unit is remembered in the config folder, since a successful upgrade recreates the container. getPalletUpgradeStatus adds the host's pallet versions (/run/versioning), and listPalletVersions lists the repo's branches and tags.
A free-text dropdown of the os-rpi branches and release tags (edge first), the machine's running / pending / stored pallet versions, and the command shown and run with the picked version.
A server bound to 0.0.0.0 without network_interfaces announced 127.0.0.1 over mDNS. UniteLabs GroundControl on another computer showed the FRAME online but sent every request to itself (ECONNREFUSED 127.0.0.1:50052). Discovery now gets all non-loopback IPv4 addresses, so each interface announces its own.
…oject The uv test jobs ran `uv sync --locked`, which refused the stale lock.
…witch into feat/sila2-unitelabs
…witch into feat/sila2-unitelabs
The module was left out of the histology commit, so detectTissue and its tests imported a file that was not in the repository.
The prescan, stage mapping, strobe calibration and manual snap took a detectorsManager acquisition handle and released it at the end. The live view starts the camera without such a handle, so the release was the last one and stopped every camera under the running live stream. Start and stop the map's own camera only when it was not running.
…ines The camera lag was calibrated by driving a line out and back, on up to six lines until one had contrast. On a dark or blank slide those were the first six lines, so the prescan did not zig-zag. The lag now starts from the last prescan's (60 ms after a start) and neighbouring lines measure it as they come; lines placed before it settled are laid out again at the end.
A 20x needs about 25 times the exposure of a 4x for the same light, so a 4x prescan after work at 20x came out white and the 20x scan after it black. The turret now keeps the exposure and gain the leaving objective was used with (setup objective.exposures / objective.gains, like zPositions) and sets the arriving objective's again. getstatus lists them per slot.
startPrescan takes illumination and intensity (0 = the light's own value). The light is switched on through LaserController for the sweep and put back as it was, also on errors and stops. Without one the lights stay as they are, as before.
Double-click and arrow-key moves ran at the stage's default speed and each one posted an info message. They now run at the map's moveSpeed (20000 steps/s by default, kept across restarts, set in the map's settings), and the stage marker on the map is the only sign of the move.
…nnel A "Prescan with" selector next to Prescan replaces the confirm dialog; it defaults to the lowest magnification. The line spacing now comes from that objective's field: started from the 20x, a 4x prescan swept lines 273 µm apart instead of 1.2 mm, 4.5 times as many as needed. The run's first lit channel is sent as the prescan's light, so the prescan no longer sweeps dark slides when the light is off.
With Keep focus the turret moves Z by the stored focus difference of the two objectives, but the experiment's positions kept the old objective's Z: a 20x scan after a 4x prescan and tissue detection ran at the 4x focus, 10 mm off. Every position's Z (and its tiles') now moves by the same difference. The switch's caption says what it does.
Every other tool stores the stage Z of the moment; a freehand area was created with Z = 0 and scanned there, far out of focus, unless the focus map or the Z override replaced it.
The backend now sets the arriving objective's own exposure and gain when the turret gets there, so a preset that sent its exposure first and then switched the objective lost its exposure. The preset now switches, waits until the turret has arrived, then sets exposure and gain.
sigExperimentTileAcquired carries the tile's centre and size (stage µm), the timepoint and the run folder, once per tile (first channel and plane), so the plate map can show what is already scanned while a run goes on.
…gend The map drew the stage, the mouse cursor and the stage trail all in red, on top of grey tiles, with the prescan images painted over everything. Now: - red is only the microscope: its field and a dot, drawn last; - blue is what will be scanned: dashed area outlines (also of freehand and tissue areas, never drawn before), light tiles, and filled tiles for what the run has taken (sigExperimentTileAcquired); - green is the tissue Detect tissue found; cyan the clear-glass spot; - the stage trail is a layer, off by default; the cursor dot is gone; - overview and prescan images lie under everything else. Line widths no longer grow with zoom. A legend under the map and swatches in the Layers menu say what each colour is.
On the FRAME the 18000 planned 20x tiles of a slide, and the 3500 of a section, merged into a solid blue block that read as "scanned". Planned tiles are grey thin lines now, drawn only when a tile is at least 8 px on screen; below that the area's outline stands for them. Blue fill means scanned only.
With a focus map every tile's Z changes by a few µm, and that Z move was a step of its own after the XY move: on the FRAME (20x, 63 tiles) it cost a blocking round trip of ~0.1 s per tile, 15 % of the tile time. Stages that move X, Y and Z together now get one XYZ command, so Z travels during the XY move; others still move XY, then Z. A Z that does not change already cost nothing (uc2rest skips it); the 90 ms after the base-Z step is the settle (performanceTPreMs) and stays.
The focus map and the shading reference are measured before the workflow starts, and getExperimentStatus said "idle" meanwhile: the WellPlate app showed idle while the stage moved, and a script waiting for idle took the run for finished (FRAME, 2026-11-28). It now says "running" with phase "preparing" until the workflow takes over, like busy_reasons did.
Only the focus map's UI states were persisted, so "Enable Focus Mapping" fell back to off on every reload and a tissue scan ran without its focus map (FRAME, 2026-11-28). The settings (on/off, grid, fit) are persisted like the other run settings, merged two levels deep so settings added later keep their defaults.
…ndings Prescan objective and light, the measured focus difference and why it has to be measured, per-objective camera settings, positions following the focus, the plate map's colours, and what the first 20x test on the FRAME showed (one XYZ move per tile, two focus layers, seams without overlap).
startPrescan's objective and light, gotoStagePosition's speed, the stored focus difference that Keep focus applies (and why it must be measured), per-objective camera settings, the preparing phase of getExperimentStatus and sigExperimentTileAcquired.
The WellPlate prescan answered "A scan is already running" while the Stage Map app was left mapping. The live map only watches the stage, so the prescan and startWellplateExperiment now stop it (busy.stop_live_map) and the prescan message says so; a stage-map prescan or strobe calibration still refuses other work.
… view The six-column table pushed Go to / Remove past the right edge of a narrow inspector, reachable only by scrolling sideways. Rows are now a grid of #, name, X, Y, Z with the buttons after them; when they do not fit beside the fields they wrap onto a second line. Header and rows share the grid.
A "Last scan" bar under the experiment controls shows the newest run (start, frames, time) with Open image (OME-Zarr viewer) and Show in File Manager. It is read again whenever a run ends. Components ask the app shell for the File Manager at a folder through one event (utils/openInFileManager).
light_on / light_back (through LaserController when there is one) were StageMapController methods; the find-sample sweep needs the same behaviour, so both use one helper. The prescan keeps its wrappers.
…n focus Z goes from the bottom of a window upwards in steps of about one depth of field (lambda/NA^2, 2..50 µm), one in-sync frame per step, then the three sharpest peaks are swept again with a fifth of the step and compared at their best, so a dust plane on the grid cannot beat the tissue between two steps. The window reaches 40 steps below the objective's stored focus and 20 above it (+Z is towards the slide on the FRAME), inside the travel limits; given zMin/zMax/step win. No clear peak: Z goes back to where it started. Stop leaves Z where it is. Progress and result in getAutofocusStatus().findSample; getFindSampleDefaults shows the window without moving. Optional light for the sweep, a live stage map yields, other work refuses. Pure logic in model/find_sample.py.
A dialog shows the objective, its stored focus and the Z window before anything moves (editable; a warning when To Z is above the default), then the sharpness curve as Z sweeps, and the result with Go to buttons for the other planes. In the WellPlate the run's first lit channel is switched on for the sweep.
A Brush tool next to Freehand. A stroke edits the area it starts in (Add also the nearest within the brush radius; clear of every area it makes a new one). It paints what the area is made of: the tissue of a Detect tissue area, whose scan outline is then grown by the same margin the detection uses (400 µm + 0.71 of a tile step), else the outline of a freehand, rectangle or circle area. On release the mask is traced back into outline loops (even-odd, so an erased hole or a split-off piece stays one area), and tiles, focus points and the area's centre follow; erasing everything removes the area. Strokes are exact capsules, and an erase stroke clears slivers thinner than three cells inside its box, which kept the scan outline where tissue had been erased. Areas with several loops tile, draw and re-tile at Start through regionScanPositions.
The flip belongs to the camera and its light path, the same for every objective. On the FRAME the hand-clicked 20x calibration had a negative Y scale and the 4x grid calibration none, so ImSwitch turned every 20x frame upside down and stitched 20x scans looked as if their rows were swapped (82 % of the row seams of a scan join better with each tile flipped). flip_disagreements() names such cameras: logged at startup, returned by getAvailableDetectors (flipWarnings) and shown in the calibration tab.
Adds the find-sample window and peak rule, the plate-map brush (tissue vs outline areas, margin, even-odd loops, sliver clean-up), the last-scan bar, the live map giving way, and why the FRAME's 20x scans had mirrored tiles (its calibration flips Y, the 4x does not).
…ops imcontrol On the openUC2 OS, the arkitekt feature bind-mounted the login at ~/.local/state/arkitekt. The image had no ~/.local, so Docker created it owned by root. pymmcore-plus configures file logging under ~/.local/share when it is imported, raised PermissionError (not ImportError), and the managers package, and with it imcontrol, failed to load. Jupyter, which writes there too, timed out. - Dockerfile: create ~/.local/share, ~/.local/state, ~/.config and ~/.cache owned by pi, so a bind mount below them leaves them writable - MMCoreManager: any import failure of the optional pymmcore-plus means "not available"; the MMCore* managers report the real error when used Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.